diff --git a/actions/run-many/dist/index.js b/actions/run-many/dist/index.js index b5872dff..8612b0c1 100644 --- a/actions/run-many/dist/index.js +++ b/actions/run-many/dist/index.js @@ -14024,360 +14024,355 @@ function installSourceMapSupport() { const { readFileSync } = __nccwpck_require__(57147) -let nativeBinding = null; -const loadErrors = []; +let nativeBinding = null +const loadErrors = [] const isMusl = () => { - let musl = false; - if (process.platform === "linux") { - musl = isMuslFromFilesystem(); - if (musl === null) { - musl = isMuslFromReport(); - } - if (musl === null) { - musl = isMuslFromChildProcess(); - } + let musl = false + if (process.platform === 'linux') { + musl = isMuslFromFilesystem() + if (musl === null) { + musl = isMuslFromReport() } - return musl; -}; + if (musl === null) { + musl = isMuslFromChildProcess() + } + } + return musl +} -const isFileMusl = (f) => f.includes("libc.musl-") || f.includes("ld-musl-"); +const isFileMusl = (f) => f.includes('libc.musl-') || f.includes('ld-musl-') const isMuslFromFilesystem = () => { - try { - return readFileSync("/usr/bin/ldd", "utf-8").includes("musl"); - } catch { - return null; - } -}; + try { + return readFileSync('/usr/bin/ldd', 'utf-8').includes('musl') + } catch { + return null + } +} const isMuslFromReport = () => { - const report = - typeof process.report.getReport === "function" - ? process.report.getReport() - : null; - if (!report) { - return null; - } - if (report.header && report.header.glibcVersionRuntime) { - return false; - } - if (Array.isArray(report.sharedObjects)) { - if (report.sharedObjects.some(isFileMusl)) { - return true; - } + const report = typeof process.report.getReport === 'function' ? process.report.getReport() : null + if (!report) { + return null + } + if (report.header && report.header.glibcVersionRuntime) { + return false + } + if (Array.isArray(report.sharedObjects)) { + if (report.sharedObjects.some(isFileMusl)) { + return true } - return false; -}; + } + return false +} const isMuslFromChildProcess = () => { + try { + return (__nccwpck_require__(32081).execSync)('ldd --version', { encoding: 'utf8' }).includes('musl') + } catch (e) { + // If we reach this case, we don't know if the system is musl or not, so is better to just fallback to false + return false + } +} + +function requireNative() { + if (process.platform === 'android') { + if (process.arch === 'arm64') { + try { + return __nccwpck_require__(77816) + } catch (e) { + loadErrors.push(e) + } + try { + return __nccwpck_require__(42210) + } catch (e) { + loadErrors.push(e) + } + + } else if (process.arch === 'arm') { + try { + return __nccwpck_require__(64560) + } catch (e) { + loadErrors.push(e) + } + try { + return __nccwpck_require__(76276) + } catch (e) { + loadErrors.push(e) + } + + } else { + loadErrors.push(new Error(`Unsupported architecture on Android ${process.arch}`)) + } + } else if (process.platform === 'win32') { + if (process.arch === 'x64') { + try { + return __nccwpck_require__(23410) + } catch (e) { + loadErrors.push(e) + } + try { + return __nccwpck_require__(65610) + } catch (e) { + loadErrors.push(e) + } + + } else if (process.arch === 'ia32') { + try { + return __nccwpck_require__(12846) + } catch (e) { + loadErrors.push(e) + } + try { + return __nccwpck_require__(89635) + } catch (e) { + loadErrors.push(e) + } + + } else if (process.arch === 'arm64') { + try { + return __nccwpck_require__(13222) + } catch (e) { + loadErrors.push(e) + } + try { + return __nccwpck_require__(69104) + } catch (e) { + loadErrors.push(e) + } + + } else { + loadErrors.push(new Error(`Unsupported architecture on Windows: ${process.arch}`)) + } + } else if (process.platform === 'darwin') { try { - return (__nccwpck_require__(32081).execSync)("ldd --version", { encoding: "utf8" }) - .includes("musl"); - } catch (e) { - // If we reach this case, we don't know if the system is musl or not, so is better to just fallback to false - return false; + return __nccwpck_require__(38310) + } catch (e) { + loadErrors.push(e) + } + try { + return __nccwpck_require__(73011) + } catch (e) { + loadErrors.push(e) + } + + if (process.arch === 'x64') { + try { + return __nccwpck_require__(59243) + } catch (e) { + loadErrors.push(e) + } + try { + return __nccwpck_require__(95794) + } catch (e) { + loadErrors.push(e) + } + + } else if (process.arch === 'arm64') { + try { + return __nccwpck_require__(35918) + } catch (e) { + loadErrors.push(e) + } + try { + return __nccwpck_require__(60225) + } catch (e) { + loadErrors.push(e) + } + + } else { + loadErrors.push(new Error(`Unsupported architecture on macOS: ${process.arch}`)) } -}; + } else if (process.platform === 'freebsd') { + if (process.arch === 'x64') { + try { + return __nccwpck_require__(43003) + } catch (e) { + loadErrors.push(e) + } + try { + return __nccwpck_require__(44546) + } catch (e) { + loadErrors.push(e) + } -function requireNative() { - if (process.platform === "android") { - if (process.arch === "arm64") { - try { - return __nccwpck_require__(77816); - } catch (e) { - loadErrors.push(e); - } - try { - return __nccwpck_require__(42210); - } catch (e) { - loadErrors.push(e); - } - } else if (process.arch === "arm") { - try { - return __nccwpck_require__(64560); - } catch (e) { - loadErrors.push(e); - } - try { - return __nccwpck_require__(76276); - } catch (e) { - loadErrors.push(e); - } - } else { - loadErrors.push( - new Error(`Unsupported architecture on Android ${process.arch}`) - ); - } - } else if (process.platform === "win32") { - if (process.arch === "x64") { - try { - return __nccwpck_require__(23410); - } catch (e) { - loadErrors.push(e); - } - try { - return __nccwpck_require__(65610); - } catch (e) { - loadErrors.push(e); - } - } else if (process.arch === "ia32") { - try { - return __nccwpck_require__(12846); - } catch (e) { - loadErrors.push(e); - } - try { - return __nccwpck_require__(89635); - } catch (e) { - loadErrors.push(e); - } - } else if (process.arch === "arm64") { - try { - return __nccwpck_require__(13222); - } catch (e) { - loadErrors.push(e); - } - try { - return __nccwpck_require__(69104); - } catch (e) { - loadErrors.push(e); - } - } else { - loadErrors.push( - new Error( - `Unsupported architecture on Windows: ${process.arch}` - ) - ); - } - } else if (process.platform === "darwin") { + } else if (process.arch === 'arm64') { + try { + return __nccwpck_require__(56350) + } catch (e) { + loadErrors.push(e) + } + try { + return __nccwpck_require__(72514) + } catch (e) { + loadErrors.push(e) + } + + } else { + loadErrors.push(new Error(`Unsupported architecture on FreeBSD: ${process.arch}`)) + } + } else if (process.platform === 'linux') { + if (process.arch === 'x64') { + if (isMusl()) { try { - return __nccwpck_require__(38310); - } catch (e) { - loadErrors.push(e); - } + return __nccwpck_require__(79698) + } catch (e) { + loadErrors.push(e) + } + try { + return __nccwpck_require__(1306) + } catch (e) { + loadErrors.push(e) + } + + } else { try { - return __nccwpck_require__(73011); - } catch (e) { - loadErrors.push(e); - } + return __nccwpck_require__(75701) + } catch (e) { + loadErrors.push(e) + } + try { + return __nccwpck_require__(74901) + } catch (e) { + loadErrors.push(e) + } + + } + } else if (process.arch === 'arm64') { + if (isMusl()) { + try { + return __nccwpck_require__(35712) + } catch (e) { + loadErrors.push(e) + } + try { + return __nccwpck_require__(2603) + } catch (e) { + loadErrors.push(e) + } + + } else { + try { + return __nccwpck_require__(83068) + } catch (e) { + loadErrors.push(e) + } + try { + return __nccwpck_require__(66336) + } catch (e) { + loadErrors.push(e) + } + + } + } else if (process.arch === 'arm') { + try { + return __nccwpck_require__(7027) + } catch (e) { + loadErrors.push(e) + } + try { + return __nccwpck_require__(15083) + } catch (e) { + loadErrors.push(e) + } + + } else if (process.arch === 'riscv64') { + if (isMusl()) { + try { + return __nccwpck_require__(37917) + } catch (e) { + loadErrors.push(e) + } + try { + return __nccwpck_require__(11978) + } catch (e) { + loadErrors.push(e) + } + + } else { + try { + return __nccwpck_require__(72752) + } catch (e) { + loadErrors.push(e) + } + try { + return __nccwpck_require__(72574) + } catch (e) { + loadErrors.push(e) + } + + } + } else if (process.arch === 's390x') { + try { + return __nccwpck_require__(52097) + } catch (e) { + loadErrors.push(e) + } + try { + return __nccwpck_require__(47035) + } catch (e) { + loadErrors.push(e) + } - if (process.arch === "x64") { - try { - return __nccwpck_require__(59243); - } catch (e) { - loadErrors.push(e); - } - try { - return __nccwpck_require__(95794); - } catch (e) { - loadErrors.push(e); - } - } else if (process.arch === "arm64") { - try { - return __nccwpck_require__(35918); - } catch (e) { - loadErrors.push(e); - } - try { - return __nccwpck_require__(60225); - } catch (e) { - loadErrors.push(e); - } - } else { - loadErrors.push( - new Error(`Unsupported architecture on macOS: ${process.arch}`) - ); - } - } else if (process.platform === "freebsd") { - if (process.arch === "x64") { - try { - return __nccwpck_require__(43003); - } catch (e) { - loadErrors.push(e); - } - try { - return __nccwpck_require__(44546); - } catch (e) { - loadErrors.push(e); - } - } else if (process.arch === "arm64") { - try { - return __nccwpck_require__(56350); - } catch (e) { - loadErrors.push(e); - } - try { - return __nccwpck_require__(72514); - } catch (e) { - loadErrors.push(e); - } - } else { - loadErrors.push( - new Error( - `Unsupported architecture on FreeBSD: ${process.arch}` - ) - ); - } - } else if (process.platform === "linux") { - if (process.arch === "x64") { - if (isMusl()) { - try { - return __nccwpck_require__(79698); - } catch (e) { - loadErrors.push(e); - } - try { - return __nccwpck_require__(1306); - } catch (e) { - loadErrors.push(e); - } - } else { - try { - return __nccwpck_require__(75701); - } catch (e) { - loadErrors.push(e); - } - try { - return __nccwpck_require__(74901); - } catch (e) { - loadErrors.push(e); - } - } - } else if (process.arch === "arm64") { - if (isMusl()) { - try { - return __nccwpck_require__(35712); - } catch (e) { - loadErrors.push(e); - } - try { - return __nccwpck_require__(2603); - } catch (e) { - loadErrors.push(e); - } - } else { - try { - return __nccwpck_require__(83068); - } catch (e) { - loadErrors.push(e); - } - try { - return __nccwpck_require__(66336); - } catch (e) { - loadErrors.push(e); - } - } - } else if (process.arch === "arm") { - try { - return __nccwpck_require__(7027); - } catch (e) { - loadErrors.push(e); - } - try { - return __nccwpck_require__(15083); - } catch (e) { - loadErrors.push(e); - } - } else if (process.arch === "riscv64") { - if (isMusl()) { - try { - return __nccwpck_require__(37917); - } catch (e) { - loadErrors.push(e); - } - try { - return __nccwpck_require__(11978); - } catch (e) { - loadErrors.push(e); - } - } else { - try { - return __nccwpck_require__(72752); - } catch (e) { - loadErrors.push(e); - } - try { - return __nccwpck_require__(72574); - } catch (e) { - loadErrors.push(e); - } - } - } else if (process.arch === "s390x") { - try { - return __nccwpck_require__(52097); - } catch (e) { - loadErrors.push(e); - } - try { - return __nccwpck_require__(47035); - } catch (e) { - loadErrors.push(e); - } - } else { - loadErrors.push( - new Error(`Unsupported architecture on Linux: ${process.arch}`) - ); - } } else { - loadErrors.push( - new Error( - `Unsupported OS: ${process.platform}, architecture: ${process.arch}` - ) - ); + loadErrors.push(new Error(`Unsupported architecture on Linux: ${process.arch}`)) } + } else { + loadErrors.push(new Error(`Unsupported OS: ${process.platform}, architecture: ${process.arch}`)) + } } -nativeBinding = requireNative(); +nativeBinding = requireNative() if (!nativeBinding || process.env.NAPI_RS_FORCE_WASI) { + try { + nativeBinding = __nccwpck_require__(82465) + } catch (err) { + if (process.env.NAPI_RS_FORCE_WASI) { + console.error(err) + } + } + if (!nativeBinding) { try { - nativeBinding = __nccwpck_require__(82465); + nativeBinding = __nccwpck_require__(74068) } catch (err) { - if (process.env.NAPI_RS_FORCE_WASI) { - console.error(err); - } - } - if (!nativeBinding) { - try { - nativeBinding = __nccwpck_require__(74068); - } catch (err) { - if (process.env.NAPI_RS_FORCE_WASI) { - console.error(err); - } - } + if (process.env.NAPI_RS_FORCE_WASI) { + console.error(err) + } } + } } if (!nativeBinding) { - if (loadErrors.length > 0) { - // TODO Link to documentation with potential fixes - // - The package owner could build/publish bindings for this arch - // - The user may need to bundle the correct files - // - The user may need to re-install node_modules to get new packages - throw new Error("Failed to load native binding", { cause: loadErrors }); - } - throw new Error(`Failed to load native binding`); -} - -module.exports.Compiler = nativeBinding.Compiler; -module.exports.JsCompiler = nativeBinding.JsCompiler; -module.exports.bundle = nativeBinding.bundle; -module.exports.getTargetTriple = nativeBinding.getTargetTriple; -module.exports.initCustomTraceSubscriber = - nativeBinding.initCustomTraceSubscriber; -module.exports.minify = nativeBinding.minify; -module.exports.minifySync = nativeBinding.minifySync; -module.exports.parse = nativeBinding.parse; -module.exports.parseFile = nativeBinding.parseFile; -module.exports.parseFileSync = nativeBinding.parseFileSync; -module.exports.parseSync = nativeBinding.parseSync; -module.exports.print = nativeBinding.print; -module.exports.printSync = nativeBinding.printSync; -module.exports.transform = nativeBinding.transform; -module.exports.transformFile = nativeBinding.transformFile; -module.exports.transformFileSync = nativeBinding.transformFileSync; -module.exports.transformSync = nativeBinding.transformSync; + if (loadErrors.length > 0) { + // TODO Link to documentation with potential fixes + // - The package owner could build/publish bindings for this arch + // - The user may need to bundle the correct files + // - The user may need to re-install node_modules to get new packages + throw new Error('Failed to load native binding', { cause: loadErrors }) + } + throw new Error(`Failed to load native binding`) +} + +module.exports.Compiler = nativeBinding.Compiler +module.exports.JsCompiler = nativeBinding.JsCompiler +module.exports.bundle = nativeBinding.bundle +module.exports.getTargetTriple = nativeBinding.getTargetTriple +module.exports.initCustomTraceSubscriber = nativeBinding.initCustomTraceSubscriber +module.exports.minify = nativeBinding.minify +module.exports.minifySync = nativeBinding.minifySync +module.exports.newMangleNameCache = nativeBinding.newMangleNameCache +module.exports.parse = nativeBinding.parse +module.exports.parseFile = nativeBinding.parseFile +module.exports.parseFileSync = nativeBinding.parseFileSync +module.exports.parseSync = nativeBinding.parseSync +module.exports.print = nativeBinding.print +module.exports.printSync = nativeBinding.printSync +module.exports.transform = nativeBinding.transform +module.exports.transformFile = nativeBinding.transformFile +module.exports.transformFileSync = nativeBinding.transformFileSync +module.exports.transformSync = nativeBinding.transformSync /***/ }), @@ -14431,8 +14426,11 @@ var __rest = (this && this.__rest) || function (s, e) { return t; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.DEFAULT_EXTENSIONS = exports.getBinaryMetadata = exports.__experimental_registerGlobalTraceConfig = exports.minifySync = exports.minify = exports.bundle = exports.transformFileSync = exports.transformFile = exports.transformSync = exports.transform = exports.printSync = exports.print = exports.parseFileSync = exports.parseFile = exports.parseSync = exports.parse = exports.Compiler = exports.plugins = exports.version = void 0; +exports.DEFAULT_EXTENSIONS = exports.getBinaryMetadata = exports.__experimental_registerGlobalTraceConfig = exports.minifySync = exports.minify = exports.bundle = exports.transformFileSync = exports.transformFile = exports.transformSync = exports.transform = exports.printSync = exports.print = exports.parseFileSync = exports.parseFile = exports.parseSync = exports.parse = exports.Compiler = exports.plugins = exports.version = exports.experimental_newMangleNameCache = void 0; const path_1 = __nccwpck_require__(71017); +// @ts-ignore +var binding_1 = __nccwpck_require__(62334); +Object.defineProperty(exports, "experimental_newMangleNameCache", ({ enumerable: true, get: function () { return binding_1.newMangleNameCache; } })); const spack_1 = __nccwpck_require__(80020); const assert = __importStar(__nccwpck_require__(39491)); // Allow overrides to the location of the .node binding file @@ -14480,10 +14478,10 @@ class Compiler { constructor() { this.fallbackBindingsPluginWarningDisplayed = false; } - minify(src, opts) { + minify(src, opts, extras) { return __awaiter(this, void 0, void 0, function* () { if (bindings) { - return bindings.minify(toBuffer(src), toBuffer(opts !== null && opts !== void 0 ? opts : {})); + return bindings.minify(toBuffer(src), toBuffer(opts !== null && opts !== void 0 ? opts : {}), extras !== null && extras !== void 0 ? extras : {}); } else if (fallbackBindings) { return fallbackBindings.minify(src, opts); @@ -14491,9 +14489,9 @@ class Compiler { throw new Error("Bindings not found."); }); } - minifySync(src, opts) { + minifySync(src, opts, extras) { if (bindings) { - return bindings.minifySync(toBuffer(src), toBuffer(opts !== null && opts !== void 0 ? opts : {})); + return bindings.minifySync(toBuffer(src), toBuffer(opts !== null && opts !== void 0 ? opts : {}), extras !== null && extras !== void 0 ? extras : {}); } else if (fallbackBindings) { return fallbackBindings.minifySync(src, opts); @@ -14756,14 +14754,14 @@ function bundle(options) { return compiler.bundle(options); } exports.bundle = bundle; -function minify(src, opts) { +function minify(src, opts, extras) { return __awaiter(this, void 0, void 0, function* () { - return compiler.minify(src, opts); + return compiler.minify(src, opts, extras); }); } exports.minify = minify; -function minifySync(src, opts) { - return compiler.minifySync(src, opts); +function minifySync(src, opts, extras) { + return compiler.minifySync(src, opts, extras); } exports.minifySync = minifySync; /** @@ -94030,7 +94028,7 @@ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ -/* global global, define, Symbol, Reflect, Promise, SuppressedError */ +/* global global, define, Symbol, Reflect, Promise, SuppressedError, Iterator */ var __extends; var __assign; var __rest; @@ -94189,8 +94187,8 @@ var __disposeResources; }; __generator = function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); + return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); @@ -94294,7 +94292,7 @@ var __disposeResources; __asyncGenerator = function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var g = generator.apply(thisArg, _arguments || []), i, q = []; - return i = {}, verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i; + return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i; function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; } function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } } function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } @@ -94392,17 +94390,22 @@ var __disposeResources; env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; env.hasError = true; } + var r, s = 0; function next() { - while (env.stack.length) { - var rec = env.stack.pop(); + while (r = env.stack.pop()) { try { - var result = rec.dispose && rec.dispose.call(rec.value); - if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); + if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next); + if (r.dispose) { + var result = r.dispose.call(r.value); + if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); + } + else s |= 1; } catch (e) { fail(e); } } + if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve(); if (env.hasError) throw env.error; } return next(); @@ -94815,7 +94818,6 @@ __export(typescript_exports, { GoToDefinition: () => ts_GoToDefinition_exports, HighlightSpanKind: () => HighlightSpanKind, IdentifierNameMap: () => IdentifierNameMap, - IdentifierNameMultiMap: () => IdentifierNameMultiMap, ImportKind: () => ImportKind, ImportsNotUsedAsValues: () => ImportsNotUsedAsValues, IndentStyle: () => IndentStyle, @@ -94826,6 +94828,7 @@ __export(typescript_exports, { InlayHintKind: () => InlayHintKind2, InlayHints: () => ts_InlayHints_exports, InternalEmitFlags: () => InternalEmitFlags, + InternalNodeBuilderFlags: () => InternalNodeBuilderFlags, InternalSymbolName: () => InternalSymbolName, IntersectionFlags: () => IntersectionFlags, InvalidatedProjectKind: () => InvalidatedProjectKind, @@ -94872,6 +94875,7 @@ __export(typescript_exports, { PollingInterval: () => PollingInterval, PollingWatchKind: () => PollingWatchKind, PragmaKindFlags: () => PragmaKindFlags, + PredicateSemantics: () => PredicateSemantics, PrivateIdentifierKind: () => PrivateIdentifierKind, ProcessLevel: () => ProcessLevel, ProgramUpdateLevel: () => ProgramUpdateLevel, @@ -94902,7 +94906,6 @@ __export(typescript_exports, { SymbolFlags: () => SymbolFlags, SymbolFormatFlags: () => SymbolFormatFlags, SyntaxKind: () => SyntaxKind, - SyntheticSymbolKind: () => SyntheticSymbolKind, Ternary: () => Ternary, ThrottledCancellationToken: () => ThrottledCancellationToken, TokenClass: () => TokenClass, @@ -94925,7 +94928,6 @@ __export(typescript_exports, { WatchLogLevel: () => WatchLogLevel, WatchType: () => WatchType, accessPrivateIdentifier: () => accessPrivateIdentifier, - addDisposableResourceHelper: () => addDisposableResourceHelper, addEmitFlags: () => addEmitFlags, addEmitHelper: () => addEmitHelper, addEmitHelpers: () => addEmitHelpers, @@ -94948,23 +94950,15 @@ __export(typescript_exports, { arrayFrom: () => arrayFrom, arrayIsEqualTo: () => arrayIsEqualTo, arrayIsHomogeneous: () => arrayIsHomogeneous, - arrayIsSorted: () => arrayIsSorted, arrayOf: () => arrayOf, arrayReverseIterator: () => arrayReverseIterator, arrayToMap: () => arrayToMap, arrayToMultiMap: () => arrayToMultiMap, arrayToNumericMap: () => arrayToNumericMap, - arraysEqual: () => arraysEqual, assertType: () => assertType, assign: () => assign, - assignHelper: () => assignHelper, - asyncDelegator: () => asyncDelegator, - asyncGeneratorHelper: () => asyncGeneratorHelper, asyncSuperHelper: () => asyncSuperHelper, - asyncValues: () => asyncValues, attachFileToDiagnostics: () => attachFileToDiagnostics, - awaitHelper: () => awaitHelper, - awaiterHelper: () => awaiterHelper, base64decode: () => base64decode, base64encode: () => base64encode, binarySearch: () => binarySearch, @@ -94977,6 +94971,7 @@ __export(typescript_exports, { buildOverload: () => buildOverload, bundlerModuleNameResolver: () => bundlerModuleNameResolver, canBeConvertedToAsync: () => canBeConvertedToAsync, + canEmitTsBuildInfo: () => canEmitTsBuildInfo, canHaveDecorators: () => canHaveDecorators, canHaveExportModifier: () => canHaveExportModifier, canHaveFlowNode: () => canHaveFlowNode, @@ -94987,8 +94982,9 @@ __export(typescript_exports, { canHaveJSDoc: () => canHaveJSDoc, canHaveLocals: () => canHaveLocals, canHaveModifiers: () => canHaveModifiers, + canHaveModuleSpecifier: () => canHaveModuleSpecifier, canHaveSymbol: () => canHaveSymbol, - canIncludeBindAndCheckDiagnsotics: () => canIncludeBindAndCheckDiagnsotics, + canIncludeBindAndCheckDiagnostics: () => canIncludeBindAndCheckDiagnostics, canJsonReportNoInputFiles: () => canJsonReportNoInputFiles, canProduceDiagnostics: () => canProduceDiagnostics, canUsePropertyAccess: () => canUsePropertyAccess, @@ -95005,16 +95001,13 @@ __export(typescript_exports, { changeFullExtension: () => changeFullExtension, changesAffectModuleResolution: () => changesAffectModuleResolution, changesAffectingProgramStructure: () => changesAffectingProgramStructure, - characterToRegularExpressionFlag: () => characterToRegularExpressionFlag, + characterCodeToRegularExpressionFlag: () => characterCodeToRegularExpressionFlag, childIsDecorated: () => childIsDecorated, classElementOrClassElementParameterIsDecorated: () => classElementOrClassElementParameterIsDecorated, classHasClassThisAssignment: () => classHasClassThisAssignment, classHasDeclaredOrExplicitlyAssignedName: () => classHasDeclaredOrExplicitlyAssignedName, classHasExplicitlyAssignedName: () => classHasExplicitlyAssignedName, classOrConstructorParameterIsDecorated: () => classOrConstructorParameterIsDecorated, - classPrivateFieldGetHelper: () => classPrivateFieldGetHelper, - classPrivateFieldInHelper: () => classPrivateFieldInHelper, - classPrivateFieldSetHelper: () => classPrivateFieldSetHelper, classicNameResolver: () => classicNameResolver, classifier: () => ts_classifier_exports, cleanExtendedConfigCache: () => cleanExtendedConfigCache, @@ -95022,7 +95015,6 @@ __export(typescript_exports, { clearMap: () => clearMap, clearSharedExtendedConfigFileWatcher: () => clearSharedExtendedConfigFileWatcher, climbPastPropertyAccess: () => climbPastPropertyAccess, - climbPastPropertyOrElementAccess: () => climbPastPropertyOrElementAccess, clone: () => clone, cloneCompilerOptions: () => cloneCompilerOptions, closeFileWatcher: () => closeFileWatcher, @@ -95035,12 +95027,10 @@ __export(typescript_exports, { commandLineOptionOfCustomType: () => commandLineOptionOfCustomType, commentPragmas: () => commentPragmas, commonOptionsWithBuild: () => commonOptionsWithBuild, - commonPackageFolders: () => commonPackageFolders, compact: () => compact, compareBooleans: () => compareBooleans, compareDataObjects: () => compareDataObjects, compareDiagnostics: () => compareDiagnostics, - compareDiagnosticsSkipRelatedInformation: () => compareDiagnosticsSkipRelatedInformation, compareEmitHelpers: () => compareEmitHelpers, compareNumberOfDirectorySeparators: () => compareNumberOfDirectorySeparators, comparePaths: () => comparePaths, @@ -95054,26 +95044,21 @@ __export(typescript_exports, { compareStringsCaseSensitiveUI: () => compareStringsCaseSensitiveUI, compareTextSpans: () => compareTextSpans, compareValues: () => compareValues, - compileOnSaveCommandLineOption: () => compileOnSaveCommandLineOption, compilerOptionsAffectDeclarationPath: () => compilerOptionsAffectDeclarationPath, compilerOptionsAffectEmit: () => compilerOptionsAffectEmit, compilerOptionsAffectSemanticDiagnostics: () => compilerOptionsAffectSemanticDiagnostics, compilerOptionsDidYouMeanDiagnostics: () => compilerOptionsDidYouMeanDiagnostics, compilerOptionsIndicateEsModules: () => compilerOptionsIndicateEsModules, - compose: () => compose, computeCommonSourceDirectoryOfFilenames: () => computeCommonSourceDirectoryOfFilenames, computeLineAndCharacterOfPosition: () => computeLineAndCharacterOfPosition, computeLineOfPosition: () => computeLineOfPosition, computeLineStarts: () => computeLineStarts, computePositionOfLineAndCharacter: () => computePositionOfLineAndCharacter, - computeSignature: () => computeSignature, computeSignatureWithDiagnostics: () => computeSignatureWithDiagnostics, computeSuggestionDiagnostics: () => computeSuggestionDiagnostics, computedOptions: () => computedOptions, concatenate: () => concatenate, concatenateDiagnosticMessageChains: () => concatenateDiagnosticMessageChains, - configDirTemplateSubstitutionOptions: () => configDirTemplateSubstitutionOptions, - configDirTemplateSubstitutionWatchOptions: () => configDirTemplateSubstitutionWatchOptions, consumesNodeCoreModules: () => consumesNodeCoreModules, contains: () => contains, containsIgnoredPath: () => containsIgnoredPath, @@ -95104,16 +95089,11 @@ __export(typescript_exports, { createAccessorPropertySetRedirector: () => createAccessorPropertySetRedirector, createBaseNodeFactory: () => createBaseNodeFactory, createBinaryExpressionTrampoline: () => createBinaryExpressionTrampoline, - createBindingHelper: () => createBindingHelper, - createBuildInfo: () => createBuildInfo, createBuilderProgram: () => createBuilderProgram, - createBuilderProgramUsingProgramBuildInfo: () => createBuilderProgramUsingProgramBuildInfo, + createBuilderProgramUsingIncrementalBuildInfo: () => createBuilderProgramUsingIncrementalBuildInfo, createBuilderStatusReporter: () => createBuilderStatusReporter, - createCacheWithRedirects: () => createCacheWithRedirects, createCacheableExportInfoMap: () => createCacheableExportInfoMap, createCachedDirectoryStructureHost: () => createCachedDirectoryStructureHost, - createClassNamedEvaluationHelperBlock: () => createClassNamedEvaluationHelperBlock, - createClassThisAssignmentBlock: () => createClassThisAssignmentBlock, createClassifier: () => createClassifier, createCommentDirectivesMap: () => createCommentDirectivesMap, createCompilerDiagnostic: () => createCompilerDiagnostic, @@ -95165,6 +95145,7 @@ __export(typescript_exports, { createMemberAccessForPropertyName: () => createMemberAccessForPropertyName, createModeAwareCache: () => createModeAwareCache, createModeAwareCacheKey: () => createModeAwareCacheKey, + createModeMismatchDetails: () => createModeMismatchDetails, createModuleNotFoundChain: () => createModuleNotFoundChain, createModuleResolutionCache: () => createModuleResolutionCache, createModuleResolutionLoader: () => createModuleResolutionLoader, @@ -95235,9 +95216,7 @@ __export(typescript_exports, { declarationNameToString: () => declarationNameToString, decodeMappings: () => decodeMappings, decodedTextSpanIntersectsWith: () => decodedTextSpanIntersectsWith, - decorateHelper: () => decorateHelper, deduplicate: () => deduplicate, - defaultIncludeSpec: () => defaultIncludeSpec, defaultInitCompilerOptions: () => defaultInitCompilerOptions, defaultMaximumTruncationLength: () => defaultMaximumTruncationLength, diagnosticCategoryName: () => diagnosticCategoryName, @@ -95248,27 +95227,22 @@ __export(typescript_exports, { displayPart: () => displayPart, displayPartsToString: () => displayPartsToString, disposeEmitNodes: () => disposeEmitNodes, - disposeResourcesHelper: () => disposeResourcesHelper, documentSpansEqual: () => documentSpansEqual, dumpTracingLegend: () => dumpTracingLegend, elementAt: () => elementAt, elideNodes: () => elideNodes, - emitComments: () => emitComments, emitDetachedComments: () => emitDetachedComments, emitFiles: () => emitFiles, emitFilesAndReportErrors: () => emitFilesAndReportErrors, emitFilesAndReportErrorsAndGetExitStatus: () => emitFilesAndReportErrorsAndGetExitStatus, emitModuleKindIsNonNodeESM: () => emitModuleKindIsNonNodeESM, emitNewLineBeforeLeadingCommentOfPosition: () => emitNewLineBeforeLeadingCommentOfPosition, - emitNewLineBeforeLeadingComments: () => emitNewLineBeforeLeadingComments, - emitNewLineBeforeLeadingCommentsOfPosition: () => emitNewLineBeforeLeadingCommentsOfPosition, emitResolverSkipsTypeChecking: () => emitResolverSkipsTypeChecking, emitSkippedWithNoDiagnostics: () => emitSkippedWithNoDiagnostics, emptyArray: () => emptyArray, emptyFileSystemEntries: () => emptyFileSystemEntries, emptyMap: () => emptyMap, emptyOptions: () => emptyOptions, - emptySet: () => emptySet, endsWith: () => endsWith, ensurePathIsNonModuleName: () => ensurePathIsNonModuleName, ensureScriptKind: () => ensureScriptKind, @@ -95279,7 +95253,6 @@ __export(typescript_exports, { equateStringsCaseInsensitive: () => equateStringsCaseInsensitive, equateStringsCaseSensitive: () => equateStringsCaseSensitive, equateValues: () => equateValues, - esDecorateHelper: () => esDecorateHelper, escapeJsxAttributeString: () => escapeJsxAttributeString, escapeLeadingUnderscores: () => escapeLeadingUnderscores, escapeNonAsciiString: () => escapeNonAsciiString, @@ -95293,15 +95266,14 @@ __export(typescript_exports, { explainFiles: () => explainFiles, explainIfFileIsRedirectAndImpliedFormat: () => explainIfFileIsRedirectAndImpliedFormat, exportAssignmentIsAlias: () => exportAssignmentIsAlias, - exportStarHelper: () => exportStarHelper, expressionResultIsUnused: () => expressionResultIsUnused, extend: () => extend, - extendsHelper: () => extendsHelper, extensionFromPath: () => extensionFromPath, extensionIsTS: () => extensionIsTS, extensionsNotSupportingExtensionlessResolution: () => extensionsNotSupportingExtensionlessResolution, externalHelpersModuleNameText: () => externalHelpersModuleNameText, factory: () => factory, + fileContainsPackageImport: () => fileContainsPackageImport, fileExtensionIs: () => fileExtensionIs, fileExtensionIsOneOf: () => fileExtensionIsOneOf, fileIncludeReasonToDiagnostics: () => fileIncludeReasonToDiagnostics, @@ -95323,7 +95295,6 @@ __export(typescript_exports, { findLast: () => findLast, findLastIndex: () => findLastIndex, findListItemInfo: () => findListItemInfo, - findMap: () => findMap, findModifier: () => findModifier, findNextToken: () => findNextToken, findPackageJson: () => findPackageJson, @@ -95371,7 +95342,6 @@ __export(typescript_exports, { forEachTsConfigPropArray: () => forEachTsConfigPropArray, forEachUnique: () => forEachUnique, forEachYieldExpression: () => forEachYieldExpression, - forSomeAncestorDirectory: () => forSomeAncestorDirectory, formatColorAndReset: () => formatColorAndReset, formatDiagnostic: () => formatDiagnostic, formatDiagnostics: () => formatDiagnostics, @@ -95382,11 +95352,8 @@ __export(typescript_exports, { formatMessage: () => formatMessage, formatStringFromArgs: () => formatStringFromArgs, formatting: () => ts_formatting_exports, - fullTripleSlashAMDReferencePathRegEx: () => fullTripleSlashAMDReferencePathRegEx, - fullTripleSlashReferencePathRegEx: () => fullTripleSlashReferencePathRegEx, generateDjb2Hash: () => generateDjb2Hash, generateTSConfig: () => generateTSConfig, - generatorHelper: () => generatorHelper, getAdjustedReferenceLocation: () => getAdjustedReferenceLocation, getAdjustedRenameLocation: () => getAdjustedRenameLocation, getAliasDeclarationFromName: () => getAliasDeclarationFromName, @@ -95405,7 +95372,6 @@ __export(typescript_exports, { getAreDeclarationMapsEnabled: () => getAreDeclarationMapsEnabled, getAssignedExpandoInitializer: () => getAssignedExpandoInitializer, getAssignedName: () => getAssignedName, - getAssignedNameOfIdentifier: () => getAssignedNameOfIdentifier, getAssignmentDeclarationKind: () => getAssignmentDeclarationKind, getAssignmentDeclarationPropertyAccessKind: () => getAssignmentDeclarationPropertyAccessKind, getAssignmentTargetKind: () => getAssignmentTargetKind, @@ -95446,7 +95412,6 @@ __export(typescript_exports, { getContainingObjectLiteralElement: () => getContainingObjectLiteralElement, getContextualTypeFromParent: () => getContextualTypeFromParent, getContextualTypeFromParentOrAncestorTypeNode: () => getContextualTypeFromParentOrAncestorTypeNode, - getCurrentTime: () => getCurrentTime, getDeclarationDiagnostics: () => getDeclarationDiagnostics, getDeclarationEmitExtensionForPath: () => getDeclarationEmitExtensionForPath, getDeclarationEmitOutputFilePath: () => getDeclarationEmitOutputFilePath, @@ -95464,6 +95429,7 @@ __export(typescript_exports, { getDefaultLibFilePath: () => getDefaultLibFilePath, getDefaultLikeExportInfo: () => getDefaultLikeExportInfo, getDefaultLikeExportNameFromDeclaration: () => getDefaultLikeExportNameFromDeclaration, + getDefaultResolutionModeForFileWorker: () => getDefaultResolutionModeForFileWorker, getDiagnosticText: () => getDiagnosticText, getDiagnosticsWithinSpan: () => getDiagnosticsWithinSpan, getDirectoryPath: () => getDirectoryPath, @@ -95494,6 +95460,7 @@ __export(typescript_exports, { getEmitFlags: () => getEmitFlags, getEmitHelpers: () => getEmitHelpers, getEmitModuleDetectionKind: () => getEmitModuleDetectionKind, + getEmitModuleFormatOfFileWorker: () => getEmitModuleFormatOfFileWorker, getEmitModuleKind: () => getEmitModuleKind, getEmitModuleResolutionKind: () => getEmitModuleResolutionKind, getEmitScriptTarget: () => getEmitScriptTarget, @@ -95544,11 +95511,11 @@ __export(typescript_exports, { getIdentifierGeneratedImportReference: () => getIdentifierGeneratedImportReference, getIdentifierTypeArguments: () => getIdentifierTypeArguments, getImmediatelyInvokedFunctionExpression: () => getImmediatelyInvokedFunctionExpression, + getImpliedNodeFormatForEmitWorker: () => getImpliedNodeFormatForEmitWorker, getImpliedNodeFormatForFile: () => getImpliedNodeFormatForFile, getImpliedNodeFormatForFileWorker: () => getImpliedNodeFormatForFileWorker, getImportNeedsImportDefaultHelper: () => getImportNeedsImportDefaultHelper, getImportNeedsImportStarHelper: () => getImportNeedsImportStarHelper, - getIndentSize: () => getIndentSize, getIndentString: () => getIndentString, getInferredLibraryNameResolveFrom: () => getInferredLibraryNameResolveFrom, getInitializedVariables: () => getInitializedVariables, @@ -95557,6 +95524,7 @@ __export(typescript_exports, { getInterfaceBaseTypeNodes: () => getInterfaceBaseTypeNodes, getInternalEmitFlags: () => getInternalEmitFlags, getInvokedExpression: () => getInvokedExpression, + getIsFileExcluded: () => getIsFileExcluded, getIsolatedModules: () => getIsolatedModules, getJSDocAugmentsTag: () => getJSDocAugmentsTag, getJSDocClassTag: () => getJSDocClassTag, @@ -95585,7 +95553,6 @@ __export(typescript_exports, { getJSDocSatisfiesExpressionType: () => getJSDocSatisfiesExpressionType, getJSDocSatisfiesTag: () => getJSDocSatisfiesTag, getJSDocTags: () => getJSDocTags, - getJSDocTagsNoCache: () => getJSDocTagsNoCache, getJSDocTemplateTag: () => getJSDocTemplateTag, getJSDocThisTag: () => getJSDocThisTag, getJSDocType: () => getJSDocType, @@ -95609,7 +95576,6 @@ __export(typescript_exports, { getLineAndCharacterOfPosition: () => getLineAndCharacterOfPosition, getLineInfo: () => getLineInfo, getLineOfLocalPosition: () => getLineOfLocalPosition, - getLineOfLocalPositionFromLineMap: () => getLineOfLocalPositionFromLineMap, getLineStartPositionForPosition: () => getLineStartPositionForPosition, getLineStarts: () => getLineStarts, getLinesBetweenPositionAndNextNonWhitespaceCharacter: () => getLinesBetweenPositionAndNextNonWhitespaceCharacter, @@ -95651,7 +95617,6 @@ __export(typescript_exports, { getNameOfScriptTarget: () => getNameOfScriptTarget, getNameOrArgument: () => getNameOrArgument, getNameTable: () => getNameTable, - getNamesForExportedSymbol: () => getNamesForExportedSymbol, getNamespaceDeclarationNode: () => getNamespaceDeclarationNode, getNewLineCharacter: () => getNewLineCharacter, getNewLineKind: () => getNewLineKind, @@ -95668,49 +95633,43 @@ __export(typescript_exports, { getNonAssignmentOperatorForCompoundAssignment: () => getNonAssignmentOperatorForCompoundAssignment, getNonAugmentationDeclaration: () => getNonAugmentationDeclaration, getNonDecoratorTokenPosOfNode: () => getNonDecoratorTokenPosOfNode, + getNonIncrementalBuildInfoRoots: () => getNonIncrementalBuildInfoRoots, + getNonModifierTokenPosOfNode: () => getNonModifierTokenPosOfNode, getNormalizedAbsolutePath: () => getNormalizedAbsolutePath, getNormalizedAbsolutePathWithoutRoot: () => getNormalizedAbsolutePathWithoutRoot, getNormalizedPathComponents: () => getNormalizedPathComponents, getObjectFlags: () => getObjectFlags, - getOperator: () => getOperator, getOperatorAssociativity: () => getOperatorAssociativity, getOperatorPrecedence: () => getOperatorPrecedence, getOptionFromName: () => getOptionFromName, getOptionsForLibraryResolution: () => getOptionsForLibraryResolution, getOptionsNameMap: () => getOptionsNameMap, getOrCreateEmitNode: () => getOrCreateEmitNode, - getOrCreateExternalHelpersModuleNameIfNeeded: () => getOrCreateExternalHelpersModuleNameIfNeeded, getOrUpdate: () => getOrUpdate, getOriginalNode: () => getOriginalNode, getOriginalNodeId: () => getOriginalNodeId, - getOriginalSourceFile: () => getOriginalSourceFile, getOutputDeclarationFileName: () => getOutputDeclarationFileName, getOutputDeclarationFileNameWorker: () => getOutputDeclarationFileNameWorker, getOutputExtension: () => getOutputExtension, getOutputFileNames: () => getOutputFileNames, getOutputJSFileNameWorker: () => getOutputJSFileNameWorker, getOutputPathsFor: () => getOutputPathsFor, - getOutputPathsForBundle: () => getOutputPathsForBundle, getOwnEmitOutputFilePath: () => getOwnEmitOutputFilePath, getOwnKeys: () => getOwnKeys, getOwnValues: () => getOwnValues, - getPackageJsonInfo: () => getPackageJsonInfo, getPackageJsonTypesVersionsPaths: () => getPackageJsonTypesVersionsPaths, - getPackageJsonsVisibleToFile: () => getPackageJsonsVisibleToFile, getPackageNameFromTypesPackageName: () => getPackageNameFromTypesPackageName, getPackageScopeForPath: () => getPackageScopeForPath, getParameterSymbolFromJSDoc: () => getParameterSymbolFromJSDoc, - getParameterTypeNode: () => getParameterTypeNode, getParentNodeInSpan: () => getParentNodeInSpan, getParseTreeNode: () => getParseTreeNode, getParsedCommandLineOfConfigFile: () => getParsedCommandLineOfConfigFile, getPathComponents: () => getPathComponents, - getPathComponentsRelativeTo: () => getPathComponentsRelativeTo, getPathFromPathComponents: () => getPathFromPathComponents, getPathUpdater: () => getPathUpdater, getPathsBasePath: () => getPathsBasePath, getPatternFromSpec: () => getPatternFromSpec, - getPendingEmitKind: () => getPendingEmitKind, + getPendingEmitKindWithSeen: () => getPendingEmitKindWithSeen, getPositionOfLineAndCharacter: () => getPositionOfLineAndCharacter, getPossibleGenericSignatures: () => getPossibleGenericSignatures, getPossibleOriginalInputExtensionForExtension: () => getPossibleOriginalInputExtensionForExtension, @@ -95723,7 +95682,6 @@ __export(typescript_exports, { getPropertyArrayElementValue: () => getPropertyArrayElementValue, getPropertyAssignmentAliasLikeExpression: () => getPropertyAssignmentAliasLikeExpression, getPropertyNameForPropertyNameNode: () => getPropertyNameForPropertyNameNode, - getPropertyNameForUniqueESSymbol: () => getPropertyNameForUniqueESSymbol, getPropertyNameFromType: () => getPropertyNameFromType, getPropertyNameOfBindingOrAssignmentElement: () => getPropertyNameOfBindingOrAssignmentElement, getPropertySymbolFromBindingElement: () => getPropertySymbolFromBindingElement, @@ -95747,13 +95705,14 @@ __export(typescript_exports, { getResolvePackageJsonExports: () => getResolvePackageJsonExports, getResolvePackageJsonImports: () => getResolvePackageJsonImports, getResolvedExternalModuleName: () => getResolvedExternalModuleName, + getResolvedModuleFromResolution: () => getResolvedModuleFromResolution, + getResolvedTypeReferenceDirectiveFromResolution: () => getResolvedTypeReferenceDirectiveFromResolution, getRestIndicatorOfBindingOrAssignmentElement: () => getRestIndicatorOfBindingOrAssignmentElement, getRestParameterElementType: () => getRestParameterElementType, getRightMostAssignedExpression: () => getRightMostAssignedExpression, getRootDeclaration: () => getRootDeclaration, getRootDirectoryOfResolutionCache: () => getRootDirectoryOfResolutionCache, getRootLength: () => getRootLength, - getRootPathSplitLength: () => getRootPathSplitLength, getScriptKind: () => getScriptKind, getScriptKindFromFileName: () => getScriptKindFromFileName, getScriptTargetFeatures: () => getScriptTargetFeatures, @@ -95765,14 +95724,12 @@ __export(typescript_exports, { getSetAccessorValueParameter: () => getSetAccessorValueParameter, getSetExternalModuleIndicator: () => getSetExternalModuleIndicator, getShebang: () => getShebang, - getSingleInitializerOfVariableStatementOrPropertyDeclaration: () => getSingleInitializerOfVariableStatementOrPropertyDeclaration, getSingleVariableOfVariableStatement: () => getSingleVariableOfVariableStatement, getSnapshotText: () => getSnapshotText, getSnippetElement: () => getSnippetElement, getSourceFileOfModule: () => getSourceFileOfModule, getSourceFileOfNode: () => getSourceFileOfNode, getSourceFilePathInNewDir: () => getSourceFilePathInNewDir, - getSourceFilePathInNewDirWorker: () => getSourceFilePathInNewDirWorker, getSourceFileVersionAsHashFromText: () => getSourceFileVersionAsHashFromText, getSourceFilesToEmit: () => getSourceFilesToEmit, getSourceMapRange: () => getSourceMapRange, @@ -95795,7 +95752,6 @@ __export(typescript_exports, { getSwitchedType: () => getSwitchedType, getSymbolId: () => getSymbolId, getSymbolNameForPrivateIdentifier: () => getSymbolNameForPrivateIdentifier, - getSymbolParentOrFail: () => getSymbolParentOrFail, getSymbolTarget: () => getSymbolTarget, getSyntacticClassifications: () => getSyntacticClassifications, getSyntacticModifierFlags: () => getSyntacticModifierFlags, @@ -95826,7 +95782,6 @@ __export(typescript_exports, { getTouchingToken: () => getTouchingToken, getTrailingCommentRanges: () => getTrailingCommentRanges, getTrailingSemicolonDeferringWriter: () => getTrailingSemicolonDeferringWriter, - getTransformFlagsSubtreeExclusions: () => getTransformFlagsSubtreeExclusions, getTransformers: () => getTransformers, getTsBuildInfoEmitOutputFilePath: () => getTsBuildInfoEmitOutputFilePath, getTsConfigObjectLiteralExpression: () => getTsConfigObjectLiteralExpression, @@ -95854,7 +95809,6 @@ __export(typescript_exports, { hasAccessorModifier: () => hasAccessorModifier, hasAmbientModifier: () => hasAmbientModifier, hasChangesInResolutions: () => hasChangesInResolutions, - hasChildOfKind: () => hasChildOfKind, hasContextSensitiveParameters: () => hasContextSensitiveParameters, hasDecorators: () => hasDecorators, hasDocComment: () => hasDocComment, @@ -95863,6 +95817,7 @@ __export(typescript_exports, { hasEffectiveModifiers: () => hasEffectiveModifiers, hasEffectiveReadonlyModifier: () => hasEffectiveReadonlyModifier, hasExtension: () => hasExtension, + hasImplementationTSFileExtension: () => hasImplementationTSFileExtension, hasIndexSignature: () => hasIndexSignature, hasInferredType: () => hasInferredType, hasInitializer: () => hasInitializer, @@ -95890,7 +95845,6 @@ __export(typescript_exports, { hasType: () => hasType, hasTypeArguments: () => hasTypeArguments, hasZeroOrOneAsteriskCharacter: () => hasZeroOrOneAsteriskCharacter, - helperString: () => helperString, hostGetCanonicalFileName: () => hostGetCanonicalFileName, hostUsesCaseSensitiveFileNames: () => hostUsesCaseSensitiveFileNames, idText: () => idText, @@ -95900,9 +95854,8 @@ __export(typescript_exports, { identitySourceMapConsumer: () => identitySourceMapConsumer, ignoreSourceNewlines: () => ignoreSourceNewlines, ignoredPaths: () => ignoredPaths, - importDefaultHelper: () => importDefaultHelper, importFromModuleSpecifier: () => importFromModuleSpecifier, - importStarHelper: () => importStarHelper, + importSyntaxAffectsModuleResolution: () => importSyntaxAffectsModuleResolution, indexOfAnyCharCode: () => indexOfAnyCharCode, indexOfNode: () => indexOfNode, indicesOf: () => indicesOf, @@ -95910,7 +95863,6 @@ __export(typescript_exports, { injectClassNamedEvaluationHelperBlockIfMissing: () => injectClassNamedEvaluationHelperBlockIfMissing, injectClassThisAssignmentIfMissing: () => injectClassThisAssignmentIfMissing, insertImports: () => insertImports, - insertLeadingStatement: () => insertLeadingStatement, insertSorted: () => insertSorted, insertStatementAfterCustomPrologue: () => insertStatementAfterCustomPrologue, insertStatementAfterStandardPrologue: () => insertStatementAfterStandardPrologue, @@ -95926,11 +95878,9 @@ __export(typescript_exports, { isAccessibilityModifier: () => isAccessibilityModifier, isAccessor: () => isAccessor, isAccessorModifier: () => isAccessorModifier, - isAliasSymbolDeclaration: () => isAliasSymbolDeclaration, isAliasableExpression: () => isAliasableExpression, isAmbientModule: () => isAmbientModule, isAmbientPropertyDeclaration: () => isAmbientPropertyDeclaration, - isAnonymousFunctionDefinition: () => isAnonymousFunctionDefinition, isAnyDirectorySeparator: () => isAnyDirectorySeparator, isAnyImportOrBareOrAccessedRequire: () => isAnyImportOrBareOrAccessedRequire, isAnyImportOrReExport: () => isAnyImportOrReExport, @@ -95966,6 +95916,7 @@ __export(typescript_exports, { isAwaitKeyword: () => isAwaitKeyword, isBigIntLiteral: () => isBigIntLiteral, isBinaryExpression: () => isBinaryExpression, + isBinaryLogicalOperator: () => isBinaryLogicalOperator, isBinaryOperatorToken: () => isBinaryOperatorToken, isBindableObjectDefinePropertyCall: () => isBindableObjectDefinePropertyCall, isBindableStaticAccessExpression: () => isBindableStaticAccessExpression, @@ -95987,7 +95938,7 @@ __export(typescript_exports, { isBreakStatement: () => isBreakStatement, isBuild: () => isBuild, isBuildInfoFile: () => isBuildInfoFile, - isBuilderProgram: () => isBuilderProgram2, + isBuilderProgram: () => isBuilderProgram, isBundle: () => isBundle, isCallChain: () => isCallChain, isCallExpression: () => isCallExpression, @@ -96006,7 +95957,6 @@ __export(typescript_exports, { isCatchClauseVariableDeclaration: () => isCatchClauseVariableDeclaration, isCatchClauseVariableDeclarationOrBindingElement: () => isCatchClauseVariableDeclarationOrBindingElement, isCheckJsEnabledForFile: () => isCheckJsEnabledForFile, - isChildOfNodeWithKind: () => isChildOfNodeWithKind, isCircularBuildOrder: () => isCircularBuildOrder, isClassDeclaration: () => isClassDeclaration, isClassElement: () => isClassElement, @@ -96018,7 +95968,6 @@ __export(typescript_exports, { isClassOrTypeElement: () => isClassOrTypeElement, isClassStaticBlockDeclaration: () => isClassStaticBlockDeclaration, isClassThisAssignmentBlock: () => isClassThisAssignmentBlock, - isCollapsedRange: () => isCollapsedRange, isColonToken: () => isColonToken, isCommaExpression: () => isCommaExpression, isCommaListExpression: () => isCommaListExpression, @@ -96061,16 +96010,13 @@ __export(typescript_exports, { isDeleteTarget: () => isDeleteTarget, isDeprecatedDeclaration: () => isDeprecatedDeclaration, isDestructuringAssignment: () => isDestructuringAssignment, - isDiagnosticWithLocation: () => isDiagnosticWithLocation, isDiskPathRoot: () => isDiskPathRoot, isDoStatement: () => isDoStatement, isDocumentRegistryEntry: () => isDocumentRegistryEntry, isDotDotDotToken: () => isDotDotDotToken, isDottedName: () => isDottedName, isDynamicName: () => isDynamicName, - isESSymbolIdentifier: () => isESSymbolIdentifier, isEffectiveExternalModule: () => isEffectiveExternalModule, - isEffectiveModuleDeclaration: () => isEffectiveModuleDeclaration, isEffectiveStrictModeSourceFile: () => isEffectiveStrictModeSourceFile, isElementAccessChain: () => isElementAccessChain, isElementAccessExpression: () => isElementAccessExpression, @@ -96140,13 +96086,11 @@ __export(typescript_exports, { isFunctionOrModuleBlock: () => isFunctionOrModuleBlock, isFunctionSymbol: () => isFunctionSymbol, isFunctionTypeNode: () => isFunctionTypeNode, - isFutureReservedKeyword: () => isFutureReservedKeyword, isGeneratedIdentifier: () => isGeneratedIdentifier, isGeneratedPrivateIdentifier: () => isGeneratedPrivateIdentifier, isGetAccessor: () => isGetAccessor, isGetAccessorDeclaration: () => isGetAccessorDeclaration, isGetOrSetAccessorDeclaration: () => isGetOrSetAccessorDeclaration, - isGlobalDeclaration: () => isGlobalDeclaration, isGlobalScopeAugmentation: () => isGlobalScopeAugmentation, isGlobalSourceFile: () => isGlobalSourceFile, isGrammarError: () => isGrammarError, @@ -96194,6 +96138,8 @@ __export(typescript_exports, { isInTemplateString: () => isInTemplateString, isInTopLevelContext: () => isInTopLevelContext, isInTypeQuery: () => isInTypeQuery, + isIncrementalBuildInfo: () => isIncrementalBuildInfo, + isIncrementalBundleEmitBuildInfo: () => isIncrementalBundleEmitBuildInfo, isIncrementalCompilation: () => isIncrementalCompilation, isIndexSignatureDeclaration: () => isIndexSignatureDeclaration, isIndexedAccessTypeNode: () => isIndexedAccessTypeNode, @@ -96300,7 +96246,6 @@ __export(typescript_exports, { isLabeledStatement: () => isLabeledStatement, isLateVisibilityPaintedStatement: () => isLateVisibilityPaintedStatement, isLeftHandSideExpression: () => isLeftHandSideExpression, - isLeftHandSideOfAssignment: () => isLeftHandSideOfAssignment, isLet: () => isLet, isLineBreak: () => isLineBreak, isLiteralComputedPropertyDeclarationName: () => isLiteralComputedPropertyDeclarationName, @@ -96308,10 +96253,7 @@ __export(typescript_exports, { isLiteralExpressionOfObject: () => isLiteralExpressionOfObject, isLiteralImportTypeNode: () => isLiteralImportTypeNode, isLiteralKind: () => isLiteralKind, - isLiteralLikeAccess: () => isLiteralLikeAccess, - isLiteralLikeElementAccess: () => isLiteralLikeElementAccess, isLiteralNameOfPropertyDeclarationOrIndexAccess: () => isLiteralNameOfPropertyDeclarationOrIndexAccess, - isLiteralTypeLikeExpression: () => isLiteralTypeLikeExpression, isLiteralTypeLiteral: () => isLiteralTypeLiteral, isLiteralTypeNode: () => isLiteralTypeNode, isLocalName: () => isLocalName, @@ -96336,6 +96278,7 @@ __export(typescript_exports, { isModuleBlock: () => isModuleBlock, isModuleBody: () => isModuleBody, isModuleDeclaration: () => isModuleDeclaration, + isModuleExportName: () => isModuleExportName, isModuleExportsAccessExpression: () => isModuleExportsAccessExpression, isModuleIdentifier: () => isModuleIdentifier, isModuleName: () => isModuleName, @@ -96345,7 +96288,6 @@ __export(typescript_exports, { isModuleWithStringLiteralName: () => isModuleWithStringLiteralName, isNameOfFunctionDeclaration: () => isNameOfFunctionDeclaration, isNameOfModuleDeclaration: () => isNameOfModuleDeclaration, - isNamedClassElement: () => isNamedClassElement, isNamedDeclaration: () => isNamedDeclaration, isNamedEvaluation: () => isNamedEvaluation, isNamedEvaluationSource: () => isNamedEvaluationSource, @@ -96363,7 +96305,6 @@ __export(typescript_exports, { isNewExpression: () => isNewExpression, isNewExpressionTarget: () => isNewExpressionTarget, isNoSubstitutionTemplateLiteral: () => isNoSubstitutionTemplateLiteral, - isNode: () => isNode, isNodeArray: () => isNodeArray, isNodeArrayMultiLine: () => isNodeArrayMultiLine, isNodeDescendantOf: () => isNodeDescendantOf, @@ -96372,14 +96313,11 @@ __export(typescript_exports, { isNodeModulesDirectory: () => isNodeModulesDirectory, isNodeWithPossibleHoistedDeclaration: () => isNodeWithPossibleHoistedDeclaration, isNonContextualKeyword: () => isNonContextualKeyword, - isNonExportDefaultModifier: () => isNonExportDefaultModifier, isNonGlobalAmbientModule: () => isNonGlobalAmbientModule, - isNonGlobalDeclaration: () => isNonGlobalDeclaration, isNonNullAccess: () => isNonNullAccess, isNonNullChain: () => isNonNullChain, isNonNullExpression: () => isNonNullExpression, isNonStaticMethodOrAccessorWithPrivateName: () => isNonStaticMethodOrAccessorWithPrivateName, - isNotEmittedOrPartiallyEmittedNode: () => isNotEmittedOrPartiallyEmittedNode, isNotEmittedStatement: () => isNotEmittedStatement, isNullishCoalesce: () => isNullishCoalesce, isNumber: () => isNumber, @@ -96395,7 +96333,6 @@ __export(typescript_exports, { isObjectLiteralMethod: () => isObjectLiteralMethod, isObjectLiteralOrClassExpressionMethodOrAccessor: () => isObjectLiteralOrClassExpressionMethodOrAccessor, isObjectTypeDeclaration: () => isObjectTypeDeclaration, - isOctalDigit: () => isOctalDigit, isOmittedExpression: () => isOmittedExpression, isOptionalChain: () => isOptionalChain, isOptionalChainRoot: () => isOptionalChainRoot, @@ -96429,7 +96366,6 @@ __export(typescript_exports, { isPrivateIdentifierClassElementDeclaration: () => isPrivateIdentifierClassElementDeclaration, isPrivateIdentifierPropertyAccessExpression: () => isPrivateIdentifierPropertyAccessExpression, isPrivateIdentifierSymbol: () => isPrivateIdentifierSymbol, - isProgramBundleEmitBuildInfo: () => isProgramBundleEmitBuildInfo, isProgramUptoDate: () => isProgramUptoDate, isPrologueDirective: () => isPrologueDirective, isPropertyAccessChain: () => isPropertyAccessChain, @@ -96442,7 +96378,6 @@ __export(typescript_exports, { isPropertyName: () => isPropertyName, isPropertyNameLiteral: () => isPropertyNameLiteral, isPropertySignature: () => isPropertySignature, - isProtoSetter: () => isProtoSetter, isPrototypeAccess: () => isPrototypeAccess, isPrototypePropertyAssignment: () => isPrototypePropertyAssignment, isPunctuation: () => isPunctuation, @@ -96452,7 +96387,6 @@ __export(typescript_exports, { isQuestionOrExclamationToken: () => isQuestionOrExclamationToken, isQuestionOrPlusOrMinusToken: () => isQuestionOrPlusOrMinusToken, isQuestionToken: () => isQuestionToken, - isRawSourceMap: () => isRawSourceMap, isReadonlyKeyword: () => isReadonlyKeyword, isReadonlyKeywordOrPlusOrMinusToken: () => isReadonlyKeywordOrPlusOrMinusToken, isRecognizedTripleSlashComment: () => isRecognizedTripleSlashComment, @@ -96474,24 +96408,22 @@ __export(typescript_exports, { isRootedDiskPath: () => isRootedDiskPath, isSameEntityName: () => isSameEntityName, isSatisfiesExpression: () => isSatisfiesExpression, - isScopeMarker: () => isScopeMarker, isSemicolonClassElement: () => isSemicolonClassElement, isSetAccessor: () => isSetAccessor, isSetAccessorDeclaration: () => isSetAccessorDeclaration, - isShebangTrivia: () => isShebangTrivia, isShiftOperatorOrHigher: () => isShiftOperatorOrHigher, isShorthandAmbientModuleSymbol: () => isShorthandAmbientModuleSymbol, isShorthandPropertyAssignment: () => isShorthandPropertyAssignment, + isSideEffectImport: () => isSideEffectImport, isSignedNumericLiteral: () => isSignedNumericLiteral, isSimpleCopiableExpression: () => isSimpleCopiableExpression, isSimpleInlineableExpression: () => isSimpleInlineableExpression, - isSimpleParameter: () => isSimpleParameter, isSimpleParameterList: () => isSimpleParameterList, isSingleOrDoubleQuote: () => isSingleOrDoubleQuote, + isSourceElement: () => isSourceElement, isSourceFile: () => isSourceFile, isSourceFileFromLibrary: () => isSourceFileFromLibrary, isSourceFileJS: () => isSourceFileJS, - isSourceFileNotJS: () => isSourceFileNotJS, isSourceFileNotJson: () => isSourceFileNotJson, isSourceMapping: () => isSourceMapping, isSpecialPropertyDeclaration: () => isSpecialPropertyDeclaration, @@ -96504,7 +96436,6 @@ __export(typescript_exports, { isStatic: () => isStatic, isStaticModifier: () => isStaticModifier, isString: () => isString, - isStringAKeyword: () => isStringAKeyword, isStringANonContextualKeyword: () => isStringANonContextualKeyword, isStringAndEmptyAnonymousObjectIntersection: () => isStringAndEmptyAnonymousObjectIntersection, isStringDoubleQuoted: () => isStringDoubleQuoted, @@ -96517,7 +96448,6 @@ __export(typescript_exports, { isStringTextContainingNode: () => isStringTextContainingNode, isSuperCall: () => isSuperCall, isSuperKeyword: () => isSuperKeyword, - isSuperOrSuperProperty: () => isSuperOrSuperProperty, isSuperProperty: () => isSuperProperty, isSupportedSourceFileName: () => isSupportedSourceFileName, isSwitchStatement: () => isSwitchStatement, @@ -96563,7 +96493,6 @@ __export(typescript_exports, { isTypeDeclaration: () => isTypeDeclaration, isTypeElement: () => isTypeElement, isTypeKeyword: () => isTypeKeyword, - isTypeKeywordToken: () => isTypeKeywordToken, isTypeKeywordTokenOrIdentifier: () => isTypeKeywordTokenOrIdentifier, isTypeLiteralNode: () => isTypeLiteralNode, isTypeNode: () => isTypeNode, @@ -96618,10 +96547,6 @@ __export(typescript_exports, { libMap: () => libMap, libs: () => libs, lineBreakPart: () => lineBreakPart, - linkNamePart: () => linkNamePart, - linkPart: () => linkPart, - linkTextPart: () => linkTextPart, - listFiles: () => listFiles, loadModuleFromGlobalCache: () => loadModuleFromGlobalCache, loadWithModeAwareCache: () => loadWithModeAwareCache, makeIdentifierFromModuleName: () => makeIdentifierFromModuleName, @@ -96631,7 +96556,6 @@ __export(typescript_exports, { map: () => map, mapAllOrFail: () => mapAllOrFail, mapDefined: () => mapDefined, - mapDefinedEntries: () => mapDefinedEntries, mapDefinedIterator: () => mapDefinedIterator, mapEntries: () => mapEntries, mapIterator: () => mapIterator, @@ -96641,18 +96565,19 @@ __export(typescript_exports, { matchPatternOrExact: () => matchPatternOrExact, matchedText: () => matchedText, matchesExclude: () => matchesExclude, + maxBy: () => maxBy, maybeBind: () => maybeBind, maybeSetLocalizedDiagnosticMessages: () => maybeSetLocalizedDiagnosticMessages, memoize: () => memoize, - memoizeCached: () => memoizeCached, memoizeOne: () => memoizeOne, - memoizeWeak: () => memoizeWeak, - metadataHelper: () => metadataHelper, min: () => min, minAndMax: () => minAndMax, missingFileModifiedTime: () => missingFileModifiedTime, modifierToFlag: () => modifierToFlag, modifiersToFlags: () => modifiersToFlags, + moduleExportNameIsDefault: () => moduleExportNameIsDefault, + moduleExportNameTextEscaped: () => moduleExportNameTextEscaped, + moduleExportNameTextUnescaped: () => moduleExportNameTextUnescaped, moduleOptionDeclaration: () => moduleOptionDeclaration, moduleResolutionIsEqualTo: () => moduleResolutionIsEqualTo, moduleResolutionNameAndModeGetter: () => moduleResolutionNameAndModeGetter, @@ -96692,11 +96617,11 @@ __export(typescript_exports, { nodePosToString: () => nodePosToString, nodeSeenTracker: () => nodeSeenTracker, nodeStartsNewLexicalEnvironment: () => nodeStartsNewLexicalEnvironment, - nodeToDisplayParts: () => nodeToDisplayParts, noop: () => noop, noopFileWatcher: () => noopFileWatcher, normalizePath: () => normalizePath, normalizeSlashes: () => normalizeSlashes, + normalizeSpans: () => normalizeSpans, not: () => not, notImplemented: () => notImplemented, notImplementedResolver: () => notImplementedResolver, @@ -96711,13 +96636,11 @@ __export(typescript_exports, { optionsForBuild: () => optionsForBuild, optionsForWatch: () => optionsForWatch, optionsHaveChanges: () => optionsHaveChanges, - optionsHaveModuleResolutionChanges: () => optionsHaveModuleResolutionChanges, or: () => or, orderedRemoveItem: () => orderedRemoveItem, orderedRemoveItemAt: () => orderedRemoveItemAt, packageIdToPackageName: () => packageIdToPackageName, packageIdToString: () => packageIdToString, - paramHelper: () => paramHelper, parameterIsThisKeyword: () => parameterIsThisKeyword, parameterNamePart: () => parameterNamePart, parseBaseNodeFactory: () => parseBaseNodeFactory, @@ -96748,10 +96671,8 @@ __export(typescript_exports, { pathIsBareSpecifier: () => pathIsBareSpecifier, pathIsRelative: () => pathIsRelative, patternText: () => patternText, - perfLogger: () => perfLogger, performIncrementalCompilation: () => performIncrementalCompilation, performance: () => ts_performance_exports, - plainJSErrors: () => plainJSErrors, positionBelongsToNode: () => positionBelongsToNode, positionIsASICandidate: () => positionIsASICandidate, positionIsSynthesized: () => positionIsSynthesized, @@ -96764,7 +96685,6 @@ __export(typescript_exports, { programContainsEsModules: () => programContainsEsModules, programContainsModules: () => programContainsModules, projectReferenceIsEqualTo: () => projectReferenceIsEqualTo, - propKeyHelper: () => propKeyHelper, propertyNamePart: () => propertyNamePart, pseudoBigIntToString: () => pseudoBigIntToString, punctuationPart: () => punctuationPart, @@ -96787,7 +96707,6 @@ __export(typescript_exports, { rangeStartPositionsAreOnSameLine: () => rangeStartPositionsAreOnSameLine, readBuilderProgram: () => readBuilderProgram, readConfigFile: () => readConfigFile, - readHelper: () => readHelper, readJson: () => readJson, readJsonConfigFile: () => readJsonConfigFile, readJsonOrUndefined: () => readJsonOrUndefined, @@ -96798,7 +96717,7 @@ __export(typescript_exports, { reducePathComponents: () => reducePathComponents, refactor: () => ts_refactor_exports, regExpEscape: () => regExpEscape, - regularExpressionFlagToCharacter: () => regularExpressionFlagToCharacter, + regularExpressionFlagToCharacterCode: () => regularExpressionFlagToCharacterCode, relativeComplement: () => relativeComplement, removeAllComments: () => removeAllComments, removeEmitHelper: () => removeEmitHelper, @@ -96806,7 +96725,6 @@ __export(typescript_exports, { removeFileExtension: () => removeFileExtension, removeIgnoredPath: () => removeIgnoredPath, removeMinAndVersionNumbers: () => removeMinAndVersionNumbers, - removeOptionality: () => removeOptionality, removePrefix: () => removePrefix, removeSuffix: () => removeSuffix, removeTrailingDirectorySeparator: () => removeTrailingDirectorySeparator, @@ -96825,20 +96743,16 @@ __export(typescript_exports, { resolveTripleslashReference: () => resolveTripleslashReference, resolveTypeReferenceDirective: () => resolveTypeReferenceDirective, resolvingEmptyArray: () => resolvingEmptyArray, - restHelper: () => restHelper, returnFalse: () => returnFalse, returnNoopFileWatcher: () => returnNoopFileWatcher, returnTrue: () => returnTrue, returnUndefined: () => returnUndefined, returnsPromise: () => returnsPromise, - runInitializersHelper: () => runInitializersHelper, sameFlatMap: () => sameFlatMap, sameMap: () => sameMap, sameMapping: () => sameMapping, - scanShebangTrivia: () => scanShebangTrivia, scanTokenAtPosition: () => scanTokenAtPosition, scanner: () => scanner, - screenStartingMessageCodes: () => screenStartingMessageCodes, semanticDiagnosticsOptionDeclarations: () => semanticDiagnosticsOptionDeclarations, serializeCompilerOptions: () => serializeCompilerOptions, server: () => ts_server_exports4, @@ -96846,16 +96760,13 @@ __export(typescript_exports, { setCommentRange: () => setCommentRange, setConfigFileInOptions: () => setConfigFileInOptions, setConstantValue: () => setConstantValue, - setEachParent: () => setEachParent, setEmitFlags: () => setEmitFlags, - setFunctionNameHelper: () => setFunctionNameHelper, setGetSourceFileAsHashVersioned: () => setGetSourceFileAsHashVersioned, setIdentifierAutoGenerate: () => setIdentifierAutoGenerate, setIdentifierGeneratedImportReference: () => setIdentifierGeneratedImportReference, setIdentifierTypeArguments: () => setIdentifierTypeArguments, setInternalEmitFlags: () => setInternalEmitFlags, setLocalizedDiagnosticMessages: () => setLocalizedDiagnosticMessages, - setModuleDefaultHelper: () => setModuleDefaultHelper, setNodeChildren: () => setNodeChildren, setNodeFlags: () => setNodeFlags, setObjectAllocator: () => setObjectAllocator, @@ -96884,7 +96795,6 @@ __export(typescript_exports, { shouldPreserveConstEnums: () => shouldPreserveConstEnums, shouldUseUriStyleNodeCoreModules: () => shouldUseUriStyleNodeCoreModules, showModuleSpecifier: () => showModuleSpecifier, - signatureHasLiteralTypes: () => signatureHasLiteralTypes, signatureHasRestParameter: () => signatureHasRestParameter, signatureToDisplayParts: () => signatureToDisplayParts, single: () => single, @@ -96893,18 +96803,17 @@ __export(typescript_exports, { singleOrMany: () => singleOrMany, singleOrUndefined: () => singleOrUndefined, skipAlias: () => skipAlias, - skipAssertions: () => skipAssertions, skipConstraint: () => skipConstraint, skipOuterExpressions: () => skipOuterExpressions, skipParentheses: () => skipParentheses, skipPartiallyEmittedExpressions: () => skipPartiallyEmittedExpressions, skipTrivia: () => skipTrivia, skipTypeChecking: () => skipTypeChecking, + skipTypeCheckingIgnoringNoCheck: () => skipTypeCheckingIgnoringNoCheck, skipTypeParentheses: () => skipTypeParentheses, skipWhile: () => skipWhile, sliceAfter: () => sliceAfter, some: () => some, - sort: () => sort, sortAndDeduplicate: () => sortAndDeduplicate, sortAndDeduplicateDiagnostics: () => sortAndDeduplicateDiagnostics, sourceFileAffectingCompilerOptions: () => sourceFileAffectingCompilerOptions, @@ -96913,8 +96822,6 @@ __export(typescript_exports, { sourceMapCommentRegExpDontCareLineStart: () => sourceMapCommentRegExpDontCareLineStart, spacePart: () => spacePart, spanMap: () => spanMap, - spreadArrayHelper: () => spreadArrayHelper, - stableSort: () => stableSort, startEndContainsRange: () => startEndContainsRange, startEndOverlapsWithStartEnd: () => startEndOverlapsWithStartEnd, startOnNewLine: () => startOnNewLine, @@ -96927,10 +96834,8 @@ __export(typescript_exports, { stringToToken: () => stringToToken, stripQuotes: () => stripQuotes, supportedDeclarationExtensions: () => supportedDeclarationExtensions, - supportedJSExtensions: () => supportedJSExtensions, supportedJSExtensionsFlat: () => supportedJSExtensionsFlat, supportedLocaleDirectories: () => supportedLocaleDirectories, - supportedTSExtensions: () => supportedTSExtensions, supportedTSExtensionsFlat: () => supportedTSExtensionsFlat, supportedTSImplementationExtensions: () => supportedTSImplementationExtensions, suppressLeadingAndTrailingTrivia: () => suppressLeadingAndTrailingTrivia, @@ -96939,16 +96844,12 @@ __export(typescript_exports, { symbolEscapedNameNoDefault: () => symbolEscapedNameNoDefault, symbolName: () => symbolName, symbolNameNoDefault: () => symbolNameNoDefault, - symbolPart: () => symbolPart, symbolToDisplayParts: () => symbolToDisplayParts, - syntaxMayBeASICandidate: () => syntaxMayBeASICandidate, - syntaxRequiresTrailingSemicolonOrASI: () => syntaxRequiresTrailingSemicolonOrASI, sys: () => sys, sysLog: () => sysLog, tagNamesAreEquivalent: () => tagNamesAreEquivalent, takeWhile: () => takeWhile, targetOptionDeclaration: () => targetOptionDeclaration, - templateObjectHelper: () => templateObjectHelper, testFormatSettings: () => testFormatSettings, textChangeRangeIsUnchanged: () => textChangeRangeIsUnchanged, textChangeRangeNewSpan: () => textChangeRangeNewSpan, @@ -96956,7 +96857,10 @@ __export(typescript_exports, { textOrKeywordPart: () => textOrKeywordPart, textPart: () => textPart, textRangeContainsPositionInclusive: () => textRangeContainsPositionInclusive, + textRangeContainsTextSpan: () => textRangeContainsTextSpan, + textRangeIntersectsWithTextSpan: () => textRangeIntersectsWithTextSpan, textSpanContainsPosition: () => textSpanContainsPosition, + textSpanContainsTextRange: () => textSpanContainsTextRange, textSpanContainsTextSpan: () => textSpanContainsTextSpan, textSpanEnd: () => textSpanEnd, textSpanIntersection: () => textSpanIntersection, @@ -96974,9 +96878,9 @@ __export(typescript_exports, { toBuilderStateFileInfoForMultiEmit: () => toBuilderStateFileInfoForMultiEmit, toEditorSettings: () => toEditorSettings, toFileNameLowerCase: () => toFileNameLowerCase, - toLowerCase: () => toLowerCase, toPath: () => toPath, toProgramEmitPending: () => toProgramEmitPending, + toSorted: () => toSorted, tokenIsIdentifierOrKeyword: () => tokenIsIdentifierOrKeyword, tokenIsIdentifierOrKeywordOrGreaterThan: () => tokenIsIdentifierOrKeywordOrGreaterThan, tokenToString: () => tokenToString, @@ -96998,11 +96902,11 @@ __export(typescript_exports, { transformESDecorators: () => transformESDecorators, transformESNext: () => transformESNext, transformGenerators: () => transformGenerators, + transformImpliedNodeFormatDependentModule: () => transformImpliedNodeFormatDependentModule, transformJsx: () => transformJsx, transformLegacyDecorators: () => transformLegacyDecorators, transformModule: () => transformModule, transformNamedEvaluation: () => transformNamedEvaluation, - transformNodeModule: () => transformNodeModule, transformNodes: () => transformNodes, transformSystemModule: () => transformSystemModule, transformTypeScript: () => transformTypeScript, @@ -97029,7 +96933,6 @@ __export(typescript_exports, { tryGetPropertyNameOfBindingOrAssignmentElement: () => tryGetPropertyNameOfBindingOrAssignmentElement, tryGetSourceMappingURL: () => tryGetSourceMappingURL, tryGetTextOfPropertyName: () => tryGetTextOfPropertyName, - tryIOAndConsumeErrors: () => tryIOAndConsumeErrors, tryParseJson: () => tryParseJson, tryParsePattern: () => tryParsePattern, tryParsePatterns: () => tryParsePatterns, @@ -97051,7 +96954,6 @@ __export(typescript_exports, { unescapeLeadingUnderscores: () => unescapeLeadingUnderscores, unmangleScopedPackageName: () => unmangleScopedPackageName, unorderedRemoveItem: () => unorderedRemoveItem, - unorderedRemoveItemAt: () => unorderedRemoveItemAt, unreachableCodeIsError: () => unreachableCodeIsError, unsetNodeChildren: () => unsetNodeChildren, unusedLabelIsError: () => unusedLabelIsError, @@ -97064,11 +96966,9 @@ __export(typescript_exports, { updateSharedExtendedConfigFileWatcher: () => updateSharedExtendedConfigFileWatcher, updateSourceFile: () => updateSourceFile, updateWatchingWildcardDirectories: () => updateWatchingWildcardDirectories, - usesExtensionsOnImports: () => usesExtensionsOnImports, usingSingleLineStringWriter: () => usingSingleLineStringWriter, utf16EncodeAsString: () => utf16EncodeAsString, validateLocaleAndSetLanguage: () => validateLocaleAndSetLanguage, - valuesHelper: () => valuesHelper, version: () => version, versionMajorMinor: () => versionMajorMinor, visitArray: () => visitArray, @@ -97081,7 +96981,6 @@ __export(typescript_exports, { visitNodes: () => visitNodes2, visitParameterList: () => visitParameterList, walkUpBindingElementsAndPatterns: () => walkUpBindingElementsAndPatterns, - walkUpLexicalEnvironments: () => walkUpLexicalEnvironments, walkUpOuterExpressions: () => walkUpOuterExpressions, walkUpParenthesizedExpressions: () => walkUpParenthesizedExpressions, walkUpParenthesizedTypes: () => walkUpParenthesizedTypes, @@ -97095,8 +96994,8 @@ __export(typescript_exports, { module.exports = __toCommonJS(typescript_exports); // src/compiler/corePublic.ts -var versionMajorMinor = "5.5"; -var version = "5.5.4"; +var versionMajorMinor = "5.6"; +var version = "5.6.2"; var Comparison = /* @__PURE__ */ ((Comparison3) => { Comparison3[Comparison3["LessThan"] = -1] = "LessThan"; Comparison3[Comparison3["EqualTo"] = 0] = "EqualTo"; @@ -97107,12 +97006,11 @@ var Comparison = /* @__PURE__ */ ((Comparison3) => { // src/compiler/core.ts var emptyArray = []; var emptyMap = /* @__PURE__ */ new Map(); -var emptySet = /* @__PURE__ */ new Set(); function length(array) { - return array ? array.length : 0; + return array !== void 0 ? array.length : 0; } function forEach(array, callback) { - if (array) { + if (array !== void 0) { for (let i = 0; i < array.length; i++) { const result = callback(array[i], i); if (result) { @@ -97123,7 +97021,7 @@ function forEach(array, callback) { return void 0; } function forEachRight(array, callback) { - if (array) { + if (array !== void 0) { for (let i = array.length - 1; i >= 0; i--) { const result = callback(array[i], i); if (result) { @@ -97179,13 +97077,13 @@ function intersperse(input, element) { } const result = []; for (let i = 0, n = input.length; i < n; i++) { - if (i) result.push(element); + if (i !== 0) result.push(element); result.push(input[i]); } return result; } function every(array, callback) { - if (array) { + if (array !== void 0) { for (let i = 0; i < array.length; i++) { if (!callback(array[i], i)) { return false; @@ -97232,30 +97130,18 @@ function findLastIndex(array, predicate, startIndex) { } return -1; } -function findMap(array, callback) { - for (let i = 0; i < array.length; i++) { - const result = callback(array[i], i); - if (result) { - return result; - } - } - return Debug.fail(); -} function contains(array, value, equalityComparer = equateValues) { - if (array) { - for (const v of array) { - if (equalityComparer(v, value)) { + if (array !== void 0) { + for (let i = 0; i < array.length; i++) { + if (equalityComparer(array[i], value)) { return true; } } } return false; } -function arraysEqual(a, b, equalityComparer = equateValues) { - return a.length === b.length && a.every((x, i) => equalityComparer(x, b[i])); -} function indexOfAnyCharCode(text, charCodes, start) { - for (let i = start || 0; i < text.length; i++) { + for (let i = start ?? 0; i < text.length; i++) { if (contains(charCodes, text.charCodeAt(i))) { return i; } @@ -97264,7 +97150,7 @@ function indexOfAnyCharCode(text, charCodes, start) { } function countWhere(array, predicate) { let count = 0; - if (array) { + if (array !== void 0) { for (let i = 0; i < array.length; i++) { const v = array[i]; if (predicate(v, i)) { @@ -97275,7 +97161,7 @@ function countWhere(array, predicate) { return count; } function filter(array, f) { - if (array) { + if (array !== void 0) { const len = array.length; let i = 0; while (i < len && f(array[i])) i++; @@ -97309,7 +97195,7 @@ function clear(array) { } function map(array, f) { let result; - if (array) { + if (array !== void 0) { result = []; for (let i = 0; i < array.length; i++) { result.push(f(array[i], i)); @@ -97323,7 +97209,7 @@ function* mapIterator(iter, mapFn) { } } function sameMap(array, f) { - if (array) { + if (array !== void 0) { for (let i = 0; i < array.length; i++) { const item = array[i]; const mapped = f(item, i); @@ -97341,7 +97227,8 @@ function sameMap(array, f) { } function flatten(array) { const result = []; - for (const v of array) { + for (let i = 0; i < array.length; i++) { + const v = array[i]; if (v) { if (isArray(v)) { addRange(result, v); @@ -97354,7 +97241,7 @@ function flatten(array) { } function flatMap(array, mapfn) { let result; - if (array) { + if (array !== void 0) { for (let i = 0; i < array.length; i++) { const v = mapfn(array[i], i); if (v) { @@ -97366,11 +97253,11 @@ function flatMap(array, mapfn) { } } } - return result || emptyArray; + return result ?? emptyArray; } function flatMapToMutable(array, mapfn) { const result = []; - if (array) { + if (array !== void 0) { for (let i = 0; i < array.length; i++) { const v = mapfn(array[i], i); if (v) { @@ -97393,7 +97280,7 @@ function* flatMapIterator(iter, mapfn) { } function sameFlatMap(array, mapfn) { let result; - if (array) { + if (array !== void 0) { for (let i = 0; i < array.length; i++) { const item = array[i]; const mapped = mapfn(item, i); @@ -97409,7 +97296,7 @@ function sameFlatMap(array, mapfn) { } } } - return result || array; + return result ?? array; } function mapAllOrFail(array, mapFn) { const result = []; @@ -97424,7 +97311,7 @@ function mapAllOrFail(array, mapFn) { } function mapDefined(array, mapFn) { const result = []; - if (array) { + if (array !== void 0) { for (let i = 0; i < array.length; i++) { const mapped = mapFn(array[i], i); if (mapped !== void 0) { @@ -97442,22 +97329,6 @@ function* mapDefinedIterator(iter, mapFn) { } } } -function mapDefinedEntries(map2, f) { - if (!map2) { - return void 0; - } - const result = /* @__PURE__ */ new Map(); - map2.forEach((value, key) => { - const entry = f(key, value); - if (entry !== void 0) { - const [newKey, newValue] = entry; - if (newKey !== void 0 && newValue !== void 0) { - result.set(newKey, newValue); - } - } - }); - return result; -} function getOrUpdate(map2, key, callback) { if (map2.has(key)) { return map2.get(key); @@ -97478,7 +97349,7 @@ function* singleIterator(value) { } function spanMap(array, keyfn, mapfn) { let result; - if (array) { + if (array !== void 0) { result = []; const len = array.length; let previousKey; @@ -97510,7 +97381,7 @@ function spanMap(array, keyfn, mapfn) { return result; } function mapEntries(map2, f) { - if (!map2) { + if (map2 === void 0) { return void 0; } const result = /* @__PURE__ */ new Map(); @@ -97521,10 +97392,10 @@ function mapEntries(map2, f) { return result; } function some(array, predicate) { - if (array) { - if (predicate) { - for (const v of array) { - if (predicate(v)) { + if (array !== void 0) { + if (predicate !== void 0) { + for (let i = 0; i < array.length; i++) { + if (predicate(array[i])) { return true; } } @@ -97549,8 +97420,8 @@ function getRangesWhere(arr, pred, cb) { if (start !== void 0) cb(start, arr.length); } function concatenate(array1, array2) { - if (!some(array2)) return array1; - if (!some(array1)) return array2; + if (array2 === void 0 || array2.length === 0) return array1; + if (array1 === void 0 || array1.length === 0) return array2; return [...array1, ...array2]; } function selectIndex(_, i) { @@ -97577,8 +97448,8 @@ function deduplicateRelational(array, equalityComparer, comparer) { } function deduplicateEquality(array, equalityComparer) { const result = []; - for (const item of array) { - pushIfUnique(result, item, equalityComparer); + for (let i = 0; i < array.length; i++) { + pushIfUnique(result, array[i], equalityComparer); } return result; } @@ -97632,19 +97503,10 @@ function insertSorted(array, insert, compare, equalityComparer, allowDuplicates) return false; } function sortAndDeduplicate(array, comparer, equalityComparer) { - return deduplicateSorted(sort(array, comparer), equalityComparer || comparer || compareStringsCaseSensitive); -} -function arrayIsSorted(array, comparer) { - if (array.length < 2) return true; - for (let i = 1, len = array.length; i < len; i++) { - if (comparer(array[i - 1], array[i]) === 1 /* GreaterThan */) { - return false; - } - } - return true; + return deduplicateSorted(toSorted(array, comparer), equalityComparer ?? comparer ?? compareStringsCaseSensitive); } function arrayIsEqualTo(array1, array2, equalityComparer = equateValues) { - if (!array1 || !array2) { + if (array1 === void 0 || array2 === void 0) { return array1 === array2; } if (array1.length !== array2.length) { @@ -97659,20 +97521,18 @@ function arrayIsEqualTo(array1, array2, equalityComparer = equateValues) { } function compact(array) { let result; - if (array) { + if (array !== void 0) { for (let i = 0; i < array.length; i++) { const v = array[i]; - if (result || !v) { - if (!result) { - result = array.slice(0, i); - } + if (result ?? !v) { + result ?? (result = array.slice(0, i)); if (v) { result.push(v); } } } } - return result || array; + return result ?? array; } function relativeComplement(arrayA, arrayB, comparer) { if (!arrayB || !arrayA || arrayB.length === 0 || arrayA.length === 0) return arrayB; @@ -97737,7 +97597,7 @@ function pushIfUnique(array, toAdd, equalityComparer) { } } function appendIfUnique(array, toAdd, equalityComparer) { - if (array) { + if (array !== void 0) { pushIfUnique(array, toAdd, equalityComparer); return array; } else { @@ -97747,19 +97607,14 @@ function appendIfUnique(array, toAdd, equalityComparer) { function stableSortIndices(array, indices, comparer) { indices.sort((x, y) => comparer(array[x], array[y]) || compareValues(x, y)); } -function sort(array, comparer) { - return array.length === 0 ? array : array.slice().sort(comparer); +function toSorted(array, comparer) { + return array.length === 0 ? emptyArray : array.slice().sort(comparer); } function* arrayReverseIterator(array) { for (let i = array.length - 1; i >= 0; i--) { yield array[i]; } } -function stableSort(array, comparer) { - const indices = indicesOf(array); - stableSortIndices(array, indices, comparer); - return indices.map((i) => array[i]); -} function rangeEquals(array1, array2, pos, end) { while (pos < end) { if (array1[pos] !== array2[pos]) { @@ -97770,7 +97625,7 @@ function rangeEquals(array1, array2, pos, end) { return true; } var elementAt = !!Array.prototype.at ? (array, offset) => array == null ? void 0 : array.at(offset) : (array, offset) => { - if (array) { + if (array !== void 0) { offset = toOffset(array, offset); if (offset < array.length) { return array[offset]; @@ -97782,7 +97637,7 @@ function firstOrUndefined(array) { return array === void 0 || array.length === 0 ? void 0 : array[0]; } function firstOrUndefinedIterator(iter) { - if (iter) { + if (iter !== void 0) { for (const value of iter) { return value; } @@ -97807,13 +97662,13 @@ function last(array) { return array[array.length - 1]; } function singleOrUndefined(array) { - return array && array.length === 1 ? array[0] : void 0; + return array !== void 0 && array.length === 1 ? array[0] : void 0; } function single(array) { return Debug.checkDefined(singleOrUndefined(array)); } function singleOrMany(array) { - return array && array.length === 1 ? array[0] : array; + return array !== void 0 && array.length === 1 ? array[0] : array; } function replaceElement(array, index, value) { const result = array.slice(0); @@ -97827,7 +97682,7 @@ function binarySearchKey(array, key, keySelector, keyComparer, offset) { if (!some(array)) { return -1; } - let low = offset || 0; + let low = offset ?? 0; let high = array.length - 1; while (low <= high) { const middle = low + (high - low >> 1); @@ -97945,7 +97800,8 @@ function equalOwnProperties(left, right, equalityComparer = equateValues) { } function arrayToMap(array, makeKey, makeValue = identity) { const result = /* @__PURE__ */ new Map(); - for (const value of array) { + for (let i = 0; i < array.length; i++) { + const value = array[i]; const key = makeKey(value); if (key !== void 0) result.set(key, makeValue(value)); } @@ -97953,14 +97809,16 @@ function arrayToMap(array, makeKey, makeValue = identity) { } function arrayToNumericMap(array, makeKey, makeValue = identity) { const result = []; - for (const value of array) { + for (let i = 0; i < array.length; i++) { + const value = array[i]; result[makeKey(value)] = makeValue(value); } return result; } function arrayToMultiMap(values, makeKey, makeValue = identity) { const result = createMultiMap(); - for (const value of values) { + for (let i = 0; i < values.length; i++) { + const value = values[i]; result.add(makeKey(value), makeValue(value)); } return result; @@ -97970,8 +97828,9 @@ function group(values, getGroupId, resultSelector = identity) { } function groupBy(values, keySelector) { const result = {}; - if (values) { - for (const value of values) { + if (values !== void 0) { + for (let i = 0; i < values.length; i++) { + const value = values[i]; const key = `${keySelector(value)}`; const array = result[key] ?? (result[key] = []); array.push(value); @@ -98010,7 +97869,7 @@ function copyProperties(first2, second) { } } function maybeBind(obj, fn) { - return fn ? fn.bind(obj) : void 0; + return fn == null ? void 0 : fn.bind(obj); } function createMultiMap() { const map2 = /* @__PURE__ */ new Map(); @@ -98020,7 +97879,7 @@ function createMultiMap() { } function multiMapAdd(key, value) { let values = this.get(key); - if (values) { + if (values !== void 0) { values.push(value); } else { this.set(key, values = [value]); @@ -98029,7 +97888,7 @@ function multiMapAdd(key, value) { } function multiMapRemove(key, value) { const values = this.get(key); - if (values) { + if (values !== void 0) { unorderedRemoveItem(values, value); if (!values.length) { this.delete(key); @@ -98037,7 +97896,7 @@ function multiMapRemove(key, value) { } } function createQueue(items) { - const elements = (items == null ? void 0 : items.slice()) || []; + const elements = (items == null ? void 0 : items.slice()) ?? []; let headIndex = 0; function isEmpty() { return headIndex === elements.length; @@ -98088,13 +97947,8 @@ function createSet(getHashCode, equals) { const hash = getHashCode(element); if (!multiMap.has(hash)) return false; const candidates = multiMap.get(hash); - if (!isArray(candidates)) return equals(candidates, element); - for (const candidate of candidates) { - if (equals(candidate, element)) { - return true; - } - } - return false; + if (isArray(candidates)) return contains(candidates, element, equals); + return equals(candidates, element); }, add(element) { const hash = getHashCode(element); @@ -98248,46 +98102,6 @@ function memoizeOne(callback) { return value; }; } -function memoizeWeak(callback) { - const map2 = /* @__PURE__ */ new WeakMap(); - return (arg) => { - let value = map2.get(arg); - if (value === void 0 && !map2.has(arg)) { - value = callback(arg); - map2.set(arg, value); - } - return value; - }; -} -function memoizeCached(callback, cache) { - return (...args) => { - let value = cache.get(args); - if (value === void 0 && !cache.has(args)) { - value = callback(...args); - cache.set(args, value); - } - return value; - }; -} -function compose(a, b, c, d, e) { - if (!!e) { - const args = []; - for (let i = 0; i < arguments.length; i++) { - args[i] = arguments[i]; - } - return (t) => reduceLeft(args, (u, f) => f(u), t); - } else if (d) { - return (t) => d(c(b(a(t)))); - } else if (c) { - return (t) => c(b(a(t))); - } else if (b) { - return (t) => b(a(t)); - } else if (a) { - return (t) => a(t); - } else { - return (t) => t; - } -} var AssertionLevel = /* @__PURE__ */ ((AssertionLevel2) => { AssertionLevel2[AssertionLevel2["None"] = 0] = "None"; AssertionLevel2[AssertionLevel2["Normal"] = 1] = "Normal"; @@ -98313,6 +98127,12 @@ function compareValues(a, b) { function compareTextSpans(a, b) { return compareValues(a == null ? void 0 : a.start, b == null ? void 0 : b.start) || compareValues(a == null ? void 0 : a.length, b == null ? void 0 : b.length); } +function maxBy(arr, init, mapper) { + for (let i = 0; i < arr.length; i++) { + init = Math.max(init, mapper(arr[i])); + } + return init; +} function min(items, compare) { return reduceLeft(items, (x, y) => compare(x, y) === -1 /* LessThan */ ? x : y); } @@ -98364,8 +98184,8 @@ function setUILocale(value) { } } function compareStringsCaseSensitiveUI(a, b) { - const comparer = uiComparerCaseSensitive || (uiComparerCaseSensitive = createUIStringComparer(uiLocale)); - return comparer(a, b); + uiComparerCaseSensitive ?? (uiComparerCaseSensitive = createUIStringComparer(uiLocale)); + return uiComparerCaseSensitive(a, b); } function compareProperties(a, b, key, comparer) { return a === b ? 0 /* EqualTo */ : a === void 0 ? -1 /* LessThan */ : b === void 0 ? 1 /* GreaterThan */ : comparer(a[key], b[key]); @@ -98525,7 +98345,8 @@ function matchedText(pattern, candidate) { function findBestPatternMatch(values, getPattern, candidate) { let matchedValue; let longestMatchPrefixLength = -1; - for (const v of values) { + for (let i = 0; i < values.length; i++) { + const v = values[i]; const pattern = getPattern(v); if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { longestMatchPrefixLength = pattern.prefix.length; @@ -98570,7 +98391,7 @@ function singleElementArray(t) { return t === void 0 ? void 0 : [t]; } function enumerateInsertsAndDeletes(newItems, oldItems, comparer, inserted, deleted, unchanged) { - unchanged = unchanged || noop; + unchanged ?? (unchanged = noop); let newIndex = 0; let oldIndex = 0; const newLen = newItems.length; @@ -98632,7 +98453,7 @@ function cartesianProductWorker(arrays, result, outer, index) { } } function takeWhile(array, predicate) { - if (array) { + if (array !== void 0) { const len = array.length; let index = 0; while (index < len && predicate(array[index])) { @@ -98642,7 +98463,7 @@ function takeWhile(array, predicate) { } } function skipWhile(array, predicate) { - if (array) { + if (array !== void 0) { const len = array.length; let index = 0; while (index < len && predicate(array[index])) { @@ -98938,7 +98759,7 @@ Node ${formatSyntaxKind(node.kind)} was unexpected.`, result.push([value, name]); } } - const sorted = stableSort(result, (x, y) => compareValues(x[0], y[0])); + const sorted = toSorted(result, (x, y) => compareValues(x[0], y[0])); enumMemberCache.set(enumObject, sorted); return sorted; } @@ -99147,7 +98968,7 @@ Node ${formatSyntaxKind(node.kind)} was unexpected.`, Object.defineProperties(array, { __tsDebuggerDisplay: { value(defaultValue) { - defaultValue = String(defaultValue).replace(/(?:,[\s\w\d_]+:[^,]+)+\]$/, "]"); + defaultValue = String(defaultValue).replace(/(?:,[\s\w]+:[^,]+)+\]$/, "]"); return `NodeArray ${defaultValue}`; } } @@ -99567,7 +99388,7 @@ m2: ${this.mapper2.__debugToString().split("\n").join("\n ")}`; } function renderGraph() { const columnCount = columnWidths.length; - const laneCount = nodes.reduce((x, n) => Math.max(x, n.lane), 0) + 1; + const laneCount = maxBy(nodes, 0, (n) => n.lane) + 1; const lanes = fill(Array(laneCount), ""); const grid = columnWidths.map(() => Array(laneCount)); const connectors = columnWidths.map(() => fill(Array(laneCount), 0)); @@ -99690,7 +99511,7 @@ var prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z- var prereleasePartRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)$/i; var buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i; var buildPartRegExp = /^[a-z0-9-]+$/i; -var numericIdentifierRegExp = /^(0|[1-9]\d*)$/; +var numericIdentifierRegExp = /^(?:0|[1-9]\d*)$/; var _Version = class _Version { constructor(major, minor = 0, patch = 0, prerelease = "", build2 = "") { if (typeof major === "string") { @@ -99813,11 +99634,11 @@ var VersionRange = class _VersionRange { return formatDisjunction(this._alternatives); } }; -var logicalOrRegExp = /\|\|/g; -var whitespaceRegExp = /\s+/g; -var partialRegExp = /^([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; +var logicalOrRegExp = /\|\|/; +var whitespaceRegExp = /\s+/; +var partialRegExp = /^([x*0]|[1-9]\d*)(?:\.([x*0]|[1-9]\d*)(?:\.([x*0]|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; var hyphenRegExp = /^\s*([a-z0-9-+.*]+)\s+-\s+([a-z0-9-+.*]+)\s*$/i; -var rangeRegExp = /^(~|\^|<|<=|>|>=|=)?\s*([a-z0-9-+.*]+)$/i; +var rangeRegExp = /^([~^<>=]|<=|>=)?\s*([a-z0-9-+.*]+)$/i; function parseRange(text) { const alternatives = []; for (let range of text.trim().split(logicalOrRegExp)) { @@ -100010,16 +99831,6 @@ function tryGetNativePerformanceHooks() { } var timestamp = nativePerformanceTime ? () => nativePerformanceTime.now() : Date.now; -// src/compiler/perfLogger.ts -var etwModule; -try { - const etwModulePath = process.env.TS_ETW_MODULE_PATH ?? "./node_modules/@microsoft/typescript-etw"; - etwModule = require(etwModulePath); -} catch (e) { - etwModule = void 0; -} -var perfLogger = (etwModule == null ? void 0 : etwModule.logEvent) ? etwModule : void 0; - // src/compiler/_namespaces/ts.performance.ts var ts_performance_exports = {}; __export(ts_performance_exports, { @@ -100908,12 +100719,21 @@ var RelationComparisonResult = /* @__PURE__ */ ((RelationComparisonResult3) => { RelationComparisonResult3[RelationComparisonResult3["None"] = 0] = "None"; RelationComparisonResult3[RelationComparisonResult3["Succeeded"] = 1] = "Succeeded"; RelationComparisonResult3[RelationComparisonResult3["Failed"] = 2] = "Failed"; - RelationComparisonResult3[RelationComparisonResult3["Reported"] = 4] = "Reported"; RelationComparisonResult3[RelationComparisonResult3["ReportsUnmeasurable"] = 8] = "ReportsUnmeasurable"; RelationComparisonResult3[RelationComparisonResult3["ReportsUnreliable"] = 16] = "ReportsUnreliable"; RelationComparisonResult3[RelationComparisonResult3["ReportsMask"] = 24] = "ReportsMask"; + RelationComparisonResult3[RelationComparisonResult3["ComplexityOverflow"] = 32] = "ComplexityOverflow"; + RelationComparisonResult3[RelationComparisonResult3["StackDepthOverflow"] = 64] = "StackDepthOverflow"; + RelationComparisonResult3[RelationComparisonResult3["Overflow"] = 96] = "Overflow"; return RelationComparisonResult3; })(RelationComparisonResult || {}); +var PredicateSemantics = /* @__PURE__ */ ((PredicateSemantics2) => { + PredicateSemantics2[PredicateSemantics2["None"] = 0] = "None"; + PredicateSemantics2[PredicateSemantics2["Always"] = 1] = "Always"; + PredicateSemantics2[PredicateSemantics2["Never"] = 2] = "Never"; + PredicateSemantics2[PredicateSemantics2["Sometimes"] = 3] = "Sometimes"; + return PredicateSemantics2; +})(PredicateSemantics || {}); var GeneratedIdentifierFlags = /* @__PURE__ */ ((GeneratedIdentifierFlags2) => { GeneratedIdentifierFlags2[GeneratedIdentifierFlags2["None"] = 0] = "None"; GeneratedIdentifierFlags2[GeneratedIdentifierFlags2["Auto"] = 1] = "Auto"; @@ -100958,6 +100778,7 @@ var TokenFlags = /* @__PURE__ */ ((TokenFlags2) => { TokenFlags2[TokenFlags2["HexEscape"] = 4096] = "HexEscape"; TokenFlags2[TokenFlags2["ContainsLeadingZero"] = 8192] = "ContainsLeadingZero"; TokenFlags2[TokenFlags2["ContainsInvalidSeparator"] = 16384] = "ContainsInvalidSeparator"; + TokenFlags2[TokenFlags2["PrecedingJSDocLeadingAsterisks"] = 32768] = "PrecedingJSDocLeadingAsterisks"; TokenFlags2[TokenFlags2["BinaryOrOctalSpecifier"] = 384] = "BinaryOrOctalSpecifier"; TokenFlags2[TokenFlags2["WithSpecifier"] = 448] = "WithSpecifier"; TokenFlags2[TokenFlags2["StringLiteralFlags"] = 7176] = "StringLiteralFlags"; @@ -101082,17 +100903,21 @@ var NodeBuilderFlags = /* @__PURE__ */ ((NodeBuilderFlags2) => { NodeBuilderFlags2[NodeBuilderFlags2["AllowEmptyTuple"] = 524288] = "AllowEmptyTuple"; NodeBuilderFlags2[NodeBuilderFlags2["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType"; NodeBuilderFlags2[NodeBuilderFlags2["AllowEmptyIndexInfoType"] = 2097152] = "AllowEmptyIndexInfoType"; - NodeBuilderFlags2[NodeBuilderFlags2["WriteComputedProps"] = 1073741824] = "WriteComputedProps"; - NodeBuilderFlags2[NodeBuilderFlags2["NoSyntacticPrinter"] = -2147483648] = "NoSyntacticPrinter"; NodeBuilderFlags2[NodeBuilderFlags2["AllowNodeModulesRelativePaths"] = 67108864] = "AllowNodeModulesRelativePaths"; - NodeBuilderFlags2[NodeBuilderFlags2["DoNotIncludeSymbolChain"] = 134217728] = "DoNotIncludeSymbolChain"; - NodeBuilderFlags2[NodeBuilderFlags2["AllowUnresolvedNames"] = 1] = "AllowUnresolvedNames"; NodeBuilderFlags2[NodeBuilderFlags2["IgnoreErrors"] = 70221824] = "IgnoreErrors"; NodeBuilderFlags2[NodeBuilderFlags2["InObjectTypeLiteral"] = 4194304] = "InObjectTypeLiteral"; NodeBuilderFlags2[NodeBuilderFlags2["InTypeAlias"] = 8388608] = "InTypeAlias"; NodeBuilderFlags2[NodeBuilderFlags2["InInitialEntityName"] = 16777216] = "InInitialEntityName"; return NodeBuilderFlags2; })(NodeBuilderFlags || {}); +var InternalNodeBuilderFlags = /* @__PURE__ */ ((InternalNodeBuilderFlags2) => { + InternalNodeBuilderFlags2[InternalNodeBuilderFlags2["None"] = 0] = "None"; + InternalNodeBuilderFlags2[InternalNodeBuilderFlags2["WriteComputedProps"] = 1] = "WriteComputedProps"; + InternalNodeBuilderFlags2[InternalNodeBuilderFlags2["NoSyntacticPrinter"] = 2] = "NoSyntacticPrinter"; + InternalNodeBuilderFlags2[InternalNodeBuilderFlags2["DoNotIncludeSymbolChain"] = 4] = "DoNotIncludeSymbolChain"; + InternalNodeBuilderFlags2[InternalNodeBuilderFlags2["AllowUnresolvedNames"] = 8] = "AllowUnresolvedNames"; + return InternalNodeBuilderFlags2; +})(InternalNodeBuilderFlags || {}); var TypeFormatFlags = /* @__PURE__ */ ((TypeFormatFlags2) => { TypeFormatFlags2[TypeFormatFlags2["None"] = 0] = "None"; TypeFormatFlags2[TypeFormatFlags2["NoTruncation"] = 1] = "NoTruncation"; @@ -101137,11 +100962,6 @@ var SymbolAccessibility = /* @__PURE__ */ ((SymbolAccessibility2) => { SymbolAccessibility2[SymbolAccessibility2["NotResolved"] = 3] = "NotResolved"; return SymbolAccessibility2; })(SymbolAccessibility || {}); -var SyntheticSymbolKind = /* @__PURE__ */ ((SyntheticSymbolKind2) => { - SyntheticSymbolKind2[SyntheticSymbolKind2["UnionOrIntersection"] = 0] = "UnionOrIntersection"; - SyntheticSymbolKind2[SyntheticSymbolKind2["Spread"] = 1] = "Spread"; - return SyntheticSymbolKind2; -})(SyntheticSymbolKind || {}); var TypePredicateKind = /* @__PURE__ */ ((TypePredicateKind2) => { TypePredicateKind2[TypePredicateKind2["This"] = 0] = "This"; TypePredicateKind2[TypePredicateKind2["Identifier"] = 1] = "Identifier"; @@ -101307,6 +101127,7 @@ var NodeCheckFlags = /* @__PURE__ */ ((NodeCheckFlags3) => { NodeCheckFlags3[NodeCheckFlags3["ContainsClassWithPrivateIdentifiers"] = 1048576] = "ContainsClassWithPrivateIdentifiers"; NodeCheckFlags3[NodeCheckFlags3["ContainsSuperPropertyInStaticInitializer"] = 2097152] = "ContainsSuperPropertyInStaticInitializer"; NodeCheckFlags3[NodeCheckFlags3["InCheckIdentifier"] = 4194304] = "InCheckIdentifier"; + NodeCheckFlags3[NodeCheckFlags3["PartiallyTypeChecked"] = 8388608] = "PartiallyTypeChecked"; NodeCheckFlags3[NodeCheckFlags3["LazyFlags"] = 539358128] = "LazyFlags"; return NodeCheckFlags3; })(NodeCheckFlags || {}); @@ -101460,7 +101281,7 @@ var AccessFlags = /* @__PURE__ */ ((AccessFlags2) => { AccessFlags2[AccessFlags2["NoIndexSignatures"] = 2] = "NoIndexSignatures"; AccessFlags2[AccessFlags2["Writing"] = 4] = "Writing"; AccessFlags2[AccessFlags2["CacheSymbol"] = 8] = "CacheSymbol"; - AccessFlags2[AccessFlags2["NoTupleBoundsCheck"] = 16] = "NoTupleBoundsCheck"; + AccessFlags2[AccessFlags2["AllowMissing"] = 16] = "AllowMissing"; AccessFlags2[AccessFlags2["ExpressionPosition"] = 32] = "ExpressionPosition"; AccessFlags2[AccessFlags2["ReportDeprecated"] = 64] = "ReportDeprecated"; AccessFlags2[AccessFlags2["SuppressNoImplicitAnyError"] = 128] = "SuppressNoImplicitAnyError"; @@ -101654,22 +101475,22 @@ var ScriptKind = /* @__PURE__ */ ((ScriptKind7) => { ScriptKind7[ScriptKind7["Deferred"] = 7] = "Deferred"; return ScriptKind7; })(ScriptKind || {}); -var ScriptTarget = /* @__PURE__ */ ((ScriptTarget11) => { - ScriptTarget11[ScriptTarget11["ES3"] = 0] = "ES3"; - ScriptTarget11[ScriptTarget11["ES5"] = 1] = "ES5"; - ScriptTarget11[ScriptTarget11["ES2015"] = 2] = "ES2015"; - ScriptTarget11[ScriptTarget11["ES2016"] = 3] = "ES2016"; - ScriptTarget11[ScriptTarget11["ES2017"] = 4] = "ES2017"; - ScriptTarget11[ScriptTarget11["ES2018"] = 5] = "ES2018"; - ScriptTarget11[ScriptTarget11["ES2019"] = 6] = "ES2019"; - ScriptTarget11[ScriptTarget11["ES2020"] = 7] = "ES2020"; - ScriptTarget11[ScriptTarget11["ES2021"] = 8] = "ES2021"; - ScriptTarget11[ScriptTarget11["ES2022"] = 9] = "ES2022"; - ScriptTarget11[ScriptTarget11["ES2023"] = 10] = "ES2023"; - ScriptTarget11[ScriptTarget11["ESNext"] = 99] = "ESNext"; - ScriptTarget11[ScriptTarget11["JSON"] = 100] = "JSON"; - ScriptTarget11[ScriptTarget11["Latest"] = 99 /* ESNext */] = "Latest"; - return ScriptTarget11; +var ScriptTarget = /* @__PURE__ */ ((ScriptTarget12) => { + ScriptTarget12[ScriptTarget12["ES3"] = 0] = "ES3"; + ScriptTarget12[ScriptTarget12["ES5"] = 1] = "ES5"; + ScriptTarget12[ScriptTarget12["ES2015"] = 2] = "ES2015"; + ScriptTarget12[ScriptTarget12["ES2016"] = 3] = "ES2016"; + ScriptTarget12[ScriptTarget12["ES2017"] = 4] = "ES2017"; + ScriptTarget12[ScriptTarget12["ES2018"] = 5] = "ES2018"; + ScriptTarget12[ScriptTarget12["ES2019"] = 6] = "ES2019"; + ScriptTarget12[ScriptTarget12["ES2020"] = 7] = "ES2020"; + ScriptTarget12[ScriptTarget12["ES2021"] = 8] = "ES2021"; + ScriptTarget12[ScriptTarget12["ES2022"] = 9] = "ES2022"; + ScriptTarget12[ScriptTarget12["ES2023"] = 10] = "ES2023"; + ScriptTarget12[ScriptTarget12["ESNext"] = 99] = "ESNext"; + ScriptTarget12[ScriptTarget12["JSON"] = 100] = "JSON"; + ScriptTarget12[ScriptTarget12["Latest"] = 99 /* ESNext */] = "Latest"; + return ScriptTarget12; })(ScriptTarget || {}); var LanguageVariant = /* @__PURE__ */ ((LanguageVariant4) => { LanguageVariant4[LanguageVariant4["Standard"] = 0] = "Standard"; @@ -102031,9 +101852,10 @@ var OuterExpressionKinds = /* @__PURE__ */ ((OuterExpressionKinds2) => { OuterExpressionKinds2[OuterExpressionKinds2["TypeAssertions"] = 2] = "TypeAssertions"; OuterExpressionKinds2[OuterExpressionKinds2["NonNullAssertions"] = 4] = "NonNullAssertions"; OuterExpressionKinds2[OuterExpressionKinds2["PartiallyEmittedExpressions"] = 8] = "PartiallyEmittedExpressions"; + OuterExpressionKinds2[OuterExpressionKinds2["ExpressionsWithTypeArguments"] = 16] = "ExpressionsWithTypeArguments"; OuterExpressionKinds2[OuterExpressionKinds2["Assertions"] = 6] = "Assertions"; - OuterExpressionKinds2[OuterExpressionKinds2["All"] = 15] = "All"; - OuterExpressionKinds2[OuterExpressionKinds2["ExcludeJSDocTypeAssertion"] = 16] = "ExcludeJSDocTypeAssertion"; + OuterExpressionKinds2[OuterExpressionKinds2["All"] = 31] = "All"; + OuterExpressionKinds2[OuterExpressionKinds2["ExcludeJSDocTypeAssertion"] = -2147483648] = "ExcludeJSDocTypeAssertion"; return OuterExpressionKinds2; })(OuterExpressionKinds || {}); var LexicalEnvironmentFlags = /* @__PURE__ */ ((LexicalEnvironmentFlags2) => { @@ -103139,7 +102961,7 @@ function patchWriteFileEnsuringDirectory(sys2) { var sys = (() => { const byteOrderMarkIndicator = "\uFEFF"; function getNodeSystem() { - const nativePattern = /^native |^\([^)]+\)$|^(internal[\\/]|[a-zA-Z0-9_\s]+(\.js)?$)/; + const nativePattern = /^native |^\([^)]+\)$|^(?:internal[\\/]|[\w\s]+(?:\.js)?$)/; const _fs = __nccwpck_require__(57147); const _path = __nccwpck_require__(71017); const _os = __nccwpck_require__(22037); @@ -103197,6 +103019,7 @@ var sys = (() => { writeFile: writeFile2, watchFile: watchFile2, watchDirectory, + preferNonRecursiveWatch: !fsSupportsRecursiveFsWatch, resolvePath: (path) => _path.resolve(path), fileExists, directoryExists, @@ -103249,7 +103072,7 @@ var sys = (() => { disableCPUProfiler, cpuProfilingEnabled: () => !!activeSession || contains(process.execArgv, "--cpu-prof") || contains(process.execArgv, "--prof"), realpath, - debugMode: !!process.env.NODE_INSPECTOR_IPC || !!process.env.VSCODE_INSPECTOR_OPTIONS || some(process.execArgv, (arg) => /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg)) || !!process.recordreplay, + debugMode: !!process.env.NODE_INSPECTOR_IPC || !!process.env.VSCODE_INSPECTOR_OPTIONS || some(process.execArgv, (arg) => /^--(?:inspect|debug)(?:-brk)?(?:=\d+)?$/i.test(arg)) || !!process.recordreplay, tryEnableSourceMapsForHost() { try { (__nccwpck_require__(9249).install)(); @@ -103259,7 +103082,7 @@ var sys = (() => { setTimeout, clearTimeout, clearScreen: () => { - process.stdout.write("\x1Bc"); + process.stdout.write("\x1B[2J\x1B[3J\x1B[H"); }, setBlocking: () => { var _a; @@ -103359,9 +103182,6 @@ var sys = (() => { } } function isFileSystemCaseSensitive() { - if (typeof process.versions.pnp !== `undefined`) { - return true; - } if (platform === "win32" || platform === "win64") { return false; } @@ -103403,11 +103223,11 @@ var sys = (() => { callback ); } - function readFileWorker(fileName, _encoding) { + function readFile(fileName, _encoding) { let buffer; try { buffer = _fs.readFileSync(fileName); - } catch (e) { + } catch { return void 0; } let len = buffer.length; @@ -103428,16 +103248,7 @@ var sys = (() => { } return buffer.toString("utf8"); } - function readFile(fileName, _encoding) { - var _a, _b; - (_a = perfLogger) == null ? void 0 : _a.logStartReadFile(fileName); - const file = readFileWorker(fileName, _encoding); - (_b = perfLogger) == null ? void 0 : _b.logStopReadFile(); - return file; - } function writeFile2(fileName, data, writeByteOrderMark) { - var _a; - (_a = perfLogger) == null ? void 0 : _a.logEvent("WriteFile: " + fileName); if (writeByteOrderMark) { data = byteOrderMarkIndicator + data; } @@ -103458,8 +103269,6 @@ var sys = (() => { } } function getAccessibleFileSystemEntries(path) { - var _a; - (_a = perfLogger) == null ? void 0 : _a.logEvent("ReadDir: " + (path || ".")); try { const entries = _fs.readdirSync(path || ".", { withFileTypes: true }); const files = []; @@ -103477,7 +103286,7 @@ var sys = (() => { if (!stat) { continue; } - } catch (e) { + } catch { continue; } } else { @@ -103492,7 +103301,7 @@ var sys = (() => { files.sort(); directories.sort(); return { files, directories }; - } catch (e) { + } catch { return emptyFileSystemEntries; } } @@ -103515,7 +103324,7 @@ var sys = (() => { default: return false; } - } catch (e) { + } catch { return false; } finally { Error.stackTraceLimit = originalStackTraceLimit; @@ -103546,7 +103355,7 @@ var sys = (() => { Error.stackTraceLimit = 0; try { return (_a = statSync(path)) == null ? void 0 : _a.mtime; - } catch (e) { + } catch { return void 0; } finally { Error.stackTraceLimit = originalStackTraceLimit; @@ -103555,14 +103364,14 @@ var sys = (() => { function setModifiedTime(path, time) { try { _fs.utimesSync(path, time, time); - } catch (e) { + } catch { return; } } function deleteFile(path) { try { return _fs.unlinkSync(path); - } catch (e) { + } catch { return; } } @@ -103616,7 +103425,7 @@ function pathIsAbsolute(path) { return getEncodedRootLength(path) !== 0; } function pathIsRelative(path) { - return /^\.\.?($|[\\/])/.test(path); + return /^\.\.?(?:$|[\\/])/.test(path); } function pathIsBareSpecifier(path) { return !pathIsAbsolute(path) && !pathIsRelative(path); @@ -103849,7 +103658,7 @@ function changeFullExtension(path, newExtension) { } return changeAnyExtension(path, newExtension); } -var relativePathSegmentRegExp = /(?:\/\/)|(?:^|\/)\.\.?(?:$|\/)/; +var relativePathSegmentRegExp = /\/\/|(?:^|\/)\.\.?(?:$|\/)/; function comparePathsWorker(a, b, componentComparer) { if (a === b) return 0 /* EqualTo */; if (a === void 0) return -1 /* LessThan */; @@ -104237,6 +104046,7 @@ var Diagnostics = { _0_resolves_to_a_type_only_declaration_and_must_be_marked_type_only_in_this_file_before_re_exporting_when_1_is_enabled_Consider_using_export_type_0_as_default: diag(1290, 1 /* Error */, "_0_resolves_to_a_type_only_declaration_and_must_be_marked_type_only_in_this_file_before_re_exporting_1290", "'{0}' resolves to a type-only declaration and must be marked type-only in this file before re-exporting when '{1}' is enabled. Consider using 'export type { {0} as default }'."), _0_resolves_to_a_type_and_must_be_marked_type_only_in_this_file_before_re_exporting_when_1_is_enabled_Consider_using_import_type_where_0_is_imported: diag(1291, 1 /* Error */, "_0_resolves_to_a_type_and_must_be_marked_type_only_in_this_file_before_re_exporting_when_1_is_enable_1291", "'{0}' resolves to a type and must be marked type-only in this file before re-exporting when '{1}' is enabled. Consider using 'import type' where '{0}' is imported."), _0_resolves_to_a_type_and_must_be_marked_type_only_in_this_file_before_re_exporting_when_1_is_enabled_Consider_using_export_type_0_as_default: diag(1292, 1 /* Error */, "_0_resolves_to_a_type_and_must_be_marked_type_only_in_this_file_before_re_exporting_when_1_is_enable_1292", "'{0}' resolves to a type and must be marked type-only in this file before re-exporting when '{1}' is enabled. Consider using 'export type { {0} as default }'."), + ESM_syntax_is_not_allowed_in_a_CommonJS_module_when_module_is_set_to_preserve: diag(1293, 1 /* Error */, "ESM_syntax_is_not_allowed_in_a_CommonJS_module_when_module_is_set_to_preserve_1293", "ESM syntax is not allowed in a CommonJS module when 'module' is set to 'preserve'."), with_statements_are_not_allowed_in_an_async_function_block: diag(1300, 1 /* 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, 1 /* 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."), The_current_file_is_a_CommonJS_module_and_cannot_use_await_at_the_top_level: diag(1309, 1 /* Error */, "The_current_file_is_a_CommonJS_module_and_cannot_use_await_at_the_top_level_1309", "The current file is a CommonJS module and cannot use 'await' at the top level."), @@ -104252,7 +104062,7 @@ var Diagnostics = { Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1321, 1 /* Error */, "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321", "Type of 'yield' operand in an async generator must either be a valid promise or must not contain a callable 'then' member."), Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1322, 1 /* Error */, "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322", "Type of iterated elements of a 'yield*' operand must either be a valid promise or must not contain a callable 'then' member."), Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_es2022_esnext_commonjs_amd_system_umd_node16_or_nodenext: diag(1323, 1 /* Error */, "Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_es2022_esnext_commonjs_amd__1323", "Dynamic imports are only supported when the '--module' flag is set to 'es2020', 'es2022', 'esnext', 'commonjs', 'amd', 'system', 'umd', 'node16', or 'nodenext'."), - Dynamic_imports_only_support_a_second_argument_when_the_module_option_is_set_to_esnext_node16_or_nodenext: diag(1324, 1 /* Error */, "Dynamic_imports_only_support_a_second_argument_when_the_module_option_is_set_to_esnext_node16_or_nod_1324", "Dynamic imports only support a second argument when the '--module' option is set to 'esnext', 'node16', or 'nodenext'."), + Dynamic_imports_only_support_a_second_argument_when_the_module_option_is_set_to_esnext_node16_nodenext_or_preserve: diag(1324, 1 /* Error */, "Dynamic_imports_only_support_a_second_argument_when_the_module_option_is_set_to_esnext_node16_nodene_1324", "Dynamic imports only support a second argument when the '--module' option is set to 'esnext', 'node16', 'nodenext', or 'preserve'."), Argument_of_dynamic_import_cannot_be_spread_element: diag(1325, 1 /* Error */, "Argument_of_dynamic_import_cannot_be_spread_element_1325", "Argument of dynamic import cannot be spread element."), This_use_of_import_is_invalid_import_calls_can_be_written_but_they_must_have_parentheses_and_cannot_have_type_arguments: diag(1326, 1 /* Error */, "This_use_of_import_is_invalid_import_calls_can_be_written_but_they_must_have_parentheses_and_cannot__1326", "This use of 'import' is invalid. 'import()' calls can be written, but they must have parentheses and cannot have type arguments."), String_literal_with_double_quotes_expected: diag(1327, 1 /* Error */, "String_literal_with_double_quotes_expected_1327", "String literal with double quotes expected."), @@ -104445,6 +104255,20 @@ var Diagnostics = { This_character_cannot_be_escaped_in_a_regular_expression: diag(1535, 1 /* Error */, "This_character_cannot_be_escaped_in_a_regular_expression_1535", "This character cannot be escaped in a regular expression."), Octal_escape_sequences_and_backreferences_are_not_allowed_in_a_character_class_If_this_was_intended_as_an_escape_sequence_use_the_syntax_0_instead: diag(1536, 1 /* Error */, "Octal_escape_sequences_and_backreferences_are_not_allowed_in_a_character_class_If_this_was_intended__1536", "Octal escape sequences and backreferences are not allowed in a character class. If this was intended as an escape sequence, use the syntax '{0}' instead."), Decimal_escape_sequences_and_backreferences_are_not_allowed_in_a_character_class: diag(1537, 1 /* Error */, "Decimal_escape_sequences_and_backreferences_are_not_allowed_in_a_character_class_1537", "Decimal escape sequences and backreferences are not allowed in a character class."), + Unicode_escape_sequences_are_only_available_when_the_Unicode_u_flag_or_the_Unicode_Sets_v_flag_is_set: diag(1538, 1 /* Error */, "Unicode_escape_sequences_are_only_available_when_the_Unicode_u_flag_or_the_Unicode_Sets_v_flag_is_se_1538", "Unicode escape sequences are only available when the Unicode (u) flag or the Unicode Sets (v) flag is set."), + A_bigint_literal_cannot_be_used_as_a_property_name: diag(1539, 1 /* Error */, "A_bigint_literal_cannot_be_used_as_a_property_name_1539", "A 'bigint' literal cannot be used as a property name."), + A_namespace_declaration_should_not_be_declared_using_the_module_keyword_Please_use_the_namespace_keyword_instead: diag( + 1540, + 2 /* Suggestion */, + "A_namespace_declaration_should_not_be_declared_using_the_module_keyword_Please_use_the_namespace_key_1540", + "A 'namespace' declaration should not be declared using the 'module' keyword. Please use the 'namespace' keyword instead.", + /*reportsUnnecessary*/ + void 0, + /*elidedInCompatabilityPyramid*/ + void 0, + /*reportsDeprecated*/ + true + ), The_types_of_0_are_incompatible_between_these_types: diag(2200, 1 /* 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, 1 /* 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( @@ -104699,7 +104523,6 @@ var Diagnostics = { The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES5_Consider_using_a_standard_function_or_method: diag(2522, 1 /* Error */, "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES5_Consider_using_a_sta_2522", "The 'arguments' object cannot be referenced in an async function or method in ES5. Consider using a standard function or method."), yield_expressions_cannot_be_used_in_a_parameter_initializer: diag(2523, 1 /* Error */, "yield_expressions_cannot_be_used_in_a_parameter_initializer_2523", "'yield' expressions cannot be used in a parameter initializer."), await_expressions_cannot_be_used_in_a_parameter_initializer: diag(2524, 1 /* Error */, "await_expressions_cannot_be_used_in_a_parameter_initializer_2524", "'await' expressions cannot be used in a parameter initializer."), - Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value: diag(2525, 1 /* Error */, "Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value_2525", "Initializer provides no value for this binding element and the binding element has no default value."), A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface: diag(2526, 1 /* Error */, "A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface_2526", "A 'this' type is available only in a non-static member of a class or interface."), The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary: diag(2527, 1 /* Error */, "The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary_2527", "The inferred type of '{0}' references an inaccessible '{1}' type. A type annotation is necessary."), A_module_cannot_have_multiple_default_exports: diag(2528, 1 /* Error */, "A_module_cannot_have_multiple_default_exports_2528", "A module cannot have multiple default exports."), @@ -105012,6 +104835,11 @@ var Diagnostics = { Import_0_conflicts_with_global_value_used_in_this_file_so_must_be_declared_with_a_type_only_import_when_isolatedModules_is_enabled: diag(2866, 1 /* Error */, "Import_0_conflicts_with_global_value_used_in_this_file_so_must_be_declared_with_a_type_only_import_w_2866", "Import '{0}' conflicts with global value used in this file, so must be declared with a type-only import when 'isolatedModules' is enabled."), Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_Bun_Try_npm_i_save_dev_types_Slashbun: diag(2867, 1 /* Error */, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_Bun_Try_npm_i_save_dev_types_Slashbun_2867", "Cannot find name '{0}'. Do you need to install type definitions for Bun? Try `npm i --save-dev @types/bun`."), Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_Bun_Try_npm_i_save_dev_types_Slashbun_and_then_add_bun_to_the_types_field_in_your_tsconfig: diag(2868, 1 /* Error */, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_Bun_Try_npm_i_save_dev_types_Slashbun_2868", "Cannot find name '{0}'. Do you need to install type definitions for Bun? Try `npm i --save-dev @types/bun` and then add 'bun' to the types field in your tsconfig."), + Right_operand_of_is_unreachable_because_the_left_operand_is_never_nullish: diag(2869, 1 /* Error */, "Right_operand_of_is_unreachable_because_the_left_operand_is_never_nullish_2869", "Right operand of ?? is unreachable because the left operand is never nullish."), + This_binary_expression_is_never_nullish_Are_you_missing_parentheses: diag(2870, 1 /* Error */, "This_binary_expression_is_never_nullish_Are_you_missing_parentheses_2870", "This binary expression is never nullish. Are you missing parentheses?"), + This_expression_is_always_nullish: diag(2871, 1 /* Error */, "This_expression_is_always_nullish_2871", "This expression is always nullish."), + This_kind_of_expression_is_always_truthy: diag(2872, 1 /* Error */, "This_kind_of_expression_is_always_truthy_2872", "This kind of expression is always truthy."), + This_kind_of_expression_is_always_falsy: diag(2873, 1 /* Error */, "This_kind_of_expression_is_always_falsy_2873", "This kind of expression is always falsy."), Import_declaration_0_is_using_private_name_1: diag(4e3, 1 /* 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, 1 /* 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, 1 /* 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}'."), @@ -105088,7 +104916,7 @@ var Diagnostics = { Extends_clause_for_inferred_type_0_has_or_is_using_private_name_1: diag(4085, 1 /* Error */, "Extends_clause_for_inferred_type_0_has_or_is_using_private_name_1_4085", "Extends clause for inferred type '{0}' has or is using private name '{1}'."), Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4091, 1 /* 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, 1 /* 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}'."), - Property_0_of_exported_class_expression_may_not_be_private_or_protected: diag(4094, 1 /* Error */, "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094", "Property '{0}' of exported class expression may not be private or protected."), + Property_0_of_exported_anonymous_class_type_may_not_be_private_or_protected: diag(4094, 1 /* Error */, "Property_0_of_exported_anonymous_class_type_may_not_be_private_or_protected_4094", "Property '{0}' of exported anonymous class type may not be private or protected."), Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: diag(4095, 1 /* Error */, "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_4095", "Public static method '{0}' of exported class has or is using name '{1}' from external module {2} but cannot be named."), Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2: diag(4096, 1 /* Error */, "Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2_4096", "Public static method '{0}' of exported class has or is using name '{1}' from private module '{2}'."), Public_static_method_0_of_exported_class_has_or_is_using_private_name_1: diag(4097, 1 /* Error */, "Public_static_method_0_of_exported_class_has_or_is_using_private_name_1_4097", "Public static method '{0}' of exported class has or is using private name '{1}'."), @@ -105125,7 +104953,6 @@ var Diagnostics = { Cannot_find_the_common_subdirectory_path_for_the_input_files: diag(5009, 1 /* 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, 1 /* 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}'."), Cannot_read_file_0_Colon_1: diag(5012, 1 /* Error */, "Cannot_read_file_0_Colon_1_5012", "Cannot read file '{0}': {1}."), - Failed_to_parse_file_0_Colon_1: diag(5014, 1 /* Error */, "Failed_to_parse_file_0_Colon_1_5014", "Failed to parse file '{0}': {1}."), Unknown_compiler_option_0: diag(5023, 1 /* Error */, "Unknown_compiler_option_0_5023", "Unknown compiler option '{0}'."), Compiler_option_0_requires_a_value_of_type_1: diag(5024, 1 /* Error */, "Compiler_option_0_requires_a_value_of_type_1_5024", "Compiler option '{0}' requires a value of type {1}."), Unknown_compiler_option_0_Did_you_mean_1: diag(5025, 1 /* Error */, "Unknown_compiler_option_0_Did_you_mean_1_5025", "Unknown compiler option '{0}'. Did you mean '{1}'?"), @@ -105188,6 +105015,7 @@ var Diagnostics = { Option_0_1_has_been_removed_Please_remove_it_from_your_configuration: diag(5108, 1 /* Error */, "Option_0_1_has_been_removed_Please_remove_it_from_your_configuration_5108", "Option '{0}={1}' has been removed. Please remove it from your configuration."), Option_moduleResolution_must_be_set_to_0_or_left_unspecified_when_option_module_is_set_to_1: diag(5109, 1 /* Error */, "Option_moduleResolution_must_be_set_to_0_or_left_unspecified_when_option_module_is_set_to_1_5109", "Option 'moduleResolution' must be set to '{0}' (or left unspecified) when option 'module' is set to '{1}'."), Option_module_must_be_set_to_0_when_option_moduleResolution_is_set_to_1: diag(5110, 1 /* Error */, "Option_module_must_be_set_to_0_when_option_moduleResolution_is_set_to_1_5110", "Option 'module' must be set to '{0}' when option 'moduleResolution' is set to '{1}'."), + Option_tsBuildInfoFile_cannot_be_specified_without_specifying_option_incremental_or_composite_or_if_not_running_tsc_b: diag(5111, 1 /* Error */, "Option_tsBuildInfoFile_cannot_be_specified_without_specifying_option_incremental_or_composite_or_if__5111", "Option 'tsBuildInfoFile' cannot be specified without specifying option 'incremental' or 'composite' or if not running 'tsc -b'."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6e3, 3 /* 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, 3 /* Message */, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, 3 /* Message */, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -105326,7 +105154,6 @@ var Diagnostics = { Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: diag(6141, 3 /* Message */, "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141", 'Parse in strict mode and emit "use strict" for each source file.'), Module_0_was_resolved_to_1_but_jsx_is_not_set: diag(6142, 1 /* Error */, "Module_0_was_resolved_to_1_but_jsx_is_not_set_6142", "Module '{0}' was resolved to '{1}', but '--jsx' is not set."), Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1: diag(6144, 3 /* Message */, "Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1_6144", "Module '{0}' was resolved as locally declared ambient module in file '{1}'."), - Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified: diag(6145, 3 /* Message */, "Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified_6145", "Module '{0}' was resolved as ambient module declared in '{1}' since this file was not modified."), Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h: diag(6146, 3 /* Message */, "Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h_6146", "Specify the JSX factory function to use when targeting 'react' JSX emit, e.g. 'React.createElement' or 'h'."), Resolution_for_module_0_was_found_in_cache_from_location_1: diag(6147, 3 /* Message */, "Resolution_for_module_0_was_found_in_cache_from_location_1_6147", "Resolution for module '{0}' was found in cache from location '{1}'."), Directory_0_does_not_exist_skipping_all_lookups_in_it: diag(6148, 3 /* Message */, "Directory_0_does_not_exist_skipping_all_lookups_in_it_6148", "Directory '{0}' does not exist, skipping all lookups in it."), @@ -105568,6 +105395,8 @@ var Diagnostics = { Exiting_conditional_exports: diag(6416, 3 /* Message */, "Exiting_conditional_exports_6416", "Exiting conditional exports."), Searching_all_ancestor_node_modules_directories_for_preferred_extensions_Colon_0: diag(6417, 3 /* Message */, "Searching_all_ancestor_node_modules_directories_for_preferred_extensions_Colon_0_6417", "Searching all ancestor node_modules directories for preferred extensions: {0}."), Searching_all_ancestor_node_modules_directories_for_fallback_extensions_Colon_0: diag(6418, 3 /* Message */, "Searching_all_ancestor_node_modules_directories_for_fallback_extensions_Colon_0_6418", "Searching all ancestor node_modules directories for fallback extensions: {0}."), + Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_program_needs_to_report_errors: diag(6419, 3 /* Message */, "Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_program_needs_to_report_errors_6419", "Project '{0}' is out of date because buildinfo file '{1}' indicates that program needs to report errors."), + Project_0_is_out_of_date_because_1: diag(6420, 3 /* Message */, "Project_0_is_out_of_date_because_1_6420", "Project '{0}' is out of date because {1}."), The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, 3 /* 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, 3 /* 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, 3 /* Message */, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), @@ -105614,6 +105443,7 @@ var Diagnostics = { Ensure_that_casing_is_correct_in_imports: diag(6637, 3 /* Message */, "Ensure_that_casing_is_correct_in_imports_6637", "Ensure that casing is correct in imports."), Emit_a_v8_CPU_profile_of_the_compiler_run_for_debugging: diag(6638, 3 /* Message */, "Emit_a_v8_CPU_profile_of_the_compiler_run_for_debugging_6638", "Emit a v8 CPU profile of the compiler run for debugging."), Allow_importing_helper_functions_from_tslib_once_per_project_instead_of_including_them_per_file: diag(6639, 3 /* Message */, "Allow_importing_helper_functions_from_tslib_once_per_project_instead_of_including_them_per_file_6639", "Allow importing helper functions from tslib once per project, instead of including them per-file."), + Skip_building_downstream_projects_on_error_in_upstream_project: diag(6640, 3 /* Message */, "Skip_building_downstream_projects_on_error_in_upstream_project_6640", "Skip building downstream projects on error in upstream project."), Specify_a_list_of_glob_patterns_that_match_files_to_be_included_in_compilation: diag(6641, 3 /* Message */, "Specify_a_list_of_glob_patterns_that_match_files_to_be_included_in_compilation_6641", "Specify a list of glob patterns that match files to be included in compilation."), Save_tsbuildinfo_files_to_allow_for_incremental_compilation_of_projects: diag(6642, 3 /* Message */, "Save_tsbuildinfo_files_to_allow_for_incremental_compilation_of_projects_6642", "Save .tsbuildinfo files to allow for incremental compilation of projects."), Include_sourcemap_files_inside_the_emitted_JavaScript: diag(6643, 3 /* Message */, "Include_sourcemap_files_inside_the_emitted_JavaScript_6643", "Include sourcemap files inside the emitted JavaScript."), @@ -105690,9 +105520,12 @@ var Diagnostics = { Require_undeclared_properties_from_index_signatures_to_use_element_accesses: diag(6717, 3 /* Message */, "Require_undeclared_properties_from_index_signatures_to_use_element_accesses_6717", "Require undeclared properties from index signatures to use element accesses."), Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types: diag(6718, 3 /* Message */, "Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types_6718", "Specify emit/checking behavior for imports that are only used for types."), Require_sufficient_annotation_on_exports_so_other_tools_can_trivially_generate_declaration_files: diag(6719, 3 /* Message */, "Require_sufficient_annotation_on_exports_so_other_tools_can_trivially_generate_declaration_files_6719", "Require sufficient annotation on exports so other tools can trivially generate declaration files."), + Built_in_iterators_are_instantiated_with_a_TReturn_type_of_undefined_instead_of_any: diag(6720, 3 /* Message */, "Built_in_iterators_are_instantiated_with_a_TReturn_type_of_undefined_instead_of_any_6720", "Built-in iterators are instantiated with a 'TReturn' type of 'undefined' instead of 'any'."), Default_catch_clause_variables_as_unknown_instead_of_any: diag(6803, 3 /* Message */, "Default_catch_clause_variables_as_unknown_instead_of_any_6803", "Default catch clause variables as 'unknown' instead of 'any'."), Do_not_transform_or_elide_any_imports_or_exports_not_marked_as_type_only_ensuring_they_are_written_in_the_output_file_s_format_based_on_the_module_setting: diag(6804, 3 /* Message */, "Do_not_transform_or_elide_any_imports_or_exports_not_marked_as_type_only_ensuring_they_are_written_i_6804", "Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting."), Disable_full_type_checking_only_critical_parse_and_emit_errors_will_be_reported: diag(6805, 3 /* Message */, "Disable_full_type_checking_only_critical_parse_and_emit_errors_will_be_reported_6805", "Disable full type checking (only critical parse and emit errors will be reported)."), + Check_side_effect_imports: diag(6806, 3 /* Message */, "Check_side_effect_imports_6806", "Check side effect imports."), + This_operation_can_be_simplified_This_shift_is_identical_to_0_1_2: diag(6807, 1 /* Error */, "This_operation_can_be_simplified_This_shift_is_identical_to_0_1_2_6807", "This operation can be simplified. This shift is identical to `{0} {1} {2}`."), one_of_Colon: diag(6900, 3 /* Message */, "one_of_Colon_6900", "one of:"), one_or_more_Colon: diag(6901, 3 /* Message */, "one_or_more_Colon_6901", "one or more:"), type_Colon: diag(6902, 3 /* Message */, "type_Colon_6902", "type:"), @@ -106186,7 +106019,8 @@ var Diagnostics = { Its_type_0_is_not_a_valid_JSX_element_type: diag(18053, 1 /* Error */, "Its_type_0_is_not_a_valid_JSX_element_type_18053", "Its type '{0}' is not a valid JSX element type."), await_using_statements_cannot_be_used_inside_a_class_static_block: diag(18054, 1 /* Error */, "await_using_statements_cannot_be_used_inside_a_class_static_block_18054", "'await using' statements cannot be used inside a class static block."), _0_has_a_string_type_but_must_have_syntactically_recognizable_string_syntax_when_isolatedModules_is_enabled: diag(18055, 1 /* Error */, "_0_has_a_string_type_but_must_have_syntactically_recognizable_string_syntax_when_isolatedModules_is__18055", "'{0}' has a string type, but must have syntactically recognizable string syntax when 'isolatedModules' is enabled."), - Enum_member_following_a_non_literal_numeric_member_must_have_an_initializer_when_isolatedModules_is_enabled: diag(18056, 1 /* Error */, "Enum_member_following_a_non_literal_numeric_member_must_have_an_initializer_when_isolatedModules_is__18056", "Enum member following a non-literal numeric member must have an initializer when 'isolatedModules' is enabled.") + Enum_member_following_a_non_literal_numeric_member_must_have_an_initializer_when_isolatedModules_is_enabled: diag(18056, 1 /* Error */, "Enum_member_following_a_non_literal_numeric_member_must_have_an_initializer_when_isolatedModules_is__18056", "Enum member following a non-literal numeric member must have an initializer when 'isolatedModules' is enabled."), + String_literal_import_and_export_names_are_not_supported_when_the_module_flag_is_set_to_es2015_or_es2020: diag(18057, 1 /* Error */, "String_literal_import_and_export_names_are_not_supported_when_the_module_flag_is_set_to_es2015_or_es_18057", "String literal import and export names are not supported when the '--module' flag is set to 'es2015' or 'es2020'.") }; // src/compiler/scanner.ts @@ -106346,16 +106180,16 @@ var textToToken = new Map(Object.entries({ "#": 63 /* HashToken */, "`": 62 /* BacktickToken */ })); -var charToRegExpFlag = new Map(Object.entries({ - d: 1 /* HasIndices */, - g: 2 /* Global */, - i: 4 /* IgnoreCase */, - m: 8 /* Multiline */, - s: 16 /* DotAll */, - u: 32 /* Unicode */, - v: 64 /* UnicodeSets */, - y: 128 /* Sticky */ -})); +var charCodeToRegExpFlag = /* @__PURE__ */ new Map([ + [100 /* d */, 1 /* HasIndices */], + [103 /* g */, 2 /* Global */], + [105 /* i */, 4 /* IgnoreCase */], + [109 /* m */, 8 /* Multiline */], + [115 /* s */, 16 /* DotAll */], + [117 /* u */, 32 /* Unicode */], + [118 /* v */, 64 /* UnicodeSets */], + [121 /* y */, 128 /* Sticky */] +]); var regExpFlagToFirstAvailableLanguageVersion = /* @__PURE__ */ new Map([ [1 /* HasIndices */, 9 /* RegularExpressionFlagsHasIndices */], [16 /* DotAll */, 5 /* RegularExpressionFlagsDotAll */], @@ -106411,12 +106245,12 @@ function tokenToString(t) { function stringToToken(s) { return textToToken.get(s); } -var regExpFlagChars = makeReverseMap(charToRegExpFlag); -function regularExpressionFlagToCharacter(f) { - return regExpFlagChars[f]; +var regExpFlagCharCodes = makeReverseMap(charCodeToRegExpFlag); +function regularExpressionFlagToCharacterCode(f) { + return regExpFlagCharCodes[f]; } -function characterToRegularExpressionFlag(c) { - return charToRegExpFlag.get(c); +function characterCodeToRegularExpressionFlag(ch) { + return charCodeToRegExpFlag.get(ch); } function computeLineStarts(text) { const result = []; @@ -106453,7 +106287,7 @@ function computePositionOfLineAndCharacter(lineStarts, line, character, debugTex if (allowEdits) { line = line < 0 ? 0 : line >= lineStarts.length ? lineStarts.length - 1 : line; } else { - Debug.fail(`Bad line number. Line: ${line}, lineStarts.length: ${lineStarts.length} , line map is correct? ${debugText !== void 0 ? arraysEqual(lineStarts, computeLineStarts(debugText)) : "unknown"}`); + Debug.fail(`Bad line number. Line: ${line}, lineStarts.length: ${lineStarts.length} , line map is correct? ${debugText !== void 0 ? arrayIsEqualTo(lineStarts, computeLineStarts(debugText)) : "unknown"}`); } } const res = lineStarts[line] + character; @@ -106885,7 +106719,6 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan var tokenFlags; var commentDirectives; var skipJsDocLeadingAsterisks = 0; - var asteriskSeen = false; var scriptKind = 0 /* Unknown */; var jsDocParsingMode = 0 /* ParseAll */; setText(text, start, length2); @@ -106903,6 +106736,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan hasExtendedUnicodeEscape: () => (tokenFlags & 8 /* ExtendedUnicodeEscape */) !== 0, hasPrecedingLineBreak: () => (tokenFlags & 1 /* PrecedingLineBreak */) !== 0, hasPrecedingJSDocComment: () => (tokenFlags & 2 /* PrecedingJSDocComment */) !== 0, + hasPrecedingJSDocLeadingAsterisks: () => (tokenFlags & 32768 /* PrecedingJSDocLeadingAsterisks */) !== 0, isIdentifier: () => token === 80 /* Identifier */ || token > 118 /* LastReservedWord */, isReservedWord: () => token >= 83 /* FirstReservedWord */ && token <= 118 /* LastReservedWord */, isUnterminated: () => (tokenFlags & 4 /* Unterminated */) !== 0, @@ -106937,7 +106771,6 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan resetTokenState, setTextPos: resetTokenState, setSkipJsDocLeadingAsterisks, - hasLeadingAsterisks, tryScan, lookAhead, scanRange @@ -107320,9 +107153,16 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan case 34 /* doubleQuote */: return '"'; case 117 /* u */: - if (flags & 17 /* ScanExtendedUnicodeEscape */ && pos < end && charCodeUnchecked(pos) === 123 /* openBrace */) { + if (pos < end && charCodeUnchecked(pos) === 123 /* openBrace */) { pos -= 2; - return scanExtendedUnicodeEscape(!!(flags & 6 /* ReportInvalidEscapeErrors */)); + const result = scanExtendedUnicodeEscape(!!(flags & 6 /* ReportInvalidEscapeErrors */)); + if (!(flags & 17 /* AllowExtendedUnicodeEscape */)) { + tokenFlags |= 2048 /* ContainsInvalidEscape */; + if (flags & 6 /* ReportInvalidEscapeErrors */) { + error2(Diagnostics.Unicode_escape_sequences_are_only_available_when_the_Unicode_u_flag_or_the_Unicode_Sets_v_flag_is_set, start2, pos - start2); + } + } + return result; } for (; pos < start2 + 6; pos++) { if (!(pos < end && isHexDigit(charCodeUnchecked(pos)))) { @@ -107340,7 +107180,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan const nextStart = pos; let nextPos = pos + 2; for (; nextPos < nextStart + 6; nextPos++) { - if (!isHexDigit(charCodeUnchecked(pos))) { + if (!isHexDigit(charCodeUnchecked(nextPos))) { return escapedValueString; } } @@ -107544,7 +107384,6 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan function scan() { fullStartPos = pos; tokenFlags = 0 /* None */; - asteriskSeen = false; while (true) { tokenStart = pos; if (pos >= end) { @@ -107660,8 +107499,8 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan return pos += 2, token = 43 /* AsteriskAsteriskToken */; } pos++; - if (skipJsDocLeadingAsterisks && !asteriskSeen && tokenFlags & 1 /* PrecedingLineBreak */) { - asteriskSeen = true; + if (skipJsDocLeadingAsterisks && (tokenFlags & 32768 /* PrecedingJSDocLeadingAsterisks */) === 0 && tokenFlags & 1 /* PrecedingLineBreak */) { + tokenFlags |= 32768 /* PrecedingJSDocLeadingAsterisks */; continue; } return token = 42 /* AsteriskToken */; @@ -108134,24 +107973,25 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan pos++; let regExpFlags = 0 /* None */; while (true) { - const ch = charCodeChecked(pos); + const ch = codePointChecked(pos); if (ch === -1 /* EOF */ || !isIdentifierPart(ch, languageVersion)) { break; } + const size = charSize(ch); if (reportErrors2) { - const flag = characterToRegularExpressionFlag(String.fromCharCode(ch)); + const flag = characterCodeToRegularExpressionFlag(ch); if (flag === void 0) { - error2(Diagnostics.Unknown_regular_expression_flag, pos, 1); + error2(Diagnostics.Unknown_regular_expression_flag, pos, size); } else if (regExpFlags & flag) { - error2(Diagnostics.Duplicate_regular_expression_flag, pos, 1); + error2(Diagnostics.Duplicate_regular_expression_flag, pos, size); } else if (((regExpFlags | flag) & 96 /* AnyUnicodeMode */) === 96 /* AnyUnicodeMode */) { - error2(Diagnostics.The_Unicode_u_flag_and_the_Unicode_Sets_v_flag_cannot_be_set_simultaneously, pos, 1); + error2(Diagnostics.The_Unicode_u_flag_and_the_Unicode_Sets_v_flag_cannot_be_set_simultaneously, pos, size); } else { regExpFlags |= flag; - checkRegularExpressionFlagAvailable(flag, pos); + checkRegularExpressionFlagAvailability(flag, size); } } - pos++; + pos += size; } if (reportErrors2) { scanRange(startOfRegExpBody, endOfRegExpBody - startOfRegExpBody, () => { @@ -108366,22 +108206,23 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan } function scanPatternModifiers(currFlags) { while (true) { - const ch = charCodeChecked(pos); + const ch = codePointChecked(pos); if (ch === -1 /* EOF */ || !isIdentifierPart(ch, languageVersion)) { break; } - const flag = characterToRegularExpressionFlag(String.fromCharCode(ch)); + const size = charSize(ch); + const flag = characterCodeToRegularExpressionFlag(ch); if (flag === void 0) { - error2(Diagnostics.Unknown_regular_expression_flag, pos, 1); + error2(Diagnostics.Unknown_regular_expression_flag, pos, size); } else if (currFlags & flag) { - error2(Diagnostics.Duplicate_regular_expression_flag, pos, 1); + error2(Diagnostics.Duplicate_regular_expression_flag, pos, size); } else if (!(flag & 28 /* Modifiers */)) { - error2(Diagnostics.This_regular_expression_flag_cannot_be_toggled_within_a_subpattern, pos, 1); + error2(Diagnostics.This_regular_expression_flag_cannot_be_toggled_within_a_subpattern, pos, size); } else { currFlags |= flag; - checkRegularExpressionFlagAvailable(flag, pos); + checkRegularExpressionFlagAvailability(flag, size); } - pos++; + pos += size; } return currFlags; } @@ -108967,7 +108808,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan return value; } function scanSourceCharacter() { - const size = anyUnicodeMode ? charSize(charCodeChecked(pos)) : 1; + const size = anyUnicodeMode ? charSize(codePointChecked(pos)) : 1; pos += size; return size > 0 ? text.substring(pos - size, pos) : ""; } @@ -108985,6 +108826,12 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan forEach(groupNameReferences, (reference) => { if (!(groupSpecifiers == null ? void 0 : groupSpecifiers.has(reference.name))) { error2(Diagnostics.There_is_no_capturing_group_named_0_in_this_regular_expression, reference.pos, reference.end - reference.pos, reference.name); + if (groupSpecifiers) { + const suggestion = getSpellingSuggestion(reference.name, groupSpecifiers, identity); + if (suggestion) { + error2(Diagnostics.Did_you_mean_0, reference.pos, reference.end - reference.pos, suggestion); + } + } } }); forEach(decimalEscapes, (escape) => { @@ -108997,10 +108844,10 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan } }); } - function checkRegularExpressionFlagAvailable(flag, pos2) { + function checkRegularExpressionFlagAvailability(flag, size) { const availableFrom = regExpFlagToFirstAvailableLanguageVersion.get(flag); if (availableFrom && languageVersion < availableFrom) { - error2(Diagnostics.This_regular_expression_flag_is_only_available_when_targeting_0_or_later, pos2, 1, getNameOfScriptTarget(availableFrom)); + error2(Diagnostics.This_regular_expression_flag_is_only_available_when_targeting_0_or_later, pos, size, getNameOfScriptTarget(availableFrom)); } } function appendIfCommentDirective(commentDirectives2, text2, commentDirectiveRegEx, lineStart) { @@ -109347,9 +109194,6 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan function setSkipJsDocLeadingAsterisks(skip) { skipJsDocLeadingAsterisks += skip ? 1 : -1; } - function hasLeadingAsterisks() { - return asteriskSeen; - } } function codePointAt(s, i) { return s.codePointAt(i); @@ -109435,12 +109279,18 @@ function textSpanIsEmpty(span) { function textSpanContainsPosition(span, position) { return position >= span.start && position < textSpanEnd(span); } -function textRangeContainsPositionInclusive(span, position) { - return position >= span.pos && position <= span.end; +function textRangeContainsPositionInclusive(range, position) { + return position >= range.pos && position <= range.end; } function textSpanContainsTextSpan(span, other) { return other.start >= span.start && textSpanEnd(other) <= textSpanEnd(span); } +function textSpanContainsTextRange(span, range) { + return range.pos >= span.start && range.end <= textSpanEnd(span); +} +function textRangeContainsTextSpan(range, span) { + return span.start >= range.pos && textSpanEnd(span) <= range.end; +} function textSpanOverlapsWith(span, other) { return textSpanOverlap(span, other) !== void 0; } @@ -109462,11 +109312,34 @@ function decodedTextSpanIntersectsWith(start1, length1, start2, length2) { function textSpanIntersectsWithPosition(span, position) { return position <= textSpanEnd(span) && position >= span.start; } +function textRangeIntersectsWithTextSpan(range, span) { + return textSpanIntersectsWith(span, range.pos, range.end - range.pos); +} function textSpanIntersection(span1, span2) { const start = Math.max(span1.start, span2.start); const end = Math.min(textSpanEnd(span1), textSpanEnd(span2)); return start <= end ? createTextSpanFromBounds(start, end) : void 0; } +function normalizeSpans(spans) { + spans = spans.filter((span) => span.length > 0).sort((a, b) => { + return a.start !== b.start ? a.start - b.start : a.length - b.length; + }); + const result = []; + let i = 0; + while (i < spans.length) { + let span = spans[i]; + let j = i + 1; + while (j < spans.length && textSpanIntersectsWithTextSpan(span, spans[j])) { + const start = Math.min(span.start, spans[j].start); + const end = Math.max(textSpanEnd(span), textSpanEnd(spans[j])); + span = createTextSpanFromBounds(start, end); + j++; + } + i = j; + result.push(span); + } + return result; +} function createTextSpan(start, length2) { if (start < 0) { throw new Error("start < 0"); @@ -109584,7 +109457,7 @@ function getNodeFlags(node) { var supportedLocaleDirectories = ["cs", "de", "es", "fr", "it", "ja", "ko", "pl", "pt-br", "ru", "tr", "zh-cn", "zh-tw"]; function validateLocaleAndSetLanguage(locale, sys2, errors) { const lowerCaseLocale = locale.toLowerCase(); - const matchResult = /^([a-z]+)([_-]([a-z]+))?$/.exec(lowerCaseLocale); + const matchResult = /^([a-z]+)(?:[_-]([a-z]+))?$/.exec(lowerCaseLocale); if (!matchResult) { if (errors) { errors.push(createCompilerDiagnostic(Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp")); @@ -109592,7 +109465,7 @@ function validateLocaleAndSetLanguage(locale, sys2, errors) { return; } const language = matchResult[1]; - const territory = matchResult[3]; + const territory = matchResult[2]; if (contains(supportedLocaleDirectories, lowerCaseLocale) && !trySetLanguageAndTerritory(language, territory, errors)) { trySetLanguageAndTerritory( language, @@ -109616,7 +109489,7 @@ function validateLocaleAndSetLanguage(locale, sys2, errors) { let fileContents = ""; try { fileContents = sys2.readFile(filePath); - } catch (e) { + } catch { if (errors2) { errors2.push(createCompilerDiagnostic(Diagnostics.Unable_to_open_file_0, filePath)); } @@ -110015,13 +109888,6 @@ function getJSDocTags(node) { false ); } -function getJSDocTagsNoCache(node) { - return getJSDocTagsWorker( - node, - /*noCache*/ - true - ); -} function getFirstJSDocTag(node, predicate, noCache) { return find(getJSDocTagsWorker(node, noCache), predicate); } @@ -110124,9 +109990,6 @@ function isNamedExportBindings(node) { function isJSDocPropertyLikeTag(node) { return node.kind === 348 /* JSDocPropertyTag */ || node.kind === 341 /* JSDocParameterTag */; } -function isNode(node) { - return isNodeKind(node.kind); -} function isNodeKind(kind) { return kind >= 166 /* FirstNode */; } @@ -110338,17 +110201,6 @@ function isMethodOrAccessor(node) { return false; } } -function isNamedClassElement(node) { - switch (node.kind) { - case 174 /* MethodDeclaration */: - case 177 /* GetAccessor */: - case 178 /* SetAccessor */: - case 172 /* PropertyDeclaration */: - return true; - default: - return false; - } -} function isModifierLike(node) { return isModifier(node) || isDecorator(node); } @@ -110582,9 +110434,6 @@ function isAssertionExpression(node) { const kind = node.kind; return kind === 216 /* TypeAssertionExpression */ || kind === 234 /* AsExpression */; } -function isNotEmittedOrPartiallyEmittedNode(node) { - return isNotEmittedStatement(node) || isPartiallyEmittedExpression(node); -} function isIterationStatement(node, lookInLabeledStatements) { switch (node.kind) { case 248 /* ForStatement */: @@ -111069,6 +110918,12 @@ function projectReferenceIsEqualTo(oldRef, newRef) { function moduleResolutionIsEqualTo(oldResolution, newResolution) { return oldResolution === newResolution || oldResolution.resolvedModule === newResolution.resolvedModule || !!oldResolution.resolvedModule && !!newResolution.resolvedModule && oldResolution.resolvedModule.isExternalLibraryImport === newResolution.resolvedModule.isExternalLibraryImport && oldResolution.resolvedModule.extension === newResolution.resolvedModule.extension && oldResolution.resolvedModule.resolvedFileName === newResolution.resolvedModule.resolvedFileName && oldResolution.resolvedModule.originalPath === newResolution.resolvedModule.originalPath && packageIdIsEqual(oldResolution.resolvedModule.packageId, newResolution.resolvedModule.packageId) && oldResolution.alternateResult === newResolution.alternateResult; } +function getResolvedModuleFromResolution(resolution) { + return resolution.resolvedModule; +} +function getResolvedTypeReferenceDirectiveFromResolution(resolution) { + return resolution.resolvedTypeReferenceDirective; +} function createModuleNotFoundChain(sourceFile, host, moduleReference, mode, packageName) { var _a; const alternateResult = (_a = host.getResolvedModule(sourceFile, moduleReference, mode)) == null ? void 0 : _a.alternateResult; @@ -111103,6 +110958,34 @@ function createModuleNotFoundChain(sourceFile, host, moduleReference, mode, pack if (result) result.repopulateInfo = () => ({ moduleReference, mode, packageName: packageName === moduleReference ? void 0 : packageName }); return result; } +function createModeMismatchDetails(currentSourceFile) { + const ext = tryGetExtensionFromPath2(currentSourceFile.fileName); + const scope = currentSourceFile.packageJsonScope; + const targetExt = ext === ".ts" /* Ts */ ? ".mts" /* Mts */ : ext === ".js" /* Js */ ? ".mjs" /* Mjs */ : void 0; + const result = scope && !scope.contents.packageJsonContent.type ? targetExt ? chainDiagnosticMessages( + /*details*/ + void 0, + Diagnostics.To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_add_the_field_type_Colon_module_to_1, + targetExt, + combinePaths(scope.packageDirectory, "package.json") + ) : chainDiagnosticMessages( + /*details*/ + void 0, + Diagnostics.To_convert_this_file_to_an_ECMAScript_module_add_the_field_type_Colon_module_to_0, + combinePaths(scope.packageDirectory, "package.json") + ) : targetExt ? chainDiagnosticMessages( + /*details*/ + void 0, + Diagnostics.To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_create_a_local_package_json_file_with_type_Colon_module, + targetExt + ) : chainDiagnosticMessages( + /*details*/ + void 0, + Diagnostics.To_convert_this_file_to_an_ECMAScript_module_create_a_local_package_json_file_with_type_Colon_module + ); + result.repopulateInfo = () => true; + return result; +} function packageIdIsEqual(a, b) { return a === b || !!a && !!b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version && a.peerDependencies === b.peerDependencies; } @@ -111328,6 +111211,13 @@ function getNonDecoratorTokenPosOfNode(node, sourceFile) { } return skipTrivia((sourceFile || getSourceFileOfNode(node)).text, lastDecorator.end); } +function getNonModifierTokenPosOfNode(node, sourceFile) { + const lastModifier = !nodeIsMissing(node) && canHaveModifiers(node) && node.modifiers ? last(node.modifiers) : void 0; + if (!lastModifier) { + return getTokenPosOfNode(node, sourceFile); + } + return skipTrivia((sourceFile || getSourceFileOfNode(node)).text, lastModifier.end); +} function getSourceTextOfNodeFromSourceFile(sourceFile, node, includeTrivia = false) { return getTextOfNodeFromSourceText(sourceFile.text, node, includeTrivia); } @@ -111335,7 +111225,16 @@ function isJSDocTypeExpressionOrChild(node) { return !!findAncestor(node, isJSDocTypeExpression); } function isExportNamespaceAsDefaultDeclaration(node) { - return !!(isExportDeclaration(node) && node.exportClause && isNamespaceExport(node.exportClause) && node.exportClause.name.escapedText === "default"); + return !!(isExportDeclaration(node) && node.exportClause && isNamespaceExport(node.exportClause) && moduleExportNameIsDefault(node.exportClause.name)); +} +function moduleExportNameTextUnescaped(node) { + return node.kind === 11 /* StringLiteral */ ? node.text : unescapeLeadingUnderscores(node.escapedText); +} +function moduleExportNameTextEscaped(node) { + return node.kind === 11 /* StringLiteral */ ? escapeLeadingUnderscores(node.text) : node.escapedText; +} +function moduleExportNameIsDefault(node) { + return (node.kind === 11 /* StringLiteral */ ? node.text : node.escapedText) === "default" /* Default */; } function getTextOfNodeFromSourceText(sourceText, node, includeTrivia = false) { if (nodeIsMissing(node)) { @@ -111388,7 +111287,11 @@ var getScriptTargetFeatures = /* @__PURE__ */ memoize( ], es2023: [ "findLastIndex", - "findLast" + "findLast", + "toReversed", + "toSorted", + "toSpliced", + "with" ] })), Iterator: new Map(Object.entries({ @@ -111665,7 +111568,11 @@ var getScriptTargetFeatures = /* @__PURE__ */ memoize( ], es2023: [ "findLastIndex", - "findLast" + "findLast", + "toReversed", + "toSorted", + "toSpliced", + "with" ] })), Uint8Array: new Map(Object.entries({ @@ -111674,7 +111581,11 @@ var getScriptTargetFeatures = /* @__PURE__ */ memoize( ], es2023: [ "findLastIndex", - "findLast" + "findLast", + "toReversed", + "toSorted", + "toSpliced", + "with" ] })), Uint8ClampedArray: new Map(Object.entries({ @@ -111683,7 +111594,11 @@ var getScriptTargetFeatures = /* @__PURE__ */ memoize( ], es2023: [ "findLastIndex", - "findLast" + "findLast", + "toReversed", + "toSorted", + "toSpliced", + "with" ] })), Int16Array: new Map(Object.entries({ @@ -111692,7 +111607,11 @@ var getScriptTargetFeatures = /* @__PURE__ */ memoize( ], es2023: [ "findLastIndex", - "findLast" + "findLast", + "toReversed", + "toSorted", + "toSpliced", + "with" ] })), Uint16Array: new Map(Object.entries({ @@ -111701,7 +111620,11 @@ var getScriptTargetFeatures = /* @__PURE__ */ memoize( ], es2023: [ "findLastIndex", - "findLast" + "findLast", + "toReversed", + "toSorted", + "toSpliced", + "with" ] })), Int32Array: new Map(Object.entries({ @@ -111710,7 +111633,11 @@ var getScriptTargetFeatures = /* @__PURE__ */ memoize( ], es2023: [ "findLastIndex", - "findLast" + "findLast", + "toReversed", + "toSorted", + "toSpliced", + "with" ] })), Uint32Array: new Map(Object.entries({ @@ -111719,7 +111646,11 @@ var getScriptTargetFeatures = /* @__PURE__ */ memoize( ], es2023: [ "findLastIndex", - "findLast" + "findLast", + "toReversed", + "toSorted", + "toSpliced", + "with" ] })), Float32Array: new Map(Object.entries({ @@ -111728,7 +111659,11 @@ var getScriptTargetFeatures = /* @__PURE__ */ memoize( ], es2023: [ "findLastIndex", - "findLast" + "findLast", + "toReversed", + "toSorted", + "toSpliced", + "with" ] })), Float64Array: new Map(Object.entries({ @@ -111737,7 +111672,11 @@ var getScriptTargetFeatures = /* @__PURE__ */ memoize( ], es2023: [ "findLastIndex", - "findLast" + "findLast", + "toReversed", + "toSorted", + "toSpliced", + "with" ] })), BigInt64Array: new Map(Object.entries({ @@ -111747,7 +111686,11 @@ var getScriptTargetFeatures = /* @__PURE__ */ memoize( ], es2023: [ "findLastIndex", - "findLast" + "findLast", + "toReversed", + "toSorted", + "toSpliced", + "with" ] })), BigUint64Array: new Map(Object.entries({ @@ -111757,7 +111700,11 @@ var getScriptTargetFeatures = /* @__PURE__ */ memoize( ], es2023: [ "findLastIndex", - "findLast" + "findLast", + "toReversed", + "toSorted", + "toSpliced", + "with" ] })), Error: new Map(Object.entries({ @@ -112048,6 +111995,7 @@ function tryGetTextOfPropertyName(name) { return ((_a = name.emitNode) == null ? void 0 : _a.autoGenerate) ? void 0 : name.escapedText; case 11 /* StringLiteral */: case 9 /* NumericLiteral */: + case 10 /* BigIntLiteral */: case 15 /* NoSubstitutionTemplateLiteral */: return escapeLeadingUnderscores(name.text); case 167 /* ComputedPropertyName */: @@ -112356,12 +112304,12 @@ function getJSDocCommentRanges(node, text) { return filter(commentRanges, (comment) => comment.end <= node.end && // Due to parse errors sometime empty parameter may get comments assigned to it that end up not in parameter range text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ && text.charCodeAt(comment.pos + 2) === 42 /* asterisk */ && text.charCodeAt(comment.pos + 3) !== 47 /* slash */); } -var fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*/; -var fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^(\/\/\/\s*/; -var fullTripleSlashLibReferenceRegEx = /^(\/\/\/\s*/; -var fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; -var fullTripleSlashAMDModuleRegEx = /^\/\/\/\s*/; -var defaultLibReferenceRegEx = /^(\/\/\/\s*/; +var fullTripleSlashReferencePathRegEx = /^\/\/\/\s*/; +var fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^\/\/\/\s*/; +var fullTripleSlashLibReferenceRegEx = /^\/\/\/\s*/; +var fullTripleSlashAMDReferencePathRegEx = /^\/\/\/\s*/; +var fullTripleSlashAMDModuleRegEx = /^\/\/\/\s*/; +var defaultLibReferenceRegEx = /^\/\/\/\s*/; function isPartOfTypeNode(node) { if (182 /* FirstTypeNode */ <= node.kind && node.kind <= 205 /* LastTypeNode */) { return true; @@ -112444,15 +112392,6 @@ function isPartOfTypeNode(node) { function isPartOfTypeExpressionWithTypeArguments(node) { return isJSDocImplementsTag(node.parent) || isJSDocAugmentsTag(node.parent) || isHeritageClause(node.parent) && !isExpressionWithTypeArgumentsInClassExtendsClause(node); } -function isChildOfNodeWithKind(node, kind) { - while (node) { - if (node.kind === kind) { - return true; - } - node = node.parent; - } - return false; -} function forEachReturnStatement(body, visitor) { return traverse(body); function traverse(node) { @@ -112789,9 +112728,6 @@ function getImmediatelyInvokedFunctionExpression(func) { } } } -function isSuperOrSuperProperty(node) { - return node.kind === 108 /* SuperKeyword */ || isSuperProperty(node); -} function isSuperProperty(node) { const kind = node.kind; return (kind === 211 /* PropertyAccessExpression */ || kind === 212 /* ElementAccessExpression */) && node.expression.kind === 108 /* SuperKeyword */; @@ -113065,9 +113001,6 @@ function isFullSourceFile(sourceFile) { function isSourceFileJS(file) { return isInJSFile(file); } -function isSourceFileNotJS(file) { - return !isInJSFile(file); -} function isInJSFile(node) { return !!node && !!(node.flags & 524288 /* JavaScriptFile */); } @@ -113369,6 +113302,23 @@ function isFunctionSymbol(symbol) { const decl = symbol.valueDeclaration; return decl.kind === 262 /* FunctionDeclaration */ || isVariableDeclaration(decl) && decl.initializer && isFunctionLike(decl.initializer); } +function canHaveModuleSpecifier(node) { + switch (node == null ? void 0 : node.kind) { + case 260 /* VariableDeclaration */: + case 208 /* BindingElement */: + case 272 /* ImportDeclaration */: + case 278 /* ExportDeclaration */: + case 271 /* ImportEqualsDeclaration */: + case 273 /* ImportClause */: + case 280 /* NamespaceExport */: + case 274 /* NamespaceImport */: + case 281 /* ExportSpecifier */: + case 276 /* ImportSpecifier */: + case 205 /* ImportType */: + return true; + } + return false; +} function tryGetModuleSpecifierFromDeclaration(node) { var _a, _b; switch (node.kind) { @@ -113850,7 +113800,7 @@ function skipTypeParentheses(node) { return node; } function skipParentheses(node, excludeJSDocTypeAssertions) { - const flags = excludeJSDocTypeAssertions ? 1 /* Parentheses */ | 16 /* ExcludeJSDocTypeAssertion */ : 1 /* Parentheses */; + const flags = excludeJSDocTypeAssertions ? 1 /* Parentheses */ | -2147483648 /* ExcludeJSDocTypeAssertion */ : 1 /* Parentheses */; return skipOuterExpressions(node, flags); } function isDeleteTarget(node) { @@ -113923,12 +113873,6 @@ function isIdentifierName(node) { } return false; } -function isAliasSymbolDeclaration(node) { - if (node.kind === 271 /* ImportEqualsDeclaration */ || node.kind === 270 /* NamespaceExportDeclaration */ || node.kind === 273 /* ImportClause */ && !!node.name || node.kind === 274 /* NamespaceImport */ || node.kind === 280 /* NamespaceExport */ || node.kind === 276 /* ImportSpecifier */ || node.kind === 281 /* ExportSpecifier */ || node.kind === 277 /* ExportAssignment */ && exportAssignmentIsAlias(node)) { - return true; - } - return isInJSFile(node) && (isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ && exportAssignmentIsAlias(node) || isPropertyAccessExpression(node) && isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 64 /* EqualsToken */ && isAliasableExpression(node.parent.right)); -} function getAliasDeclarationFromName(node) { switch (node.parent.kind) { case 273 /* ImportClause */: @@ -114022,17 +113966,10 @@ function isContextualKeyword(token) { function isNonContextualKeyword(token) { return isKeyword(token) && !isContextualKeyword(token); } -function isFutureReservedKeyword(token) { - return 119 /* FirstFutureReservedWord */ <= token && token <= 127 /* LastFutureReservedWord */; -} function isStringANonContextualKeyword(name) { const token = stringToToken(name); return token !== void 0 && isNonContextualKeyword(token); } -function isStringAKeyword(name) { - const token = stringToToken(name); - return token !== void 0 && isKeyword(token); -} function isIdentifierANonContextualKeyword(node) { const originalKeywordKind = identifierToKeywordKind(node); return !!originalKeywordKind && !isContextualKeyword(originalKeywordKind); @@ -114106,6 +114043,7 @@ function getPropertyNameForPropertyNameNode(name) { case 11 /* StringLiteral */: case 15 /* NoSubstitutionTemplateLiteral */: case 9 /* NumericLiteral */: + case 10 /* BigIntLiteral */: return escapeLeadingUnderscores(name.text); case 167 /* ComputedPropertyName */: const nameExpression = name.expression; @@ -114141,9 +114079,6 @@ function getTextOfIdentifierOrLiteral(node) { function getEscapedTextOfIdentifierOrLiteral(node) { return isMemberName(node) ? node.escapedText : isJsxNamespacedName(node) ? getEscapedTextOfJsxNamespacedName(node) : escapeLeadingUnderscores(node.text); } -function getPropertyNameForUniqueESSymbol(symbol) { - return `__@${getSymbolId(symbol)}@${symbol.escapedName}`; -} function getSymbolNameForPrivateIdentifier(containingClassSymbol, description3) { return `__#${getSymbolId(containingClassSymbol)}@${description3}`; } @@ -114153,9 +114088,6 @@ function isKnownSymbol(symbol) { function isPrivateIdentifierSymbol(symbol) { return startsWith(symbol.escapedName, "__#"); } -function isESSymbolIdentifier(node) { - return node.kind === 80 /* Identifier */ && node.escapedText === "Symbol"; -} function isProtoSetter(node) { return isIdentifier(node) ? idText(node) === "__proto__" : isStringLiteral(node) && node.text === "__proto__"; } @@ -114245,9 +114177,6 @@ function nodeStartsNewLexicalEnvironment(node) { function nodeIsSynthesized(range) { return positionIsSynthesized(range.pos) || positionIsSynthesized(range.end); } -function getOriginalSourceFile(sourceFile) { - return getParseTreeNode(sourceFile, isSourceFile) || sourceFile; -} var Associativity = /* @__PURE__ */ ((Associativity2) => { Associativity2[Associativity2["Left"] = 0] = "Left"; Associativity2[Associativity2["Right"] = 1] = "Right"; @@ -114550,9 +114479,9 @@ function containsInvalidEscapeFlag(node) { function hasInvalidEscape(template) { return template && !!(isNoSubstitutionTemplateLiteral(template) ? containsInvalidEscapeFlag(template) : containsInvalidEscapeFlag(template.head) || some(template.templateSpans, (span) => containsInvalidEscapeFlag(span.literal))); } -var doubleQuoteEscapedCharsRegExp = /[\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; -var singleQuoteEscapedCharsRegExp = /[\\'\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; -var backtickQuoteEscapedCharsRegExp = /\r\n|[\\`\u0000-\u001f\t\v\f\b\r\u2028\u2029\u0085]/g; +var doubleQuoteEscapedCharsRegExp = /[\\"\u0000-\u001f\u2028\u2029\u0085]/g; +var singleQuoteEscapedCharsRegExp = /[\\'\u0000-\u001f\u2028\u2029\u0085]/g; +var backtickQuoteEscapedCharsRegExp = /\r\n|[\\`\u0000-\u001f\u2028\u2029\u0085]/g; var escapedCharsMap = new Map(Object.entries({ " ": "\\t", "\v": "\\v", @@ -115407,9 +115336,6 @@ function tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node) { function isAssignmentExpression(node, excludeCompoundAssignment) { return isBinaryExpression(node) && (excludeCompoundAssignment ? node.operatorToken.kind === 64 /* EqualsToken */ : isAssignmentOperator(node.operatorToken.kind)) && isLeftHandSideExpression(node.left); } -function isLeftHandSideOfAssignment(node) { - return isAssignmentExpression(node.parent) && node.parent.left === node; -} function isDestructuringAssignment(node) { if (isAssignmentExpression( node, @@ -115663,9 +115589,6 @@ function moveRangePastModifiers(node) { const lastModifier = canHaveModifiers(node) ? lastOrUndefined(node.modifiers) : void 0; return lastModifier && !positionIsSynthesized(lastModifier.end) ? moveRangePos(node, lastModifier.end) : moveRangePastDecorators(node); } -function isCollapsedRange(range) { - return range.pos === range.end; -} function createTokenRange(pos, token) { return createRange(pos, pos + tokenToString(token).length); } @@ -115907,9 +115830,6 @@ function getClassLikeDeclarationOfSymbol(symbol) { function getObjectFlags(type) { return type.flags & 3899393 /* ObjectFlagsType */ ? type.objectFlags : 0; } -function forSomeAncestorDirectory(directory, callback) { - return !!forEachAncestorDirectory(directory, (d) => callback(d) ? true : void 0); -} function isUMDExportSymbol(symbol) { return !!symbol && !!symbol.declarations && !!symbol.declarations[0] && isNamespaceExportDeclaration(symbol.declarations[0]); } @@ -116109,7 +116029,7 @@ function setObjectAllocator(alloc) { forEach(objectAllocatorPatchers, (fn) => fn(objectAllocator)); } function formatStringFromArgs(text, args) { - return text.replace(/{(\d+)}/g, (_match, index) => "" + Debug.checkDefined(args[+index])); + return text.replace(/\{(\d+)\}/g, (_match, index) => "" + Debug.checkDefined(args[+index])); } var localizedDiagnosticMessages; function setLocalizedDiagnosticMessages(messages) { @@ -116383,8 +116303,8 @@ function walkTreeForJSXTags(node) { function isFileModuleFromUsingJSXTag(file) { return !file.isDeclarationFile ? walkTreeForJSXTags(file) : void 0; } -function isFileForcedToBeModuleByFormat(file) { - return (file.impliedNodeFormat === 99 /* ESNext */ || fileExtensionIsOneOf(file.fileName, [".cjs" /* Cjs */, ".cts" /* Cts */, ".mjs" /* Mjs */, ".mts" /* Mts */])) && !file.isDeclarationFile ? true : void 0; +function isFileForcedToBeModuleByFormat(file, options) { + return (getImpliedNodeFormatForEmitWorker(file, options) === 99 /* ESNext */ || fileExtensionIsOneOf(file.fileName, [".cjs" /* Cjs */, ".cts" /* Cts */, ".mjs" /* Mjs */, ".mts" /* Mts */])) && !file.isDeclarationFile ? true : void 0; } function getSetExternalModuleIndicator(options) { switch (getEmitModuleDetectionKind(options)) { @@ -116403,10 +116323,14 @@ function getSetExternalModuleIndicator(options) { } checks.push(isFileForcedToBeModuleByFormat); const combined = or(...checks); - const callback = (file) => void (file.externalModuleIndicator = combined(file)); + const callback = (file) => void (file.externalModuleIndicator = combined(file, options)); return callback; } } +function importSyntaxAffectsModuleResolution(options) { + const moduleResolution = getEmitModuleResolutionKind(options); + return 3 /* Node16 */ <= moduleResolution && moduleResolution <= 99 /* NodeNext */ || getResolvePackageJsonExports(options) || getResolvePackageJsonImports(options); +} function createComputedCompilerOptions(options) { return options; } @@ -116605,6 +116529,12 @@ var computedOptions = createComputedCompilerOptions({ return getStrictOptionValue(compilerOptions, "strictPropertyInitialization"); } }, + strictBuiltinIteratorReturn: { + dependencies: ["strict"], + computeValue: (compilerOptions) => { + return getStrictOptionValue(compilerOptions, "strictBuiltinIteratorReturn"); + } + }, alwaysStrict: { dependencies: ["strict"], computeValue: (compilerOptions) => { @@ -116683,7 +116613,12 @@ function getJSXTransformEnabled(options) { function getJSXImplicitImportBase(compilerOptions, file) { const jsxImportSourcePragmas = file == null ? void 0 : file.pragmas.get("jsximportsource"); const jsxImportSourcePragma = isArray(jsxImportSourcePragmas) ? jsxImportSourcePragmas[jsxImportSourcePragmas.length - 1] : jsxImportSourcePragmas; - return compilerOptions.jsx === 4 /* ReactJSX */ || compilerOptions.jsx === 5 /* ReactJSXDev */ || compilerOptions.jsxImportSource || jsxImportSourcePragma ? (jsxImportSourcePragma == null ? void 0 : jsxImportSourcePragma.arguments.factory) || compilerOptions.jsxImportSource || "react" : void 0; + const jsxRuntimePragmas = file == null ? void 0 : file.pragmas.get("jsxruntime"); + const jsxRuntimePragma = isArray(jsxRuntimePragmas) ? jsxRuntimePragmas[jsxRuntimePragmas.length - 1] : jsxRuntimePragmas; + if ((jsxRuntimePragma == null ? void 0 : jsxRuntimePragma.arguments.factory) === "classic") { + return void 0; + } + return compilerOptions.jsx === 4 /* ReactJSX */ || compilerOptions.jsx === 5 /* ReactJSXDev */ || compilerOptions.jsxImportSource || jsxImportSourcePragma || (jsxRuntimePragma == null ? void 0 : jsxRuntimePragma.arguments.factory) === "automatic" ? (jsxImportSourcePragma == null ? void 0 : jsxImportSourcePragma.arguments.factory) || compilerOptions.jsxImportSource || "react" : void 0; } function getJSXRuntimeImport(base, options) { return base ? `${base}/${options.jsx === 5 /* ReactJSXDev */ ? "jsx-dev-runtime" : "jsx-runtime"}` : void 0; @@ -116927,7 +116862,7 @@ function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNa if (visited.has(canonicalPath)) return; visited.set(canonicalPath, true); const { files, directories } = getFileSystemEntries(path2); - for (const current of sort(files, compareStringsCaseSensitive)) { + for (const current of toSorted(files, compareStringsCaseSensitive)) { const name = combinePaths(path2, current); const absoluteName = combinePaths(absolutePath, current); if (extensions && !fileExtensionIsOneOf(name, extensions)) continue; @@ -116947,7 +116882,7 @@ function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNa return; } } - for (const current of sort(directories, compareStringsCaseSensitive)) { + for (const current of toSorted(directories, compareStringsCaseSensitive)) { const name = combinePaths(path2, current); const absoluteName = combinePaths(absolutePath, current); if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) && (!excludeRegex || !excludeRegex.test(absoluteName))) { @@ -117043,6 +116978,9 @@ function hasJSFileExtension(fileName) { function hasTSFileExtension(fileName) { return some(supportedTSExtensionsFlat, (extension) => fileExtensionIs(fileName, extension)); } +function hasImplementationTSFileExtension(fileName) { + return some(supportedTSImplementationExtensions, (extension) => fileExtensionIs(fileName, extension)) && !isDeclarationFileName(fileName); +} var ModuleSpecifierEnding = /* @__PURE__ */ ((ModuleSpecifierEnding2) => { ModuleSpecifierEnding2[ModuleSpecifierEnding2["Minimal"] = 0] = "Minimal"; ModuleSpecifierEnding2[ModuleSpecifierEnding2["Index"] = 1] = "Index"; @@ -117250,9 +117188,27 @@ function rangeOfTypeParameters(sourceFile, typeParameters) { return { pos, end }; } function skipTypeChecking(sourceFile, options, host) { - return options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib || options.noCheck || host.isSourceOfProjectReferenceRedirect(sourceFile.fileName) || !canIncludeBindAndCheckDiagnsotics(sourceFile, options); + return skipTypeCheckingWorker( + sourceFile, + options, + host, + /*ignoreNoCheck*/ + false + ); +} +function skipTypeCheckingIgnoringNoCheck(sourceFile, options, host) { + return skipTypeCheckingWorker( + sourceFile, + options, + host, + /*ignoreNoCheck*/ + true + ); +} +function skipTypeCheckingWorker(sourceFile, options, host, ignoreNoCheck) { + return options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib || !ignoreNoCheck && options.noCheck || host.isSourceOfProjectReferenceRedirect(sourceFile.fileName) || !canIncludeBindAndCheckDiagnostics(sourceFile, options); } -function canIncludeBindAndCheckDiagnsotics(sourceFile, options) { +function canIncludeBindAndCheckDiagnostics(sourceFile, options) { if (!!sourceFile.checkJsDirective && sourceFile.checkJsDirective.enabled === false) return false; if (sourceFile.scriptKind === 3 /* TS */ || sourceFile.scriptKind === 4 /* TSX */ || sourceFile.scriptKind === 5 /* External */) return true; const isJs = sourceFile.scriptKind === 1 /* JS */ || sourceFile.scriptKind === 2 /* JSX */; @@ -117426,14 +117382,6 @@ function setParent(child, parent2) { } return child; } -function setEachParent(children, parent2) { - if (children) { - for (const child of children) { - setParent(child, parent2); - } - } - return children; -} function setParentRecursive(rootNode, incremental) { if (!rootNode) return rootNode; forEachChildRecursively(rootNode, isJSDocNode(rootNode) ? bindParentToChildIgnoringJSDoc : bindParentToChild); @@ -117577,7 +117525,7 @@ function isFunctionExpressionOrArrowFunction(node) { return node.kind === 218 /* FunctionExpression */ || node.kind === 219 /* ArrowFunction */; } function escapeSnippetText(text) { - return text.replace(/\$/gm, () => "\\$"); + return text.replace(/\$/g, () => "\\$"); } function isNumericLiteralName(name) { return (+name).toString() === name; @@ -117636,10 +117584,6 @@ function getNodeModulePathParts(fullPath) { fileNameIndex = partStart; return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex, topLevelPackageNameIndex, packageRootIndex, fileNameIndex } : void 0; } -function getParameterTypeNode(parameter) { - var _a; - return parameter.kind === 341 /* JSDocParameterTag */ ? (_a = parameter.typeExpression) == null ? void 0 : _a.type : parameter.type; -} function isTypeDeclaration(node) { switch (node.kind) { case 168 /* TypeParameter */: @@ -117760,6 +117704,105 @@ function replaceFirstStar(s, replacement) { function getNameFromImportAttribute(node) { return isIdentifier(node.name) ? node.name.escapedText : escapeLeadingUnderscores(node.name.text); } +function isSourceElement(node) { + switch (node.kind) { + case 168 /* TypeParameter */: + case 169 /* Parameter */: + case 172 /* PropertyDeclaration */: + case 171 /* PropertySignature */: + case 185 /* ConstructorType */: + case 184 /* FunctionType */: + case 179 /* CallSignature */: + case 180 /* ConstructSignature */: + case 181 /* IndexSignature */: + case 174 /* MethodDeclaration */: + case 173 /* MethodSignature */: + case 175 /* ClassStaticBlockDeclaration */: + case 176 /* Constructor */: + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + case 183 /* TypeReference */: + case 182 /* TypePredicate */: + case 186 /* TypeQuery */: + case 187 /* TypeLiteral */: + case 188 /* ArrayType */: + case 189 /* TupleType */: + case 192 /* UnionType */: + case 193 /* IntersectionType */: + case 196 /* ParenthesizedType */: + case 190 /* OptionalType */: + case 191 /* RestType */: + case 197 /* ThisType */: + case 198 /* TypeOperator */: + case 194 /* ConditionalType */: + case 195 /* InferType */: + case 203 /* TemplateLiteralType */: + case 205 /* ImportType */: + case 202 /* NamedTupleMember */: + case 328 /* JSDocAugmentsTag */: + case 329 /* JSDocImplementsTag */: + case 346 /* JSDocTypedefTag */: + case 338 /* JSDocCallbackTag */: + case 340 /* JSDocEnumTag */: + case 345 /* JSDocTemplateTag */: + case 344 /* JSDocTypeTag */: + case 324 /* JSDocLink */: + case 325 /* JSDocLinkCode */: + case 326 /* JSDocLinkPlain */: + case 341 /* JSDocParameterTag */: + case 348 /* JSDocPropertyTag */: + case 317 /* JSDocFunctionType */: + case 315 /* JSDocNonNullableType */: + case 314 /* JSDocNullableType */: + case 312 /* JSDocAllType */: + case 313 /* JSDocUnknownType */: + case 322 /* JSDocTypeLiteral */: + case 318 /* JSDocVariadicType */: + case 309 /* JSDocTypeExpression */: + case 333 /* JSDocPublicTag */: + case 335 /* JSDocProtectedTag */: + case 334 /* JSDocPrivateTag */: + case 350 /* JSDocSatisfiesTag */: + case 343 /* JSDocThisTag */: + case 199 /* IndexedAccessType */: + case 200 /* MappedType */: + case 262 /* FunctionDeclaration */: + case 241 /* Block */: + case 268 /* ModuleBlock */: + case 243 /* VariableStatement */: + case 244 /* ExpressionStatement */: + case 245 /* IfStatement */: + case 246 /* DoStatement */: + case 247 /* WhileStatement */: + case 248 /* ForStatement */: + case 249 /* ForInStatement */: + case 250 /* ForOfStatement */: + case 251 /* ContinueStatement */: + case 252 /* BreakStatement */: + case 253 /* ReturnStatement */: + case 254 /* WithStatement */: + case 255 /* SwitchStatement */: + case 256 /* LabeledStatement */: + case 257 /* ThrowStatement */: + case 258 /* TryStatement */: + case 260 /* VariableDeclaration */: + case 208 /* BindingElement */: + case 263 /* ClassDeclaration */: + case 264 /* InterfaceDeclaration */: + case 265 /* TypeAliasDeclaration */: + case 266 /* EnumDeclaration */: + case 267 /* ModuleDeclaration */: + case 272 /* ImportDeclaration */: + case 271 /* ImportEqualsDeclaration */: + case 278 /* ExportDeclaration */: + case 277 /* ExportAssignment */: + case 242 /* EmptyStatement */: + case 259 /* DebuggerStatement */: + case 282 /* MissingDeclaration */: + return true; + } + return false; +} function evaluatorResult(value, isSyntacticallyString = false, resolvedOtherFiles = false, hasExternalReferences = false) { return { value, isSyntacticallyString, resolvedOtherFiles, hasExternalReferences }; } @@ -118311,6 +118354,10 @@ function hasInferredType(node) { return false; } } +function isSideEffectImport(node) { + const ancestor = findAncestor(node, isImportDeclaration); + return !!ancestor && !ancestor.importClause; +} // src/compiler/factory/baseNodeFactory.ts function createBaseNodeFactory() { @@ -120087,7 +120134,11 @@ function createNodeFactory(flags, baseFactory2) { node.modifiers = asNodeArray(modifiers); node.parameters = createNodeArray(parameters); node.body = body; - node.transformFlags = propagateChildrenFlags(node.modifiers) | propagateChildrenFlags(node.parameters) | propagateChildFlags(node.body) & ~67108864 /* ContainsPossibleTopLevelAwait */ | 1024 /* ContainsES2015 */; + if (!node.body) { + node.transformFlags = 1 /* ContainsTypeScript */; + } else { + node.transformFlags = propagateChildrenFlags(node.modifiers) | propagateChildrenFlags(node.parameters) | propagateChildFlags(node.body) & ~67108864 /* ContainsPossibleTopLevelAwait */ | 1024 /* ContainsES2015 */; + } node.typeParameters = void 0; node.type = void 0; node.typeArguments = void 0; @@ -122713,6 +122764,8 @@ function createNodeFactory(flags, baseFactory2) { return updateSatisfiesExpression(outerExpression, expression, outerExpression.type); case 235 /* NonNullExpression */: return updateNonNullExpression(outerExpression, expression); + case 233 /* ExpressionWithTypeArguments */: + return updateExpressionWithTypeArguments(outerExpression, expression, outerExpression.typeArguments); case 354 /* PartiallyEmittedExpression */: return updatePartiallyEmittedExpression(outerExpression, expression); } @@ -122720,7 +122773,7 @@ function createNodeFactory(flags, baseFactory2) { function isIgnorableParen(node) { return isParenthesizedExpression(node) && nodeIsSynthesized(node) && nodeIsSynthesized(getSourceMapRange(node)) && nodeIsSynthesized(getCommentRange(node)) && !some(getSyntheticLeadingComments(node)) && !some(getSyntheticTrailingComments(node)); } - function restoreOuterExpressions(outerExpression, innerExpression, kinds = 15 /* All */) { + function restoreOuterExpressions(outerExpression, innerExpression, kinds = 31 /* All */) { if (outerExpression && isOuterExpression(outerExpression, kinds) && !isIgnorableParen(outerExpression)) { return updateOuterExpression( outerExpression, @@ -122766,7 +122819,7 @@ function createNodeFactory(flags, baseFactory2) { } } function createCallBinding(expression, recordTempVariable, languageVersion, cacheIdentifiers = false) { - const callee = skipOuterExpressions(expression, 15 /* All */); + const callee = skipOuterExpressions(expression, 31 /* All */); let thisArg; let target; if (isSuperProperty(callee)) { @@ -124254,7 +124307,7 @@ var asyncGeneratorHelper = { var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var g = generator.apply(thisArg, _arguments || []), i, q = []; - return i = {}, verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i; + return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i; function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; } function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } } function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } @@ -124436,8 +124489,8 @@ var generatorHelper = { priority: 6, text: ` var __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); + return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); @@ -124600,17 +124653,22 @@ var disposeResourcesHelper = { env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; env.hasError = true; } + var r, s = 0; function next() { - while (env.stack.length) { - var rec = env.stack.pop(); + while (r = env.stack.pop()) { try { - var result = rec.dispose && rec.dispose.call(rec.value); - if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); + if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next); + if (r.dispose) { + var result = r.dispose.call(r.value); + if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); + } + else s |= 1; } catch (e) { fail(e); } } + if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve(); if (env.hasError) throw env.error; } return next(); @@ -125111,6 +125169,9 @@ function isNamedExports(node) { function isExportSpecifier(node) { return node.kind === 281 /* ExportSpecifier */; } +function isModuleExportName(node) { + return node.kind === 80 /* Identifier */ || node.kind === 11 /* StringLiteral */; +} function isMissingDeclaration(node) { return node.kind === 282 /* MissingDeclaration */; } @@ -125495,17 +125556,6 @@ function createForOfBindingStatement(factory2, node, boundValue) { ); } } -function insertLeadingStatement(factory2, dest, source) { - if (isBlock(dest)) { - return factory2.updateBlock(dest, setTextRange(factory2.createNodeArray([source, ...dest.statements]), dest.statements)); - } else { - return factory2.createBlock( - factory2.createNodeArray([dest, source]), - /*multiLine*/ - true - ); - } -} function createExpressionFromEntityName(factory2, node) { if (isQualifiedName(node)) { const left = createExpressionFromEntityName(factory2, node.left); @@ -125737,18 +125787,19 @@ function getJSDocTypeAssertionType(node) { Debug.assertIsDefined(type); return type; } -function isOuterExpression(node, kinds = 15 /* All */) { +function isOuterExpression(node, kinds = 31 /* All */) { switch (node.kind) { case 217 /* ParenthesizedExpression */: - if (kinds & 16 /* ExcludeJSDocTypeAssertion */ && isJSDocTypeAssertion(node)) { + if (kinds & -2147483648 /* ExcludeJSDocTypeAssertion */ && isJSDocTypeAssertion(node)) { return false; } return (kinds & 1 /* Parentheses */) !== 0; case 216 /* TypeAssertionExpression */: case 234 /* AsExpression */: - case 233 /* ExpressionWithTypeArguments */: case 238 /* SatisfiesExpression */: return (kinds & 2 /* TypeAssertions */) !== 0; + case 233 /* ExpressionWithTypeArguments */: + return (kinds & 16 /* ExpressionsWithTypeArguments */) !== 0; case 235 /* NonNullExpression */: return (kinds & 4 /* NonNullAssertions */) !== 0; case 354 /* PartiallyEmittedExpression */: @@ -125756,13 +125807,13 @@ function isOuterExpression(node, kinds = 15 /* All */) { } return false; } -function skipOuterExpressions(node, kinds = 15 /* All */) { +function skipOuterExpressions(node, kinds = 31 /* All */) { while (isOuterExpression(node, kinds)) { node = node.expression; } return node; } -function walkUpOuterExpressions(node, kinds = 15 /* All */) { +function walkUpOuterExpressions(node, kinds = 31 /* All */) { let parent2 = node.parent; while (isOuterExpression(parent2, kinds)) { parent2 = parent2.parent; @@ -125770,9 +125821,6 @@ function walkUpOuterExpressions(node, kinds = 15 /* All */) { } return parent2; } -function skipAssertions(node) { - return skipOuterExpressions(node, 6 /* Assertions */); -} function startOnNewLine(node) { return setStartsOnNewLine( node, @@ -125794,7 +125842,7 @@ function createExternalHelpersImportDeclarationIfNeeded(nodeFactory, helperFacto if (compilerOptions.importHelpers && isEffectiveExternalModule(sourceFile, compilerOptions)) { let namedBindings; const moduleKind = getEmitModuleKind(compilerOptions); - if (moduleKind >= 5 /* ES2015 */ && moduleKind <= 99 /* ESNext */ || sourceFile.impliedNodeFormat === 99 /* ESNext */) { + if (moduleKind >= 5 /* ES2015 */ && moduleKind <= 99 /* ESNext */ || getImpliedNodeFormatForEmitWorker(sourceFile, compilerOptions) === 99 /* ESNext */) { const helpers = getEmitHelpers(sourceFile); if (helpers) { const helperNames = []; @@ -125859,8 +125907,7 @@ function getOrCreateExternalHelpersModuleNameIfNeeded(factory2, node, compilerOp if (externalHelpersModuleName) { return externalHelpersModuleName; } - const moduleKind = getEmitModuleKind(compilerOptions); - let create = (hasExportStarsToExportValues || getESModuleInterop(compilerOptions) && hasImportStarOrImportDefault) && moduleKind !== 4 /* System */ && (moduleKind < 5 /* ES2015 */ || node.impliedNodeFormat === 1 /* CommonJS */); + let create = (hasExportStarsToExportValues || getESModuleInterop(compilerOptions) && hasImportStarOrImportDefault) && getEmitModuleFormatOfFileWorker(node, compilerOptions) < 4 /* System */; if (!create) { const helpers = getEmitHelpers(node); if (helpers) { @@ -125883,6 +125930,9 @@ function getLocalNameForExternalImport(factory2, node, sourceFile) { const namespaceDeclaration = getNamespaceDeclarationNode(node); if (namespaceDeclaration && !isDefaultImport(node) && !isExportNamespaceAsDefaultDeclaration(node)) { const name = namespaceDeclaration.name; + if (name.kind === 11 /* StringLiteral */) { + return factory2.getGeneratedNameForNode(node); + } return isGeneratedIdentifier(name) ? name : factory2.createIdentifier(getSourceTextOfNodeFromSourceFile(sourceFile, name) || idText(name)); } if (node.kind === 272 /* ImportDeclaration */ && node.importClause) { @@ -126075,10 +126125,6 @@ function isQuestionOrPlusOrMinusToken(node) { function isModuleName(node) { return isIdentifier(node) || isStringLiteral(node); } -function isLiteralTypeLikeExpression(node) { - const kind = node.kind; - return kind === 106 /* NullKeyword */ || kind === 112 /* TrueKeyword */ || kind === 97 /* FalseKeyword */ || isLiteralExpression(node) || isPrefixUnaryExpression(node); -} function isExponentiationOperator(kind) { return kind === 43 /* AsteriskAsteriskToken */; } @@ -126264,10 +126310,6 @@ function isExportOrDefaultModifier(node) { const kind = node.kind; return isExportOrDefaultKeywordKind(kind); } -function isNonExportDefaultModifier(node) { - const kind = node.kind; - return isModifierKind(kind) && !isExportOrDefaultKeywordKind(kind); -} function elideNodes(factory2, nodes) { if (nodes === void 0) return void 0; if (nodes.length === 0) return nodes; @@ -127043,7 +127085,7 @@ function setExternalModuleIndicator(sourceFile) { sourceFile.externalModuleIndicator = isFileProbablyExternalModule(sourceFile); } function createSourceFile(fileName, sourceText, languageVersionOrOptions, setParentNodes = false, scriptKind) { - var _a, _b, _c, _d; + var _a, _b; (_a = tracing) == null ? void 0 : _a.push( tracing.Phase.Parse, "createSourceFile", @@ -127053,7 +127095,6 @@ function createSourceFile(fileName, sourceText, languageVersionOrOptions, setPar ); mark("beforeParse"); let result; - (_b = perfLogger) == null ? void 0 : _b.logStartParseSourceFile(fileName); const { languageVersion, setExternalModuleIndicator: overrideSetExternalModuleIndicator, @@ -127089,10 +127130,9 @@ function createSourceFile(fileName, sourceText, languageVersionOrOptions, setPar jsDocParsingMode ); } - (_c = perfLogger) == null ? void 0 : _c.logStopParseSourceFile(); mark("afterParse"); measure("Parse", "beforeParse", "afterParse"); - (_d = tracing) == null ? void 0 : _d.pop(); + (_b = tracing) == null ? void 0 : _b.pop(); return result; } function parseIsolatedEntityName(text, languageVersion) { @@ -128032,7 +128072,7 @@ var Parser; function createIdentifier(isIdentifier3, diagnosticMessage, privateIdentifierDiagnosticMessage) { if (isIdentifier3) { identifierCount++; - const pos = scanner2.hasLeadingAsterisks() ? scanner2.getTokenStart() : getNodePos(); + const pos = scanner2.hasPrecedingJSDocLeadingAsterisks() ? scanner2.getTokenStart() : getNodePos(); const originalKeywordKind = token(); const text = internIdentifier(scanner2.getTokenValue()); const hasExtendedUnicodeEscape = scanner2.hasExtendedUnicodeEscape(); @@ -128080,13 +128120,13 @@ var Parser; return createIdentifier(tokenIsIdentifierOrKeyword(token())); } function isLiteralPropertyName() { - return tokenIsIdentifierOrKeyword(token()) || token() === 11 /* StringLiteral */ || token() === 9 /* NumericLiteral */; + return tokenIsIdentifierOrKeyword(token()) || token() === 11 /* StringLiteral */ || token() === 9 /* NumericLiteral */ || token() === 10 /* BigIntLiteral */; } function isImportAttributeName2() { return tokenIsIdentifierOrKeyword(token()) || token() === 11 /* StringLiteral */; } function parsePropertyNameWorker(allowComputedPropertyNames) { - if (token() === 11 /* StringLiteral */ || token() === 9 /* NumericLiteral */) { + if (token() === 11 /* StringLiteral */ || token() === 9 /* NumericLiteral */ || token() === 10 /* BigIntLiteral */) { const node = parseLiteralNode(); node.text = internIdentifier(node.text); return node; @@ -128245,6 +128285,9 @@ var Parser; if (token() === 161 /* FromKeyword */ && lookAhead(nextTokenIsStringLiteral)) { return false; } + if (token() === 11 /* StringLiteral */) { + return true; + } return tokenIsIdentifierOrKeyword(token()); case 13 /* JsxAttributes */: return tokenIsIdentifierOrKeyword(token()) || token() === 19 /* OpenBraceToken */; @@ -132310,7 +132353,7 @@ var Parser; if (isIndexSignature()) { return parseIndexSignatureDeclaration(pos, hasJSDoc, modifiers); } - if (tokenIsIdentifierOrKeyword(token()) || token() === 11 /* StringLiteral */ || token() === 9 /* NumericLiteral */ || token() === 42 /* AsteriskToken */ || token() === 23 /* OpenBracketToken */) { + if (tokenIsIdentifierOrKeyword(token()) || token() === 11 /* StringLiteral */ || token() === 9 /* NumericLiteral */ || token() === 10 /* BigIntLiteral */ || token() === 42 /* AsteriskToken */ || token() === 23 /* OpenBracketToken */) { const isAmbient = some(modifiers, isDeclareModifier); if (isAmbient) { for (const m of modifiers) { @@ -132693,6 +132736,12 @@ var Parser; const name = parseIdentifier(); return finishNode(factory2.createNamespaceImport(name), pos); } + function canParseModuleExportName() { + return tokenIsIdentifierOrKeyword(token()) || token() === 11 /* StringLiteral */; + } + function parseModuleExportName(parseName) { + return token() === 11 /* StringLiteral */ ? parseLiteralNode() : parseName(); + } function parseNamedImportsOrExports(kind) { const pos = getNodePos(); const node = kind === 275 /* NamedImports */ ? factory2.createNamedImports(parseBracketedList(23 /* ImportOrExportSpecifiers */, parseImportSpecifier, 19 /* OpenBraceToken */, 20 /* CloseBraceToken */)) : factory2.createNamedExports(parseBracketedList(23 /* ImportOrExportSpecifiers */, parseExportSpecifier, 19 /* OpenBraceToken */, 20 /* CloseBraceToken */)); @@ -132713,42 +132762,51 @@ var Parser; let isTypeOnly = false; let propertyName; let canParseAsKeyword = true; - let name = parseIdentifierName(); - if (name.escapedText === "type") { + let name = parseModuleExportName(parseIdentifierName); + if (name.kind === 80 /* Identifier */ && name.escapedText === "type") { if (token() === 130 /* AsKeyword */) { const firstAs = parseIdentifierName(); if (token() === 130 /* AsKeyword */) { const secondAs = parseIdentifierName(); - if (tokenIsIdentifierOrKeyword(token())) { + if (canParseModuleExportName()) { isTypeOnly = true; propertyName = firstAs; - name = parseNameWithKeywordCheck(); + name = parseModuleExportName(parseNameWithKeywordCheck); canParseAsKeyword = false; } else { propertyName = name; name = secondAs; canParseAsKeyword = false; } - } else if (tokenIsIdentifierOrKeyword(token())) { + } else if (canParseModuleExportName()) { propertyName = name; canParseAsKeyword = false; - name = parseNameWithKeywordCheck(); + name = parseModuleExportName(parseNameWithKeywordCheck); } else { isTypeOnly = true; name = firstAs; } - } else if (tokenIsIdentifierOrKeyword(token())) { + } else if (canParseModuleExportName()) { isTypeOnly = true; - name = parseNameWithKeywordCheck(); + name = parseModuleExportName(parseNameWithKeywordCheck); } } if (canParseAsKeyword && token() === 130 /* AsKeyword */) { propertyName = name; parseExpected(130 /* AsKeyword */); - name = parseNameWithKeywordCheck(); + name = parseModuleExportName(parseNameWithKeywordCheck); } - if (kind === 276 /* ImportSpecifier */ && checkIdentifierIsKeyword) { - parseErrorAt(checkIdentifierStart, checkIdentifierEnd, Diagnostics.Identifier_expected); + if (kind === 276 /* ImportSpecifier */) { + if (name.kind !== 80 /* Identifier */) { + parseErrorAt(skipTrivia(sourceText, name.pos), name.end, Diagnostics.Identifier_expected); + name = setTextRangePosEnd(createMissingNode( + 80 /* Identifier */, + /*reportAtCurrentPosition*/ + false + ), name.pos, name.pos); + } else if (checkIdentifierIsKeyword) { + parseErrorAt(checkIdentifierStart, checkIdentifierEnd, Diagnostics.Identifier_expected); + } } const node = kind === 276 /* ImportSpecifier */ ? factory2.createImportSpecifier(isTypeOnly, propertyName, name) : factory2.createExportSpecifier(isTypeOnly, propertyName, name); return finishNode(node, pos); @@ -132760,7 +132818,7 @@ var Parser; } } function parseNamespaceExport(pos) { - return finishNode(factory2.createNamespaceExport(parseIdentifierName()), pos); + return finishNode(factory2.createNamespaceExport(parseModuleExportName(parseIdentifierName)), pos); } function parseExportDeclaration(pos, hasJSDoc, modifiers) { const savedAwaitContext = inAwaitContext(); @@ -134413,8 +134471,8 @@ function getNamedArgRegEx(name) { namedArgRegExCache.set(name, result); return result; } -var tripleSlashXMLCommentStartRegEx = /^\/\/\/\s*<(\S+)\s.*?\/>/im; -var singleLinePragmaRegEx = /^\/\/\/?\s*@([^\s:]+)(.*)\s*$/im; +var tripleSlashXMLCommentStartRegEx = /^\/\/\/\s*<(\S+)\s.*?\/>/m; +var singleLinePragmaRegEx = /^\/\/\/?\s*@([^\s:]+)((?:[^\S\r\n]|:).*)?$/m; function extractPragmas(pragmas, range, text) { const tripleSlash = range.kind === 2 /* SingleLineCommentTrivia */ && tripleSlashXMLCommentStartRegEx.exec(text); if (tripleSlash) { @@ -134455,7 +134513,7 @@ function extractPragmas(pragmas, range, text) { return addPragmaForMatch(pragmas, range, 2 /* SingleLine */, singleLine); } if (range.kind === 3 /* MultiLineCommentTrivia */) { - const multiLinePragmaRegEx = /@(\S+)(\s+.*)?$/gim; + const multiLinePragmaRegEx = /@(\S+)(\s+(?:\S.*)?)?$/gm; let multiLineMatch; while (multiLineMatch = multiLinePragmaRegEx.exec(text)) { addPragmaForMatch(pragmas, range, 4 /* MultiLine */, multiLineMatch); @@ -134611,6 +134669,7 @@ var libEntries = [ ["esnext.array", "lib.esnext.array.d.ts"], ["esnext.regexp", "lib.esnext.regexp.d.ts"], ["esnext.string", "lib.esnext.string.d.ts"], + ["esnext.iterator", "lib.esnext.iterator.d.ts"], ["decorators", "lib.decorators.d.ts"], ["decorators.legacy", "lib.decorators.legacy.d.ts"] ]; @@ -134789,7 +134848,6 @@ var commonOptionsWithBuild = [ name: "generateTrace", type: "string", isFilePath: true, - isCommandLineOnly: true, paramType: Diagnostics.DIRECTORY, category: Diagnostics.Compiler_Diagnostics, description: Diagnostics.Generates_an_event_trace_and_a_list_of_types @@ -134855,6 +134913,25 @@ var commonOptionsWithBuild = [ description: Diagnostics.Include_sourcemap_files_inside_the_emitted_JavaScript, defaultValueDescription: false }, + { + name: "noCheck", + type: "boolean", + showInSimplifiedHelpView: false, + category: Diagnostics.Compiler_Diagnostics, + description: Diagnostics.Disable_full_type_checking_only_critical_parse_and_emit_errors_will_be_reported, + transpileOptionValue: true, + defaultValueDescription: false + // Not setting affectsSemanticDiagnostics or affectsBuildInfo because we dont want all diagnostics to go away, its handled in builder + }, + { + name: "noEmit", + type: "boolean", + showInSimplifiedHelpView: true, + category: Diagnostics.Emit, + description: Diagnostics.Disable_emitting_files_from_a_compilation, + transpileOptionValue: void 0, + defaultValueDescription: false + }, { name: "assumeChangesOnlyAffectDirectDependencies", type: "boolean", @@ -135119,29 +135196,6 @@ var commandOptionsWithoutBuild = [ defaultValueDescription: false, description: Diagnostics.Disable_emitting_comments }, - { - name: "noCheck", - type: "boolean", - showInSimplifiedHelpView: false, - category: Diagnostics.Compiler_Diagnostics, - description: Diagnostics.Disable_full_type_checking_only_critical_parse_and_emit_errors_will_be_reported, - transpileOptionValue: true, - defaultValueDescription: false, - affectsSemanticDiagnostics: true, - affectsBuildInfo: true, - extraValidation() { - return [Diagnostics.Unknown_compiler_option_0, "noCheck"]; - } - }, - { - name: "noEmit", - type: "boolean", - showInSimplifiedHelpView: true, - category: Diagnostics.Emit, - description: Diagnostics.Disable_emitting_files_from_a_compilation, - transpileOptionValue: void 0, - defaultValueDescription: false - }, { name: "importHelpers", type: "boolean", @@ -135266,6 +135320,16 @@ var commandOptionsWithoutBuild = [ description: Diagnostics.Check_for_class_properties_that_are_declared_but_not_set_in_the_constructor, defaultValueDescription: Diagnostics.false_unless_strict_is_set }, + { + name: "strictBuiltinIteratorReturn", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + strictFlag: true, + category: Diagnostics.Type_Checking, + description: Diagnostics.Built_in_iterators_are_instantiated_with_a_TReturn_type_of_undefined_instead_of_any, + defaultValueDescription: Diagnostics.false_unless_strict_is_set + }, { name: "noImplicitThis", type: "boolean", @@ -135541,6 +135605,15 @@ var commandOptionsWithoutBuild = [ category: Diagnostics.Modules, description: Diagnostics.Conditions_to_set_in_addition_to_the_resolver_specific_defaults_when_resolving_imports }, + { + name: "noUncheckedSideEffectImports", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + category: Diagnostics.Modules, + description: Diagnostics.Check_side_effect_imports, + defaultValueDescription: false + }, // Source Maps { name: "sourceRoot", @@ -135996,6 +136069,13 @@ var optionsForBuild = [ description: Diagnostics.Delete_the_outputs_of_all_projects, type: "boolean", defaultValueDescription: false + }, + { + name: "stopBuildOnErrors", + category: Diagnostics.Command_line_Options, + description: Diagnostics.Skip_building_downstream_projects_on_error_in_upstream_project, + type: "boolean", + defaultValueDescription: false } ]; var buildOpts = [ @@ -136678,9 +136758,7 @@ function convertToTSConfig(configParseResult, configFileName, host) { return config; } function optionMapToObject(optionMap) { - return { - ...arrayFrom(optionMap.entries()).reduce((prev, cur) => ({ ...prev, [cur[0]]: cur[1] }), {}) - }; + return Object.fromEntries(optionMap); } function filterSameAsDefaultInclude(specs) { if (!length(specs)) return void 0; @@ -137548,7 +137626,7 @@ function convertJsonOptionOfCustomType(opt, value, errors, valueExpression, sour function convertJsonOptionOfListType(option, values, basePath, errors, propertyAssignment, valueExpression, sourceFile) { return filter(map(values, (v, index) => convertJsonOption(option.element, v, basePath, errors, propertyAssignment, valueExpression == null ? void 0 : valueExpression.elements[index], sourceFile)), (v) => option.listPreserveFalsyValues ? true : !!v); } -var invalidTrailingRecursionPattern = /(^|\/)\*\*\/?$/; +var invalidTrailingRecursionPattern = /(?:^|\/)\*\*\/?$/; var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/; function getFileNamesFromConfigSpecs(configFileSpecs, basePath, options, host, extraFileExtensions = emptyArray) { basePath = normalizePath(basePath); @@ -137816,69 +137894,6 @@ function getDefaultValueForOption(option) { } } -// src/compiler/pnpapi.ts -function getPnpApi(path) { - if (typeof process.versions.pnp === "undefined") { - return; - } - const { findPnpApi } = __nccwpck_require__(98188); - if (findPnpApi) { - return findPnpApi(`${path}/`); - } -} -function getPnpApiPath(path) { - var _a; - return (_a = getPnpApi(path)) == null ? void 0 : _a.resolveRequest( - "pnpapi", - /*issuer*/ - null - ); -} - -// src/compiler/pnp.ts -function getPnpTypeRoots(currentDirectory) { - const pnpApi = getPnpApi(currentDirectory); - if (!pnpApi) { - return []; - } - currentDirectory = resolvePath(currentDirectory); - const currentPackage = pnpApi.findPackageLocator(`${currentDirectory}/`); - if (!currentPackage) { - return []; - } - const { packageDependencies } = pnpApi.getPackageInformation(currentPackage); - const typeRoots = []; - for (const [name, referencish] of Array.from(packageDependencies.entries())) { - if (name.startsWith(`@types/`) && referencish !== null) { - const dependencyLocator = pnpApi.getLocator(name, referencish); - const { packageLocation } = pnpApi.getPackageInformation(dependencyLocator); - typeRoots.push(getDirectoryPath(packageLocation)); - } - } - return typeRoots; -} -function isImportablePathPnp(fromPath, toPath3) { - const pnpApi = getPnpApi(fromPath); - const fromLocator = pnpApi.findPackageLocator(fromPath); - const toLocator = pnpApi.findPackageLocator(toPath3); - if (toLocator === null) { - return false; - } - const fromInfo = pnpApi.getPackageInformation(fromLocator); - const toReference = fromInfo.packageDependencies.get(toLocator.name); - if (toReference) { - return toReference === toLocator.reference; - } - for (const reference of fromInfo.packageDependencies.values()) { - if (Array.isArray(reference)) { - if (reference[0] === toLocator.name && reference[1] === toLocator.reference) { - return true; - } - } - } - return false; -} - // src/compiler/moduleNameResolver.ts function trace(host, message, ...args) { host.trace(formatMessage(message, ...args)); @@ -138104,7 +138119,7 @@ function getEffectiveTypeRoots(options, host) { return getDefaultTypeRoots(currentDirectory); } } -function getNodeModulesTypeRoots(currentDirectory) { +function getDefaultTypeRoots(currentDirectory) { let typeRoots; forEachAncestorDirectory(normalizePath(currentDirectory), (directory) => { const atTypes = combinePaths(directory, nodeModulesAtTypes); @@ -138117,15 +138132,6 @@ function arePathsEqual(path1, path2, host) { const useCaseSensitiveFileNames2 = typeof host.useCaseSensitiveFileNames === "function" ? host.useCaseSensitiveFileNames() : host.useCaseSensitiveFileNames; return comparePaths(path1, path2, !useCaseSensitiveFileNames2) === 0 /* EqualTo */; } -function getDefaultTypeRoots(currentDirectory) { - const nmTypes = getNodeModulesTypeRoots(currentDirectory); - const pnpTypes = getPnpTypeRoots(currentDirectory); - if (nmTypes == null ? void 0 : nmTypes.length) { - return [...nmTypes, ...pnpTypes]; - } else if (pnpTypes.length) { - return pnpTypes; - } -} function getOriginalAndResolvedFileName(fileName, host, traceEnabled) { const resolvedFileName = realPath(fileName, host, traceEnabled); const pathsAreEqual = arePathsEqual(fileName, resolvedFileName, host); @@ -138375,21 +138381,6 @@ function getConditions(options, resolutionMode) { } function resolvePackageNameToPackageJson(packageName, containingDirectory, options, host, cache) { const moduleResolutionState = getTemporaryModuleResolutionState(cache == null ? void 0 : cache.getPackageJsonInfoCache(), host, options); - const pnpapi = getPnpApi(containingDirectory); - if (pnpapi) { - try { - const resolution = pnpapi.resolveToUnqualified(packageName, `${containingDirectory}/`, { considerBuiltins: false }); - const candidate = normalizeSlashes(resolution).replace(/\/$/, ""); - return getPackageJsonInfo( - candidate, - /*onlyRecordFailures*/ - false, - moduleResolutionState - ); - } catch { - return; - } - } return forEachAncestorDirectory(containingDirectory, (ancestorDirectory) => { if (getBaseFileName(ancestorDirectory) !== "node_modules") { const nodeModulesFolder = combinePaths(ancestorDirectory, "node_modules"); @@ -138769,7 +138760,6 @@ function resolveModuleNameFromCache(moduleName, containingFile, cache, mode) { ); } function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode) { - var _a, _b, _c; const traceEnabled = isTraceEnabled(compilerOptions, host); if (redirectedReference) { compilerOptions = redirectedReference.commandLine.options; @@ -138798,7 +138788,6 @@ function resolveModuleName(moduleName, containingFile, compilerOptions, host, ca trace(host, Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ModuleResolutionKind[moduleResolution]); } } - (_a = perfLogger) == null ? void 0 : _a.logStartResolveModule(moduleName); switch (moduleResolution) { case 3 /* Node16 */: result = node16ModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode); @@ -138818,8 +138807,6 @@ function resolveModuleName(moduleName, containingFile, compilerOptions, host, ca default: return Debug.fail(`Unexpected moduleResolution: ${moduleResolution}`); } - if (result && result.resolvedModule) (_b = perfLogger) == null ? void 0 : _b.logInfoEvent(`Module "${moduleName}" resolved to "${result.resolvedModule.resolvedFileName}"`); - (_c = perfLogger) == null ? void 0 : _c.logStopResolveModule(result && result.resolvedModule ? "" + result.resolvedModule.resolvedFileName : "null"); if (cache && !cache.isReadonly) { cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference).set(moduleName, resolutionMode, result); if (!isExternalModuleNameRelative(moduleName)) { @@ -139526,22 +139513,16 @@ function getTemporaryModuleResolutionState(packageJsonInfoCache, host, options) resolvedPackageDirectory: false }; } -function getPackageScopeForPath(fileName, state) { - const parts = getPathComponents(fileName); - parts.pop(); - while (parts.length > 0) { - const pkg = getPackageJsonInfo( - getPathFromPathComponents(parts), +function getPackageScopeForPath(directory, state) { + return forEachAncestorDirectory( + directory, + (dir) => getPackageJsonInfo( + dir, /*onlyRecordFailures*/ false, state - ); - if (pkg) { - return pkg; - } - parts.pop(); - } - return void 0; + ) + ); } function getVersionPathsOfPackageJsonInfo(packageJsonInfo, state) { if (packageJsonInfo.contents.versionPaths === void 0) { @@ -139704,7 +139685,7 @@ function noKeyStartsWithDot(obj) { } function loadModuleFromSelfNameReference(extensions, moduleName, directory, state, cache, redirectedReference) { var _a, _b; - const directoryPath = getNormalizedAbsolutePath(combinePaths(directory, "dummy"), (_b = (_a = state.host).getCurrentDirectory) == null ? void 0 : _b.call(_a)); + const directoryPath = getNormalizedAbsolutePath(directory, (_b = (_a = state.host).getCurrentDirectory) == null ? void 0 : _b.call(_a)); const scope = getPackageScopeForPath(directoryPath, state); if (!scope || !scope.contents.packageJsonContent.exports) { return void 0; @@ -139800,7 +139781,7 @@ function loadModuleFromImports(extensions, moduleName, directory, state, cache, void 0 ); } - const directoryPath = getNormalizedAbsolutePath(combinePaths(directory, "dummy"), (_b = (_a = state.host).getCurrentDirectory) == null ? void 0 : _b.call(_a)); + const directoryPath = getNormalizedAbsolutePath(directory, (_b = (_a = state.host).getCurrentDirectory) == null ? void 0 : _b.call(_a)); const scope = getPackageScopeForPath(directoryPath, state); if (!scope) { if (state.traceEnabled) { @@ -139868,7 +139849,7 @@ function loadModuleFromImportsOrExports(extensions, state, cache, redirectedRefe moduleName ); } - const expandingKeys = sort(filter(getOwnKeys(lookupTable), (k) => hasOneAsterisk(k) || endsWith(k, "/")), comparePatternKeys); + const expandingKeys = toSorted(filter(getOwnKeys(lookupTable), (k) => hasOneAsterisk(k) || endsWith(k, "/")), comparePatternKeys); for (const potentialTarget of expandingKeys) { if (state.features & 16 /* ExportsPatternTrailers */ && matchesPatternWithTrailer(potentialTarget, moduleName)) { const target = lookupTable[potentialTarget]; @@ -140181,15 +140162,7 @@ function loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, return lookup(secondaryExtensions); } function lookup(extensions2) { - const issuer = normalizeSlashes(directory); - if (getPnpApi(issuer)) { - const resolutionFromCache = tryFindNonRelativeModuleNameInCache(cache, moduleName, mode, issuer, redirectedReference, state); - if (resolutionFromCache) { - return resolutionFromCache; - } - return toSearchResult(loadModuleFromImmediateNodeModulesDirectoryPnP(extensions2, moduleName, issuer, state, typesScopeOnly, cache, redirectedReference)); - } - return forEachAncestorDirectory(issuer, (ancestorDirectory) => { + return forEachAncestorDirectory(normalizeSlashes(directory), (ancestorDirectory) => { if (getBaseFileName(ancestorDirectory) !== "node_modules") { const resolutionFromCache = tryFindNonRelativeModuleNameInCache(cache, moduleName, mode, ancestorDirectory, redirectedReference, state); if (resolutionFromCache) { @@ -140224,40 +140197,11 @@ function loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, dir return loadModuleFromSpecificNodeModulesDirectory(4 /* Declaration */, mangleScopedPackageNameWithTrace(moduleName, state), nodeModulesAtTypes2, nodeModulesAtTypesExists, state, cache, redirectedReference); } } -function loadModuleFromImmediateNodeModulesDirectoryPnP(extensions, moduleName, directory, state, typesScopeOnly, cache, redirectedReference) { - const issuer = normalizeSlashes(directory); - if (!typesScopeOnly) { - const packageResult = tryLoadModuleUsingPnpResolution(extensions, moduleName, issuer, state, cache, redirectedReference); - if (packageResult) { - return packageResult; - } - } - if (extensions & 4 /* Declaration */) { - return tryLoadModuleUsingPnpResolution(4 /* Declaration */, `@types/${mangleScopedPackageNameWithTrace(moduleName, state)}`, issuer, state, cache, redirectedReference); - } -} function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesDirectory, nodeModulesDirectoryExists, state, cache, redirectedReference) { + var _a, _b; const candidate = normalizePath(combinePaths(nodeModulesDirectory, moduleName)); const { packageName, rest } = parsePackageName(moduleName); const packageDirectory = combinePaths(nodeModulesDirectory, packageName); - return loadModuleFromSpecificNodeModulesDirectoryImpl(extensions, nodeModulesDirectoryExists, state, cache, redirectedReference, candidate, rest, packageDirectory); -} -function loadModuleFromPnpResolution(extensions, packageDirectory, rest, state, cache, redirectedReference) { - const candidate = normalizePath(combinePaths(packageDirectory, rest)); - return loadModuleFromSpecificNodeModulesDirectoryImpl( - extensions, - /*nodeModulesDirectoryExists*/ - true, - state, - cache, - redirectedReference, - candidate, - rest, - packageDirectory - ); -} -function loadModuleFromSpecificNodeModulesDirectoryImpl(extensions, nodeModulesDirectoryExists, state, cache, redirectedReference, candidate, rest, packageDirectory) { - var _a, _b; let rootPackageInfo; let packageInfo = getPackageJsonInfo(candidate, !nodeModulesDirectoryExists, state); if (rest !== "" && packageInfo && (!(state.features & 8 /* Exports */) || !hasProperty(((_a = rootPackageInfo = getPackageJsonInfo(packageDirectory, !nodeModulesDirectoryExists, state)) == null ? void 0 : _a.contents.packageJsonContent) ?? emptyArray, "exports"))) { @@ -140558,18 +140502,6 @@ function traceIfEnabled(state, diagnostic, ...args) { function useCaseSensitiveFileNames(state) { return !state.host.useCaseSensitiveFileNames ? true : typeof state.host.useCaseSensitiveFileNames === "boolean" ? state.host.useCaseSensitiveFileNames : state.host.useCaseSensitiveFileNames(); } -function loadPnpPackageResolution(packageName, containingDirectory) { - try { - const resolution = getPnpApi(containingDirectory).resolveToUnqualified(packageName, `${containingDirectory}/`, { considerBuiltins: false }); - return normalizeSlashes(resolution).replace(/\/$/, ""); - } catch { - } -} -function tryLoadModuleUsingPnpResolution(extensions, moduleName, containingDirectory, state, cache, redirectedReference) { - const { packageName, rest } = parsePackageName(moduleName); - const packageResolution = loadPnpPackageResolution(packageName, containingDirectory); - return packageResolution ? loadModuleFromPnpResolution(extensions, packageResolution, rest, state, cache, redirectedReference) : void 0; -} // src/compiler/binder.ts var ModuleInstanceState = /* @__PURE__ */ ((ModuleInstanceState2) => { @@ -140661,6 +140593,9 @@ function getModuleInstanceStateWorker(node, visited) { } function getModuleInstanceStateForAliasTarget(specifier, visited) { const name = specifier.propertyName || specifier.name; + if (name.kind !== 80 /* Identifier */) { + return 1 /* Instantiated */; + } let p = specifier.parent; while (p) { if (isBlock(p) || isModuleBlock(p) || isSourceFile(p)) { @@ -140713,11 +140648,8 @@ function createFlowNode(flags, node, antecedent) { } var binder = /* @__PURE__ */ createBinder(); function bindSourceFile(file, options) { - var _a, _b; mark("beforeBind"); - (_a = perfLogger) == null ? void 0 : _a.logStartBindFile("" + file.fileName); binder(file, options); - (_b = perfLogger) == null ? void 0 : _b.logStopBindFile(); mark("afterBind"); measure("Bind", "beforeBind", "afterBind"); } @@ -140917,7 +140849,7 @@ function createBinder() { } function declareSymbol(symbolTable, parent3, node, includes, excludes, isReplaceableByMethod, isComputedName) { Debug.assert(isComputedName || !hasDynamicName(node)); - const isDefaultExport = hasSyntacticModifier(node, 2048 /* Default */) || isExportSpecifier(node) && node.name.escapedText === "default"; + const isDefaultExport = hasSyntacticModifier(node, 2048 /* Default */) || isExportSpecifier(node) && moduleExportNameIsDefault(node.name); const name = isComputedName ? "__computed" /* Computed */ : isDefaultExport && parent3 ? "default" /* Default */ : getDeclarationName(node); let symbol; if (name === void 0) { @@ -142014,6 +141946,8 @@ function createBinder() { } function bindJSDocImportTag(node) { bind(node.tagName); + bind(node.moduleSpecifier); + bind(node.attributes); if (typeof node.comment !== "string") { bindEach(node.comment); } @@ -143397,21 +143331,25 @@ function createBinder() { const reportError = ( // report error on all statements except empty ones isStatementButNotDeclaration(node) && node.kind !== 242 /* EmptyStatement */ || // report error on class declarations - node.kind === 263 /* ClassDeclaration */ || // report error on instantiated modules or const-enums only modules if preserveConstEnums is set + node.kind === 263 /* ClassDeclaration */ || // report errors on enums with preserved emit + isEnumDeclarationWithPreservedEmit(node, options) || // report error on instantiated modules node.kind === 267 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node) ); if (reportError) { currentFlow = reportedUnreachableFlow; if (!options.allowUnreachableCode) { const isError = unreachableCodeIsError(options) && !(node.flags & 33554432 /* Ambient */) && (!isVariableStatement(node) || !!(getCombinedNodeFlags(node.declarationList) & 7 /* BlockScoped */) || node.declarationList.declarations.some((d) => !!d.initializer)); - eachUnreachableRange(node, (start, end) => errorOrSuggestionOnRange(isError, start, end, Diagnostics.Unreachable_code_detected)); + eachUnreachableRange(node, options, (start, end) => errorOrSuggestionOnRange(isError, start, end, Diagnostics.Unreachable_code_detected)); } } } return true; } } -function eachUnreachableRange(node, cb) { +function isEnumDeclarationWithPreservedEmit(node, options) { + return node.kind === 266 /* EnumDeclaration */ && (!isEnumConst(node) || shouldPreserveConstEnums(options)); +} +function eachUnreachableRange(node, options, cb) { if (isStatement(node) && isExecutableStatement(node) && isBlock(node.parent)) { const { statements } = node.parent; const slice = sliceAfter(statements, node); @@ -143419,22 +143357,22 @@ function eachUnreachableRange(node, cb) { } else { cb(node, node); } -} -function isExecutableStatement(s) { - return !isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && !isEnumDeclaration(s) && // `var x;` may declare a variable used above - !(isVariableStatement(s) && !(getCombinedNodeFlags(s) & 7 /* BlockScoped */) && s.declarationList.declarations.some((d) => !d.initializer)); -} -function isPurelyTypeDeclaration(s) { - switch (s.kind) { - case 264 /* InterfaceDeclaration */: - case 265 /* TypeAliasDeclaration */: - return true; - case 267 /* ModuleDeclaration */: - return getModuleInstanceState(s) !== 1 /* Instantiated */; - case 266 /* EnumDeclaration */: - return hasSyntacticModifier(s, 4096 /* Const */); - default: - return false; + function isExecutableStatement(s) { + return !isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && // `var x;` may declare a variable used above + !(isVariableStatement(s) && !(getCombinedNodeFlags(s) & 7 /* BlockScoped */) && s.declarationList.declarations.some((d) => !d.initializer)); + } + function isPurelyTypeDeclaration(s) { + switch (s.kind) { + case 264 /* InterfaceDeclaration */: + case 265 /* TypeAliasDeclaration */: + return true; + case 267 /* ModuleDeclaration */: + return getModuleInstanceState(s) !== 1 /* Instantiated */; + case 266 /* EnumDeclaration */: + return !isEnumDeclarationWithPreservedEmit(s, options); + default: + return false; + } } } function isExportsOrModuleExportsOrAlias(sourceFile, node) { @@ -143703,6 +143641,28 @@ __export(ts_moduleSpecifiers_exports, { }); // src/compiler/moduleSpecifiers.ts +var stringToRegex = memoizeOne((pattern) => { + try { + let slash = pattern.indexOf("/"); + if (slash !== 0) { + return new RegExp(pattern); + } + const lastSlash = pattern.lastIndexOf("/"); + if (slash === lastSlash) { + return new RegExp(pattern); + } + while ((slash = pattern.indexOf("/", slash + 1)) !== lastSlash) { + if (pattern[slash - 1] !== "\\") { + return new RegExp(pattern); + } + } + const flags = pattern.substring(lastSlash + 1).replace(/[^iu]/g, ""); + pattern = pattern.substring(1, lastSlash); + return new RegExp(pattern, flags); + } catch { + return void 0; + } +}); var RelativePreference = /* @__PURE__ */ ((RelativePreference2) => { RelativePreference2[RelativePreference2["Relative"] = 0] = "Relative"; RelativePreference2[RelativePreference2["NonRelative"] = 1] = "NonRelative"; @@ -143710,13 +143670,16 @@ var RelativePreference = /* @__PURE__ */ ((RelativePreference2) => { RelativePreference2[RelativePreference2["ExternalNonRelative"] = 3] = "ExternalNonRelative"; return RelativePreference2; })(RelativePreference || {}); -function getModuleSpecifierPreferences({ importModuleSpecifierPreference, importModuleSpecifierEnding }, compilerOptions, importingSourceFile, oldImportSpecifier) { +function getModuleSpecifierPreferences({ importModuleSpecifierPreference, importModuleSpecifierEnding, autoImportSpecifierExcludeRegexes }, host, compilerOptions, importingSourceFile, oldImportSpecifier) { const filePreferredEnding = getPreferredEnding(); return { + excludeRegexes: autoImportSpecifierExcludeRegexes, relativePreference: oldImportSpecifier !== void 0 ? isExternalModuleNameRelative(oldImportSpecifier) ? 0 /* Relative */ : 1 /* NonRelative */ : importModuleSpecifierPreference === "relative" ? 0 /* Relative */ : importModuleSpecifierPreference === "non-relative" ? 1 /* NonRelative */ : importModuleSpecifierPreference === "project-relative" ? 3 /* ExternalNonRelative */ : 2 /* Shortest */, getAllowedEndingsInPreferredOrder: (syntaxImpliedNodeFormat) => { - const preferredEnding = syntaxImpliedNodeFormat !== importingSourceFile.impliedNodeFormat ? getPreferredEnding(syntaxImpliedNodeFormat) : filePreferredEnding; - if ((syntaxImpliedNodeFormat ?? importingSourceFile.impliedNodeFormat) === 99 /* ESNext */) { + const impliedNodeFormat = getDefaultResolutionModeForFile(importingSourceFile, host, compilerOptions); + const preferredEnding = syntaxImpliedNodeFormat !== impliedNodeFormat ? getPreferredEnding(syntaxImpliedNodeFormat) : filePreferredEnding; + const moduleResolution = getEmitModuleResolutionKind(compilerOptions); + if ((syntaxImpliedNodeFormat ?? impliedNodeFormat) === 99 /* ESNext */ && 3 /* Node16 */ <= moduleResolution && moduleResolution <= 99 /* NodeNext */) { if (shouldAllowImportingTsExtension(compilerOptions, importingSourceFile.fileName)) { return [3 /* TsExtension */, 2 /* JsExtension */]; } @@ -143747,19 +143710,19 @@ function getModuleSpecifierPreferences({ importModuleSpecifierPreference, import } return getModuleSpecifierEndingPreference( importModuleSpecifierEnding, - resolutionMode ?? importingSourceFile.impliedNodeFormat, + resolutionMode ?? getDefaultResolutionModeForFile(importingSourceFile, host, compilerOptions), compilerOptions, isFullSourceFile(importingSourceFile) ? importingSourceFile : void 0 ); } } function updateModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName2, host, oldImportSpecifier, options = {}) { - const res = getModuleSpecifierWorker(compilerOptions, importingSourceFile, importingSourceFileName, toFileName2, host, getModuleSpecifierPreferences({}, compilerOptions, importingSourceFile, oldImportSpecifier), {}, options); + const res = getModuleSpecifierWorker(compilerOptions, importingSourceFile, importingSourceFileName, toFileName2, host, getModuleSpecifierPreferences({}, host, compilerOptions, importingSourceFile, oldImportSpecifier), {}, options); if (res === oldImportSpecifier) return void 0; return res; } function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName2, host, options = {}) { - return getModuleSpecifierWorker(compilerOptions, importingSourceFile, importingSourceFileName, toFileName2, host, getModuleSpecifierPreferences({}, compilerOptions, importingSourceFile), {}, options); + return getModuleSpecifierWorker(compilerOptions, importingSourceFile, importingSourceFileName, toFileName2, host, getModuleSpecifierPreferences({}, host, compilerOptions, importingSourceFile), {}, options); } function getNodeModulesPackageName(compilerOptions, importingSourceFile, nodeModulesFileName, host, preferences, options = {}) { const info = getInfo(importingSourceFile.fileName, host); @@ -143789,7 +143752,7 @@ function getModuleSpecifierWorker(compilerOptions, importingSourceFile, importin /*packageNameOnly*/ void 0, options.overrideImportMode - )) || getLocalModuleSpecifier(toFileName2, info, compilerOptions, host, options.overrideImportMode || importingSourceFile.impliedNodeFormat, preferences); + )) || getLocalModuleSpecifier(toFileName2, info, compilerOptions, host, options.overrideImportMode || getDefaultResolutionModeForFile(importingSourceFile, host, compilerOptions), preferences); } function tryGetModuleSpecifiersFromCache(moduleSymbol, importingSourceFile, host, userPreferences, options = {}) { const result = tryGetModuleSpecifiersFromCacheWorker( @@ -143827,7 +143790,13 @@ function getModuleSpecifiers(moduleSymbol, checker, compilerOptions, importingSo function getModuleSpecifiersWithCacheInfo(moduleSymbol, checker, compilerOptions, importingSourceFile, host, userPreferences, options = {}, forAutoImport) { let computedWithoutCache = false; const ambient = tryGetModuleNameFromAmbientModule(moduleSymbol, checker); - if (ambient) return { kind: "ambient", moduleSpecifiers: [ambient], computedWithoutCache }; + if (ambient) { + return { + kind: "ambient", + moduleSpecifiers: !(forAutoImport && isExcludedByRegex(ambient, userPreferences.autoImportSpecifierExcludeRegexes)) ? [ambient] : emptyArray, + computedWithoutCache + }; + } let [kind, specifiers, moduleSourceFile, modulePaths, cache] = tryGetModuleSpecifiersFromCacheWorker( moduleSymbol, importingSourceFile, @@ -143851,7 +143820,7 @@ function getModuleSpecifiersWithCacheInfo(moduleSymbol, checker, compilerOptions cache == null ? void 0 : cache.set(importingSourceFile.path, moduleSourceFile.path, userPreferences, options, result.kind, modulePaths, result.moduleSpecifiers); return result; } -function getLocalModuleSpecifierBetweenFileNames(importingFile, targetFileName, compilerOptions, host, options = {}) { +function getLocalModuleSpecifierBetweenFileNames(importingFile, targetFileName, compilerOptions, host, preferences, options = {}) { const info = getInfo(importingFile.fileName, host); const importMode = options.overrideImportMode ?? importingFile.impliedNodeFormat; return getLocalModuleSpecifier( @@ -143860,17 +143829,21 @@ function getLocalModuleSpecifierBetweenFileNames(importingFile, targetFileName, compilerOptions, host, importMode, - getModuleSpecifierPreferences({}, compilerOptions, importingFile) + getModuleSpecifierPreferences(preferences, host, compilerOptions, importingFile) ); } function computeModuleSpecifiers(modulePaths, compilerOptions, importingSourceFile, host, userPreferences, options = {}, forAutoImport) { const info = getInfo(importingSourceFile.fileName, host); - const preferences = getModuleSpecifierPreferences(userPreferences, compilerOptions, importingSourceFile); + const preferences = getModuleSpecifierPreferences(userPreferences, host, compilerOptions, importingSourceFile); const existingSpecifier = isFullSourceFile(importingSourceFile) && forEach(modulePaths, (modulePath) => forEach( host.getFileIncludeReasons().get(toPath(modulePath.path, host.getCurrentDirectory(), info.getCanonicalFileName)), (reason) => { if (reason.kind !== 3 /* Import */ || reason.file !== importingSourceFile.path) return void 0; - if (importingSourceFile.impliedNodeFormat && importingSourceFile.impliedNodeFormat !== getModeForResolutionAtIndex(importingSourceFile, reason.index, compilerOptions)) return void 0; + const existingMode = host.getModeForResolutionAtIndex(importingSourceFile, reason.index); + const targetMode = options.overrideImportMode ?? host.getDefaultResolutionModeForFile(importingSourceFile); + if (existingMode !== targetMode && existingMode !== void 0 && targetMode !== void 0) { + return void 0; + } const specifier = getModuleNameStringLiteralAt(importingSourceFile, reason.index).text; return preferences.relativePreference !== 1 /* NonRelative */ || !pathIsRelative(specifier) ? specifier : void 0; } @@ -143895,9 +143868,11 @@ function computeModuleSpecifiers(modulePaths, compilerOptions, importingSourceFi void 0, options.overrideImportMode ) : void 0; - nodeModulesSpecifiers = append(nodeModulesSpecifiers, specifier); - if (specifier && modulePath.isRedirect) { - return { kind: "node_modules", moduleSpecifiers: nodeModulesSpecifiers, computedWithoutCache: true }; + if (specifier && !(forAutoImport && isExcludedByRegex(specifier, preferences.excludeRegexes))) { + nodeModulesSpecifiers = append(nodeModulesSpecifiers, specifier); + if (modulePath.isRedirect) { + return { kind: "node_modules", moduleSpecifiers: nodeModulesSpecifiers, computedWithoutCache: true }; + } } if (!specifier) { const local = getLocalModuleSpecifier( @@ -143910,7 +143885,7 @@ function computeModuleSpecifiers(modulePaths, compilerOptions, importingSourceFi /*pathsOnly*/ modulePath.isRedirect ); - if (!local) { + if (!local || forAutoImport && isExcludedByRegex(local, preferences.excludeRegexes)) { continue; } if (modulePath.isRedirect) { @@ -143926,7 +143901,13 @@ function computeModuleSpecifiers(modulePaths, compilerOptions, importingSourceFi } } } - return (pathsSpecifiers == null ? void 0 : pathsSpecifiers.length) ? { kind: "paths", moduleSpecifiers: pathsSpecifiers, computedWithoutCache: true } : (redirectPathsSpecifiers == null ? void 0 : redirectPathsSpecifiers.length) ? { kind: "redirect", moduleSpecifiers: redirectPathsSpecifiers, computedWithoutCache: true } : (nodeModulesSpecifiers == null ? void 0 : nodeModulesSpecifiers.length) ? { kind: "node_modules", moduleSpecifiers: nodeModulesSpecifiers, computedWithoutCache: true } : { kind: "relative", moduleSpecifiers: Debug.checkDefined(relativeSpecifiers), computedWithoutCache: true }; + return (pathsSpecifiers == null ? void 0 : pathsSpecifiers.length) ? { kind: "paths", moduleSpecifiers: pathsSpecifiers, computedWithoutCache: true } : (redirectPathsSpecifiers == null ? void 0 : redirectPathsSpecifiers.length) ? { kind: "redirect", moduleSpecifiers: redirectPathsSpecifiers, computedWithoutCache: true } : (nodeModulesSpecifiers == null ? void 0 : nodeModulesSpecifiers.length) ? { kind: "node_modules", moduleSpecifiers: nodeModulesSpecifiers, computedWithoutCache: true } : { kind: "relative", moduleSpecifiers: relativeSpecifiers ?? emptyArray, computedWithoutCache: true }; +} +function isExcludedByRegex(moduleSpecifier, excludeRegexes) { + return some(excludeRegexes, (pattern) => { + var _a; + return !!((_a = stringToRegex(pattern)) == null ? void 0 : _a.test(moduleSpecifier)); + }); } function getInfo(importingSourceFileName, host) { importingSourceFileName = getNormalizedAbsolutePath(importingSourceFileName, host.getCurrentDirectory()); @@ -143939,7 +143920,7 @@ function getInfo(importingSourceFileName, host) { canonicalSourceDirectory: getCanonicalFileName(sourceDirectory) }; } -function getLocalModuleSpecifier(moduleFileName, info, compilerOptions, host, importMode, { getAllowedEndingsInPreferredOrder: getAllowedEndingsInPrefererredOrder, relativePreference }, pathsOnly) { +function getLocalModuleSpecifier(moduleFileName, info, compilerOptions, host, importMode, { getAllowedEndingsInPreferredOrder: getAllowedEndingsInPrefererredOrder, relativePreference, excludeRegexes }, pathsOnly) { const { baseUrl, paths, rootDirs } = compilerOptions; if (pathsOnly && !paths) { return void 0; @@ -143955,7 +143936,14 @@ function getLocalModuleSpecifier(moduleFileName, info, compilerOptions, host, im if (!relativeToBaseUrl) { return pathsOnly ? void 0 : relativePath; } - const fromPackageJsonImports = pathsOnly ? void 0 : tryGetModuleNameFromPackageJsonImports(moduleFileName, sourceDirectory, compilerOptions, host, importMode); + const fromPackageJsonImports = pathsOnly ? void 0 : tryGetModuleNameFromPackageJsonImports( + moduleFileName, + sourceDirectory, + compilerOptions, + host, + importMode, + prefersTsExtension(allowedEndings) + ); const fromPaths = pathsOnly || fromPackageJsonImports === void 0 ? paths && tryGetModuleNameFromPaths(relativeToBaseUrl, paths, allowedEndings, host, compilerOptions) : void 0; if (pathsOnly) { return fromPaths; @@ -143964,6 +143952,14 @@ function getLocalModuleSpecifier(moduleFileName, info, compilerOptions, host, im if (!maybeNonRelative) { return relativePath; } + const relativeIsExcluded = isExcludedByRegex(relativePath, excludeRegexes); + const nonRelativeIsExcluded = isExcludedByRegex(maybeNonRelative, excludeRegexes); + if (!relativeIsExcluded && nonRelativeIsExcluded) { + return relativePath; + } + if (relativeIsExcluded && !nonRelativeIsExcluded) { + return maybeNonRelative; + } if (relativePreference === 1 /* NonRelative */ && !pathIsRelative(maybeNonRelative)) { return maybeNonRelative; } @@ -144078,7 +144074,7 @@ function getAllModulePathsWorker(info, importedFileName, host, compilerOptions, if (cache && links && host.readFile && !pathContainsNodeModules(info.importingSourceFileName)) { Debug.type(host); const state = getTemporaryModuleResolutionState(cache.getPackageJsonInfoCache(), host, {}); - const packageJson = getPackageScopeForPath(info.importingSourceFileName, state); + const packageJson = getPackageScopeForPath(getDirectoryPath(info.importingSourceFileName), state); if (packageJson) { const toResolve = getAllRuntimeDependencies(packageJson.contents.packageJsonContent); for (const depName of toResolve || emptyArray) { @@ -144105,15 +144101,7 @@ function getAllModulePathsWorker(info, importedFileName, host, compilerOptions, /*preferSymlinks*/ true, (path, isRedirect) => { - let isInNodeModules = pathContainsNodeModules(path); - const pnpapi = getPnpApi(path); - if (!isInNodeModules && pnpapi) { - const fromLocator = pnpapi.findPackageLocator(info.importingSourceFileName); - const toLocator = pnpapi.findPackageLocator(path); - if (fromLocator && toLocator && fromLocator !== toLocator) { - isInNodeModules = true; - } - } + const isInNodeModules = pathContainsNodeModules(path); allFileNames.set(path, { path: info.getCanonicalFileName(path), isRedirect, isInNodeModules }); importedFileFromNodeModules = importedFileFromNodeModules || isInNodeModules; } @@ -144211,7 +144199,7 @@ function tryGetModuleNameFromPaths(relativeToBaseUrl, paths, allowedEndings, hos return ending !== 0 /* Minimal */ || value === processEnding(relativeToBaseUrl, [ending], compilerOptions, host); } } -function tryGetModuleNameFromExportsOrImports(options, host, targetFilePath, packageDirectory, packageName, exports2, conditions, mode, isImports) { +function tryGetModuleNameFromExportsOrImports(options, host, targetFilePath, packageDirectory, packageName, exports2, conditions, mode, isImports, preferTsExtension) { if (typeof exports2 === "string") { const ignoreCase = !hostUsesCaseSensitiveFileNames(host); const getCommonSourceDirectory2 = () => host.getCommonSourceDirectory(); @@ -144223,6 +144211,7 @@ function tryGetModuleNameFromExportsOrImports(options, host, targetFilePath, pac void 0 ); const extensionSwappedTarget = hasTSFileExtension(targetFilePath) ? removeFileExtension(targetFilePath) + tryGetJSExtensionForFile(targetFilePath, options) : void 0; + const canTryTsExtension = preferTsExtension && hasImplementationTSFileExtension(targetFilePath); switch (mode) { case 0 /* Exact */: if (extensionSwappedTarget && comparePaths(extensionSwappedTarget, pathOrPattern, ignoreCase) === 0 /* EqualTo */ || comparePaths(targetFilePath, pathOrPattern, ignoreCase) === 0 /* EqualTo */ || outputFile && comparePaths(outputFile, pathOrPattern, ignoreCase) === 0 /* EqualTo */ || declarationFile && comparePaths(declarationFile, pathOrPattern, ignoreCase) === 0 /* EqualTo */) { @@ -144230,6 +144219,19 @@ function tryGetModuleNameFromExportsOrImports(options, host, targetFilePath, pac } break; case 1 /* Directory */: + if (canTryTsExtension && containsPath(targetFilePath, pathOrPattern, ignoreCase)) { + const fragment = getRelativePathFromDirectory( + pathOrPattern, + targetFilePath, + /*ignoreCase*/ + false + ); + return { moduleFileToTry: getNormalizedAbsolutePath( + combinePaths(combinePaths(packageName, exports2), fragment), + /*currentDirectory*/ + void 0 + ) }; + } if (extensionSwappedTarget && containsPath(pathOrPattern, extensionSwappedTarget, ignoreCase)) { const fragment = getRelativePathFromDirectory( pathOrPattern, @@ -144243,7 +144245,7 @@ function tryGetModuleNameFromExportsOrImports(options, host, targetFilePath, pac void 0 ) }; } - if (containsPath(pathOrPattern, targetFilePath, ignoreCase)) { + if (!canTryTsExtension && containsPath(pathOrPattern, targetFilePath, ignoreCase)) { const fragment = getRelativePathFromDirectory( pathOrPattern, targetFilePath, @@ -144266,12 +144268,12 @@ function tryGetModuleNameFromExportsOrImports(options, host, targetFilePath, pac return { moduleFileToTry: combinePaths(packageName, fragment) }; } if (declarationFile && containsPath(pathOrPattern, declarationFile, ignoreCase)) { - const fragment = getRelativePathFromDirectory( + const fragment = changeFullExtension(getRelativePathFromDirectory( pathOrPattern, declarationFile, /*ignoreCase*/ false - ); + ), getJSExtensionForFile(declarationFile, options)); return { moduleFileToTry: combinePaths(packageName, fragment) }; } break; @@ -144279,11 +144281,15 @@ function tryGetModuleNameFromExportsOrImports(options, host, targetFilePath, pac const starPos = pathOrPattern.indexOf("*"); const leadingSlice = pathOrPattern.slice(0, starPos); const trailingSlice = pathOrPattern.slice(starPos + 1); + if (canTryTsExtension && startsWith(targetFilePath, leadingSlice, ignoreCase) && endsWith(targetFilePath, trailingSlice, ignoreCase)) { + const starReplacement = targetFilePath.slice(leadingSlice.length, targetFilePath.length - trailingSlice.length); + return { moduleFileToTry: replaceFirstStar(packageName, starReplacement) }; + } if (extensionSwappedTarget && startsWith(extensionSwappedTarget, leadingSlice, ignoreCase) && endsWith(extensionSwappedTarget, trailingSlice, ignoreCase)) { const starReplacement = extensionSwappedTarget.slice(leadingSlice.length, extensionSwappedTarget.length - trailingSlice.length); return { moduleFileToTry: replaceFirstStar(packageName, starReplacement) }; } - if (startsWith(targetFilePath, leadingSlice, ignoreCase) && endsWith(targetFilePath, trailingSlice, ignoreCase)) { + if (!canTryTsExtension && startsWith(targetFilePath, leadingSlice, ignoreCase) && endsWith(targetFilePath, trailingSlice, ignoreCase)) { const starReplacement = targetFilePath.slice(leadingSlice.length, targetFilePath.length - trailingSlice.length); return { moduleFileToTry: replaceFirstStar(packageName, starReplacement) }; } @@ -144293,17 +144299,19 @@ function tryGetModuleNameFromExportsOrImports(options, host, targetFilePath, pac } if (declarationFile && startsWith(declarationFile, leadingSlice, ignoreCase) && endsWith(declarationFile, trailingSlice, ignoreCase)) { const starReplacement = declarationFile.slice(leadingSlice.length, declarationFile.length - trailingSlice.length); - return { moduleFileToTry: replaceFirstStar(packageName, starReplacement) }; + const substituted = replaceFirstStar(packageName, starReplacement); + const jsExtension = tryGetJSExtensionForFile(declarationFile, options); + return jsExtension ? { moduleFileToTry: changeFullExtension(substituted, jsExtension) } : void 0; } break; } } else if (Array.isArray(exports2)) { - return forEach(exports2, (e) => tryGetModuleNameFromExportsOrImports(options, host, targetFilePath, packageDirectory, packageName, e, conditions, mode, isImports)); + return forEach(exports2, (e) => tryGetModuleNameFromExportsOrImports(options, host, targetFilePath, packageDirectory, packageName, e, conditions, mode, isImports, preferTsExtension)); } else if (typeof exports2 === "object" && exports2 !== null) { for (const key of getOwnKeys(exports2)) { if (key === "default" || conditions.indexOf(key) >= 0 || isApplicableVersionedTypesKey(conditions, key)) { const subTarget = exports2[key]; - const result = tryGetModuleNameFromExportsOrImports(options, host, targetFilePath, packageDirectory, packageName, subTarget, conditions, mode, isImports); + const result = tryGetModuleNameFromExportsOrImports(options, host, targetFilePath, packageDirectory, packageName, subTarget, conditions, mode, isImports, preferTsExtension); if (result) { return result; } @@ -144331,6 +144339,8 @@ function tryGetModuleNameFromExports(options, host, targetFilePath, packageDirec conditions, mode, /*isImports*/ + false, + /*preferTsExtension*/ false ); }); @@ -144345,10 +144355,12 @@ function tryGetModuleNameFromExports(options, host, targetFilePath, packageDirec conditions, 0 /* Exact */, /*isImports*/ + false, + /*preferTsExtension*/ false ); } -function tryGetModuleNameFromPackageJsonImports(moduleFileName, sourceDirectory, options, host, importMode) { +function tryGetModuleNameFromPackageJsonImports(moduleFileName, sourceDirectory, options, host, importMode, preferTsExtension) { var _a, _b, _c; if (!host.readFile || !getResolvePackageJsonImports(options)) { return void 0; @@ -144381,7 +144393,8 @@ function tryGetModuleNameFromPackageJsonImports(moduleFileName, sourceDirectory, conditions, mode, /*isImports*/ - true + true, + preferTsExtension ); })) == null ? void 0 : _c.moduleFileToTry; } @@ -144404,45 +144417,11 @@ function tryGetModuleNameAsNodeModule({ path, isRedirect }, { getCanonicalFileNa if (!host.fileExists || !host.readFile) { return void 0; } - let parts = getNodeModulePathParts(path); - let pnpPackageName; - const pnpApi = getPnpApi(path); - if (pnpApi) { - const fromLocator = pnpApi.findPackageLocator(importingSourceFile.fileName); - const toLocator = pnpApi.findPackageLocator(path); - if (fromLocator === toLocator) { - return void 0; - } - if (fromLocator && toLocator) { - const fromInfo = pnpApi.getPackageInformation(fromLocator); - if (toLocator.reference === fromInfo.packageDependencies.get(toLocator.name)) { - pnpPackageName = toLocator.name; - } else { - for (const [name, reference] of fromInfo.packageDependencies) { - if (Array.isArray(reference)) { - if (reference[0] === toLocator.name && reference[1] === toLocator.reference) { - pnpPackageName = name; - break; - } - } - } - } - if (!parts) { - const toInfo = pnpApi.getPackageInformation(toLocator); - parts = { - topLevelNodeModulesIndex: void 0, - topLevelPackageNameIndex: void 0, - // The last character from packageLocation is the trailing "/", we want to point to it - packageRootIndex: toInfo.packageLocation.length - 1, - fileNameIndex: path.lastIndexOf(`/`) - }; - } - } - } + const parts = getNodeModulePathParts(path); if (!parts) { return void 0; } - const preferences = getModuleSpecifierPreferences(userPreferences, options, importingSourceFile); + const preferences = getModuleSpecifierPreferences(userPreferences, host, options, importingSourceFile); const allowedEndings = preferences.getAllowedEndingsInPreferredOrder(); let moduleSpecifier = path; let isPackageRootPath = false; @@ -144475,16 +144454,14 @@ function tryGetModuleNameAsNodeModule({ path, isRedirect }, { getCanonicalFileNa if (isRedirect && !isPackageRootPath) { return void 0; } - if (typeof process.versions.pnp === "undefined") { - const globalTypingsCacheLocation = host.getGlobalTypingsCacheLocation && host.getGlobalTypingsCacheLocation(); - const pathToTopLevelNodeModules = getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)); - if (!(startsWith(canonicalSourceDirectory, pathToTopLevelNodeModules) || globalTypingsCacheLocation && startsWith(getCanonicalFileName(globalTypingsCacheLocation), pathToTopLevelNodeModules))) { - return void 0; - } + const globalTypingsCacheLocation = host.getGlobalTypingsCacheLocation && host.getGlobalTypingsCacheLocation(); + const pathToTopLevelNodeModules = getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)); + if (!(startsWith(canonicalSourceDirectory, pathToTopLevelNodeModules) || globalTypingsCacheLocation && startsWith(getCanonicalFileName(globalTypingsCacheLocation), pathToTopLevelNodeModules))) { + return void 0; } - const nodeModulesDirectoryName = typeof pnpPackageName !== "undefined" ? pnpPackageName + moduleSpecifier.substring(parts.packageRootIndex) : moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1); - const packageNameFromPath = getPackageNameFromTypesPackageName(nodeModulesDirectoryName); - return getEmitModuleResolutionKind(options) === 1 /* Classic */ && packageNameFromPath === nodeModulesDirectoryName ? void 0 : packageNameFromPath; + const nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1); + const packageName = getPackageNameFromTypesPackageName(nodeModulesDirectoryName); + return getEmitModuleResolutionKind(options) === 1 /* Classic */ && packageName === nodeModulesDirectoryName ? void 0 : packageName; function tryDirectoryWithPackageJson(packageRootIndex) { var _a, _b; const packageRootPath = path.substring(0, packageRootIndex); @@ -144494,12 +144471,20 @@ function tryGetModuleNameAsNodeModule({ path, isRedirect }, { getCanonicalFileNa const cachedPackageJson = (_b = (_a = host.getPackageJsonInfoCache) == null ? void 0 : _a.call(host)) == null ? void 0 : _b.getPackageJsonInfo(packageJsonPath); if (isPackageJsonInfo(cachedPackageJson) || cachedPackageJson === void 0 && host.fileExists(packageJsonPath)) { const packageJsonContent = (cachedPackageJson == null ? void 0 : cachedPackageJson.contents.packageJsonContent) || tryParseJson(host.readFile(packageJsonPath)); - const importMode = overrideMode || importingSourceFile.impliedNodeFormat; + const importMode = overrideMode || getDefaultResolutionModeForFile(importingSourceFile, host, options); if (getResolvePackageJsonExports(options)) { const nodeModulesDirectoryName2 = packageRootPath.substring(parts.topLevelPackageNameIndex + 1); - const packageName = getPackageNameFromTypesPackageName(pnpPackageName ? pnpPackageName : nodeModulesDirectoryName2); + const packageName2 = getPackageNameFromTypesPackageName(nodeModulesDirectoryName2); const conditions = getConditions(options, importMode); - const fromExports = (packageJsonContent == null ? void 0 : packageJsonContent.exports) ? tryGetModuleNameFromExports(options, host, path, packageRootPath, packageName, packageJsonContent.exports, conditions) : void 0; + const fromExports = (packageJsonContent == null ? void 0 : packageJsonContent.exports) ? tryGetModuleNameFromExports( + options, + host, + path, + packageRootPath, + packageName2, + packageJsonContent.exports, + conditions + ) : void 0; if (fromExports) { return { ...fromExports, verbatimFromExports: true }; } @@ -144644,6 +144629,13 @@ function getRelativePathIfInSameVolume(path, directoryPath, getCanonicalFileName function isPathRelativeToParent(path) { return startsWith(path, ".."); } +function getDefaultResolutionModeForFile(file, host, compilerOptions) { + return isFullSourceFile(file) ? host.getDefaultResolutionModeForFile(file) : getDefaultResolutionModeForFileWorker(file, compilerOptions); +} +function prefersTsExtension(allowedEndings) { + const tsPriority = allowedEndings.indexOf(3 /* TsExtension */); + return tsPriority > -1 && tsPriority < allowedEndings.indexOf(2 /* JsExtension */); +} // src/compiler/checker.ts var ambientModuleSymbolRegex = /^".+"$/; @@ -144825,10 +144817,12 @@ function createTypeChecker(host) { var strictFunctionTypes = getStrictOptionValue(compilerOptions, "strictFunctionTypes"); var strictBindCallApply = getStrictOptionValue(compilerOptions, "strictBindCallApply"); var strictPropertyInitialization = getStrictOptionValue(compilerOptions, "strictPropertyInitialization"); + var strictBuiltinIteratorReturn = getStrictOptionValue(compilerOptions, "strictBuiltinIteratorReturn"); var noImplicitAny = getStrictOptionValue(compilerOptions, "noImplicitAny"); var noImplicitThis = getStrictOptionValue(compilerOptions, "noImplicitThis"); var useUnknownInCatchVariables = getStrictOptionValue(compilerOptions, "useUnknownInCatchVariables"); var exactOptionalPropertyTypes = compilerOptions.exactOptionalPropertyTypes; + var noUncheckedSideEffectImports = !!compilerOptions.noUncheckedSideEffectImports; var checkBinaryExpression = createCheckBinaryExpression(); var emitResolver = createResolver(); var nodeBuilder = createNodeBuilder(); @@ -144958,6 +144952,7 @@ function createTypeChecker(host) { getNonOptionalType: removeOptionalTypeMarker, getTypeArguments, typeToTypeNode: nodeBuilder.typeToTypeNode, + typePredicateToTypePredicateNode: nodeBuilder.typePredicateToTypePredicateNode, indexInfoToIndexSignatureDeclaration: nodeBuilder.indexInfoToIndexSignatureDeclaration, signatureToSignatureDeclaration: nodeBuilder.signatureToSignatureDeclaration, symbolToEntityName: nodeBuilder.symbolToEntityName, @@ -145123,13 +145118,6 @@ function createTypeChecker(host) { /*withAugmentations*/ true ), - tryFindAmbientModuleWithoutAugmentations: (moduleName) => { - return tryFindAmbientModule( - moduleName, - /*withAugmentations*/ - false - ); - }, getApparentType, getUnionType, isTypeAssignableTo, @@ -145143,6 +145131,7 @@ function createTypeChecker(host) { getNumberType: () => numberType, getNumberLiteralType, getBigIntType: () => bigintType, + getBigIntLiteralType, createPromiseType, createArrayType, getElementTypeOfArrayType, @@ -145163,13 +145152,13 @@ function createTypeChecker(host) { /*reportErrors*/ false ), - getAsyncIterableType: () => { + getAnyAsyncIterableType: () => { const type = getGlobalAsyncIterableType( /*reportErrors*/ false ); if (type === emptyGenericType) return void 0; - return type; + return createTypeReference(type, [anyType, anyType, anyType]); }, isSymbolAccessible, isArrayType, @@ -145641,8 +145630,6 @@ function createTypeChecker(host) { } }; var anyIterationTypes = createIterationTypes(anyType, anyType, anyType); - var anyIterationTypesExceptNext = createIterationTypes(anyType, anyType, unknownType); - var defaultIterationTypes = createIterationTypes(neverType, anyType, undefinedType); var asyncIterationTypesResolver = { iterableCacheKey: "iterationTypesOfAsyncIterable", iteratorCacheKey: "iterationTypesOfAsyncIterator", @@ -145650,7 +145637,9 @@ function createTypeChecker(host) { getGlobalIteratorType: getGlobalAsyncIteratorType, getGlobalIterableType: getGlobalAsyncIterableType, getGlobalIterableIteratorType: getGlobalAsyncIterableIteratorType, + getGlobalIteratorObjectType: getGlobalAsyncIteratorObjectType, getGlobalGeneratorType: getGlobalAsyncGeneratorType, + getGlobalBuiltinIteratorTypes: getGlobalBuiltinAsyncIteratorTypes, resolveIterationType: (type, errorNode) => getAwaitedType(type, errorNode, Diagnostics.Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member), mustHaveANextMethodDiagnostic: Diagnostics.An_async_iterator_must_have_a_next_method, mustBeAMethodDiagnostic: Diagnostics.The_0_property_of_an_async_iterator_must_be_a_method, @@ -145663,7 +145652,9 @@ function createTypeChecker(host) { getGlobalIteratorType, getGlobalIterableType, getGlobalIterableIteratorType, + getGlobalIteratorObjectType, getGlobalGeneratorType, + getGlobalBuiltinIteratorTypes, resolveIterationType: (type, _errorNode) => type, mustHaveANextMethodDiagnostic: Diagnostics.An_iterator_must_have_a_next_method, mustBeAMethodDiagnostic: Diagnostics.The_0_property_of_an_iterator_must_be_a_method, @@ -145701,12 +145692,16 @@ function createTypeChecker(host) { var deferredGlobalIterableType; var deferredGlobalIteratorType; var deferredGlobalIterableIteratorType; + var deferredGlobalIteratorObjectType; var deferredGlobalGeneratorType; var deferredGlobalIteratorYieldResultType; var deferredGlobalIteratorReturnResultType; var deferredGlobalAsyncIterableType; var deferredGlobalAsyncIteratorType; var deferredGlobalAsyncIterableIteratorType; + var deferredGlobalBuiltinIteratorTypes; + var deferredGlobalBuiltinAsyncIteratorTypes; + var deferredGlobalAsyncIteratorObjectType; var deferredGlobalAsyncGeneratorType; var deferredGlobalTemplateStringsArrayType; var deferredGlobalImportMetaType; @@ -145742,6 +145737,7 @@ function createTypeChecker(host) { var contextualTypes = []; var contextualIsCache = []; var contextualTypeCount = 0; + var contextualBindingPatterns = []; var inferenceContextNodes = []; var inferenceContexts = []; var inferenceContextCount = 0; @@ -146059,7 +146055,7 @@ function createTypeChecker(host) { } if (source.exports) { if (!target.exports) target.exports = createSymbolTable(); - mergeSymbolTable(target.exports, source.exports, unidirectional); + mergeSymbolTable(target.exports, source.exports, unidirectional, target); } if (!unidirectional) { recordMergedSymbol(target, source); @@ -146139,10 +146135,14 @@ function createTypeChecker(host) { mergeSymbolTable(combined, second); return combined; } - function mergeSymbolTable(target, source, unidirectional = false) { + function mergeSymbolTable(target, source, unidirectional = false, mergedParent) { source.forEach((sourceSymbol, id) => { const targetSymbol = target.get(id); - target.set(id, targetSymbol ? mergeSymbol(targetSymbol, sourceSymbol, unidirectional) : getMergedSymbol(sourceSymbol)); + const merged = targetSymbol ? mergeSymbol(targetSymbol, sourceSymbol, unidirectional) : getMergedSymbol(sourceSymbol); + if (mergedParent && targetSymbol) { + merged.parent = mergedParent; + } + target.set(id, merged); }); } function mergeModuleAugmentation(moduleName) { @@ -146160,6 +146160,8 @@ function createTypeChecker(host) { moduleName, moduleName, moduleNotFoundError, + /*ignoreErrors*/ + false, /*isForAugmentation*/ true ); @@ -146796,9 +146798,9 @@ function createTypeChecker(host) { } } function getDeclarationOfAliasSymbol(symbol) { - return symbol.declarations && findLast(symbol.declarations, isAliasSymbolDeclaration2); + return symbol.declarations && findLast(symbol.declarations, isAliasSymbolDeclaration); } - function isAliasSymbolDeclaration2(node) { + function isAliasSymbolDeclaration(node) { return node.kind === 271 /* ImportEqualsDeclaration */ || node.kind === 270 /* NamespaceExportDeclaration */ || node.kind === 273 /* ImportClause */ && !!node.name || node.kind === 274 /* NamespaceImport */ || node.kind === 280 /* NamespaceExport */ || node.kind === 276 /* ImportSpecifier */ || node.kind === 281 /* ExportSpecifier */ || node.kind === 277 /* ExportAssignment */ && exportAssignmentIsAlias(node) || isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ && exportAssignmentIsAlias(node) || isAccessExpression(node) && isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 64 /* EqualsToken */ && isAliasableOrJsExpression(node.parent.right) || node.kind === 304 /* ShorthandPropertyAssignment */ || node.kind === 303 /* PropertyAssignment */ && isAliasableOrJsExpression(node.initializer) || node.kind === 260 /* VariableDeclaration */ && isVariableDeclarationInitializedToBareOrAccessedRequire(node) || node.kind === 208 /* BindingElement */ && isVariableDeclarationInitializedToBareOrAccessedRequire(node.parent.parent); } function isAliasableOrJsExpression(e) { @@ -146842,7 +146844,7 @@ function createTypeChecker(host) { const isExport = typeOnlyDeclaration.kind === 281 /* ExportSpecifier */ || typeOnlyDeclaration.kind === 278 /* ExportDeclaration */; const message = isExport ? Diagnostics.An_import_alias_cannot_reference_a_declaration_that_was_exported_using_export_type : Diagnostics.An_import_alias_cannot_reference_a_declaration_that_was_imported_using_import_type; const relatedMessage = isExport ? Diagnostics._0_was_exported_here : Diagnostics._0_was_imported_here; - const name = typeOnlyDeclaration.kind === 278 /* ExportDeclaration */ ? "*" : unescapeLeadingUnderscores(typeOnlyDeclaration.name.escapedText); + const name = typeOnlyDeclaration.kind === 278 /* ExportDeclaration */ ? "*" : moduleExportNameTextUnescaped(typeOnlyDeclaration.name); addRelatedInfo(error2(node.moduleReference, message), createDiagnosticForNode(typeOnlyDeclaration, relatedMessage, name)); } } @@ -146867,22 +146869,28 @@ function createTypeChecker(host) { function isSyntacticDefault(node) { return isExportAssignment(node) && !node.isExportEquals || hasSyntacticModifier(node, 2048 /* Default */) || isExportSpecifier(node) || isNamespaceExport(node); } - function getUsageModeForExpression(usage) { - return isStringLiteralLike(usage) ? host.getModeForUsageLocation(getSourceFileOfNode(usage), usage) : void 0; + function getEmitSyntaxForModuleSpecifierExpression(usage) { + return isStringLiteralLike(usage) ? host.getEmitSyntaxForUsageLocation(getSourceFileOfNode(usage), usage) : void 0; } function isESMFormatImportImportingCommonjsFormatFile(usageMode, targetMode) { return usageMode === 99 /* ESNext */ && targetMode === 1 /* CommonJS */; } - function isOnlyImportedAsDefault(usage) { - const usageMode = getUsageModeForExpression(usage); - return usageMode === 99 /* ESNext */ && endsWith(usage.text, ".json" /* Json */); + function isOnlyImportableAsDefault(usage) { + if (100 /* Node16 */ <= moduleKind && moduleKind <= 199 /* NodeNext */) { + const usageMode = getEmitSyntaxForModuleSpecifierExpression(usage); + return usageMode === 99 /* ESNext */ && endsWith(usage.text, ".json" /* Json */); + } + return false; } function canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias, usage) { - const usageMode = file && getUsageModeForExpression(usage); - if (file && usageMode !== void 0 && 100 /* Node16 */ <= moduleKind && moduleKind <= 199 /* NodeNext */) { - const result = isESMFormatImportImportingCommonjsFormatFile(usageMode, file.impliedNodeFormat); - if (usageMode === 99 /* ESNext */ || result) { - return result; + const usageMode = file && getEmitSyntaxForModuleSpecifierExpression(usage); + if (file && usageMode !== void 0) { + const targetMode = host.getImpliedNodeFormatForEmit(file); + if (usageMode === 99 /* ESNext */ && targetMode === 1 /* CommonJS */ && 100 /* Node16 */ <= moduleKind && moduleKind <= 199 /* NodeNext */) { + return true; + } + if (usageMode === 99 /* ESNext */ && targetMode === 99 /* ESNext */) { + return false; } } if (!allowSyntheticDefaultImports) { @@ -146941,7 +146949,7 @@ function createTypeChecker(host) { if (!specifier) { return exportDefaultSymbol; } - const hasDefaultOnly = isOnlyImportedAsDefault(specifier); + const hasDefaultOnly = isOnlyImportableAsDefault(specifier); const hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias, specifier); if (!exportDefaultSymbol && !hasSyntheticDefault && !hasDefaultOnly) { if (hasExportAssignmentSymbol(moduleSymbol) && !allowSyntheticDefaultImports) { @@ -147080,12 +147088,12 @@ function createTypeChecker(host) { if (valueSymbol.exports) result.exports = new Map(valueSymbol.exports); return result; } - function getExportOfModule(symbol, name, specifier, dontResolveAlias) { + function getExportOfModule(symbol, nameText, specifier, dontResolveAlias) { var _a; if (symbol.flags & 1536 /* Module */) { - const exportSymbol = getExportsOfSymbol(symbol).get(name.escapedText); + const exportSymbol = getExportsOfSymbol(symbol).get(nameText); const resolved = resolveSymbol(exportSymbol, dontResolveAlias); - const exportStarDeclaration = (_a = getSymbolLinks(symbol).typeOnlyExportStarMap) == null ? void 0 : _a.get(name.escapedText); + const exportStarDeclaration = (_a = getSymbolLinks(symbol).typeOnlyExportStarMap) == null ? void 0 : _a.get(nameText); markSymbolOfAliasDeclarationIfTypeOnly( specifier, exportSymbol, @@ -147093,7 +147101,7 @@ function createTypeChecker(host) { /*overwriteEmpty*/ false, exportStarDeclaration, - name.escapedText + nameText ); return resolved; } @@ -147111,10 +147119,11 @@ function createTypeChecker(host) { const moduleSpecifier = getExternalModuleRequireArgument(node) || node.moduleSpecifier; const moduleSymbol = resolveExternalModuleName(node, moduleSpecifier); const name = !isPropertyAccessExpression(specifier) && specifier.propertyName || specifier.name; - if (!isIdentifier(name)) { + if (!isIdentifier(name) && name.kind !== 11 /* StringLiteral */) { return void 0; } - const suppressInteropError = name.escapedText === "default" /* Default */ && allowSyntheticDefaultImports; + const nameText = moduleExportNameTextEscaped(name); + const suppressInteropError = nameText === "default" /* Default */ && allowSyntheticDefaultImports; const targetSymbol = resolveESModuleSymbol( moduleSymbol, moduleSpecifier, @@ -147123,7 +147132,7 @@ function createTypeChecker(host) { suppressInteropError ); if (targetSymbol) { - if (name.escapedText) { + if (nameText || name.kind === 11 /* StringLiteral */) { if (isShorthandAmbientModuleSymbol(moduleSymbol)) { return moduleSymbol; } @@ -147131,18 +147140,18 @@ function createTypeChecker(host) { if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports.get("export=" /* ExportEquals */)) { symbolFromVariable = getPropertyOfType( getTypeOfSymbol(targetSymbol), - name.escapedText, + nameText, /*skipObjectFunctionPropertyAugment*/ true ); } else { - symbolFromVariable = getPropertyOfVariable(targetSymbol, name.escapedText); + symbolFromVariable = getPropertyOfVariable(targetSymbol, nameText); } symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias); - let symbolFromModule = getExportOfModule(targetSymbol, name, specifier, dontResolveAlias); - if (symbolFromModule === void 0 && name.escapedText === "default" /* Default */) { + let symbolFromModule = getExportOfModule(targetSymbol, nameText, specifier, dontResolveAlias); + if (symbolFromModule === void 0 && nameText === "default" /* Default */) { const file = (_a = moduleSymbol.declarations) == null ? void 0 : _a.find(isSourceFile); - if (isOnlyImportedAsDefault(moduleSpecifier) || canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias, moduleSpecifier)) { + if (isOnlyImportableAsDefault(moduleSpecifier) || canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias, moduleSpecifier)) { symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); } } @@ -147158,7 +147167,7 @@ function createTypeChecker(host) { var _a; const moduleName = getFullyQualifiedName(moduleSymbol, node); const declarationName = declarationNameToString(name); - const suggestion = getSuggestedSymbolForNonexistentModule(name, targetSymbol); + const suggestion = isIdentifier(name) ? getSuggestedSymbolForNonexistentModule(name, targetSymbol) : void 0; if (suggestion !== void 0) { const suggestionName = symbolToString(suggestion); const diagnostic = error2(name, Diagnostics._0_has_no_exported_member_named_1_Did_you_mean_2, moduleName, declarationName, suggestionName); @@ -147180,7 +147189,7 @@ function createTypeChecker(host) { } function reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName) { var _a, _b; - const localSymbol = (_b = (_a = tryCast(moduleSymbol.valueDeclaration, canHaveLocals)) == null ? void 0 : _a.locals) == null ? void 0 : _b.get(name.escapedText); + const localSymbol = (_b = (_a = tryCast(moduleSymbol.valueDeclaration, canHaveLocals)) == null ? void 0 : _a.locals) == null ? void 0 : _b.get(moduleExportNameTextEscaped(name)); const exports2 = moduleSymbol.exports; if (localSymbol) { const exportedEqualsSymbol = exports2 == null ? void 0 : exports2.get("export=" /* ExportEquals */); @@ -147212,7 +147221,7 @@ function createTypeChecker(host) { } } function getTargetOfImportSpecifier(node, dontResolveAlias) { - if (isImportSpecifier(node) && idText(node.propertyName || node.name) === "default" /* Default */) { + if (isImportSpecifier(node) && moduleExportNameIsDefault(node.propertyName || node.name)) { const specifier = getModuleSpecifierForImportOrExport(node); const moduleSymbol = specifier && resolveExternalModuleName(node, specifier); if (moduleSymbol) { @@ -147256,19 +147265,23 @@ function createTypeChecker(host) { } } function getTargetOfExportSpecifier(node, meaning, dontResolveAlias) { - if (idText(node.propertyName || node.name) === "default" /* Default */) { + const name = node.propertyName || node.name; + if (moduleExportNameIsDefault(name)) { const specifier = getModuleSpecifierForImportOrExport(node); const moduleSymbol = specifier && resolveExternalModuleName(node, specifier); if (moduleSymbol) { return getTargetofModuleDefault(moduleSymbol, node, !!dontResolveAlias); } } - const resolved = node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node, dontResolveAlias) : resolveEntityName( - node.propertyName || node.name, - meaning, - /*ignoreErrors*/ - false, - dontResolveAlias + const resolved = node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node, dontResolveAlias) : name.kind === 11 /* StringLiteral */ ? void 0 : ( + // Skip for invalid syntax like this: export { "x" } + resolveEntityName( + name, + meaning, + /*ignoreErrors*/ + false, + dontResolveAlias + ) ); markSymbolOfAliasDeclarationIfTypeOnly( node, @@ -147716,14 +147729,14 @@ function createTypeChecker(host) { function resolveExternalModuleName(location, moduleReferenceExpression, ignoreErrors) { const isClassic = getEmitModuleResolutionKind(compilerOptions) === 1 /* Classic */; const errorMessage = isClassic ? Diagnostics.Cannot_find_module_0_Did_you_mean_to_set_the_moduleResolution_option_to_nodenext_or_to_add_aliases_to_the_paths_option : Diagnostics.Cannot_find_module_0_or_its_corresponding_type_declarations; - return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ignoreErrors ? void 0 : errorMessage); + return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ignoreErrors ? void 0 : errorMessage, ignoreErrors); } - function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, isForAugmentation = false) { - return isStringLiteralLike(moduleReferenceExpression) ? resolveExternalModule(location, moduleReferenceExpression.text, moduleNotFoundError, moduleReferenceExpression, isForAugmentation) : void 0; + function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, ignoreErrors = false, isForAugmentation = false) { + return isStringLiteralLike(moduleReferenceExpression) ? resolveExternalModule(location, moduleReferenceExpression.text, moduleNotFoundError, !ignoreErrors ? moduleReferenceExpression : void 0, isForAugmentation) : void 0; } function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation = false) { var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k; - if (startsWith(moduleReference, "@types/")) { + if (errorNode && startsWith(moduleReference, "@types/")) { const diag2 = Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1; const withoutAtTypePrefix = removePrefix(moduleReference, "@types/"); error2(errorNode, diag2, withoutAtTypePrefix, moduleReference); @@ -147742,10 +147755,10 @@ function createTypeChecker(host) { /*requireStringLiteralLikeArgument*/ true ) ? location.initializer.arguments[0] : void 0) || ((_c = findAncestor(location, isImportCall)) == null ? void 0 : _c.arguments[0]) || ((_d = findAncestor(location, isImportDeclaration)) == null ? void 0 : _d.moduleSpecifier) || ((_e = findAncestor(location, isExternalModuleImportEqualsDeclaration)) == null ? void 0 : _e.moduleReference.expression) || ((_f = findAncestor(location, isExportDeclaration)) == null ? void 0 : _f.moduleSpecifier); - const mode = contextSpecifier && isStringLiteralLike(contextSpecifier) ? host.getModeForUsageLocation(currentSourceFile, contextSpecifier) : currentSourceFile.impliedNodeFormat; + const mode = contextSpecifier && isStringLiteralLike(contextSpecifier) ? host.getModeForUsageLocation(currentSourceFile, contextSpecifier) : host.getDefaultResolutionModeForFile(currentSourceFile); const moduleResolutionKind = getEmitModuleResolutionKind(compilerOptions); const resolvedModule = (_g = host.getResolvedModule(currentSourceFile, moduleReference, mode)) == null ? void 0 : _g.resolvedModule; - const resolutionDiagnostic = resolvedModule && getResolutionDiagnostic(compilerOptions, resolvedModule, currentSourceFile); + const resolutionDiagnostic = errorNode && resolvedModule && getResolutionDiagnostic(compilerOptions, resolvedModule, currentSourceFile); const sourceFile = resolvedModule && (!resolutionDiagnostic || resolutionDiagnostic === Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set) && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { if (resolutionDiagnostic) { @@ -147753,7 +147766,7 @@ function createTypeChecker(host) { } if (resolvedModule.resolvedUsingTsExtension && isDeclarationFileName(moduleReference)) { const importOrExport = ((_h = findAncestor(location, isImportDeclaration)) == null ? void 0 : _h.importClause) || findAncestor(location, or(isImportEqualsDeclaration, isExportDeclaration)); - if (importOrExport && !importOrExport.isTypeOnly || findAncestor(location, isImportCall)) { + if (errorNode && importOrExport && !importOrExport.isTypeOnly || findAncestor(location, isImportCall)) { error2( errorNode, Diagnostics.A_declaration_file_cannot_be_imported_without_import_type_Did_you_mean_to_import_an_implementation_file_0_instead, @@ -147762,13 +147775,13 @@ function createTypeChecker(host) { } } else if (resolvedModule.resolvedUsingTsExtension && !shouldAllowImportingTsExtension(compilerOptions, currentSourceFile.fileName)) { const importOrExport = ((_i = findAncestor(location, isImportDeclaration)) == null ? void 0 : _i.importClause) || findAncestor(location, or(isImportEqualsDeclaration, isExportDeclaration)); - if (!((importOrExport == null ? void 0 : importOrExport.isTypeOnly) || findAncestor(location, isImportTypeNode))) { + if (errorNode && !((importOrExport == null ? void 0 : importOrExport.isTypeOnly) || findAncestor(location, isImportTypeNode))) { const tsExtension = Debug.checkDefined(tryExtractTSExtension(moduleReference)); error2(errorNode, Diagnostics.An_import_path_can_only_end_with_a_0_extension_when_allowImportingTsExtensions_is_enabled, tsExtension); } } if (sourceFile.symbol) { - if (resolvedModule.isExternalLibraryImport && !resolutionExtensionIsTSOrJson(resolvedModule.extension)) { + if (errorNode && resolvedModule.isExternalLibraryImport && !resolutionExtensionIsTSOrJson(resolvedModule.extension)) { errorOnImplicitAnyModule( /*isError*/ false, @@ -147779,7 +147792,7 @@ function createTypeChecker(host) { moduleReference ); } - if (moduleResolutionKind === 3 /* Node16 */ || moduleResolutionKind === 99 /* NodeNext */) { + if (errorNode && (moduleResolutionKind === 3 /* Node16 */ || moduleResolutionKind === 99 /* NodeNext */)) { const isSyncImport = currentSourceFile.impliedNodeFormat === 1 /* CommonJS */ && !findAncestor(location, isImportCall) || !!findAncestor(location, isImportEqualsDeclaration); const overrideHost = findAncestor(location, (l) => isImportTypeNode(l) || isExportDeclaration(l) || isImportDeclaration(l) || isJSDocImportTag(l)); if (isSyncImport && sourceFile.impliedNodeFormat === 99 /* ESNext */ && !hasResolutionModeOverride(overrideHost)) { @@ -147789,41 +147802,7 @@ function createTypeChecker(host) { let diagnosticDetails; const ext = tryGetExtensionFromPath2(currentSourceFile.fileName); if (ext === ".ts" /* Ts */ || ext === ".js" /* Js */ || ext === ".tsx" /* Tsx */ || ext === ".jsx" /* Jsx */) { - const scope = currentSourceFile.packageJsonScope; - const targetExt = ext === ".ts" /* Ts */ ? ".mts" /* Mts */ : ext === ".js" /* Js */ ? ".mjs" /* Mjs */ : void 0; - if (scope && !scope.contents.packageJsonContent.type) { - if (targetExt) { - diagnosticDetails = chainDiagnosticMessages( - /*details*/ - void 0, - Diagnostics.To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_add_the_field_type_Colon_module_to_1, - targetExt, - combinePaths(scope.packageDirectory, "package.json") - ); - } else { - diagnosticDetails = chainDiagnosticMessages( - /*details*/ - void 0, - Diagnostics.To_convert_this_file_to_an_ECMAScript_module_add_the_field_type_Colon_module_to_0, - combinePaths(scope.packageDirectory, "package.json") - ); - } - } else { - if (targetExt) { - diagnosticDetails = chainDiagnosticMessages( - /*details*/ - void 0, - Diagnostics.To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_create_a_local_package_json_file_with_type_Colon_module, - targetExt - ); - } else { - diagnosticDetails = chainDiagnosticMessages( - /*details*/ - void 0, - Diagnostics.To_convert_this_file_to_an_ECMAScript_module_create_a_local_package_json_file_with_type_Colon_module - ); - } - } + diagnosticDetails = createModeMismatchDetails(currentSourceFile); } diagnostics.add(createDiagnosticForNodeFromMessageChain( getSourceFileOfNode(errorNode), @@ -147839,7 +147818,7 @@ function createTypeChecker(host) { } return getMergedSymbol(sourceFile.symbol); } - if (moduleNotFoundError) { + if (errorNode && moduleNotFoundError && !isSideEffectImport(errorNode)) { error2(errorNode, Diagnostics.File_0_is_not_a_module, sourceFile.fileName); } return void 0; @@ -147854,6 +147833,9 @@ function createTypeChecker(host) { return getMergedSymbol(pattern.symbol); } } + if (!errorNode) { + return void 0; + } if (resolvedModule && !resolutionExtensionIsTSOrJson(resolvedModule.extension) && resolutionDiagnostic === void 0 || resolutionDiagnostic === Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { if (isForAugmentation) { const diag2 = Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; @@ -147921,6 +147903,9 @@ function createTypeChecker(host) { } } function errorOnImplicitAnyModule(isError, errorNode, sourceFile, mode, { packageId, resolvedFileName }, moduleReference) { + if (isSideEffectImport(errorNode)) { + return; + } let errorInfo; if (!isExternalModuleNameRelative(moduleReference) && packageId) { errorInfo = createModuleNotFoundChain(sourceFile, host, moduleReference, mode, packageId.name); @@ -147986,7 +147971,7 @@ function createTypeChecker(host) { return cloneTypeAsModuleType(symbol, defaultOnlyType, referenceParent); } const targetFile = (_a = moduleSymbol == null ? void 0 : moduleSymbol.declarations) == null ? void 0 : _a.find(isSourceFile); - const isEsmCjsRef = targetFile && isESMFormatImportImportingCommonjsFormatFile(getUsageModeForExpression(reference), targetFile.impliedNodeFormat); + const isEsmCjsRef = targetFile && isESMFormatImportImportingCommonjsFormatFile(getEmitSyntaxForModuleSpecifierExpression(reference), host.getImpliedNodeFormatForEmit(targetFile)); if (getESModuleInterop(compilerOptions) || isEsmCjsRef) { let sigs = getSignaturesOfStructuredType(type, 0 /* Call */); if (!sigs || !sigs.length) { @@ -148849,6 +148834,7 @@ function createTypeChecker(host) { } function symbolToString(symbol, enclosingDeclaration, meaning, flags = 4 /* AllowAnyNodeKind */, writer) { let nodeFlags = 70221824 /* IgnoreErrors */; + let internalNodeFlags = 0 /* None */; if (flags & 2 /* UseOnlyExternalAliasing */) { nodeFlags |= 128 /* UseOnlyExternalAliasing */; } @@ -148859,15 +148845,15 @@ function createTypeChecker(host) { nodeFlags |= 16384 /* UseAliasDefinedOutsideCurrentScope */; } if (flags & 32 /* DoNotIncludeSymbolChain */) { - nodeFlags |= 134217728 /* DoNotIncludeSymbolChain */; + internalNodeFlags |= 4 /* DoNotIncludeSymbolChain */; } if (flags & 16 /* WriteComputedProps */) { - nodeFlags |= 1073741824 /* WriteComputedProps */; + internalNodeFlags |= 1 /* WriteComputedProps */; } const builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToNode : nodeBuilder.symbolToEntityName; return writer ? symbolToStringWorker(writer).getText() : usingSingleLineStringWriter(symbolToStringWorker); function symbolToStringWorker(writer2) { - const entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags); + const entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags, internalNodeFlags); const printer = (enclosingDeclaration == null ? void 0 : enclosingDeclaration.kind) === 307 /* SourceFile */ ? createPrinterWithRemoveCommentsNeverAsciiEscape() : createPrinterWithRemoveComments(); const sourceFile = enclosingDeclaration && getSourceFileOfNode(enclosingDeclaration); printer.writeNode( @@ -148904,7 +148890,13 @@ function createTypeChecker(host) { } function typeToString(type, enclosingDeclaration, flags = 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */, writer = createTextWriter("")) { const noTruncation = compilerOptions.noErrorTruncation || flags & 1 /* NoTruncation */; - const typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | (noTruncation ? 1 /* NoTruncation */ : 0)); + const typeNode = nodeBuilder.typeToTypeNode( + type, + enclosingDeclaration, + toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | (noTruncation ? 1 /* NoTruncation */ : 0 /* None */), + /*internalFlags*/ + void 0 + ); if (typeNode === void 0) return Debug.fail("should always get typenode"); const printer = type !== unresolvedType ? createPrinterWithRemoveComments() : createPrinterWithDefaults(); const sourceFile = enclosingDeclaration && getSourceFileOfNode(enclosingDeclaration); @@ -148953,31 +148945,31 @@ function createTypeChecker(host) { } function createNodeBuilder() { return { - typeToTypeNode: (type, enclosingDeclaration, flags, tracker) => withContext2(enclosingDeclaration, flags, tracker, (context) => typeToTypeNodeHelper(type, context)), - typePredicateToTypePredicateNode: (typePredicate, enclosingDeclaration, flags, tracker) => withContext2(enclosingDeclaration, flags, tracker, (context) => typePredicateToTypePredicateNodeHelper(typePredicate, context)), - expressionOrTypeToTypeNode: (expr, type, addUndefined, enclosingDeclaration, flags, tracker) => withContext2(enclosingDeclaration, flags, tracker, (context) => expressionOrTypeToTypeNode(context, expr, type, addUndefined)), - serializeTypeForDeclaration: (declaration, type, symbol, enclosingDeclaration, flags, tracker) => withContext2(enclosingDeclaration, flags, tracker, (context) => serializeTypeForDeclaration(context, declaration, type, symbol)), - serializeReturnTypeForSignature: (signature, enclosingDeclaration, flags, tracker) => withContext2(enclosingDeclaration, flags, tracker, (context) => serializeReturnTypeForSignature(context, signature)), - indexInfoToIndexSignatureDeclaration: (indexInfo, enclosingDeclaration, flags, tracker) => withContext2(enclosingDeclaration, flags, tracker, (context) => indexInfoToIndexSignatureDeclarationHelper( + typeToTypeNode: (type, enclosingDeclaration, flags, internalFlags, tracker) => withContext2(enclosingDeclaration, flags, internalFlags, tracker, (context) => typeToTypeNodeHelper(type, context)), + typePredicateToTypePredicateNode: (typePredicate, enclosingDeclaration, flags, internalFlags, tracker) => withContext2(enclosingDeclaration, flags, internalFlags, tracker, (context) => typePredicateToTypePredicateNodeHelper(typePredicate, context)), + expressionOrTypeToTypeNode: (expr, type, addUndefined, enclosingDeclaration, flags, internalFlags, tracker) => withContext2(enclosingDeclaration, flags, internalFlags, tracker, (context) => expressionOrTypeToTypeNode(context, expr, type, addUndefined)), + serializeTypeForDeclaration: (declaration, type, symbol, enclosingDeclaration, flags, internalFlags, tracker) => withContext2(enclosingDeclaration, flags, internalFlags, tracker, (context) => serializeTypeForDeclaration(context, declaration, type, symbol)), + serializeReturnTypeForSignature: (signature, enclosingDeclaration, flags, internalFlags, tracker) => withContext2(enclosingDeclaration, flags, internalFlags, tracker, (context) => serializeReturnTypeForSignature(context, signature)), + indexInfoToIndexSignatureDeclaration: (indexInfo, enclosingDeclaration, flags, internalFlags, tracker) => withContext2(enclosingDeclaration, flags, internalFlags, tracker, (context) => indexInfoToIndexSignatureDeclarationHelper( indexInfo, context, /*typeNode*/ void 0 )), - signatureToSignatureDeclaration: (signature, kind, enclosingDeclaration, flags, tracker) => withContext2(enclosingDeclaration, flags, tracker, (context) => signatureToSignatureDeclarationHelper(signature, kind, context)), - symbolToEntityName: (symbol, meaning, enclosingDeclaration, flags, tracker) => withContext2(enclosingDeclaration, flags, tracker, (context) => symbolToName( + signatureToSignatureDeclaration: (signature, kind, enclosingDeclaration, flags, internalFlags, tracker) => withContext2(enclosingDeclaration, flags, internalFlags, tracker, (context) => signatureToSignatureDeclarationHelper(signature, kind, context)), + symbolToEntityName: (symbol, meaning, enclosingDeclaration, flags, internalFlags, tracker) => withContext2(enclosingDeclaration, flags, internalFlags, tracker, (context) => symbolToName( symbol, context, meaning, /*expectsIdentifier*/ false )), - symbolToExpression: (symbol, meaning, enclosingDeclaration, flags, tracker) => withContext2(enclosingDeclaration, flags, tracker, (context) => symbolToExpression(symbol, context, meaning)), - symbolToTypeParameterDeclarations: (symbol, enclosingDeclaration, flags, tracker) => withContext2(enclosingDeclaration, flags, tracker, (context) => typeParametersToTypeParameterDeclarations(symbol, context)), - symbolToParameterDeclaration: (symbol, enclosingDeclaration, flags, tracker) => withContext2(enclosingDeclaration, flags, tracker, (context) => symbolToParameterDeclaration(symbol, context)), - typeParameterToDeclaration: (parameter, enclosingDeclaration, flags, tracker) => withContext2(enclosingDeclaration, flags, tracker, (context) => typeParameterToDeclaration(parameter, context)), - symbolTableToDeclarationStatements: (symbolTable, enclosingDeclaration, flags, tracker) => withContext2(enclosingDeclaration, flags, tracker, (context) => symbolTableToDeclarationStatements(symbolTable, context)), - symbolToNode: (symbol, meaning, enclosingDeclaration, flags, tracker) => withContext2(enclosingDeclaration, flags, tracker, (context) => symbolToNode(symbol, context, meaning)) + symbolToExpression: (symbol, meaning, enclosingDeclaration, flags, internalFlags, tracker) => withContext2(enclosingDeclaration, flags, internalFlags, tracker, (context) => symbolToExpression(symbol, context, meaning)), + symbolToTypeParameterDeclarations: (symbol, enclosingDeclaration, flags, internalFlags, tracker) => withContext2(enclosingDeclaration, flags, internalFlags, tracker, (context) => typeParametersToTypeParameterDeclarations(symbol, context)), + symbolToParameterDeclaration: (symbol, enclosingDeclaration, flags, internalFlags, tracker) => withContext2(enclosingDeclaration, flags, internalFlags, tracker, (context) => symbolToParameterDeclaration(symbol, context)), + typeParameterToDeclaration: (parameter, enclosingDeclaration, flags, internalFlags, tracker) => withContext2(enclosingDeclaration, flags, internalFlags, tracker, (context) => typeParameterToDeclaration(parameter, context)), + symbolTableToDeclarationStatements: (symbolTable, enclosingDeclaration, flags, internalFlags, tracker) => withContext2(enclosingDeclaration, flags, internalFlags, tracker, (context) => symbolTableToDeclarationStatements(symbolTable, context)), + symbolToNode: (symbol, meaning, enclosingDeclaration, flags, internalFlags, tracker) => withContext2(enclosingDeclaration, flags, internalFlags, tracker, (context) => symbolToNode(symbol, context, meaning)) }; function getTypeFromTypeNode2(context, node, noMappedTypes) { const type = getTypeFromTypeNodeWithoutContext(node); @@ -148993,19 +148985,26 @@ function createTypeChecker(host) { if (!location) { return range; } - if (!context.enclosingFile || context.enclosingFile !== getSourceFileOfNode(getOriginalNode(location))) { - return setOriginalNode(range, location); + let original = range.original; + while (original && original !== location) { + original = original.original; + } + if (!original) { + setOriginalNode(range, location); + } + if (context.enclosingFile && context.enclosingFile === getSourceFileOfNode(getOriginalNode(location))) { + return setTextRange(range, location); } - return setTextRange(setOriginalNode(range, location), location); + return range; } function expressionOrTypeToTypeNode(context, expr, type, addUndefined) { - const oldFlags = context.flags; - if (expr && !(context.flags & -2147483648 /* NoSyntacticPrinter */)) { + const restoreFlags = saveRestoreFlags(context); + if (expr && !(context.internalFlags & 2 /* NoSyntacticPrinter */)) { syntacticNodeBuilder.serializeTypeOfExpression(expr, context, addUndefined); } - context.flags |= -2147483648 /* NoSyntacticPrinter */; + context.internalFlags |= 2 /* NoSyntacticPrinter */; const result = expressionOrTypeToTypeNodeHelper(context, expr, type, addUndefined); - context.flags = oldFlags; + restoreFlags(); return result; } function expressionOrTypeToTypeNodeHelper(context, expr, type, addUndefined) { @@ -149058,7 +149057,7 @@ function createTypeChecker(host) { return void 0; } function symbolToNode(symbol, context, meaning) { - if (context.flags & 1073741824 /* WriteComputedProps */) { + if (context.internalFlags & 1 /* WriteComputedProps */) { if (symbol.valueDeclaration) { const name = getNameOfDeclaration(symbol.valueDeclaration); if (name && isComputedPropertyName(name)) return name; @@ -149071,12 +149070,13 @@ function createTypeChecker(host) { } return symbolToExpression(symbol, context, meaning); } - function withContext2(enclosingDeclaration, flags, tracker, cb) { - const moduleResolverHost = (tracker == null ? void 0 : tracker.trackSymbol) ? tracker.moduleResolverHost : flags & 134217728 /* DoNotIncludeSymbolChain */ ? createBasicNodeBuilderModuleSpecifierResolutionHost(host) : void 0; + function withContext2(enclosingDeclaration, flags, internalFlags, tracker, cb) { + const moduleResolverHost = (tracker == null ? void 0 : tracker.trackSymbol) ? tracker.moduleResolverHost : (internalFlags || 0 /* None */) & 4 /* DoNotIncludeSymbolChain */ ? createBasicNodeBuilderModuleSpecifierResolutionHost(host) : void 0; const context = { enclosingDeclaration, enclosingFile: enclosingDeclaration && getSourceFileOfNode(enclosingDeclaration), flags: flags || 0 /* None */, + internalFlags: internalFlags || 0 /* None */, tracker: void 0, encounteredError: false, reportedDiagnostic: false, @@ -149106,14 +149106,23 @@ function createTypeChecker(host) { } return context.encounteredError ? void 0 : resultingNode; } + function saveRestoreFlags(context) { + const flags = context.flags; + const internalFlags = context.internalFlags; + return restore; + function restore() { + context.flags = flags; + context.internalFlags = internalFlags; + } + } function checkTruncationLength(context) { if (context.truncating) return context.truncating; return context.truncating = context.approximateLength > (context.flags & 1 /* NoTruncation */ ? noTruncationMaximumTruncationLength : defaultMaximumTruncationLength); } function typeToTypeNodeHelper(type, context) { - const savedFlags = context.flags; + const restoreFlags = saveRestoreFlags(context); const typeNode = typeToTypeNodeWorker(type, context); - context.flags = savedFlags; + restoreFlags(); return typeNode; } function typeToTypeNodeWorker(type, context) { @@ -149567,7 +149576,7 @@ function createTypeChecker(host) { context.symbolDepth = /* @__PURE__ */ new Map(); } const links = context.enclosingDeclaration && getNodeLinks(context.enclosingDeclaration); - const key = `${getTypeId(type2)}|${context.flags}`; + const key = `${getTypeId(type2)}|${context.flags}|${context.internalFlags}`; if (links) { links.serializedTypes || (links.serializedTypes = /* @__PURE__ */ new Map()); } @@ -149673,10 +149682,10 @@ function createTypeChecker(host) { } return typeToTypeNodeHelper(getIntersectionType(types), context); } - const savedFlags = context.flags; + const restoreFlags = saveRestoreFlags(context); context.flags |= 4194304 /* InObjectTypeLiteral */; const members = createTypeNodesFromResolvedType(resolved); - context.flags = savedFlags; + restoreFlags(); const typeLiteralNode = factory.createTypeLiteralNode(members); context.approximateLength += 2; setEmitFlags(typeLiteralNode, context.flags & 1024 /* MultilineObjectLiterals */ ? 0 : 1 /* SingleLine */); @@ -149739,23 +149748,51 @@ function createTypeChecker(host) { } while (i < length2 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent2); if (!rangeEquals(outerTypeParameters, typeArguments, start, i)) { const typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context); - const flags2 = context.flags; + const restoreFlags2 = saveRestoreFlags(context); context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; const ref = symbolToTypeNode(parent2, context, 788968 /* Type */, typeArgumentSlice); - context.flags = flags2; + restoreFlags2(); resultType = !resultType ? ref : appendReferenceToType(resultType, ref); } } } let typeArgumentNodes; if (typeArguments.length > 0) { - const typeParameterCount = (type2.target.typeParameters || emptyArray).length; + let typeParameterCount = 0; + if (type2.target.typeParameters) { + typeParameterCount = Math.min(type2.target.typeParameters.length, typeArguments.length); + if (isReferenceToType2(type2, getGlobalIterableType( + /*reportErrors*/ + false + )) || isReferenceToType2(type2, getGlobalIterableIteratorType( + /*reportErrors*/ + false + )) || isReferenceToType2(type2, getGlobalAsyncIterableType( + /*reportErrors*/ + false + )) || isReferenceToType2(type2, getGlobalAsyncIterableIteratorType( + /*reportErrors*/ + false + ))) { + if (!type2.node || !isTypeReferenceNode(type2.node) || !type2.node.typeArguments || type2.node.typeArguments.length < typeParameterCount) { + while (typeParameterCount > 0) { + const typeArgument = typeArguments[typeParameterCount - 1]; + const typeParameter = type2.target.typeParameters[typeParameterCount - 1]; + const defaultType = getDefaultFromTypeParameter(typeParameter); + if (!defaultType || !isTypeIdenticalTo(typeArgument, defaultType)) { + break; + } + typeParameterCount--; + } + } + } + } typeArgumentNodes = mapToTypeNodes(typeArguments.slice(i, typeParameterCount), context); } - const flags = context.flags; + const restoreFlags = saveRestoreFlags(context); context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */; const finalRef = symbolToTypeNode(type2.symbol, context, 788968 /* Type */, typeArgumentNodes); - context.flags = flags; + restoreFlags(); return !resultType ? finalRef : appendReferenceToType(resultType, finalRef); } } @@ -150067,7 +150104,7 @@ function createTypeChecker(host) { } } if (seenNames) { - const saveContextFlags = context.flags; + const restoreFlags = saveRestoreFlags(context); context.flags |= 64 /* UseFullyQualifiedType */; seenNames.forEach((types2) => { if (!arrayIsHomogeneous(types2, ([a], [b]) => typesAreSameReference(a, b))) { @@ -150076,7 +150113,7 @@ function createTypeChecker(host) { } } }); - context.flags = saveContextFlags; + restoreFlags(); } return result; } @@ -150128,19 +150165,19 @@ function createTypeChecker(host) { } else { typeParameters = signature.typeParameters && signature.typeParameters.map((parameter) => typeParameterToDeclaration(parameter, context)); } - const flags = context.flags; + const restoreFlags = saveRestoreFlags(context); context.flags &= ~256 /* SuppressAnyReturnType */; const parameters = (some(expandedParams, (p) => p !== expandedParams[expandedParams.length - 1] && !!(getCheckFlags(p) & 32768 /* RestParameter */)) ? signature.parameters : expandedParams).map((parameter) => symbolToParameterDeclaration(parameter, context, kind === 176 /* Constructor */)); const thisParameter = context.flags & 33554432 /* OmitThisParameter */ ? void 0 : tryGetThisParameterDeclaration(signature, context); if (thisParameter) { parameters.unshift(thisParameter); } - context.flags = flags; + restoreFlags(); const returnTypeNode = serializeReturnTypeForSignature(context, signature); let modifiers = options == null ? void 0 : options.modifiers; if (kind === 185 /* ConstructorType */ && signature.flags & 4 /* Abstract */) { - const flags2 = modifiersToFlags(modifiers); - modifiers = factory.createModifiersFromModifierFlags(flags2 | 64 /* Abstract */); + const flags = modifiersToFlags(modifiers); + modifiers = factory.createModifiersFromModifierFlags(flags | 64 /* Abstract */); } const node = kind === 179 /* CallSignature */ ? factory.createCallSignature(typeParameters, parameters, returnTypeNode) : kind === 180 /* ConstructSignature */ ? factory.createConstructSignature(typeParameters, parameters, returnTypeNode) : kind === 173 /* MethodSignature */ ? factory.createMethodSignature(modifiers, (options == null ? void 0 : options.name) ?? factory.createIdentifier(""), options == null ? void 0 : options.questionToken, typeParameters, parameters, returnTypeNode) : kind === 174 /* MethodDeclaration */ ? factory.createMethodDeclaration( modifiers, @@ -150360,13 +150397,13 @@ function createTypeChecker(host) { } } function typeParameterToDeclarationWithConstraint(type, context, constraintNode) { - const savedContextFlags = context.flags; + const restoreFlags = saveRestoreFlags(context); context.flags &= ~512 /* WriteTypeParametersInQualifiedName */; const modifiers = factory.createModifiersFromModifierFlags(getTypeParameterModifiers(type)); const name = typeParameterToName(type, context); const defaultParameter = getDefaultFromTypeParameter(type); const defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); - context.flags = savedContextFlags; + restoreFlags(); return factory.createTypeParameterDeclaration(modifiers, name, constraintNode, defaultParameterNode); } function typeToTypeNodeHelperWithPossibleReusableTypeNode(type, typeNode, context) { @@ -150470,7 +150507,7 @@ function createTypeChecker(host) { function lookupSymbolChainWorker(symbol, context, meaning, yieldModuleSymbol) { let chain; const isTypeParameter = symbol.flags & 262144 /* TypeParameter */; - if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */) && !(context.flags & 134217728 /* DoNotIncludeSymbolChain */)) { + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */) && !(context.internalFlags & 4 /* DoNotIncludeSymbolChain */)) { chain = Debug.checkDefined(getSymbolChain( symbol, meaning, @@ -150606,8 +150643,10 @@ function createTypeChecker(host) { } return getSourceFileOfNode(getNonAugmentationDeclaration(symbol)).fileName; } + const enclosingDeclaration = getOriginalNode(context.enclosingDeclaration); + const originalModuleSpecifier = canHaveModuleSpecifier(enclosingDeclaration) ? tryGetModuleSpecifierFromDeclaration(enclosingDeclaration) : void 0; const contextFile = context.enclosingFile; - const resolutionMode = overrideImportMode || (contextFile == null ? void 0 : contextFile.impliedNodeFormat); + const resolutionMode = overrideImportMode || originalModuleSpecifier && host.getModeForUsageLocation(contextFile, originalModuleSpecifier) || contextFile && host.getDefaultResolutionModeForFile(contextFile); const cacheKey = createModeAwareCacheKey(contextFile.path, resolutionMode); const links = getSymbolLinks(symbol); let specifier = links.specifierCache && links.specifierCache.get(cacheKey); @@ -150992,21 +151031,21 @@ function createTypeChecker(host) { } function serializeTypeForDeclaration(context, declaration, type, symbol) { var _a, _b; - const addUndefinedForParameter = declaration && (isParameter(declaration) || isJSDocParameterTag(declaration)) && requiresAddingImplicitUndefined(declaration); + const addUndefinedForParameter = declaration && (isParameter(declaration) || isJSDocParameterTag(declaration)) && requiresAddingImplicitUndefined(declaration, context.enclosingDeclaration); const enclosingDeclaration = context.enclosingDeclaration; - const oldFlags = context.flags; - if (declaration && hasInferredType(declaration) && !(context.flags & -2147483648 /* NoSyntacticPrinter */)) { + const restoreFlags = saveRestoreFlags(context); + if (declaration && hasInferredType(declaration) && !(context.internalFlags & 2 /* NoSyntacticPrinter */)) { syntacticNodeBuilder.serializeTypeOfDeclaration(declaration, context); } - context.flags |= -2147483648 /* NoSyntacticPrinter */; - if (enclosingDeclaration && (!isErrorType(type) || context.flags & 1 /* AllowUnresolvedNames */)) { + context.internalFlags |= 2 /* NoSyntacticPrinter */; + if (enclosingDeclaration && (!isErrorType(type) || context.internalFlags & 8 /* AllowUnresolvedNames */)) { const declWithExistingAnnotation = declaration && getNonlocalEffectiveTypeAnnotationNode(declaration) ? declaration : getDeclarationWithTypeAnnotation(symbol); if (declWithExistingAnnotation && !isFunctionLikeDeclaration(declWithExistingAnnotation) && !isGetAccessorDeclaration(declWithExistingAnnotation)) { const existing = getNonlocalEffectiveTypeAnnotationNode(declWithExistingAnnotation); const addUndefined = addUndefinedForParameter || !!(symbol.flags & 4 /* Property */ && symbol.flags & 16777216 /* Optional */ && isOptionalDeclaration(declWithExistingAnnotation) && ((_a = symbol.links) == null ? void 0 : _a.mappedType) && containsNonMissingUndefinedType(type)); const result2 = !isTypePredicateNode(existing) && tryReuseExistingTypeNode(context, existing, type, declWithExistingAnnotation, addUndefined); if (result2) { - context.flags = oldFlags; + restoreFlags(); return result2; } } @@ -151017,7 +151056,7 @@ function createTypeChecker(host) { const decl = declaration ?? symbol.valueDeclaration ?? ((_b = symbol.declarations) == null ? void 0 : _b[0]); const expr = decl && isDeclarationWithPossibleInnerTypeNodeReuse(decl) ? getPossibleTypeNodeReuseExpression(decl) : void 0; const result = expressionOrTypeToTypeNode(context, expr, type, addUndefinedForParameter); - context.flags = oldFlags; + restoreFlags(); return result; } function typeNodeIsEquivalentToType(annotatedDeclaration, type, typeFromTypeNode) { @@ -151031,26 +151070,26 @@ function createTypeChecker(host) { } function serializeReturnTypeForSignature(context, signature) { const suppressAny = context.flags & 256 /* SuppressAnyReturnType */; - const flags = context.flags; + const restoreFlags = saveRestoreFlags(context); if (suppressAny) context.flags &= ~256 /* SuppressAnyReturnType */; let returnTypeNode; const returnType = getReturnTypeOfSignature(signature); if (returnType && !(suppressAny && isTypeAny(returnType))) { - if (signature.declaration && !(context.flags & -2147483648 /* NoSyntacticPrinter */)) { + if (signature.declaration && !(context.internalFlags & 2 /* NoSyntacticPrinter */)) { syntacticNodeBuilder.serializeReturnTypeForSignature(signature.declaration, context); } - context.flags |= -2147483648 /* NoSyntacticPrinter */; + context.internalFlags |= 2 /* NoSyntacticPrinter */; returnTypeNode = serializeReturnTypeForSignatureWorker(context, signature); } else if (!suppressAny) { returnTypeNode = factory.createKeywordTypeNode(133 /* AnyKeyword */); } - context.flags = flags; + restoreFlags(); return returnTypeNode; } function serializeReturnTypeForSignatureWorker(context, signature) { const typePredicate = getTypePredicateOfSignature(signature); const type = getReturnTypeOfSignature(signature); - if (context.enclosingDeclaration && (!isErrorType(type) || context.flags & 1 /* AllowUnresolvedNames */) && signature.declaration && !nodeIsSynthesized(signature.declaration)) { + if (context.enclosingDeclaration && (!isErrorType(type) || context.internalFlags & 8 /* AllowUnresolvedNames */) && signature.declaration && !nodeIsSynthesized(signature.declaration)) { const annotation = getNonlocalEffectiveReturnTypeAnnotationNode(signature.declaration); if (annotation) { const result = tryReuseExistingTypeNode(context, annotation, type, context.enclosingDeclaration); @@ -151124,6 +151163,8 @@ function createTypeChecker(host) { } introducesError = true; return { introducesError, node, sym }; + } else { + sym = symAtLocation; } } if (sym) { @@ -151550,7 +151591,7 @@ function createTypeChecker(host) { if (!hasDynamicName(node)) { return visitEachChild2(node, visitExistingNodeTreeSymbols); } - if (!(context.flags & 1 /* AllowUnresolvedNames */ && isEntityNameExpression(node.name.expression) && checkComputedPropertyName(node.name).flags & 1 /* Any */)) { + if (!(context.internalFlags & 8 /* AllowUnresolvedNames */ && isEntityNameExpression(node.name.expression) && checkComputedPropertyName(node.name).flags & 1 /* Any */)) { return void 0; } } @@ -151901,9 +151942,10 @@ function createTypeChecker(host) { if (index >= 0) { const exportDecl = statements[index]; const replacements = mapDefined(exportDecl.exportClause.elements, (e) => { - if (!e.propertyName) { + if (!e.propertyName && e.name.kind !== 11 /* StringLiteral */) { + const name = e.name; const indices = indicesOf(statements); - const associatedIndices = filter(indices, (i) => nodeHasName(statements[i], e.name)); + const associatedIndices = filter(indices, (i) => nodeHasName(statements[i], name)); if (length(associatedIndices) && every(associatedIndices, (i) => canHaveExportModifier(statements[i]))) { for (const index2 of associatedIndices) { statements[index2] = addExportModifier(statements[index2]); @@ -152201,7 +152243,7 @@ function createTypeChecker(host) { const typeParamDecls = map(typeParams, (p) => typeParameterToDeclaration(p, context)); const jsdocAliasDecl = (_a2 = symbol.declarations) == null ? void 0 : _a2.find(isJSDocTypeAlias); const commentText = getTextOfJSDocComment(jsdocAliasDecl ? jsdocAliasDecl.comment || jsdocAliasDecl.parent.comment : void 0); - const oldFlags = context.flags; + const restoreFlags = saveRestoreFlags(context); context.flags |= 8388608 /* InTypeAlias */; const oldEnclosingDecl = context.enclosingDeclaration; context.enclosingDeclaration = jsdocAliasDecl; @@ -152225,7 +152267,7 @@ function createTypeChecker(host) { ), modifierFlags ); - context.flags = oldFlags; + restoreFlags(); context.enclosingDeclaration = oldEnclosingDecl; } function serializeInterface(symbol, symbolName2, modifierFlags) { @@ -152537,7 +152579,7 @@ function createTypeChecker(host) { function getSomeTargetNameFromDeclarations(declarations) { return firstDefined(declarations, (d) => { if (isImportSpecifier(d) || isExportSpecifier(d)) { - return idText(d.propertyName || d.name); + return moduleExportNameTextUnescaped(d.propertyName || d.name); } if (isBinaryExpression(d) || isExportAssignment(d)) { const expression = isExportAssignment(d) ? d.expression : d.right; @@ -152545,7 +152587,7 @@ function createTypeChecker(host) { return idText(expression.name); } } - if (isAliasSymbolDeclaration2(d)) { + if (isAliasSymbolDeclaration(d)) { const name = getNameOfDeclaration(d); if (name && isIdentifier(name)) { return idText(name); @@ -152555,7 +152597,7 @@ function createTypeChecker(host) { }); } function serializeAsAlias(symbol, localName, modifierFlags) { - var _a2, _b, _c, _d, _e, _f; + var _a2, _b, _c, _d, _e; const node = getDeclarationOfAliasSymbol(symbol); if (!node) return Debug.fail(); const target = getMergedSymbol(getTargetOfAliasDeclaration( @@ -152753,8 +152795,11 @@ function createTypeChecker(host) { } case 281 /* ExportSpecifier */: const specifier = node.parent.parent.moduleSpecifier; - if (specifier && ((_f = node.propertyName) == null ? void 0 : _f.escapedText) === "default" /* Default */) { - verbatimTargetName = "default" /* Default */; + if (specifier) { + const propertyName = node.propertyName; + if (propertyName && moduleExportNameIsDefault(propertyName)) { + verbatimTargetName = "default" /* Default */; + } } serializeExportSpecifier( unescapeLeadingUnderscores(symbol.escapedName), @@ -153231,10 +153276,10 @@ function createTypeChecker(host) { } function getNameCandidateWorker(symbol, localName) { if (localName === "default" /* Default */ || localName === "__class" /* Class */ || localName === "__function" /* Function */) { - const flags = context.flags; + const restoreFlags = saveRestoreFlags(context); context.flags |= 16777216 /* InInitialEntityName */; const nameCandidate = getNameOfSymbolAsWritten(symbol, context); - context.flags = flags; + restoreFlags(); localName = nameCandidate.length > 0 && isSingleOrDoubleQuote(nameCandidate.charCodeAt(0)) ? stripQuotes(nameCandidate) : nameCandidate; } if (localName === "default" /* Default */) { @@ -153242,7 +153287,7 @@ function createTypeChecker(host) { } else if (localName === "export=" /* ExportEquals */) { localName = "_exports"; } - localName = isIdentifierText(localName, languageVersion) && !isStringANonContextualKeyword(localName) ? localName : "_" + localName.replace(/[^a-zA-Z0-9]/g, "_"); + localName = isIdentifierText(localName, languageVersion) && !isStringANonContextualKeyword(localName) ? localName : "_" + localName.replace(/[^a-z0-9]/gi, "_"); return localName; } function getInternalSymbolName(symbol, localName) { @@ -153467,7 +153512,7 @@ function createTypeChecker(host) { } function collectLinkedAliases(node, setVisibility) { let exportSymbol; - if (node.parent && node.parent.kind === 277 /* ExportAssignment */) { + if (node.kind !== 11 /* StringLiteral */ && node.parent && node.parent.kind === 277 /* ExportAssignment */) { exportSymbol = resolveName( node, node, @@ -153752,6 +153797,7 @@ function createTypeChecker(host) { } else if (strictNullChecks && pattern.parent.initializer && !hasTypeFacts(getTypeOfInitializer(pattern.parent.initializer), 65536 /* EQUndefined */)) { parentType = getTypeWithFacts(parentType, 524288 /* NEUndefined */); } + const accessFlags = 32 /* ExpressionPosition */ | (noTupleBoundsCheck || hasDefaultValue(declaration) ? 16 /* AllowMissing */ : 0); let type; if (pattern.kind === 206 /* ObjectBindingPattern */) { if (declaration.dotDotDotToken) { @@ -153770,7 +153816,7 @@ function createTypeChecker(host) { } else { const name = declaration.propertyName || declaration.name; const indexType = getLiteralTypeFromPropertyName(name); - const declaredType = getIndexedAccessType(parentType, indexType, 32 /* ExpressionPosition */, name); + const declaredType = getIndexedAccessType(parentType, indexType, accessFlags, name); type = getFlowTypeOfDestructuring(declaration, declaredType); } } else { @@ -153781,7 +153827,6 @@ function createTypeChecker(host) { type = everyType(baseConstraint, isTupleType) ? mapType(baseConstraint, (t) => sliceTupleType(t, index)) : createArrayType(elementType); } else if (isArrayLikeType(parentType)) { const indexType = getNumberLiteralType(index); - const accessFlags = 32 /* ExpressionPosition */ | (noTupleBoundsCheck || hasDefaultValue(declaration) ? 16 /* NoTupleBoundsCheck */ : 0); const declaredType = getIndexedAccessTypeOrUndefined(parentType, indexType, accessFlags, declaration.name) || errorType; type = getFlowTypeOfDestructuring(declaration, declaredType); } else { @@ -154267,7 +154312,7 @@ function createTypeChecker(host) { /*reportErrors*/ false ) : unknownType; - return addOptionality(widenTypeInferredFromInitializer(element, checkDeclarationInitializer(element, reportErrors2 ? 0 /* Normal */ : 1 /* Contextual */, contextualType))); + return addOptionality(widenTypeInferredFromInitializer(element, checkDeclarationInitializer(element, 0 /* Normal */, contextualType))); } if (isBindingPattern(element.name)) { return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors2); @@ -154338,7 +154383,10 @@ function createTypeChecker(host) { return result; } function getTypeFromBindingPattern(pattern, includePatternInType = false, reportErrors2 = false) { - return pattern.kind === 206 /* ObjectBindingPattern */ ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors2) : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors2); + if (includePatternInType) contextualBindingPatterns.push(pattern); + const result = pattern.kind === 206 /* ObjectBindingPattern */ ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors2) : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors2); + if (includePatternInType) contextualBindingPatterns.pop(); + return result; } function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors2) { return widenTypeForVariableLikeDeclaration(getTypeForVariableLikeDeclaration( @@ -154419,18 +154467,18 @@ function createTypeChecker(host) { } return false; } - function getTypeOfVariableOrParameterOrProperty(symbol, checkMode) { + function getTypeOfVariableOrParameterOrProperty(symbol) { const links = getSymbolLinks(symbol); if (!links.type) { - const type = getTypeOfVariableOrParameterOrPropertyWorker(symbol, checkMode); - if (!links.type && !isParameterOfContextSensitiveSignature(symbol) && !checkMode) { + const type = getTypeOfVariableOrParameterOrPropertyWorker(symbol); + if (!links.type && !isParameterOfContextSensitiveSignature(symbol)) { links.type = type; } return type; } return links.type; } - function getTypeOfVariableOrParameterOrPropertyWorker(symbol, checkMode) { + function getTypeOfVariableOrParameterOrPropertyWorker(symbol) { if (symbol.flags & 4194304 /* Prototype */) { return getTypeOfPrototypeProperty(symbol); } @@ -154465,9 +154513,6 @@ function createTypeChecker(host) { if (symbol.flags & 512 /* ValueModule */ && !(symbol.flags & 67108864 /* Assignment */)) { return getTypeOfFuncClassEnumModule(symbol); } - if (isBindingElement(declaration) && checkMode === 1 /* Contextual */) { - return errorType; - } return reportCircularityError(symbol); } let type; @@ -154505,9 +154550,6 @@ function createTypeChecker(host) { if (symbol.flags & 512 /* ValueModule */ && !(symbol.flags & 67108864 /* Assignment */)) { return getTypeOfFuncClassEnumModule(symbol); } - if (isBindingElement(declaration) && checkMode === 1 /* Contextual */) { - return type; - } return reportCircularityError(symbol); } return type; @@ -154736,7 +154778,7 @@ function createTypeChecker(host) { } return getTypeOfSymbol(symbol); } - function getTypeOfSymbol(symbol, checkMode) { + function getTypeOfSymbol(symbol) { const checkFlags = getCheckFlags(symbol); if (checkFlags & 65536 /* DeferredType */) { return getTypeOfSymbolWithDeferredType(symbol); @@ -154751,7 +154793,7 @@ function createTypeChecker(host) { return getTypeOfReverseMappedSymbol(symbol); } if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) { - return getTypeOfVariableOrParameterOrProperty(symbol, checkMode); + return getTypeOfVariableOrParameterOrProperty(symbol); } if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) { return getTypeOfFuncClassEnumModule(symbol); @@ -154770,6 +154812,17 @@ function createTypeChecker(host) { function getNonMissingTypeOfSymbol(symbol) { return removeMissingType(getTypeOfSymbol(symbol), !!(symbol.flags & 16777216 /* Optional */)); } + function isReferenceToSomeType(type, targets) { + if (type === void 0 || (getObjectFlags(type) & 4 /* Reference */) === 0) { + return false; + } + for (const target of targets) { + if (type.target === target) { + return true; + } + } + return false; + } function isReferenceToType2(type, target) { return type !== void 0 && target !== void 0 && (getObjectFlags(type) & 4 /* Reference */) !== 0 && type.target === target; } @@ -154809,7 +154862,8 @@ function createTypeChecker(host) { if (!node) { return void 0; } - switch (node.kind) { + const kind = node.kind; + switch (kind) { case 263 /* ClassDeclaration */: case 231 /* ClassExpression */: case 264 /* InterfaceDeclaration */: @@ -154831,13 +154885,19 @@ function createTypeChecker(host) { case 200 /* MappedType */: case 194 /* ConditionalType */: { const outerTypeParameters = getOuterTypeParameters(node, includeThisTypes); - if (node.kind === 200 /* MappedType */) { + if ((kind === 218 /* FunctionExpression */ || kind === 219 /* ArrowFunction */ || isObjectLiteralMethod(node)) && isContextSensitive(node)) { + const signature = firstOrUndefined(getSignaturesOfType(getTypeOfSymbol(getSymbolOfDeclaration(node)), 0 /* Call */)); + if (signature && signature.typeParameters) { + return [...outerTypeParameters || emptyArray, ...signature.typeParameters]; + } + } + if (kind === 200 /* MappedType */) { return append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfDeclaration(node.typeParameter))); - } else if (node.kind === 194 /* ConditionalType */) { + } else if (kind === 194 /* ConditionalType */) { return concatenate(outerTypeParameters, getInferTypeParameters(node)); } const outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, getEffectiveTypeParameterDeclarations(node)); - const thisType = includeThisTypes && (node.kind === 263 /* ClassDeclaration */ || node.kind === 231 /* ClassExpression */ || node.kind === 264 /* InterfaceDeclaration */ || isJSConstructor(node)) && getDeclaredTypeOfClassOrInterface(getSymbolOfDeclaration(node)).thisType; + const thisType = includeThisTypes && (kind === 263 /* ClassDeclaration */ || kind === 231 /* ClassExpression */ || kind === 264 /* InterfaceDeclaration */ || isJSConstructor(node)) && getDeclaredTypeOfClassOrInterface(getSymbolOfDeclaration(node)).thisType; return thisType ? append(outerAndOwnTypeParameters, thisType) : outerAndOwnTypeParameters; } case 341 /* JSDocParameterTag */: @@ -155191,6 +155251,9 @@ function createTypeChecker(host) { links.instantiations = /* @__PURE__ */ new Map(); links.instantiations.set(getTypeListId(typeParameters), type); } + if (type === intrinsicMarkerType && symbol.escapedName === "BuiltinIteratorReturn") { + type = getBuiltinIteratorReturnType(); + } } else { type = errorType; if (declaration.kind === 340 /* JSDocEnumTag */) { @@ -155655,18 +155718,18 @@ function createTypeChecker(host) { function getExpandedParameters(sig, skipUnionExpanding) { if (signatureHasRestParameter(sig)) { const restIndex = sig.parameters.length - 1; - const restName = sig.parameters[restIndex].escapedName; - const restType = getTypeOfSymbol(sig.parameters[restIndex]); + const restSymbol = sig.parameters[restIndex]; + const restType = getTypeOfSymbol(restSymbol); if (isTupleType(restType)) { - return [expandSignatureParametersWithTupleMembers(restType, restIndex, restName)]; + return [expandSignatureParametersWithTupleMembers(restType, restIndex, restSymbol)]; } else if (!skipUnionExpanding && restType.flags & 1048576 /* Union */ && every(restType.types, isTupleType)) { - return map(restType.types, (t) => expandSignatureParametersWithTupleMembers(t, restIndex, restName)); + return map(restType.types, (t) => expandSignatureParametersWithTupleMembers(t, restIndex, restSymbol)); } } return [sig.parameters]; - function expandSignatureParametersWithTupleMembers(restType, restIndex, restName) { + function expandSignatureParametersWithTupleMembers(restType, restIndex, restSymbol) { const elementTypes = getTypeArguments(restType); - const associatedNames = getUniqAssociatedNamesFromTupleType(restType, restName); + const associatedNames = getUniqAssociatedNamesFromTupleType(restType, restSymbol); const restParams = map(elementTypes, (t, i) => { const name = associatedNames && associatedNames[i] ? associatedNames[i] : getParameterNameAtPosition(sig, restIndex + i, restType); const flags = restType.target.elementFlags[i]; @@ -155677,19 +155740,29 @@ function createTypeChecker(host) { }); return concatenate(sig.parameters.slice(0, restIndex), restParams); } - function getUniqAssociatedNamesFromTupleType(type, restName) { - const associatedNamesMap = /* @__PURE__ */ new Map(); - return map(type.target.labeledElementDeclarations, (labeledElement, i) => { - const name = getTupleElementLabel(labeledElement, i, restName); - const prevCounter = associatedNamesMap.get(name); - if (prevCounter === void 0) { - associatedNamesMap.set(name, 1); - return name; - } else { - associatedNamesMap.set(name, prevCounter + 1); - return `${name}_${prevCounter}`; + function getUniqAssociatedNamesFromTupleType(type, restSymbol) { + const names = map(type.target.labeledElementDeclarations, (labeledElement, i) => getTupleElementLabel(labeledElement, i, type.target.elementFlags[i], restSymbol)); + if (names) { + const duplicates = []; + const uniqueNames = /* @__PURE__ */ new Set(); + for (let i = 0; i < names.length; i++) { + const name = names[i]; + if (!tryAddToSet(uniqueNames, name)) { + duplicates.push(i); + } } - }); + const counters = /* @__PURE__ */ new Map(); + for (const i of duplicates) { + let counter = counters.get(names[i]) ?? 1; + let name; + while (!tryAddToSet(uniqueNames, name = `${names[i]}_${counter}`)) { + counter++; + } + names[i] = name; + counters.set(names[i], counter + 1); + } + } + return names; } } function getDefaultConstructSignatures(classType) { @@ -157636,8 +157709,11 @@ function createTypeChecker(host) { true ); } + function getTypeParametersForMapper(signature) { + return sameMap(signature.typeParameters, (tp) => tp.mapper ? instantiateType(tp, tp.mapper) : tp); + } function createSignatureTypeMapper(signature, typeArguments) { - return createTypeMapper(sameMap(signature.typeParameters, (tp) => tp.mapper ? instantiateType(tp, tp.mapper) : tp), typeArguments); + return createTypeMapper(getTypeParametersForMapper(signature), typeArguments); } function getErasedSignature(signature) { return signature.typeParameters ? signature.erasedSignatureCache || (signature.erasedSignatureCache = createErasedSignature(signature)) : signature; @@ -157898,14 +157974,14 @@ function createTypeChecker(host) { var _a, _b; if (!type.resolvedTypeArguments) { if (!pushTypeResolution(type, 5 /* ResolvedTypeArguments */)) { - return ((_a = type.target.localTypeParameters) == null ? void 0 : _a.map(() => errorType)) || emptyArray; + return concatenate(type.target.outerTypeParameters, (_a = type.target.localTypeParameters) == null ? void 0 : _a.map(() => errorType)) || emptyArray; } const node = type.node; const typeArguments = !node ? emptyArray : node.kind === 183 /* TypeReference */ ? concatenate(type.target.outerTypeParameters, getEffectiveTypeArguments2(node, type.target.localTypeParameters)) : node.kind === 188 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] : map(node.elements, getTypeFromTypeNode); if (popTypeResolution()) { type.resolvedTypeArguments ?? (type.resolvedTypeArguments = type.mapper ? instantiateTypes(typeArguments, type.mapper) : typeArguments); } else { - type.resolvedTypeArguments ?? (type.resolvedTypeArguments = ((_b = type.target.localTypeParameters) == null ? void 0 : _b.map(() => errorType)) || emptyArray); + type.resolvedTypeArguments ?? (type.resolvedTypeArguments = concatenate(type.target.outerTypeParameters, ((_b = type.target.localTypeParameters) == null ? void 0 : _b.map(() => errorType)) || emptyArray)); error2( type.node || currentNode, type.target.symbol ? Diagnostics.Type_arguments_for_0_circularly_reference_themselves : Diagnostics.Tuple_type_arguments_circularly_reference_themselves, @@ -158356,6 +158432,18 @@ function createTypeChecker(host) { const symbol = getGlobalTypeSymbol(name, reportErrors2); return symbol || reportErrors2 ? getTypeOfGlobalSymbol(symbol, arity) : void 0; } + function getGlobalBuiltinTypes(typeNames, arity) { + let types; + for (const typeName of typeNames) { + types = append(types, getGlobalType( + typeName, + arity, + /*reportErrors*/ + false + )); + } + return types ?? emptyArray; + } function getGlobalTypedPropertyDescriptorType() { return deferredGlobalTypedPropertyDescriptorType || (deferredGlobalTypedPropertyDescriptorType = getGlobalType( "TypedPropertyDescriptor", @@ -158458,7 +158546,7 @@ function createTypeChecker(host) { return deferredGlobalAsyncIterableType || (deferredGlobalAsyncIterableType = getGlobalType( "AsyncIterable", /*arity*/ - 1, + 3, reportErrors2 )) || emptyGenericType; } @@ -158474,7 +158562,18 @@ function createTypeChecker(host) { return deferredGlobalAsyncIterableIteratorType || (deferredGlobalAsyncIterableIteratorType = getGlobalType( "AsyncIterableIterator", /*arity*/ - 1, + 3, + reportErrors2 + )) || emptyGenericType; + } + function getGlobalBuiltinAsyncIteratorTypes() { + return deferredGlobalBuiltinAsyncIteratorTypes ?? (deferredGlobalBuiltinAsyncIteratorTypes = getGlobalBuiltinTypes(["ReadableStreamAsyncIterator"], 1)); + } + function getGlobalAsyncIteratorObjectType(reportErrors2) { + return deferredGlobalAsyncIteratorObjectType || (deferredGlobalAsyncIteratorObjectType = getGlobalType( + "AsyncIteratorObject", + /*arity*/ + 3, reportErrors2 )) || emptyGenericType; } @@ -158490,7 +158589,7 @@ function createTypeChecker(host) { return deferredGlobalIterableType || (deferredGlobalIterableType = getGlobalType( "Iterable", /*arity*/ - 1, + 3, reportErrors2 )) || emptyGenericType; } @@ -158506,7 +158605,21 @@ function createTypeChecker(host) { return deferredGlobalIterableIteratorType || (deferredGlobalIterableIteratorType = getGlobalType( "IterableIterator", /*arity*/ - 1, + 3, + reportErrors2 + )) || emptyGenericType; + } + function getBuiltinIteratorReturnType() { + return strictBuiltinIteratorReturn ? undefinedType : anyType; + } + function getGlobalBuiltinIteratorTypes() { + return deferredGlobalBuiltinIteratorTypes ?? (deferredGlobalBuiltinIteratorTypes = getGlobalBuiltinTypes(["ArrayIterator", "MapIterator", "SetIterator", "StringIterator"], 1)); + } + function getGlobalIteratorObjectType(reportErrors2) { + return deferredGlobalIteratorObjectType || (deferredGlobalIteratorObjectType = getGlobalType( + "IteratorObject", + /*arity*/ + 3, reportErrors2 )) || emptyGenericType; } @@ -158688,7 +158801,7 @@ function createTypeChecker(host) { return createTypeFromGenericGlobalType(getGlobalIterableType( /*reportErrors*/ true - ), [iteratedType]); + ), [iteratedType, voidType, undefinedType]); } function createArrayType(elementType, readonly) { return createTypeFromGenericGlobalType(readonly ? globalReadonlyArrayType : globalArrayType, [elementType]); @@ -159352,6 +159465,12 @@ function createTypeChecker(host) { function eachUnionContains(unionTypes2, type) { for (const u of unionTypes2) { if (!containsType(u.types, type)) { + if (type === missingType) { + return containsType(u.types, undefinedType); + } + if (type === undefinedType) { + return containsType(u.types, missingType); + } const primitive = type.flags & 128 /* StringLiteral */ ? stringType : type.flags & (32 /* Enum */ | 256 /* NumberLiteral */) ? numberType : type.flags & 2048 /* BigIntLiteral */ ? bigintType : type.flags & 8192 /* UniqueESSymbol */ ? esSymbolType : void 0; if (!primitive || !containsType(u.types, primitive)) { return false; @@ -159408,6 +159527,13 @@ function createTypeChecker(host) { for (const t of u.types) { if (insertType(checked, t)) { if (eachUnionContains(unionTypes2, t)) { + if (t === undefinedType && result.length && result[0] === missingType) { + continue; + } + if (t === missingType && result.length && result[0] === undefinedType) { + result[0] = missingType; + continue; + } insertType(result, t); } } @@ -159492,7 +159618,7 @@ function createTypeChecker(host) { } else if (every(typeSet, (t) => !!(t.flags & 1048576 /* Union */ && (t.types[0].flags & 65536 /* Null */ || t.types[1].flags & 65536 /* Null */)))) { removeFromEach(typeSet, 65536 /* Null */); result = getUnionType([getIntersectionType(typeSet, flags), nullType], 1 /* Literal */, aliasSymbol, aliasTypeArguments); - } else if (typeSet.length >= 4) { + } else if (typeSet.length >= 3 && types.length > 2) { const middle = Math.floor(typeSet.length / 2); result = getIntersectionType([getIntersectionType(typeSet.slice(0, middle), flags), getIntersectionType(typeSet.slice(middle), flags)], flags, aliasSymbol, aliasTypeArguments); } else { @@ -159888,7 +160014,7 @@ function createTypeChecker(host) { } if (everyType(objectType, isTupleType) && isNumericLiteralName(propName)) { const index = +propName; - if (accessNode && everyType(objectType, (t) => !t.target.hasRestElement) && !(accessFlags & 16 /* NoTupleBoundsCheck */)) { + if (accessNode && everyType(objectType, (t) => !(t.target.combinedFlags & 12 /* Variable */)) && !(accessFlags & 16 /* AllowMissing */)) { const indexNode = getIndexNodeForAccessExpression(accessNode); if (isTupleType(objectType)) { if (index < 0) { @@ -160027,17 +160153,21 @@ function createTypeChecker(host) { return void 0; } } + if (accessFlags & 16 /* AllowMissing */ && isObjectLiteralType2(objectType)) { + return undefinedType; + } if (isJSLiteralType(objectType)) { return anyType; } if (accessNode) { const indexNode = getIndexNodeForAccessExpression(accessNode); - if (indexType.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) { + if (indexNode.kind !== 10 /* BigIntLiteral */ && indexType.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) { error2(indexNode, Diagnostics.Property_0_does_not_exist_on_type_1, "" + indexType.value, typeToString(objectType)); } else if (indexType.flags & (4 /* String */ | 8 /* Number */)) { error2(indexNode, Diagnostics.Type_0_has_no_matching_index_signature_for_type_1, typeToString(objectType), typeToString(indexType)); } else { - error2(indexNode, Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType)); + const typeString = indexNode.kind === 10 /* BigIntLiteral */ ? "bigint" : typeToString(indexType); + error2(indexNode, Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeString); } } if (isTypeAny(indexType)) { @@ -162298,7 +162428,7 @@ function createTypeChecker(host) { } const id = getSymbolId(sourceSymbol) + "," + getSymbolId(targetSymbol); const entry = enumRelation.get(id); - if (entry !== void 0 && !(!(entry & 4 /* Reported */) && entry & 2 /* Failed */ && errorReporter)) { + if (entry !== void 0 && !(entry & 2 /* Failed */ && errorReporter)) { return !!(entry & 1 /* Succeeded */); } const targetEnumType = getTypeOfSymbol(targetSymbol); @@ -162313,10 +162443,8 @@ function createTypeChecker(host) { void 0, 64 /* UseFullyQualifiedType */ )); - enumRelation.set(id, 2 /* Failed */ | 4 /* Reported */); - } else { - enumRelation.set(id, 2 /* Failed */); } + enumRelation.set(id, 2 /* Failed */); return false; } const sourceValue = getEnumMemberValue(getDeclarationOfKind(sourceProperty, 306 /* EnumMember */)).value; @@ -162325,26 +162453,22 @@ function createTypeChecker(host) { const sourceIsString = typeof sourceValue === "string"; const targetIsString = typeof targetValue === "string"; if (sourceValue !== void 0 && targetValue !== void 0) { - if (!errorReporter) { - enumRelation.set(id, 2 /* Failed */); - } else { + if (errorReporter) { const escapedSource = sourceIsString ? `"${escapeString(sourceValue)}"` : sourceValue; const escapedTarget = targetIsString ? `"${escapeString(targetValue)}"` : targetValue; errorReporter(Diagnostics.Each_declaration_of_0_1_differs_in_its_value_where_2_was_expected_but_3_was_given, symbolName(targetSymbol), symbolName(targetProperty), escapedTarget, escapedSource); - enumRelation.set(id, 2 /* Failed */ | 4 /* Reported */); } + enumRelation.set(id, 2 /* Failed */); return false; } if (sourceIsString || targetIsString) { - if (!errorReporter) { - enumRelation.set(id, 2 /* Failed */); - } else { + if (errorReporter) { const knownStringValue = sourceValue ?? targetValue; Debug.assert(typeof knownStringValue === "string"); const escapedValue = `"${escapeString(knownStringValue)}"`; errorReporter(Diagnostics.One_value_of_0_1_is_the_string_2_and_the_other_is_assumed_to_be_an_unknown_numeric_value, symbolName(targetSymbol), symbolName(targetProperty), escapedValue); - enumRelation.set(id, 2 /* Failed */ | 4 /* Reported */); } + enumRelation.set(id, 2 /* Failed */); return false; } } @@ -162502,7 +162626,7 @@ function createTypeChecker(host) { /*ignoreConstraints*/ false ); - relation.set(id, 4 /* Reported */ | 2 /* Failed */); + relation.set(id, 2 /* Failed */ | (relationCount <= 0 ? 32 /* ComplexityOverflow */ : 64 /* StackDepthOverflow */)); (_a = tracing) == null ? void 0 : _a.instant(tracing.Phase.CheckTypes, "checkTypeRelatedTo_DepthLimit", { sourceId: source.id, targetId: target.id, depth: sourceDepth, targetDepth }); const message = relationCount <= 0 ? Diagnostics.Excessive_complexity_comparing_types_0_and_1 : Diagnostics.Excessive_stack_depth_comparing_types_0_and_1; const diag2 = error2(errorNode || currentNode, message, typeToString(source), typeToString(target)); @@ -163355,7 +163479,7 @@ function createTypeChecker(host) { ); const entry = relation.get(id); if (entry !== void 0) { - if (reportErrors2 && entry & 2 /* Failed */ && !(entry & 4 /* Reported */)) { + if (reportErrors2 && entry & 2 /* Failed */ && !(entry & 96 /* Overflow */)) { } else { if (outofbandVarianceMarkerHandler) { const saved = entry & 24 /* ReportsMask */; @@ -163366,6 +163490,11 @@ function createTypeChecker(host) { instantiateType(source2, reportUnreliableMapper); } } + if (reportErrors2 && entry & 96 /* Overflow */) { + const message = entry & 32 /* ComplexityOverflow */ ? Diagnostics.Excessive_complexity_comparing_types_0_and_1 : Diagnostics.Excessive_stack_depth_comparing_types_0_and_1; + reportError(message, typeToString(source2), typeToString(target2)); + overrideNextErrorInfo++; + } return entry & 1 /* Succeeded */ ? -1 /* True */ : 0 /* False */; } } @@ -163463,7 +163592,7 @@ function createTypeChecker(host) { } } } else { - relation.set(id, (reportErrors2 ? 4 /* Reported */ : 0) | 2 /* Failed */ | propagatingVarianceFlags); + relation.set(id, 2 /* Failed */ | propagatingVarianceFlags); relationCount--; resetMaybeStack( /*markAllAsSucceeded*/ @@ -164356,7 +164485,7 @@ function createTypeChecker(host) { const sourceArity = getTypeReferenceArity(source2); const targetArity = getTypeReferenceArity(target2); const sourceRestFlag = isTupleType(source2) ? source2.target.combinedFlags & 4 /* Rest */ : 4 /* Rest */; - const targetRestFlag = target2.target.combinedFlags & 4 /* Rest */; + const targetHasRestElement = !!(target2.target.combinedFlags & 12 /* Variable */); const sourceMinLength = isTupleType(source2) ? source2.target.minLength : 0; const targetMinLength = target2.target.minLength; if (!sourceRestFlag && sourceArity < targetMinLength) { @@ -164365,13 +164494,13 @@ function createTypeChecker(host) { } return 0 /* False */; } - if (!targetRestFlag && targetArity < sourceMinLength) { + if (!targetHasRestElement && targetArity < sourceMinLength) { if (reportErrors2) { reportError(Diagnostics.Source_has_0_element_s_but_target_allows_only_1, sourceMinLength, targetArity); } return 0 /* False */; } - if (!targetRestFlag && (sourceRestFlag || targetArity < sourceArity)) { + if (!targetHasRestElement && (sourceRestFlag || targetArity < sourceArity)) { if (reportErrors2) { if (sourceMinLength < targetMinLength) { reportError(Diagnostics.Target_requires_0_element_s_but_source_may_have_fewer, targetMinLength); @@ -164385,7 +164514,6 @@ function createTypeChecker(host) { const targetTypeArguments = getTypeArguments(target2); const targetStartCount = getStartElementCount(target2.target, 11 /* NonRest */); const targetEndCount = getEndElementCount(target2.target, 11 /* NonRest */); - const targetHasRestElement = target2.target.hasRestElement; let canExcludeDiscriminants = !!excludedProperties; for (let sourcePosition = 0; sourcePosition < sourceArity; sourcePosition++) { const sourceFlags = isTupleType(source2) ? source2.target.elementFlags[sourcePosition] : 4 /* Rest */; @@ -164845,7 +164973,7 @@ function createTypeChecker(host) { for (let i = 0; i < types.length; i++) { if (include[i]) { const targetType = getTypeOfPropertyOrIndexSignatureOfType(types[i], propertyName); - if (targetType && related(getDiscriminatingType(), targetType)) { + if (targetType && someType(getDiscriminatingType(), (t) => !!related(t, targetType))) { matched = true; } else { include[i] = 3 /* Maybe */; @@ -165625,6 +165753,7 @@ function createTypeChecker(host) { return type; } function reportWideningErrorsInType(type) { + var _a; let errorReported = false; if (getObjectFlags(type) & 65536 /* ContainsWideningType */) { if (type.flags & 1048576 /* Union */) { @@ -165632,27 +165761,28 @@ function createTypeChecker(host) { errorReported = true; } else { for (const t of type.types) { - if (reportWideningErrorsInType(t)) { - errorReported = true; - } + errorReported || (errorReported = reportWideningErrorsInType(t)); } } - } - if (isArrayOrTupleType(type)) { + } else if (isArrayOrTupleType(type)) { for (const t of getTypeArguments(type)) { - if (reportWideningErrorsInType(t)) { - errorReported = true; - } + errorReported || (errorReported = reportWideningErrorsInType(t)); } - } - if (isObjectLiteralType2(type)) { + } else if (isObjectLiteralType2(type)) { for (const p of getPropertiesOfObjectType(type)) { const t = getTypeOfSymbol(p); if (getObjectFlags(t) & 65536 /* ContainsWideningType */) { - if (!reportWideningErrorsInType(t)) { - error2(p.valueDeclaration, Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolToString(p), typeToString(getWidenedType(t))); + errorReported = reportWideningErrorsInType(t); + if (!errorReported) { + const valueDeclaration = (_a = p.declarations) == null ? void 0 : _a.find((d) => { + var _a2; + return ((_a2 = d.symbol.valueDeclaration) == null ? void 0 : _a2.parent) === type.symbol.valueDeclaration; + }); + if (valueDeclaration) { + error2(valueDeclaration, Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolToString(p), typeToString(getWidenedType(t))); + errorReported = true; + } } - errorReported = true; } } } @@ -166031,7 +166161,7 @@ function createTypeChecker(host) { return firstOrUndefinedIterator(getUnmatchedProperties(source, target, requireOptionalProperties, matchDiscriminantProperties)); } function tupleTypesDefinitelyUnrelated(source, target) { - return !(target.target.combinedFlags & 8 /* Variadic */) && target.target.minLength > source.target.minLength || !target.target.hasRestElement && (source.target.hasRestElement || target.target.fixedLength < source.target.fixedLength); + return !(target.target.combinedFlags & 8 /* Variadic */) && target.target.minLength > source.target.minLength || !(target.target.combinedFlags & 12 /* Variable */) && (!!(source.target.combinedFlags & 12 /* Variable */) || target.target.fixedLength < source.target.fixedLength); } function typesDefinitelyUnrelated(source, target) { return isTupleType(source) && isTupleType(target) ? tupleTypesDefinitelyUnrelated(source, target) : !!getUnmatchedProperty( @@ -166120,7 +166250,7 @@ function createTypeChecker(host) { return false; } function inferTypesFromTemplateLiteralType(source, target) { - return source.flags & 128 /* StringLiteral */ ? inferFromLiteralPartsToTemplateLiteral([source.value], emptyArray, target) : source.flags & 134217728 /* TemplateLiteral */ ? arraysEqual(source.texts, target.texts) ? map(source.types, (s, i) => { + return source.flags & 128 /* StringLiteral */ ? inferFromLiteralPartsToTemplateLiteral([source.value], emptyArray, target) : source.flags & 134217728 /* TemplateLiteral */ ? arrayIsEqualTo(source.texts, target.texts) ? map(source.types, (s, i) => { return isTypeAssignableTo(getBaseConstraintOrType(s), getBaseConstraintOrType(target.types[i])) ? s : getStringLikeTypeForType(s); }) : inferFromLiteralPartsToTemplateLiteral(source.texts, source.types, target) : void 0; } @@ -166649,7 +166779,7 @@ function createTypeChecker(host) { return; } const startLength = isTupleType(source) ? Math.min(source.target.fixedLength, target.target.fixedLength) : 0; - const endLength = Math.min(isTupleType(source) ? getEndElementCount(source.target, 3 /* Fixed */) : 0, target.target.hasRestElement ? getEndElementCount(target.target, 3 /* Fixed */) : 0); + const endLength = Math.min(isTupleType(source) ? getEndElementCount(source.target, 3 /* Fixed */) : 0, target.target.combinedFlags & 12 /* Variable */ ? getEndElementCount(target.target, 3 /* Fixed */) : 0); for (let i = 0; i < startLength; i++) { inferFromTypes(getTypeArguments(source)[i], elementTypes[i]); } @@ -166670,7 +166800,7 @@ function createTypeChecker(host) { } else if (elementFlags[startLength] & 8 /* Variadic */ && elementFlags[startLength + 1] & 4 /* Rest */) { const param = (_a = getInferenceInfoForType(elementTypes[startLength])) == null ? void 0 : _a.typeParameter; const constraint = param && getBaseConstraintOfType(param); - if (constraint && isTupleType(constraint) && !constraint.target.hasRestElement) { + if (constraint && isTupleType(constraint) && !(constraint.target.combinedFlags & 12 /* Variable */)) { const impliedArity = constraint.target.fixedLength; inferFromTypes(sliceTupleType(source, startLength, sourceArity - (startLength + impliedArity)), elementTypes[startLength]); inferFromTypes(getElementTypeOfSliceOfTupleType(source, startLength + impliedArity, endLength), elementTypes[startLength + 1]); @@ -166678,7 +166808,7 @@ function createTypeChecker(host) { } else if (elementFlags[startLength] & 4 /* Rest */ && elementFlags[startLength + 1] & 8 /* Variadic */) { const param = (_b = getInferenceInfoForType(elementTypes[startLength + 1])) == null ? void 0 : _b.typeParameter; const constraint = param && getBaseConstraintOfType(param); - if (constraint && isTupleType(constraint) && !constraint.target.hasRestElement) { + if (constraint && isTupleType(constraint) && !(constraint.target.combinedFlags & 12 /* Variable */)) { const impliedArity = constraint.target.fixedLength; const endIndex = sourceArity - getEndElementCount(target.target, 3 /* Fixed */); const startIndex = endIndex - impliedArity; @@ -166830,7 +166960,7 @@ function createTypeChecker(host) { const inferredCovariantType = inference.candidates ? getCovariantInference(inference, context.signature) : void 0; const inferredContravariantType = inference.contraCandidates ? getContravariantInference(inference) : void 0; if (inferredCovariantType || inferredContravariantType) { - const preferCovariantType = inferredCovariantType && (!inferredContravariantType || !(inferredCovariantType.flags & 131072 /* Never */) && some(inference.contraCandidates, (t) => isTypeSubtypeOf(inferredCovariantType, t)) && every(context.inferences, (other) => other !== inference && getConstraintOfTypeParameter(other.typeParameter) !== inference.typeParameter || every(other.candidates, (t) => isTypeSubtypeOf(t, inferredCovariantType)))); + const preferCovariantType = inferredCovariantType && (!inferredContravariantType || !(inferredCovariantType.flags & (131072 /* Never */ | 1 /* Any */)) && some(inference.contraCandidates, (t) => isTypeAssignableTo(inferredCovariantType, t)) && every(context.inferences, (other) => other !== inference && getConstraintOfTypeParameter(other.typeParameter) !== inference.typeParameter || every(other.candidates, (t) => isTypeAssignableTo(t, inferredCovariantType)))); inferredType = preferCovariantType ? inferredCovariantType : inferredContravariantType; fallbackType = preferCovariantType ? inferredContravariantType : inferredCovariantType; } else if (context.flags & 1 /* NoDefault */) { @@ -167217,6 +167347,9 @@ function createTypeChecker(host) { return isTypeAssignableTo(assignedType, reducedType) ? reducedType : declaredType; } function isFunctionObjectType(type) { + if (getObjectFlags(type) & 256 /* EvolvingArray */) { + return false; + } const resolved = resolveStructuredTypeMembers(type); return !!(resolved.callSignatures.length || resolved.constructSignatures.length || resolved.members.get("bind") && isTypeSubtypeOf(type, globalFunctionType)); } @@ -168284,7 +168417,7 @@ function createTypeChecker(host) { return getEvolvingArrayType(getUnionType(map(types, getElementTypeOfEvolvingArrayType))); } const result = recombineUnknownType(getUnionType(sameMap(types, finalizeEvolvingArrayType), subtypeReduction)); - if (result !== declaredType && result.flags & declaredType.flags & 1048576 /* Union */ && arraysEqual(result.types, declaredType.types)) { + if (result !== declaredType && result.flags & declaredType.flags & 1048576 /* Union */ && arrayIsEqualTo(result.types, declaredType.types)) { return declaredType; } return result; @@ -169044,9 +169177,10 @@ function createTypeChecker(host) { return; case 281 /* ExportSpecifier */: const exportDeclaration = node.parent.parent; - if (!node.isTypeOnly && !exportDeclaration.isTypeOnly && !exportDeclaration.moduleSpecifier) { + const name = node.propertyName || node.name; + if (!node.isTypeOnly && !exportDeclaration.isTypeOnly && !exportDeclaration.moduleSpecifier && name.kind !== 11 /* StringLiteral */) { const symbol = resolveEntityName( - node.propertyName || node.name, + name, 111551 /* Value */, /*ignoreErrors*/ true, @@ -169340,6 +169474,9 @@ function createTypeChecker(host) { function markExportSpecifierAliasReferenced(location) { if (!location.parent.parent.moduleSpecifier && !location.isTypeOnly && !location.parent.parent.isTypeOnly) { const exportedName = location.propertyName || location.name; + if (exportedName.kind === 11 /* StringLiteral */) { + return; + } const symbol = resolveName( exportedName, exportedName.escapedText, @@ -169354,7 +169491,7 @@ function createTypeChecker(host) { const target = symbol && (symbol.flags & 2097152 /* Alias */ ? resolveAlias(symbol) : symbol); if (!target || getSymbolFlags(target) & 111551 /* Value */) { markExportAsReferenced(location); - markIdentifierAliasReferenced(location.propertyName || location.name); + markIdentifierAliasReferenced(exportedName); } } return; @@ -169470,7 +169607,7 @@ function createTypeChecker(host) { markAliasSymbolAsReferenced(rootSymbol); } else if (forDecoratorMetadata && getIsolatedModules(compilerOptions) && getEmitModuleKind(compilerOptions) >= 5 /* ES2015 */ && !symbolIsValue(rootSymbol) && !some(rootSymbol.declarations, isTypeOnlyImportOrExportDeclaration)) { const diag2 = error2(typeName, Diagnostics.A_type_referenced_in_a_decorated_signature_must_be_imported_with_import_type_or_a_namespace_import_when_isolatedModules_and_emitDecoratorMetadata_are_enabled); - const aliasDeclaration = find(rootSymbol.declarations || emptyArray, isAliasSymbolDeclaration2); + const aliasDeclaration = find(rootSymbol.declarations || emptyArray, isAliasSymbolDeclaration); if (aliasDeclaration) { addRelatedInfo(diag2, createDiagnosticForNode(aliasDeclaration, Diagnostics._0_was_imported_here, idText(rootName))); } @@ -169494,9 +169631,9 @@ function createTypeChecker(host) { ); } } - function getNarrowedTypeOfSymbol(symbol, location, checkMode) { + function getNarrowedTypeOfSymbol(symbol, location) { var _a; - const type = getTypeOfSymbol(symbol, checkMode); + const type = getTypeOfSymbol(symbol); const declaration = symbol.valueDeclaration; if (declaration) { if (isBindingElement(declaration) && !declaration.initializer && !declaration.dotDotDotToken && declaration.parent.elements.length >= 2) { @@ -169635,7 +169772,10 @@ function createTypeChecker(host) { } const localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); let declaration = localOrExportSymbol.valueDeclaration; - let type = getNarrowedTypeOfSymbol(localOrExportSymbol, node, checkMode); + if (declaration && declaration.kind === 208 /* BindingElement */ && contains(contextualBindingPatterns, declaration.parent) && findAncestor(node, (parent2) => parent2 === declaration.parent)) { + return nonInferrableAnyType; + } + let type = getNarrowedTypeOfSymbol(localOrExportSymbol, node); const assignmentKind = getAssignmentTargetKind(node); if (assignmentKind) { if (!(localOrExportSymbol.flags & 3 /* Variable */) && !(isInJSFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) { @@ -170587,7 +170727,7 @@ function createTypeChecker(host) { type, (t) => { var _a; - if (isGenericMappedType(t) && !t.declaration.nameType) { + if (isGenericMappedType(t) && getMappedTypeNameTypeKind(t) !== 2 /* Remapping */) { const constraint = getConstraintTypeFromMappedType(t); const constraintOfConstraint = getBaseConstraintOfType(constraint) || constraint; const propertyNameType = nameType || getStringLiteralType(unescapeLeadingUnderscores(name)); @@ -170685,7 +170825,7 @@ function createTypeChecker(host) { return removeMissingType(getTypeArguments(t)[index], !!(t.target.elementFlags[index] && 2 /* Optional */)); } const offset = length2 !== void 0 && (lastSpreadIndex === void 0 || index > lastSpreadIndex) ? length2 - index : 0; - const fixedEndLength = offset > 0 && t.target.hasRestElement ? getEndElementCount(t.target, 3 /* Fixed */) : 0; + const fixedEndLength = offset > 0 && t.target.combinedFlags & 12 /* Variable */ ? getEndElementCount(t.target, 3 /* Fixed */) : 0; if (offset > 0 && offset <= fixedEndLength) { return getTypeArguments(t)[getTypeReferenceArity(t) - offset]; } @@ -171328,7 +171468,7 @@ function createTypeChecker(host) { return node.isSpread ? getIndexedAccessType(node.type, numberType) : node.type; } function hasDefaultValue(node) { - return node.kind === 208 /* BindingElement */ && !!node.initializer || node.kind === 226 /* BinaryExpression */ && node.operatorToken.kind === 64 /* EqualsToken */; + return node.kind === 208 /* BindingElement */ && !!node.initializer || node.kind === 303 /* PropertyAssignment */ && hasDefaultValue(node.initializer) || node.kind === 304 /* ShorthandPropertyAssignment */ && !!node.objectAssignmentInitializer || node.kind === 226 /* BinaryExpression */ && node.operatorToken.kind === 64 /* EqualsToken */; } function isSpreadIntoCallOrNew(node) { const parent2 = walkUpParenthesizedExpressions(node.parent); @@ -171497,7 +171637,6 @@ function createTypeChecker(host) { return links.immediateTarget; } function checkObjectLiteral(node, checkMode = 0 /* Normal */) { - var _a; const inDestructuringPattern = isAssignmentTarget(node); checkGrammarObjectLiteralExpression(node, inDestructuringPattern); const allPropertiesTable = strictNullChecks ? createSymbolTable() : void 0; @@ -171552,11 +171691,8 @@ function createTypeChecker(host) { if (nameType) { prop.links.nameType = nameType; } - if (inDestructuringPattern) { - const isOptional = memberDecl.kind === 303 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer) || memberDecl.kind === 304 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer; - if (isOptional) { - prop.flags |= 16777216 /* Optional */; - } + if (inDestructuringPattern && hasDefaultValue(memberDecl)) { + prop.flags |= 16777216 /* Optional */; } else if (contextualTypeHasPattern && !(getObjectFlags(contextualType) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { const impliedProp = getPropertyOfType(contextualType, member.escapedName); if (impliedProp) { @@ -171631,21 +171767,6 @@ function createTypeChecker(host) { propertiesArray.push(member); } popContextualType(); - if (contextualTypeHasPattern) { - const rootPatternParent = findAncestor(contextualType.pattern.parent, (n) => n.kind === 260 /* VariableDeclaration */ || n.kind === 226 /* BinaryExpression */ || n.kind === 169 /* Parameter */); - const spreadOrOutsideRootObject = findAncestor(node, (n) => n === rootPatternParent || n.kind === 305 /* SpreadAssignment */); - if (spreadOrOutsideRootObject.kind !== 305 /* SpreadAssignment */) { - for (const prop of getPropertiesOfType(contextualType)) { - if (!propertiesTable.get(prop.escapedName) && !getPropertyOfType(spread, prop.escapedName)) { - if (!(prop.flags & 16777216 /* Optional */)) { - error2(prop.valueDeclaration || ((_a = tryCast(prop, isTransientSymbol)) == null ? void 0 : _a.links.bindingElement), Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); - } - propertiesTable.set(prop.escapedName, prop); - propertiesArray.push(prop); - } - } - } - } if (isErrorType(spread)) { return errorType; } @@ -172321,8 +172442,21 @@ function createTypeChecker(host) { function getEnclosingClassFromThisParameter(node) { const thisParameter = getThisParameterFromNodeContext(node); let thisType = (thisParameter == null ? void 0 : thisParameter.type) && getTypeFromTypeNode(thisParameter.type); - if (thisType && thisType.flags & 262144 /* TypeParameter */) { - thisType = getConstraintOfTypeParameter(thisType); + if (thisType) { + if (thisType.flags & 262144 /* TypeParameter */) { + thisType = getConstraintOfTypeParameter(thisType); + } + } else { + const thisContainer = getThisContainer( + node, + /*includeArrowFunctions*/ + false, + /*includeClassComputedPropertyName*/ + false + ); + if (isFunctionLike(thisContainer)) { + thisType = getContextualThisParameterType(thisContainer); + } } if (thisType && getObjectFlags(thisType) & (3 /* ClassOrInterface */ | 4 /* Reference */)) { return getTargetType(thisType); @@ -172838,7 +172972,7 @@ function createTypeChecker(host) { addErrorOrSuggestion(!isUncheckedJS || errorInfo.code !== Diagnostics.Property_0_may_not_exist_on_type_1_Did_you_mean_2.code, resultDiagnostic); } function containerSeemsToBeEmptyDomElement(containingType) { - return compilerOptions.lib && !compilerOptions.lib.includes("dom") && everyContainedType(containingType, (type) => type.symbol && /^(EventTarget|Node|((HTML[a-zA-Z]*)?Element))$/.test(unescapeLeadingUnderscores(type.symbol.escapedName))) && isEmptyObjectType(containingType); + return compilerOptions.lib && !compilerOptions.lib.includes("dom") && everyContainedType(containingType, (type) => type.symbol && /^(?:EventTarget|Node|(?:HTML[a-zA-Z]*)?Element)$/.test(unescapeLeadingUnderscores(type.symbol.escapedName))) && isEmptyObjectType(containingType); } function typeHasStaticProperty(propName, containingType) { const prop = containingType.symbol && getPropertyOfType(getTypeOfSymbol(containingType.symbol), propName); @@ -173279,7 +173413,7 @@ function createTypeChecker(host) { return void 0; } function instantiateSignatureInContextOf(signature, contextualSignature, inferenceContext, compareTypes) { - const context = createInferenceContext(signature.typeParameters, signature, 0 /* None */, compareTypes); + const context = createInferenceContext(getTypeParametersForMapper(signature), signature, 0 /* None */, compareTypes); const restType = getEffectiveRestType(contextualSignature); const mapper = inferenceContext && (restType && restType.flags & 262144 /* TypeParameter */ ? inferenceContext.nonFixingMapper : inferenceContext.mapper); const sourceSignature = mapper ? instantiateSignature(contextualSignature, mapper) : contextualSignature; @@ -175099,7 +175233,7 @@ function createTypeChecker(host) { return createAnonymousType(anonymousSymbol, memberTable, emptyArray, emptyArray, emptyArray); } function getTypeWithSyntheticDefaultOnly(type, symbol, originalSymbol, moduleSpecifier) { - const hasDefaultOnly = isOnlyImportedAsDefault(moduleSpecifier); + const hasDefaultOnly = isOnlyImportableAsDefault(moduleSpecifier); if (hasDefaultOnly && type && !isErrorType(type)) { const synthType = type; if (!synthType.defaultOnlyType) { @@ -175425,14 +175559,45 @@ function createTypeChecker(host) { !!declaration && (hasInitializer(declaration) || isOptionalDeclaration(declaration)) ); } - function getTupleElementLabel(d, index, restParameterName = "arg") { + function getTupleElementLabelFromBindingElement(node, index, elementFlags) { + switch (node.name.kind) { + case 80 /* Identifier */: { + const name = node.name.escapedText; + if (node.dotDotDotToken) { + return elementFlags & 12 /* Variable */ ? name : `${name}_${index}`; + } else { + return elementFlags & 3 /* Fixed */ ? name : `${name}_n`; + } + } + case 207 /* ArrayBindingPattern */: { + if (node.dotDotDotToken) { + const elements = node.name.elements; + const lastElement = tryCast(lastOrUndefined(elements), isBindingElement); + const elementCount = elements.length - ((lastElement == null ? void 0 : lastElement.dotDotDotToken) ? 1 : 0); + if (index < elementCount) { + const element = elements[index]; + if (isBindingElement(element)) { + return getTupleElementLabelFromBindingElement(element, index, elementFlags); + } + } else if (lastElement == null ? void 0 : lastElement.dotDotDotToken) { + return getTupleElementLabelFromBindingElement(lastElement, index - elementCount, elementFlags); + } + } + break; + } + } + return `arg_${index}`; + } + function getTupleElementLabel(d, index = 0, elementFlags = 3 /* Fixed */, restSymbol) { if (!d) { - return `${restParameterName}_${index}`; + const restParameter = tryCast(restSymbol == null ? void 0 : restSymbol.valueDeclaration, isParameter); + return restParameter ? getTupleElementLabelFromBindingElement(restParameter, index, elementFlags) : `${(restSymbol == null ? void 0 : restSymbol.escapedName) ?? "arg"}_${index}`; } Debug.assert(isIdentifier(d.name)); return d.name.escapedText; } function getParameterNameAtPosition(signature, pos, overrideRestType) { + var _a; const paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); if (pos < paramCount) { return signature.parameters[pos].escapedName; @@ -175440,9 +175605,11 @@ function createTypeChecker(host) { const restParameter = signature.parameters[paramCount] || unknownSymbol; const restType = overrideRestType || getTypeOfSymbol(restParameter); if (isTupleType(restType)) { - const associatedNames = restType.target.labeledElementDeclarations; + const tupleType = restType.target; const index = pos - paramCount; - return getTupleElementLabel(associatedNames == null ? void 0 : associatedNames[index], index, restParameter.escapedName); + const associatedName = (_a = tupleType.labeledElementDeclarations) == null ? void 0 : _a[index]; + const elementFlags = tupleType.elementFlags[index]; + return getTupleElementLabel(associatedName, index, elementFlags, restParameter); } return restParameter.escapedName; } @@ -175515,7 +175682,7 @@ function createTypeChecker(host) { if (signatureHasRestParameter(signature)) { const restType = getTypeOfSymbol(signature.parameters[paramCount]); const index = pos - paramCount; - if (!isTupleType(restType) || restType.target.hasRestElement || index < restType.target.fixedLength) { + if (!isTupleType(restType) || restType.target.combinedFlags & 12 /* Variable */ || index < restType.target.fixedLength) { return getIndexedAccessType(restType, getNumberLiteralType(index)); } } @@ -175553,7 +175720,7 @@ function createTypeChecker(host) { if (signatureHasRestParameter(signature)) { const restType = getTypeOfSymbol(signature.parameters[length2 - 1]); if (isTupleType(restType)) { - return length2 + restType.target.fixedLength - (restType.target.hasRestElement ? 0 : 1); + return length2 + restType.target.fixedLength - (restType.target.combinedFlags & 12 /* Variable */ ? 0 : 1); } } return length2; @@ -175596,7 +175763,7 @@ function createTypeChecker(host) { function hasEffectiveRestParameter(signature) { if (signatureHasRestParameter(signature)) { const restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); - return !isTupleType(restType) || restType.target.hasRestElement; + return !isTupleType(restType) || !!(restType.target.combinedFlags & 12 /* Variable */); } return false; } @@ -175606,7 +175773,7 @@ function createTypeChecker(host) { if (!isTupleType(restType)) { return isTypeAny(restType) ? anyArrayType : restType; } - if (restType.target.hasRestElement) { + if (restType.target.combinedFlags & 12 /* Variable */) { return sliceTupleType(restType, restType.target.fixedLength); } } @@ -176120,30 +176287,15 @@ function createTypeChecker(host) { /*errorNode*/ void 0 ) || unknownType; - nextType = resolver.resolveIterationType( - nextType, - /*errorNode*/ - void 0 - ) || unknownType; if (globalGeneratorType === emptyGenericType) { - const globalType = resolver.getGlobalIterableIteratorType( + const globalIterableIteratorType = resolver.getGlobalIterableIteratorType( /*reportErrors*/ false ); - const iterationTypes = globalType !== emptyGenericType ? getIterationTypesOfGlobalIterableType(globalType, resolver) : void 0; - const iterableIteratorReturnType = iterationTypes ? iterationTypes.returnType : anyType; - const iterableIteratorNextType = iterationTypes ? iterationTypes.nextType : undefinedType; - if (isTypeAssignableTo(returnType, iterableIteratorReturnType) && isTypeAssignableTo(iterableIteratorNextType, nextType)) { - if (globalType !== emptyGenericType) { - return createTypeFromGenericGlobalType(globalType, [yieldType]); - } - resolver.getGlobalIterableIteratorType( - /*reportErrors*/ - true - ); - return emptyObjectType; + if (globalIterableIteratorType !== emptyGenericType) { + return createTypeFromGenericGlobalType(globalIterableIteratorType, [yieldType, returnType, nextType]); } - resolver.getGlobalGeneratorType( + resolver.getGlobalIterableIteratorType( /*reportErrors*/ true ); @@ -176923,7 +177075,7 @@ function createTypeChecker(host) { ); } } - const elementType = getIndexedAccessType(objectLiteralType, exprType, 32 /* ExpressionPosition */, name); + const elementType = getIndexedAccessType(objectLiteralType, exprType, 32 /* ExpressionPosition */ | (hasDefaultValue(property) ? 16 /* AllowMissing */ : 0), name); const type = getFlowTypeOfDestructuring(property, elementType); return checkDestructuringAssignment(property.kind === 304 /* ShorthandPropertyAssignment */ ? property : property.initializer, type); } else if (property.kind === 305 /* SpreadAssignment */) { @@ -176972,7 +177124,7 @@ function createTypeChecker(host) { if (element.kind !== 230 /* SpreadElement */) { const indexType = getNumberLiteralType(elementIndex); if (isArrayLikeType(sourceType)) { - const accessFlags = 32 /* ExpressionPosition */ | (hasDefaultValue(element) ? 16 /* NoTupleBoundsCheck */ : 0); + const accessFlags = 32 /* ExpressionPosition */ | (hasDefaultValue(element) ? 16 /* AllowMissing */ : 0); const elementType2 = getIndexedAccessTypeOrUndefined(sourceType, indexType, accessFlags, createSyntheticExpression(element, indexType)) || errorType; const assignedType = hasDefaultValue(element) ? getTypeWithFacts(elementType2, 524288 /* NEUndefined */) : elementType2; const type = getFlowTypeOfDestructuring(element, assignedType); @@ -177122,7 +177274,7 @@ function createTypeChecker(host) { setLastResult(state, checkExpression(node.right, checkMode)); return state; } - checkGrammarNullishCoalesceWithLogicalExpression(node); + checkNullishCoalesceOperands(node); const operator = node.operatorToken.kind; if (operator === 64 /* EqualsToken */ && (node.left.kind === 210 /* ObjectLiteralExpression */ || node.left.kind === 209 /* ArrayLiteralExpression */)) { state.skip = true; @@ -177155,7 +177307,9 @@ function createTypeChecker(host) { if (operator === 56 /* AmpersandAmpersandToken */ || isIfStatement(parent2)) { checkTestingKnownTruthyCallableOrAwaitableOrEnumMemberType(node.left, leftType, isIfStatement(parent2) ? parent2.thenStatement : void 0); } - checkTruthinessOfType(leftType, node.left); + if (isBinaryLogicalOperator(operator)) { + checkTruthinessOfType(leftType, node.left); + } } } } @@ -177212,7 +177366,7 @@ function createTypeChecker(host) { state.typeStack[state.stackIndex + 1] = type; } } - function checkGrammarNullishCoalesceWithLogicalExpression(node) { + function checkNullishCoalesceOperands(node) { const { left, operatorToken, right } = node; if (operatorToken.kind === 61 /* QuestionQuestionToken */) { if (isBinaryExpression(left) && (left.operatorToken.kind === 57 /* BarBarToken */ || left.operatorToken.kind === 56 /* AmpersandAmpersandToken */)) { @@ -177221,7 +177375,55 @@ function createTypeChecker(host) { if (isBinaryExpression(right) && (right.operatorToken.kind === 57 /* BarBarToken */ || right.operatorToken.kind === 56 /* AmpersandAmpersandToken */)) { grammarErrorOnNode(right, Diagnostics._0_and_1_operations_cannot_be_mixed_without_parentheses, tokenToString(right.operatorToken.kind), tokenToString(operatorToken.kind)); } + const leftTarget = skipOuterExpressions(left, 31 /* All */); + const nullishSemantics = getSyntacticNullishnessSemantics(leftTarget); + if (nullishSemantics !== 3 /* Sometimes */) { + if (node.parent.kind === 226 /* BinaryExpression */) { + error2(leftTarget, Diagnostics.This_binary_expression_is_never_nullish_Are_you_missing_parentheses); + } else { + if (nullishSemantics === 1 /* Always */) { + error2(leftTarget, Diagnostics.This_expression_is_always_nullish); + } else { + error2(leftTarget, Diagnostics.Right_operand_of_is_unreachable_because_the_left_operand_is_never_nullish); + } + } + } + } + } + function getSyntacticNullishnessSemantics(node) { + node = skipOuterExpressions(node); + switch (node.kind) { + case 223 /* AwaitExpression */: + case 213 /* CallExpression */: + case 212 /* ElementAccessExpression */: + case 214 /* NewExpression */: + case 211 /* PropertyAccessExpression */: + case 229 /* YieldExpression */: + case 110 /* ThisKeyword */: + return 3 /* Sometimes */; + case 226 /* BinaryExpression */: + switch (node.operatorToken.kind) { + case 64 /* EqualsToken */: + case 61 /* QuestionQuestionToken */: + case 78 /* QuestionQuestionEqualsToken */: + case 57 /* BarBarToken */: + case 76 /* BarBarEqualsToken */: + case 56 /* AmpersandAmpersandToken */: + case 77 /* AmpersandAmpersandEqualsToken */: + return 3 /* Sometimes */; + } + return 2 /* Never */; + case 227 /* ConditionalExpression */: + return getSyntacticNullishnessSemantics(node.whenTrue) | getSyntacticNullishnessSemantics(node.whenFalse); + case 106 /* NullKeyword */: + return 1 /* Always */; + case 80 /* Identifier */: + if (getResolvedSymbol(node) === undefinedSymbol) { + return 1 /* Always */; + } + return 3 /* Sometimes */; } + return 2 /* Never */; } function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) { const operator = operatorToken.kind; @@ -177229,7 +177431,7 @@ function createTypeChecker(host) { return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode, right.kind === 110 /* ThisKeyword */); } let leftType; - if (isLogicalOrCoalescingBinaryOperator(operator)) { + if (isBinaryLogicalOperator(operator)) { leftType = checkTruthinessExpression(left, checkMode); } else { leftType = checkExpression(left, checkMode); @@ -177309,6 +177511,29 @@ function createTypeChecker(host) { } if (leftOk && rightOk) { checkAssignmentOperator(resultType2); + switch (operator) { + case 48 /* LessThanLessThanToken */: + case 71 /* LessThanLessThanEqualsToken */: + case 49 /* GreaterThanGreaterThanToken */: + case 72 /* GreaterThanGreaterThanEqualsToken */: + case 50 /* GreaterThanGreaterThanGreaterThanToken */: + case 73 /* GreaterThanGreaterThanGreaterThanEqualsToken */: + const rhsEval = evaluate(right); + if (typeof rhsEval.value === "number" && Math.abs(rhsEval.value) >= 32) { + errorOrSuggestion( + isEnumMember(walkUpParenthesizedExpressions(right.parent.parent)), + // elevate from suggestion to error within an enum member + errorNode || operatorToken, + Diagnostics.This_operation_can_be_simplified_This_shift_is_identical_to_0_1_2, + getTextOfNode(left), + tokenToString(operator), + rhsEval.value % 32 + ); + } + break; + default: + break; + } } return resultType2; } @@ -177667,9 +177892,8 @@ function createTypeChecker(host) { const iterationTypes = returnType && getIterationTypesOfGeneratorFunctionReturnType(returnType, isAsync); const signatureYieldType = iterationTypes && iterationTypes.yieldType || anyType; const signatureNextType = iterationTypes && iterationTypes.nextType || anyType; - const resolvedSignatureNextType = isAsync ? getAwaitedType(signatureNextType) || anyType : signatureNextType; const yieldExpressionType = node.expression ? checkExpression(node.expression) : undefinedWideningType; - const yieldedType = getYieldedTypeOfYieldExpression(node, yieldExpressionType, resolvedSignatureNextType, isAsync); + const yieldedType = getYieldedTypeOfYieldExpression(node, yieldExpressionType, signatureNextType, isAsync); if (returnType && yieldedType) { checkTypeAssignableToAndOptionallyElaborate(yieldedType, signatureYieldType, node.expression || node, node.expression); } @@ -177811,9 +178035,56 @@ function createTypeChecker(host) { void 0, checkMode || 0 /* Normal */ ) : checkExpressionCached(initializer, checkMode)); - return isParameter(declaration) && declaration.name.kind === 207 /* ArrayBindingPattern */ && isTupleType(type) && !type.target.hasRestElement && getTypeReferenceArity(type) < declaration.name.elements.length ? padTupleType(type, declaration.name) : type; + if (isParameter(isBindingElement(declaration) ? walkUpBindingElementsAndPatterns(declaration) : declaration)) { + if (declaration.name.kind === 206 /* ObjectBindingPattern */ && isObjectLiteralType2(type)) { + return padObjectLiteralType(type, declaration.name); + } + if (declaration.name.kind === 207 /* ArrayBindingPattern */ && isTupleType(type)) { + return padTupleType(type, declaration.name); + } + } + return type; + } + function padObjectLiteralType(type, pattern) { + let missingElements; + for (const e of pattern.elements) { + if (e.initializer) { + const name = getPropertyNameFromBindingElement(e); + if (name && !getPropertyOfType(type, name)) { + missingElements = append(missingElements, e); + } + } + } + if (!missingElements) { + return type; + } + const members = createSymbolTable(); + for (const prop of getPropertiesOfObjectType(type)) { + members.set(prop.escapedName, prop); + } + for (const e of missingElements) { + const symbol = createSymbol(4 /* Property */ | 16777216 /* Optional */, getPropertyNameFromBindingElement(e)); + symbol.links.type = getTypeFromBindingElement( + e, + /*includePatternInType*/ + false, + /*reportErrors*/ + false + ); + members.set(symbol.escapedName, symbol); + } + const result = createAnonymousType(type.symbol, members, emptyArray, emptyArray, getIndexInfosOfType(type)); + result.objectFlags = type.objectFlags; + return result; + } + function getPropertyNameFromBindingElement(e) { + const exprType = getLiteralTypeFromPropertyName(e.propertyName || e.name); + return isTypeUsableAsPropertyName(exprType) ? getPropertyNameFromType(exprType) : void 0; } function padTupleType(type, pattern) { + if (type.target.combinedFlags & 12 /* Variable */ || getTypeReferenceArity(type) >= pattern.elements.length) { + return type; + } const patternElements = pattern.elements; const elementTypes = getElementTypes(type).slice(); const elementFlags = type.target.elementFlags.slice(); @@ -178122,7 +178393,17 @@ function createTypeChecker(host) { if (!ok) { error2(node, Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query); } - if (getIsolatedModules(compilerOptions)) { + if (compilerOptions.isolatedModules || compilerOptions.verbatimModuleSyntax && ok && !resolveName( + node, + getFirstIdentifier(node), + 2097152 /* Alias */, + /*nameNotFoundMessage*/ + void 0, + /*isUse*/ + false, + /*excludeGlobals*/ + true + )) { Debug.assert(!!(type.symbol.flags & 128 /* ConstEnum */)); const constEnumDeclaration = type.symbol.valueDeclaration; const redirect = host.getRedirectReferenceForResolutionFromSourceOfProject(getSourceFileOfNode(constEnumDeclaration).resolvedPath); @@ -178346,9 +178627,7 @@ function createTypeChecker(host) { } checkSourceElement(node.type); const { parameterName } = node; - if (typePredicate.kind === 0 /* This */ || typePredicate.kind === 2 /* AssertsThis */) { - getTypeFromThisTypeNode(parameterName); - } else { + if (typePredicate.kind !== 0 /* This */ && typePredicate.kind !== 2 /* AssertsThis */) { if (typePredicate.parameterIndex >= 0) { if (signatureHasRestParameter(signature) && typePredicate.parameterIndex === signature.parameters.length - 1) { error2(parameterName, Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); @@ -179083,16 +179362,20 @@ function createTypeChecker(host) { const someButNotAllOverloadFlags = someOverloadFlags ^ allOverloadFlags; if (someButNotAllOverloadFlags !== 0) { const canonicalFlags = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck2); - forEach(overloads, (o) => { - const deviation = getEffectiveDeclarationFlags(o, flagsToCheck2) ^ canonicalFlags; - if (deviation & 32 /* Export */) { - error2(getNameOfDeclaration(o), Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); - } else if (deviation & 128 /* Ambient */) { - error2(getNameOfDeclaration(o), Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); - } else if (deviation & (2 /* Private */ | 4 /* Protected */)) { - error2(getNameOfDeclaration(o) || o, Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); - } else if (deviation & 64 /* Abstract */) { - error2(getNameOfDeclaration(o), Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); + group(overloads, (o) => getSourceFileOfNode(o).fileName).forEach((overloadsInFile) => { + const canonicalFlagsForFile = getEffectiveDeclarationFlags(getCanonicalOverload(overloadsInFile, implementation), flagsToCheck2); + for (const o of overloadsInFile) { + const deviation = getEffectiveDeclarationFlags(o, flagsToCheck2) ^ canonicalFlags; + const deviationInFile = getEffectiveDeclarationFlags(o, flagsToCheck2) ^ canonicalFlagsForFile; + if (deviationInFile & 32 /* Export */) { + error2(getNameOfDeclaration(o), Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported); + } else if (deviationInFile & 128 /* Ambient */) { + error2(getNameOfDeclaration(o), Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); + } else if (deviation & (2 /* Private */ | 4 /* Protected */)) { + error2(getNameOfDeclaration(o) || o, Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); + } else if (deviation & 64 /* Abstract */) { + error2(getNameOfDeclaration(o), Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract); + } } }); } @@ -180227,7 +180510,7 @@ function createTypeChecker(host) { if (!wrappingDeclaration.type) { addRelatedInfo( diagnostic, - createFileDiagnostic(getSourceFileOfNode(wrappingDeclaration), wrappingDeclaration.end, 1, Diagnostics.We_can_only_write_a_type_for_0_by_adding_a_type_for_the_entire_parameter_here, declarationNameToString(node.propertyName)) + createFileDiagnostic(getSourceFileOfNode(wrappingDeclaration), wrappingDeclaration.end, 0, Diagnostics.We_can_only_write_a_type_for_0_by_adding_a_type_for_the_entire_parameter_here, declarationNameToString(node.propertyName)) ); } diagnostics.add(diagnostic); @@ -180326,7 +180609,7 @@ function createTypeChecker(host) { }); } function checkCollisionWithRequireExportsInGeneratedCode(node, name) { - if (moduleKind >= 5 /* ES2015 */ && !(moduleKind >= 100 /* Node16 */ && getSourceFileOfNode(node).impliedNodeFormat === 1 /* CommonJS */)) { + if (host.getEmitModuleFormatOfFile(getSourceFileOfNode(node)) >= 5 /* ES2015 */) { return; } if (!name || !needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) { @@ -180536,6 +180819,9 @@ function createTypeChecker(host) { checkAliasSymbol(node); return; } + if (node.name.kind === 10 /* BigIntLiteral */) { + error2(node.name, Diagnostics.A_bigint_literal_cannot_be_used_as_a_property_name); + } const type = convertAutoToAny(getTypeOfSymbol(symbol)); if (node === symbol.valueDeclaration) { const initializer = hasOnlyExpressionInitializer(node) && getEffectiveInitializer(node); @@ -180563,7 +180849,7 @@ function createTypeChecker(host) { ); if (globalAsyncDisposableType !== emptyObjectType && globalDisposableType !== emptyObjectType) { const optionalDisposableType = getUnionType([globalAsyncDisposableType, globalDisposableType, nullType, undefinedType]); - checkTypeAssignableTo(initializerType, optionalDisposableType, initializer, Diagnostics.The_initializer_of_an_await_using_declaration_must_be_either_an_object_with_a_Symbol_asyncDispose_or_Symbol_dispose_method_or_be_null_or_undefined); + checkTypeAssignableTo(widenTypeForVariableLikeDeclaration(initializerType, node), optionalDisposableType, initializer, Diagnostics.The_initializer_of_an_await_using_declaration_must_be_either_an_object_with_a_Symbol_asyncDispose_or_Symbol_dispose_method_or_be_null_or_undefined); } } else if (blockScopeKind === 4 /* Using */) { const globalDisposableType = getGlobalDisposableType( @@ -180572,7 +180858,7 @@ function createTypeChecker(host) { ); if (globalDisposableType !== emptyObjectType) { const optionalDisposableType = getUnionType([globalDisposableType, nullType, undefinedType]); - checkTypeAssignableTo(initializerType, optionalDisposableType, initializer, Diagnostics.The_initializer_of_a_using_declaration_must_be_either_an_object_with_a_Symbol_dispose_method_or_be_null_or_undefined); + checkTypeAssignableTo(widenTypeForVariableLikeDeclaration(initializerType, node), optionalDisposableType, initializer, Diagnostics.The_initializer_of_a_using_declaration_must_be_either_an_object_with_a_Symbol_dispose_method_or_be_null_or_undefined); } } } @@ -180690,7 +180976,7 @@ function createTypeChecker(host) { bothHelper(location, body2); return; } - const type = location === condExpr2 ? condType : checkTruthinessExpression(location); + const type = location === condExpr2 ? condType : checkExpression(location); if (type.flags & 1024 /* EnumLiteral */ && isPropertyAccessExpression(location) && (getNodeLinks(location.expression).resolvedSymbol ?? unknownSymbol).flags & 384 /* Enum */) { error2(location, Diagnostics.This_condition_will_always_return_0, !!type.value ? "true" : "false"); return; @@ -180785,9 +181071,51 @@ function createTypeChecker(host) { function checkTruthinessOfType(type, node) { if (type.flags & 16384 /* Void */) { error2(node, Diagnostics.An_expression_of_type_void_cannot_be_tested_for_truthiness); + } else { + const semantics = getSyntacticTruthySemantics(node); + if (semantics !== 3 /* Sometimes */) { + error2( + node, + semantics === 1 /* Always */ ? Diagnostics.This_kind_of_expression_is_always_truthy : Diagnostics.This_kind_of_expression_is_always_falsy + ); + } } return type; } + function getSyntacticTruthySemantics(node) { + node = skipOuterExpressions(node); + switch (node.kind) { + case 9 /* NumericLiteral */: + if (node.text === "0" || node.text === "1") { + return 3 /* Sometimes */; + } + return 1 /* Always */; + case 209 /* ArrayLiteralExpression */: + case 219 /* ArrowFunction */: + case 10 /* BigIntLiteral */: + case 231 /* ClassExpression */: + case 218 /* FunctionExpression */: + case 284 /* JsxElement */: + case 285 /* JsxSelfClosingElement */: + case 210 /* ObjectLiteralExpression */: + case 14 /* RegularExpressionLiteral */: + return 1 /* Always */; + case 222 /* VoidExpression */: + case 106 /* NullKeyword */: + return 2 /* Never */; + case 15 /* NoSubstitutionTemplateLiteral */: + case 11 /* StringLiteral */: + return !!node.text ? 1 /* Always */ : 2 /* Never */; + case 227 /* ConditionalExpression */: + return getSyntacticTruthySemantics(node.whenTrue) | getSyntacticTruthySemantics(node.whenFalse); + case 80 /* Identifier */: + if (getResolvedSymbol(node) === undefinedSymbol) { + return 2 /* Never */; + } + return 3 /* Sometimes */; + } + return 3 /* Sometimes */; + } function checkTruthinessExpression(node, checkMode) { return checkTruthinessOfType(checkExpression(node, checkMode), node); } @@ -181170,30 +181498,21 @@ function createTypeChecker(host) { function getIterationTypesOfIterableCached(type, resolver) { return getCachedIterationTypes(type, resolver.iterableCacheKey); } - function getIterationTypesOfGlobalIterableType(globalType, resolver) { - const globalIterationTypes = getIterationTypesOfIterableCached(globalType, resolver) || getIterationTypesOfIterableSlow( - globalType, - resolver, - /*errorNode*/ - void 0, - /*errorOutputContainer*/ - void 0, - /*noCache*/ - false - ); - return globalIterationTypes === noIterationTypes ? defaultIterationTypes : globalIterationTypes; - } function getIterationTypesOfIterableFast(type, resolver) { - let globalType; - if (isReferenceToType2(type, globalType = resolver.getGlobalIterableType( + if (isReferenceToType2(type, resolver.getGlobalIterableType( + /*reportErrors*/ + false + )) || isReferenceToType2(type, resolver.getGlobalIteratorObjectType( /*reportErrors*/ false - )) || isReferenceToType2(type, globalType = resolver.getGlobalIterableIteratorType( + )) || isReferenceToType2(type, resolver.getGlobalIterableIteratorType( + /*reportErrors*/ + false + )) || isReferenceToType2(type, resolver.getGlobalGeneratorType( /*reportErrors*/ false ))) { - const [yieldType] = getTypeArguments(type); - const { returnType, nextType } = getIterationTypesOfGlobalIterableType(globalType, resolver); + const [yieldType, returnType, nextType] = getTypeArguments(type); return setCachedIterationTypes(type, resolver.iterableCacheKey, createIterationTypes(resolver.resolveIterationType( yieldType, /*errorNode*/ @@ -181204,11 +181523,10 @@ function createTypeChecker(host) { void 0 ) || returnType, nextType)); } - if (isReferenceToType2(type, resolver.getGlobalGeneratorType( - /*reportErrors*/ - false - ))) { - const [yieldType, returnType, nextType] = getTypeArguments(type); + if (isReferenceToSomeType(type, resolver.getGlobalBuiltinIteratorTypes())) { + const [yieldType] = getTypeArguments(type); + const returnType = getBuiltinIteratorReturnType(); + const nextType = unknownType; return setCachedIterationTypes(type, resolver.iterableCacheKey, createIterationTypes(resolver.resolveIterationType( yieldType, /*errorNode*/ @@ -181249,10 +181567,10 @@ function createTypeChecker(host) { !!getAwaitedTypeOfPromise(type) || !allowAsyncIterables && isForOfStatement(errorNode.parent) && errorNode.parent.expression === errorNode && getGlobalAsyncIterableType( /*reportErrors*/ false - ) !== emptyGenericType && isTypeAssignableTo(type, getGlobalAsyncIterableType( + ) !== emptyGenericType && isTypeAssignableTo(type, createTypeFromGenericGlobalType(getGlobalAsyncIterableType( /*reportErrors*/ false - )) + ), [anyType, anyType, anyType])) ); return errorAndMaybeSuggestAwait(errorNode, suggestAwait, message, typeToString(type)); } @@ -181282,26 +181600,13 @@ function createTypeChecker(host) { return getCachedIterationTypes(type, resolver.iteratorCacheKey); } function getIterationTypesOfIteratorFast(type, resolver) { - const globalType = resolver.getGlobalIterableIteratorType( + if (isReferenceToType2(type, resolver.getGlobalIterableIteratorType( /*reportErrors*/ false - ); - if (isReferenceToType2(type, globalType)) { - const [yieldType] = getTypeArguments(type); - const globalIterationTypes = getIterationTypesOfIteratorCached(globalType, resolver) || getIterationTypesOfIteratorSlow( - globalType, - resolver, - /*errorNode*/ - void 0, - /*errorOutputContainer*/ - void 0, - /*noCache*/ - false - ); - const { returnType, nextType } = globalIterationTypes === noIterationTypes ? defaultIterationTypes : globalIterationTypes; - return setCachedIterationTypes(type, resolver.iteratorCacheKey, createIterationTypes(yieldType, returnType, nextType)); - } - if (isReferenceToType2(type, resolver.getGlobalIteratorType( + )) || isReferenceToType2(type, resolver.getGlobalIteratorType( + /*reportErrors*/ + false + )) || isReferenceToType2(type, resolver.getGlobalIteratorObjectType( /*reportErrors*/ false )) || isReferenceToType2(type, resolver.getGlobalGeneratorType( @@ -181311,6 +181616,12 @@ function createTypeChecker(host) { const [yieldType, returnType, nextType] = getTypeArguments(type); return setCachedIterationTypes(type, resolver.iteratorCacheKey, createIterationTypes(yieldType, returnType, nextType)); } + if (isReferenceToSomeType(type, resolver.getGlobalBuiltinIteratorTypes())) { + const [yieldType] = getTypeArguments(type); + const returnType = getBuiltinIteratorReturnType(); + const nextType = unknownType; + return setCachedIterationTypes(type, resolver.iteratorCacheKey, createIterationTypes(yieldType, returnType, nextType)); + } } function isIteratorResult(type, kind) { const doneType = getTypeOfPropertyOfType(type, "done") || falseType; @@ -181378,7 +181689,7 @@ function createTypeChecker(host) { } const methodType = method && !(methodName === "next" && method.flags & 16777216 /* Optional */) ? methodName === "next" ? getTypeOfSymbol(method) : getTypeWithFacts(getTypeOfSymbol(method), 2097152 /* NEUndefinedOrNull */) : void 0; if (isTypeAny(methodType)) { - return methodName === "next" ? anyIterationTypes : anyIterationTypesExceptNext; + return anyIterationTypes; } const methodSignatures = methodType ? getSignaturesOfType(methodType, 0 /* Call */) : emptyArray; if (methodSignatures.length === 0) { @@ -181747,7 +182058,7 @@ function createTypeChecker(host) { } } function checkClassNameCollisionWithObject(name) { - if (languageVersion >= 1 /* ES5 */ && name.escapedText === "Object" && (moduleKind < 5 /* ES2015 */ || getSourceFileOfNode(name).impliedNodeFormat === 1 /* CommonJS */)) { + if (languageVersion >= 1 /* ES5 */ && name.escapedText === "Object" && host.getEmitModuleFormatOfFile(getSourceFileOfNode(name)) < 5 /* ES2015 */) { error2(name, Diagnostics.Class_name_cannot_be_Object_when_targeting_ES5_with_module_0, ModuleKind[moduleKind]); } } @@ -182126,23 +182437,22 @@ function createTypeChecker(host) { hasAbstractModifier(member), isStatic(member), memberIsParameterProperty, - symbolName(declaredProp), + declaredProp, reportErrors2 ? member : void 0 ); } - function checkMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, memberHasOverrideModifier, memberHasAbstractModifier, memberIsStatic, memberIsParameterProperty, memberName, errorNode) { + function checkMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, memberHasOverrideModifier, memberHasAbstractModifier, memberIsStatic, memberIsParameterProperty, member, errorNode) { const isJs = isInJSFile(node); const nodeInAmbientContext = !!(node.flags & 33554432 /* Ambient */); if (baseWithThis && (memberHasOverrideModifier || compilerOptions.noImplicitOverride)) { - const memberEscapedName = escapeLeadingUnderscores(memberName); const thisType = memberIsStatic ? staticType : typeWithThis; const baseType = memberIsStatic ? baseStaticType : baseWithThis; - const prop = getPropertyOfType(thisType, memberEscapedName); - const baseProp = getPropertyOfType(baseType, memberEscapedName); + const prop = getPropertyOfType(thisType, member.escapedName); + const baseProp = getPropertyOfType(baseType, member.escapedName); const baseClassName = typeToString(baseWithThis); if (prop && !baseProp && memberHasOverrideModifier) { if (errorNode) { - const suggestion = getSuggestedSymbolForNonexistentClassMember(memberName, baseType); + const suggestion = getSuggestedSymbolForNonexistentClassMember(symbolName(member), baseType); suggestion ? error2( errorNode, isJs ? Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1 : Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1, @@ -182259,7 +182569,7 @@ function createTypeChecker(host) { isStatic(member), /*memberIsParameterProperty*/ false, - symbolName(memberSymbol) + memberSymbol ); } function getTargetSymbol(s) { @@ -182517,7 +182827,9 @@ function createTypeChecker(host) { checkExportsOnMergedDeclarations(node); checkTypeParameters(node.typeParameters); if (node.type.kind === 141 /* IntrinsicKeyword */) { - if (!intrinsicTypeKinds.has(node.name.escapedText) || length(node.typeParameters) !== 1) { + const typeParameterCount = length(node.typeParameters); + const valid = typeParameterCount === 0 ? node.name.escapedText === "BuiltinIteratorReturn" : typeParameterCount === 1 && intrinsicTypeKinds.has(node.name.escapedText); + if (!valid) { error2(node.type, Diagnostics.The_intrinsic_keyword_can_only_be_used_to_declare_compiler_provided_intrinsic_types); } } else { @@ -182807,6 +183119,14 @@ function createTypeChecker(host) { } if (isIdentifier(node.name)) { checkCollisionsForDeclarationName(node, node.name); + if (!(node.flags & (32 /* Namespace */ | 2048 /* GlobalAugmentation */))) { + const sourceFile = getSourceFileOfNode(node); + const pos = getNonModifierTokenPosOfNode(node); + const span = getSpanOfTokenAtPosition(sourceFile, pos); + suggestionDiagnostics.add( + createFileDiagnostic(sourceFile, span.start, span.length, Diagnostics.A_namespace_declaration_should_not_be_declared_using_the_module_keyword_Please_use_the_namespace_keyword_instead) + ); + } } checkExportsOnMergedDeclarations(node); const symbol = getSymbolOfDeclaration(node); @@ -182828,7 +183148,7 @@ function createTypeChecker(host) { getNodeLinks(node).flags |= 2048 /* LexicalModuleMergesWithClass */; } } - if (compilerOptions.verbatimModuleSyntax && node.parent.kind === 307 /* SourceFile */ && (moduleKind === 1 /* CommonJS */ || node.parent.impliedNodeFormat === 1 /* CommonJS */)) { + if (compilerOptions.verbatimModuleSyntax && node.parent.kind === 307 /* SourceFile */ && host.getEmitModuleFormatOfFile(node.parent) === 1 /* CommonJS */) { const exportModifier = (_b = node.modifiers) == null ? void 0 : _b.find((m) => m.kind === 95 /* ExportKeyword */); if (exportModifier) { error2(exportModifier, Diagnostics.A_top_level_export_modifier_cannot_be_used_on_value_declarations_in_a_CommonJS_module_when_verbatimModuleSyntax_is_enabled); @@ -182871,6 +183191,7 @@ function createTypeChecker(host) { grammarErrorOnFirstToken(node, Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations); break; case 271 /* ImportEqualsDeclaration */: + if (isInternalModuleImportEqualsDeclaration(node)) break; case 272 /* ImportDeclaration */: grammarErrorOnFirstToken(node, Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module); break; @@ -182950,6 +183271,16 @@ function createTypeChecker(host) { } return true; } + function checkModuleExportName(name, allowStringLiteral = true) { + if (name === void 0 || name.kind !== 11 /* StringLiteral */) { + return; + } + if (!allowStringLiteral) { + grammarErrorOnNode(name, Diagnostics.Identifier_expected); + } else if (moduleKind === 5 /* ES2015 */ || moduleKind === 6 /* ES2020 */) { + grammarErrorOnNode(name, Diagnostics.String_literal_import_and_export_names_are_not_supported_when_the_module_flag_is_set_to_es2015_or_es2020); + } + } function checkAliasSymbol(node) { var _a, _b, _c, _d; let symbol = getSymbolOfDeclaration(node); @@ -182961,7 +183292,7 @@ function createTypeChecker(host) { Debug.assert(node.kind !== 280 /* NamespaceExport */); if (node.kind === 281 /* ExportSpecifier */) { const diag2 = error2(errorNode, Diagnostics.Types_cannot_appear_in_export_declarations_in_JavaScript_files); - const alreadyExportedSymbol = (_b = (_a = getSourceFileOfNode(node).symbol) == null ? void 0 : _a.exports) == null ? void 0 : _b.get((node.propertyName || node.name).escapedText); + const alreadyExportedSymbol = (_b = (_a = getSourceFileOfNode(node).symbol) == null ? void 0 : _a.exports) == null ? void 0 : _b.get(moduleExportNameTextEscaped(node.propertyName || node.name)); if (alreadyExportedSymbol === target) { const exportingDeclaration = (_c = alreadyExportedSymbol.declarations) == null ? void 0 : _c.find(isJSDocNode); if (exportingDeclaration) { @@ -183016,7 +183347,7 @@ function createTypeChecker(host) { if (compilerOptions.verbatimModuleSyntax) { Debug.assertIsDefined(node.name, "An ImportClause with a symbol should have a name"); const message = compilerOptions.verbatimModuleSyntax && isInternalModuleImportEqualsDeclaration(node) ? Diagnostics.An_import_alias_cannot_resolve_to_a_type_or_type_only_declaration_when_verbatimModuleSyntax_is_enabled : isType ? Diagnostics._0_is_a_type_and_must_be_imported_using_a_type_only_import_when_verbatimModuleSyntax_is_enabled : Diagnostics._0_resolves_to_a_type_only_declaration_and_must_be_imported_using_a_type_only_import_when_verbatimModuleSyntax_is_enabled; - const name = idText(node.kind === 276 /* ImportSpecifier */ ? node.propertyName || node.name : node.name); + const name = moduleExportNameTextUnescaped(node.kind === 276 /* ImportSpecifier */ ? node.propertyName || node.name : node.name); addTypeOnlyDeclarationRelatedInfo( error2(node, message, name), isType ? void 0 : typeOnlyAlias, @@ -183030,7 +183361,7 @@ function createTypeChecker(host) { } case 281 /* ExportSpecifier */: { if (compilerOptions.verbatimModuleSyntax || getSourceFileOfNode(typeOnlyAlias) !== getSourceFileOfNode(node)) { - const name = idText(node.propertyName || node.name); + const name = moduleExportNameTextUnescaped(node.propertyName || node.name); const diagnostic = isType ? error2(node, Diagnostics.Re_exporting_a_type_when_0_is_enabled_requires_using_export_type, isolatedModulesLikeFlagName) : error2(node, Diagnostics._0_resolves_to_a_type_only_declaration_and_must_be_re_exported_using_a_type_only_re_export_when_1_is_enabled, name, isolatedModulesLikeFlagName); addTypeOnlyDeclarationRelatedInfo(diagnostic, isType ? void 0 : typeOnlyAlias, name); break; @@ -183038,8 +183369,17 @@ function createTypeChecker(host) { } } } - if (compilerOptions.verbatimModuleSyntax && node.kind !== 271 /* ImportEqualsDeclaration */ && !isInJSFile(node) && (moduleKind === 1 /* CommonJS */ || getSourceFileOfNode(node).impliedNodeFormat === 1 /* CommonJS */)) { + if (compilerOptions.verbatimModuleSyntax && node.kind !== 271 /* ImportEqualsDeclaration */ && !isInJSFile(node) && host.getEmitModuleFormatOfFile(getSourceFileOfNode(node)) === 1 /* CommonJS */) { error2(node, Diagnostics.ESM_syntax_is_not_allowed_in_a_CommonJS_module_when_verbatimModuleSyntax_is_enabled); + } else if (moduleKind === 200 /* Preserve */ && node.kind !== 271 /* ImportEqualsDeclaration */ && node.kind !== 260 /* VariableDeclaration */ && host.getEmitModuleFormatOfFile(getSourceFileOfNode(node)) === 1 /* CommonJS */) { + error2(node, Diagnostics.ESM_syntax_is_not_allowed_in_a_CommonJS_module_when_module_is_set_to_preserve); + } + if (compilerOptions.verbatimModuleSyntax && !isTypeOnlyImportOrExportDeclaration(node) && !(node.flags & 33554432 /* Ambient */) && targetFlags & 128 /* ConstEnum */) { + const constEnumDeclaration = target.valueDeclaration; + const redirect = host.getRedirectReferenceForResolutionFromSourceOfProject(getSourceFileOfNode(constEnumDeclaration).resolvedPath); + if (constEnumDeclaration.flags & 33554432 /* Ambient */ && (!redirect || !shouldPreserveConstEnums(redirect.commandLine.options))) { + error2(node, Diagnostics.Cannot_access_ambient_const_enums_when_0_is_enabled, isolatedModulesLikeFlagName); + } } } if (isImportSpecifier(node)) { @@ -183078,8 +183418,11 @@ function createTypeChecker(host) { function checkImportBinding(node) { checkCollisionsForDeclarationName(node, node.name); checkAliasSymbol(node); - if (node.kind === 276 /* ImportSpecifier */ && idText(node.propertyName || node.name) === "default" && getESModuleInterop(compilerOptions) && moduleKind !== 4 /* System */ && (moduleKind < 5 /* ES2015 */ || getSourceFileOfNode(node).impliedNodeFormat === 1 /* CommonJS */)) { - checkExternalEmitHelpers(node, 131072 /* ImportDefault */); + if (node.kind === 276 /* ImportSpecifier */) { + checkModuleExportName(node.propertyName); + if (moduleExportNameIsDefault(node.propertyName || node.name) && getESModuleInterop(compilerOptions) && host.getEmitModuleFormatOfFile(getSourceFileOfNode(node)) < 4 /* System */) { + checkExternalEmitHelpers(node, 131072 /* ImportDefault */); + } } } function checkImportAttributes(declaration) { @@ -183099,7 +183442,7 @@ function createTypeChecker(host) { if (validForTypeAttributes && override) { return; } - const mode = moduleKind === 199 /* NodeNext */ && declaration.moduleSpecifier && getUsageModeForExpression(declaration.moduleSpecifier); + const mode = moduleKind === 199 /* NodeNext */ && declaration.moduleSpecifier && getEmitSyntaxForModuleSpecifierExpression(declaration.moduleSpecifier); if (mode !== 99 /* ESNext */ && moduleKind !== 99 /* ESNext */ && moduleKind !== 200 /* Preserve */) { const message = isImportAttributes2 ? moduleKind === 199 /* NodeNext */ ? Diagnostics.Import_attributes_are_not_allowed_on_statements_that_compile_to_CommonJS_require_calls : Diagnostics.Import_attributes_are_only_supported_when_the_module_option_is_set_to_esnext_nodenext_or_preserve : moduleKind === 199 /* NodeNext */ ? Diagnostics.Import_assertions_are_not_allowed_on_statements_that_compile_to_CommonJS_require_calls : Diagnostics.Import_assertions_are_only_supported_when_the_module_option_is_set_to_esnext_nodenext_or_preserve; return grammarErrorOnNode(node, message); @@ -183132,7 +183475,7 @@ function createTypeChecker(host) { if (importClause.namedBindings) { if (importClause.namedBindings.kind === 274 /* NamespaceImport */) { checkImportBinding(importClause.namedBindings); - if (moduleKind !== 4 /* System */ && (moduleKind < 5 /* ES2015 */ || getSourceFileOfNode(node).impliedNodeFormat === 1 /* CommonJS */) && getESModuleInterop(compilerOptions)) { + if (host.getEmitModuleFormatOfFile(getSourceFileOfNode(node)) < 4 /* System */ && getESModuleInterop(compilerOptions)) { checkExternalEmitHelpers(node, 65536 /* ImportStar */); } } else { @@ -183142,6 +183485,8 @@ function createTypeChecker(host) { } } } + } else if (noUncheckedSideEffectImports && !importClause) { + void resolveExternalModuleName(node, node.moduleSpecifier); } } checkImportAttributes(node); @@ -183172,7 +183517,7 @@ function createTypeChecker(host) { grammarErrorOnNode(node, Diagnostics.An_import_alias_cannot_use_import_type); } } else { - if (moduleKind >= 5 /* ES2015 */ && moduleKind !== 200 /* Preserve */ && getSourceFileOfNode(node).impliedNodeFormat === void 0 && !node.isTypeOnly && !(node.flags & 33554432 /* Ambient */)) { + if (5 /* ES2015 */ <= moduleKind && moduleKind <= 99 /* ESNext */ && !node.isTypeOnly && !(node.flags & 33554432 /* Ambient */)) { grammarErrorOnNode(node, 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); } } @@ -183200,8 +183545,9 @@ function createTypeChecker(host) { error2(node.moduleSpecifier, Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol)); } else if (node.exportClause) { checkAliasSymbol(node.exportClause); + checkModuleExportName(node.exportClause.name); } - if (moduleKind !== 4 /* System */ && (moduleKind < 5 /* ES2015 */ || getSourceFileOfNode(node).impliedNodeFormat === 1 /* CommonJS */)) { + if (host.getEmitModuleFormatOfFile(getSourceFileOfNode(node)) < 4 /* System */) { if (node.exportClause) { if (getESModuleInterop(compilerOptions)) { checkExternalEmitHelpers(node, 65536 /* ImportStar */); @@ -183230,6 +183576,9 @@ function createTypeChecker(host) { } function checkExportSpecifier(node) { checkAliasSymbol(node); + const hasModuleSpecifier = node.parent.parent.moduleSpecifier !== void 0; + checkModuleExportName(node.propertyName, hasModuleSpecifier); + checkModuleExportName(node.name); if (getEmitDeclarations(compilerOptions)) { collectLinkedAliases( node.propertyName || node.name, @@ -183237,8 +183586,11 @@ function createTypeChecker(host) { true ); } - if (!node.parent.parent.moduleSpecifier) { + if (!hasModuleSpecifier) { const exportedName = node.propertyName || node.name; + if (exportedName.kind === 11 /* StringLiteral */) { + return; + } const symbol = resolveName( exportedName, exportedName.escapedText, @@ -183254,7 +183606,7 @@ function createTypeChecker(host) { markLinkedReferences(node, 7 /* ExportSpecifier */); } } else { - if (getESModuleInterop(compilerOptions) && moduleKind !== 4 /* System */ && (moduleKind < 5 /* ES2015 */ || getSourceFileOfNode(node).impliedNodeFormat === 1 /* CommonJS */) && idText(node.propertyName || node.name) === "default") { + if (getESModuleInterop(compilerOptions) && host.getEmitModuleFormatOfFile(getSourceFileOfNode(node)) < 4 /* System */ && moduleExportNameIsDefault(node.propertyName || node.name)) { checkExternalEmitHelpers(node, 131072 /* ImportDefault */); } } @@ -183280,7 +183632,7 @@ function createTypeChecker(host) { if (typeAnnotationNode) { checkTypeAssignableTo(checkExpressionCached(node.expression), getTypeFromTypeNode(typeAnnotationNode), node.expression); } - const isIllegalExportDefaultInCJS = !node.isExportEquals && !(node.flags & 33554432 /* Ambient */) && compilerOptions.verbatimModuleSyntax && (moduleKind === 1 /* CommonJS */ || getSourceFileOfNode(node).impliedNodeFormat === 1 /* CommonJS */); + const isIllegalExportDefaultInCJS = !node.isExportEquals && !(node.flags & 33554432 /* Ambient */) && compilerOptions.verbatimModuleSyntax && host.getEmitModuleFormatOfFile(getSourceFileOfNode(node)) === 1 /* CommonJS */; if (node.expression.kind === 80 /* Identifier */) { const id = node.expression; const sym = getExportSymbolOfValueSymbolIfExported(resolveEntityName( @@ -183360,7 +183712,7 @@ function createTypeChecker(host) { grammarErrorOnNode(node.expression, Diagnostics.The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context); } if (node.isExportEquals) { - if (moduleKind >= 5 /* ES2015 */ && moduleKind !== 200 /* Preserve */ && (node.flags & 33554432 /* Ambient */ && getSourceFileOfNode(node).impliedNodeFormat === 99 /* ESNext */ || !(node.flags & 33554432 /* Ambient */) && getSourceFileOfNode(node).impliedNodeFormat !== 1 /* CommonJS */)) { + if (moduleKind >= 5 /* ES2015 */ && moduleKind !== 200 /* Preserve */ && (node.flags & 33554432 /* Ambient */ && host.getImpliedNodeFormatForEmit(getSourceFileOfNode(node)) === 99 /* ESNext */ || !(node.flags & 33554432 /* Ambient */) && host.getImpliedNodeFormatForEmit(getSourceFileOfNode(node)) !== 1 /* CommonJS */)) { grammarErrorOnNode(node, Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead); } else if (moduleKind === 4 /* System */ && !(node.flags & 33554432 /* Ambient */)) { grammarErrorOnNode(node, Diagnostics.Export_assignment_is_not_supported_when_module_flag_is_system); @@ -183421,6 +183773,9 @@ function createTypeChecker(host) { } } function checkSourceElementWorker(node) { + if (getNodeCheckFlags(node) & 8388608 /* PartiallyTypeChecked */) { + return; + } if (canHaveJSDoc(node)) { forEach(node.jsDoc, ({ comment, tags }) => { checkJSDocCommentWorker(comment); @@ -183764,19 +184119,21 @@ function createTypeChecker(host) { currentNode = saveCurrentNode; (_b = tracing) == null ? void 0 : _b.pop(); } - function checkSourceFile(node) { + function checkSourceFile(node, nodesToCheck) { var _a, _b; (_a = tracing) == null ? void 0 : _a.push( tracing.Phase.Check, - "checkSourceFile", + nodesToCheck ? "checkSourceFileNodes" : "checkSourceFile", { path: node.path }, /*separateBeginAndEnd*/ true ); - mark("beforeCheck"); - checkSourceFileWorker(node); - mark("afterCheck"); - measure("Check", "beforeCheck", "afterCheck"); + const beforeMark = nodesToCheck ? "beforeCheckNodes" : "beforeCheck"; + const afterMark = nodesToCheck ? "afterCheckNodes" : "afterCheck"; + mark(beforeMark); + nodesToCheck ? checkSourceFileNodesWorker(node, nodesToCheck) : checkSourceFileWorker(node); + mark(afterMark); + measure("Check", beforeMark, afterMark); (_b = tracing) == null ? void 0 : _b.pop(); } function unusedIsError(kind, isAmbient) { @@ -183807,6 +184164,13 @@ function createTypeChecker(host) { clear(potentialWeakMapSetCollisions); clear(potentialReflectCollisions); clear(potentialUnusedRenamedBindingElementsInTypes); + if (links.flags & 8388608 /* PartiallyTypeChecked */) { + potentialThisCollisions = links.potentialThisCollisions; + potentialNewTargetCollisions = links.potentialNewTargetCollisions; + potentialWeakMapSetCollisions = links.potentialWeakMapSetCollisions; + potentialReflectCollisions = links.potentialReflectCollisions; + potentialUnusedRenamedBindingElementsInTypes = links.potentialUnusedRenamedBindingElementsInTypes; + } forEach(node.statements, checkSourceElement); checkSourceElement(node.endOfFileToken); checkDeferredNodes(node); @@ -183847,10 +184211,38 @@ function createTypeChecker(host) { links.flags |= 1 /* TypeChecked */; } } - function getDiagnostics2(sourceFile, ct) { + function checkSourceFileNodesWorker(file, nodes) { + const links = getNodeLinks(file); + if (!(links.flags & 1 /* TypeChecked */)) { + if (skipTypeChecking(file, compilerOptions, host)) { + return; + } + checkGrammarSourceFile(file); + clear(potentialThisCollisions); + clear(potentialNewTargetCollisions); + clear(potentialWeakMapSetCollisions); + clear(potentialReflectCollisions); + clear(potentialUnusedRenamedBindingElementsInTypes); + forEach(nodes, checkSourceElement); + checkDeferredNodes(file); + (links.potentialThisCollisions || (links.potentialThisCollisions = [])).push(...potentialThisCollisions); + (links.potentialNewTargetCollisions || (links.potentialNewTargetCollisions = [])).push(...potentialNewTargetCollisions); + (links.potentialWeakMapSetCollisions || (links.potentialWeakMapSetCollisions = [])).push(...potentialWeakMapSetCollisions); + (links.potentialReflectCollisions || (links.potentialReflectCollisions = [])).push(...potentialReflectCollisions); + (links.potentialUnusedRenamedBindingElementsInTypes || (links.potentialUnusedRenamedBindingElementsInTypes = [])).push( + ...potentialUnusedRenamedBindingElementsInTypes + ); + links.flags |= 8388608 /* PartiallyTypeChecked */; + for (const node of nodes) { + const nodeLinks2 = getNodeLinks(node); + nodeLinks2.flags |= 8388608 /* PartiallyTypeChecked */; + } + } + } + function getDiagnostics2(sourceFile, ct, nodesToCheck) { try { cancellationToken = ct; - return getDiagnosticsWorker(sourceFile); + return getDiagnosticsWorker(sourceFile, nodesToCheck); } finally { cancellationToken = void 0; } @@ -183861,20 +184253,23 @@ function createTypeChecker(host) { } deferredDiagnosticsCallbacks = []; } - function checkSourceFileWithEagerDiagnostics(sourceFile) { + function checkSourceFileWithEagerDiagnostics(sourceFile, nodesToCheck) { ensurePendingDiagnosticWorkComplete(); const oldAddLazyDiagnostics = addLazyDiagnostic; addLazyDiagnostic = (cb) => cb(); - checkSourceFile(sourceFile); + checkSourceFile(sourceFile, nodesToCheck); addLazyDiagnostic = oldAddLazyDiagnostics; } - function getDiagnosticsWorker(sourceFile) { + function getDiagnosticsWorker(sourceFile, nodesToCheck) { if (sourceFile) { ensurePendingDiagnosticWorkComplete(); const previousGlobalDiagnostics = diagnostics.getGlobalDiagnostics(); const previousGlobalDiagnosticsSize = previousGlobalDiagnostics.length; - checkSourceFileWithEagerDiagnostics(sourceFile); + checkSourceFileWithEagerDiagnostics(sourceFile, nodesToCheck); const semanticDiagnostics = diagnostics.getDiagnostics(sourceFile.fileName); + if (nodesToCheck) { + return semanticDiagnostics; + } const currentGlobalDiagnostics = diagnostics.getGlobalDiagnostics(); if (currentGlobalDiagnostics !== previousGlobalDiagnostics) { const deferredGlobalDiagnostics = relativeComplement(previousGlobalDiagnostics, currentGlobalDiagnostics, compareDiagnostics); @@ -183884,7 +184279,7 @@ function createTypeChecker(host) { } return semanticDiagnostics; } - forEach(host.getSourceFiles(), checkSourceFileWithEagerDiagnostics); + forEach(host.getSourceFiles(), (file) => checkSourceFileWithEagerDiagnostics(file)); return diagnostics.getDiagnostics(); } function getGlobalDiagnostics() { @@ -184409,7 +184804,11 @@ function createTypeChecker(host) { } function getExportSpecifierLocalTargetSymbol(node) { if (isExportSpecifier(node)) { - return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node) : resolveEntityName(node.propertyName || node.name, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); + const name = node.propertyName || node.name; + return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node) : name.kind === 11 /* StringLiteral */ ? void 0 : ( + // Skip for invalid syntax like this: export { "x" } + resolveEntityName(name, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */) + ); } else { return resolveEntityName(node, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */); } @@ -184755,7 +185154,7 @@ function createTypeChecker(host) { } function isReferencedAliasDeclaration(node, checkChildren) { Debug.assert(canCollectSymbolAliasAccessabilityData); - if (isAliasSymbolDeclaration2(node)) { + if (isAliasSymbolDeclaration(node)) { const symbol = getSymbolOfDeclaration(node); const links = symbol && getSymbolLinks(symbol); if (links == null ? void 0 : links.referenced) { @@ -184791,11 +185190,17 @@ function createTypeChecker(host) { const type = getTypeFromTypeNode(typeNode); return containsUndefinedType(type); } - function requiresAddingImplicitUndefined(parameter) { - return (isRequiredInitializedParameter(parameter) || isOptionalUninitializedParameterProperty(parameter)) && !declaredParameterTypeContainsUndefined(parameter); + function requiresAddingImplicitUndefined(parameter, enclosingDeclaration) { + return (isRequiredInitializedParameter(parameter, enclosingDeclaration) || isOptionalUninitializedParameterProperty(parameter)) && !declaredParameterTypeContainsUndefined(parameter); } - function isRequiredInitializedParameter(parameter) { - return !!strictNullChecks && !isOptionalParameter(parameter) && !isJSDocParameterTag(parameter) && !!parameter.initializer && !hasSyntacticModifier(parameter, 31 /* ParameterPropertyModifier */); + function isRequiredInitializedParameter(parameter, enclosingDeclaration) { + if (!strictNullChecks || isOptionalParameter(parameter) || isJSDocParameterTag(parameter) || !parameter.initializer) { + return false; + } + if (hasSyntacticModifier(parameter, 31 /* ParameterPropertyModifier */)) { + return !!enclosingDeclaration && isFunctionLikeDeclaration(enclosingDeclaration); + } + return true; } function isOptionalUninitializedParameterProperty(parameter) { return strictNullChecks && isOptionalParameter(parameter) && (isJSDocParameterTag(parameter) || !parameter.initializer) && hasSyntacticModifier(parameter, 31 /* ParameterPropertyModifier */); @@ -184842,7 +185247,7 @@ function createTypeChecker(host) { return !!(getNodeCheckFlags(node) & flag); } function calculateNodeCheckFlagWorker(node, flag) { - if (!compilerOptions.noCheck && canIncludeBindAndCheckDiagnsotics(getSourceFileOfNode(node), compilerOptions)) { + if (!compilerOptions.noCheck && canIncludeBindAndCheckDiagnostics(getSourceFileOfNode(node), compilerOptions)) { return; } const links = getNodeLinks(node); @@ -184909,11 +185314,14 @@ function createTypeChecker(host) { } function checkSingleIdentifier(node2) { const nodeLinks2 = getNodeLinks(node2); - nodeLinks2.calculatedFlags |= 536870912 /* ConstructorReference */ | 16384 /* CapturedBlockScopedBinding */ | 32768 /* BlockScopedBindingInLoop */; - if (isIdentifier(node2) && isExpressionNodeOrShorthandPropertyAssignmentName(node2) && !(isPropertyAccessExpression(node2.parent) && node2.parent.name === node2)) { - const s = getResolvedSymbol(node2); - if (s && s !== unknownSymbol) { - checkIdentifierCalculateNodeCheckFlags(node2, s); + nodeLinks2.calculatedFlags |= 536870912 /* ConstructorReference */; + if (isIdentifier(node2)) { + nodeLinks2.calculatedFlags |= 32768 /* BlockScopedBindingInLoop */ | 16384 /* CapturedBlockScopedBinding */; + if (isExpressionNodeOrShorthandPropertyAssignmentName(node2) && !(isPropertyAccessExpression(node2.parent) && node2.parent.name === node2)) { + const s = getResolvedSymbol(node2); + if (s && s !== unknownSymbol) { + checkIdentifierCalculateNodeCheckFlags(node2, s); + } } } } @@ -185066,14 +185474,14 @@ function createTypeChecker(host) { return 11 /* ObjectType */; } } - function createTypeOfDeclaration(declarationIn, enclosingDeclaration, flags, tracker) { + function createTypeOfDeclaration(declarationIn, enclosingDeclaration, flags, internalFlags, tracker) { const declaration = getParseTreeNode(declarationIn, isVariableLikeOrAccessor); if (!declaration) { return factory.createToken(133 /* AnyKeyword */); } const symbol = getSymbolOfDeclaration(declaration); const type = symbol && !(symbol.flags & (2048 /* TypeLiteral */ | 131072 /* Signature */)) ? getWidenedLiteralType(getTypeOfSymbol(symbol)) : errorType; - return nodeBuilder.serializeTypeForDeclaration(declaration, type, symbol, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker); + return nodeBuilder.serializeTypeForDeclaration(declaration, type, symbol, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, internalFlags, tracker); } function isDeclarationWithPossibleInnerTypeNodeReuse(declaration) { return isFunctionLike(declaration) || isExportAssignment(declaration) || isVariableLike(declaration); @@ -185116,14 +185524,14 @@ function createTypeChecker(host) { } return candidateExpr; } - function createReturnTypeOfSignatureDeclaration(signatureDeclarationIn, enclosingDeclaration, flags, tracker) { + function createReturnTypeOfSignatureDeclaration(signatureDeclarationIn, enclosingDeclaration, flags, internalFlags, tracker) { const signatureDeclaration = getParseTreeNode(signatureDeclarationIn, isFunctionLike); if (!signatureDeclaration) { return factory.createToken(133 /* AnyKeyword */); } - return nodeBuilder.serializeReturnTypeForSignature(getSignatureFromDeclaration(signatureDeclaration), enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker); + return nodeBuilder.serializeReturnTypeForSignature(getSignatureFromDeclaration(signatureDeclaration), enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, internalFlags, tracker); } - function createTypeOfExpression(exprIn, enclosingDeclaration, flags, tracker) { + function createTypeOfExpression(exprIn, enclosingDeclaration, flags, internalFlags, tracker) { const expr = getParseTreeNode(exprIn, isExpression); if (!expr) { return factory.createToken(133 /* AnyKeyword */); @@ -185136,6 +185544,7 @@ function createTypeChecker(host) { void 0, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, + internalFlags, tracker ); } @@ -185241,6 +185650,8 @@ function createTypeChecker(host) { enclosing, /*flags*/ void 0, + /*internalFlags*/ + void 0, tracker ) : type === trueType ? factory.createTrue() : type === falseType && factory.createFalse(); if (enumResult) return enumResult; @@ -185369,15 +185780,15 @@ function createTypeChecker(host) { const parseDecl = getParseTreeNode(decl); return !!parseNode && !!parseDecl && (isVariableDeclaration(parseDecl) || isBindingElement(parseDecl)) && isBindingCapturedByNode(parseNode, parseDecl); }, - getDeclarationStatementsForSourceFile: (node, flags, tracker) => { + getDeclarationStatementsForSourceFile: (node, flags, internalFlags, tracker) => { const n = getParseTreeNode(node); Debug.assert(n && n.kind === 307 /* SourceFile */, "Non-sourcefile node passed into getDeclarationsForSourceFile"); const sym = getSymbolOfDeclaration(node); if (!sym) { - return !node.locals ? [] : nodeBuilder.symbolTableToDeclarationStatements(node.locals, node, flags, tracker); + return !node.locals ? [] : nodeBuilder.symbolTableToDeclarationStatements(node.locals, node, flags, internalFlags, tracker); } resolveExternalModuleSymbol(sym); - return !sym.exports ? [] : nodeBuilder.symbolTableToDeclarationStatements(sym.exports, node, flags, tracker); + return !sym.exports ? [] : nodeBuilder.symbolTableToDeclarationStatements(sym.exports, node, flags, internalFlags, tracker); }, isImportRequiredByAugmentation, isDefinitelyReferenceToGlobalSymbolObject @@ -185858,7 +186269,7 @@ function createTypeChecker(host) { break; case 95 /* ExportKeyword */: if (compilerOptions.verbatimModuleSyntax && !(node.flags & 33554432 /* Ambient */) && node.kind !== 265 /* TypeAliasDeclaration */ && node.kind !== 264 /* InterfaceDeclaration */ && // ModuleDeclaration needs to be checked that it is uninstantiated later - node.kind !== 267 /* ModuleDeclaration */ && node.parent.kind === 307 /* SourceFile */ && (moduleKind === 1 /* CommonJS */ || getSourceFileOfNode(node).impliedNodeFormat === 1 /* CommonJS */)) { + node.kind !== 267 /* ModuleDeclaration */ && node.parent.kind === 307 /* SourceFile */ && host.getEmitModuleFormatOfFile(getSourceFileOfNode(node)) === 1 /* CommonJS */) { return grammarErrorOnNode(modifier, Diagnostics.A_top_level_export_modifier_cannot_be_used_on_value_declarations_in_a_CommonJS_module_when_verbatimModuleSyntax_is_enabled); } if (flags & 32 /* Export */) { @@ -186365,6 +186776,13 @@ function createTypeChecker(host) { if (name.kind === 9 /* NumericLiteral */) { checkGrammarNumericLiteral(name); } + if (name.kind === 10 /* BigIntLiteral */) { + addErrorOrSuggestion( + /*isError*/ + true, + createDiagnosticForNode(name, Diagnostics.A_bigint_literal_cannot_be_used_as_a_property_name) + ); + } currentKind = 4 /* PropertyAssignment */; break; case 174 /* MethodDeclaration */: @@ -186461,6 +186879,7 @@ function createTypeChecker(host) { } case 7 /* ES2022 */: case 99 /* ESNext */: + case 200 /* Preserve */: case 4 /* System */: if (languageVersion >= 4 /* ES2017 */) { break; @@ -186767,7 +187186,7 @@ function createTypeChecker(host) { const message = node.initializer ? Diagnostics.Declarations_with_initializers_cannot_also_have_definite_assignment_assertions : !node.type ? Diagnostics.Declarations_with_definite_assignment_assertions_must_also_have_type_annotations : Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context; return grammarErrorOnNode(node.exclamationToken, message); } - if ((moduleKind < 5 /* ES2015 */ || getSourceFileOfNode(node).impliedNodeFormat === 1 /* CommonJS */) && moduleKind !== 4 /* System */ && !(node.parent.parent.flags & 33554432 /* Ambient */) && hasSyntacticModifier(node.parent.parent, 32 /* Export */)) { + if (host.getEmitModuleFormatOfFile(getSourceFileOfNode(node)) < 4 /* System */ && !(node.parent.parent.flags & 33554432 /* Ambient */) && hasSyntacticModifier(node.parent.parent, 32 /* Export */)) { checkESModuleMarker(node.name); } return !!blockScopeKind && checkGrammarNameInLetOrConstDeclarations(node.name); @@ -187076,11 +187495,11 @@ function createTypeChecker(host) { return grammarErrorOnNode(node, Diagnostics.This_use_of_import_is_invalid_import_calls_can_be_written_but_they_must_have_parentheses_and_cannot_have_type_arguments); } const nodeArguments = node.arguments; - if (moduleKind !== 99 /* ESNext */ && moduleKind !== 199 /* NodeNext */ && moduleKind !== 100 /* Node16 */) { + if (moduleKind !== 99 /* ESNext */ && moduleKind !== 199 /* NodeNext */ && moduleKind !== 100 /* Node16 */ && moduleKind !== 200 /* Preserve */) { checkGrammarForDisallowedTrailingComma(nodeArguments); if (nodeArguments.length > 1) { const importAttributesArgument = nodeArguments[1]; - return grammarErrorOnNode(importAttributesArgument, Diagnostics.Dynamic_imports_only_support_a_second_argument_when_the_module_option_is_set_to_esnext_node16_or_nodenext); + return grammarErrorOnNode(importAttributesArgument, Diagnostics.Dynamic_imports_only_support_a_second_argument_when_the_module_option_is_set_to_esnext_node16_nodenext_or_preserve); } } if (nodeArguments.length === 0 || nodeArguments.length > 2) { @@ -187219,7 +187638,7 @@ function isDeclarationNameOrImportPropertyName(name) { switch (name.parent.kind) { case 276 /* ImportSpecifier */: case 281 /* ExportSpecifier */: - return isIdentifier(name); + return isIdentifier(name) || name.kind === 11 /* StringLiteral */; default: return isDeclarationName(name); } @@ -187268,7 +187687,9 @@ function createBasicNodeBuilderModuleSpecifierResolutionHost(host) { isSourceOfProjectReferenceRedirect: (fileName) => host.isSourceOfProjectReferenceRedirect(fileName), fileExists: (fileName) => host.fileExists(fileName), getFileIncludeReasons: () => host.getFileIncludeReasons(), - readFile: host.readFile ? (fileName) => host.readFile(fileName) : void 0 + readFile: host.readFile ? (fileName) => host.readFile(fileName) : void 0, + getDefaultResolutionModeForFile: (file) => host.getDefaultResolutionModeForFile(file), + getModeForResolutionAtIndex: (file, index) => host.getModeForResolutionAtIndex(file, index) }; } var SymbolTrackerImpl = class _SymbolTrackerImpl { @@ -188462,7 +188883,7 @@ var visitEachChildTable = { return context.factory.updateImportSpecifier( node, node.isTypeOnly, - nodeVisitor(node.propertyName, visitor, isIdentifier), + nodeVisitor(node.propertyName, visitor, isModuleExportName), Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)) ); }, @@ -188493,8 +188914,8 @@ var visitEachChildTable = { return context.factory.updateExportSpecifier( node, node.isTypeOnly, - nodeVisitor(node.propertyName, visitor, isIdentifier), - Debug.checkDefined(nodeVisitor(node.name, visitor, isIdentifier)) + nodeVisitor(node.propertyName, visitor, isModuleExportName), + Debug.checkDefined(nodeVisitor(node.name, visitor, isModuleExportName)) ); }, // Module references @@ -189210,7 +189631,7 @@ function containsDefaultReference(node) { return some(node.elements, isNamedDefaultReference); } function isNamedDefaultReference(e) { - return e.propertyName !== void 0 ? e.propertyName.escapedText === "default" /* Default */ : e.name.escapedText === "default" /* Default */; + return moduleExportNameIsDefault(e.propertyName || e.name); } function chainBundle(context, transformSourceFile) { return transformSourceFileOrBundle; @@ -189286,9 +189707,10 @@ function collectExternalModuleInfo(context, sourceFile) { hasImportDefault || (hasImportDefault = containsDefaultReference(node.exportClause)); } else { const name = node.exportClause.name; - if (!uniqueExports.get(idText(name))) { + const nameText = moduleExportNameTextUnescaped(name); + if (!uniqueExports.get(nameText)) { multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name); - uniqueExports.set(idText(name), true); + uniqueExports.set(nameText, true); exportedNames = append(exportedNames, name); } hasImportStar = true; @@ -189346,26 +189768,29 @@ function collectExternalModuleInfo(context, sourceFile) { return { externalImports, exportSpecifiers, exportEquals, hasExportStarsToExportValues, exportedBindings, exportedNames, exportedFunctions, externalHelpersImportDeclaration }; function addExportedNamesForExportDeclaration(node) { for (const specifier of cast(node.exportClause, isNamedExports).elements) { - if (!uniqueExports.get(idText(specifier.name))) { + const specifierNameText = moduleExportNameTextUnescaped(specifier.name); + if (!uniqueExports.get(specifierNameText)) { const name = specifier.propertyName || specifier.name; - if (!node.moduleSpecifier) { - exportSpecifiers.add(name, specifier); - } - const decl = resolver.getReferencedImportDeclaration(name) || resolver.getReferencedValueDeclaration(name); - if (decl) { - if (decl.kind === 262 /* FunctionDeclaration */) { - addExportedFunctionDeclaration(decl, specifier.name, specifier.name.escapedText === "default" /* Default */); - continue; + if (name.kind !== 11 /* StringLiteral */) { + if (!node.moduleSpecifier) { + exportSpecifiers.add(name, specifier); + } + const decl = resolver.getReferencedImportDeclaration(name) || resolver.getReferencedValueDeclaration(name); + if (decl) { + if (decl.kind === 262 /* FunctionDeclaration */) { + addExportedFunctionDeclaration(decl, specifier.name, moduleExportNameIsDefault(specifier.name)); + continue; + } + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(decl), specifier.name); } - multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(decl), specifier.name); } - uniqueExports.set(idText(specifier.name), true); + uniqueExports.set(specifierNameText, true); exportedNames = append(exportedNames, specifier.name); } } } function addExportedFunctionDeclaration(node, name, isDefault) { - exportedFunctions.add(node); + exportedFunctions.add(getOriginalNode(node, isFunctionDeclaration)); if (isDefault) { if (!hasExportDefault) { multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name ?? context.factory.getDeclarationName(node)); @@ -189373,9 +189798,10 @@ function collectExternalModuleInfo(context, sourceFile) { } } else { name ?? (name = node.name); - if (!uniqueExports.get(idText(name))) { + const nameText = moduleExportNameTextUnescaped(name); + if (!uniqueExports.get(nameText)) { multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name); - uniqueExports.set(idText(name), true); + uniqueExports.set(nameText, true); } } } @@ -190091,7 +190517,7 @@ function createDestructuringPropertyAccess(flattenContext, value, propertyName) propertyName ); return flattenContext.context.factory.createElementAccessExpression(value, argumentExpression); - } else if (isStringOrNumericLiteralLike(propertyName)) { + } else if (isStringOrNumericLiteralLike(propertyName) || isBigIntLiteral(propertyName)) { const argumentExpression = factory2.cloneNode(propertyName); return flattenContext.context.factory.createElementAccessExpression(value, argumentExpression); } else { @@ -190516,7 +190942,6 @@ function transformTypeScript(context) { let currentNamespaceContainerName; let currentLexicalScope; let currentScopeFirstDeclarationsOfName; - let currentClassHasParameterProperties; let enabledSubstitutions; let applicableSubstitutions; return transformSourceFileOrBundle; @@ -190544,14 +190969,12 @@ function transformTypeScript(context) { function saveStateAndInvoke(node, f) { const savedCurrentScope = currentLexicalScope; const savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName; - const savedCurrentClassHasParameterProperties = currentClassHasParameterProperties; onBeforeVisitNode(node); const visited = f(node); if (currentLexicalScope !== savedCurrentScope) { currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; } currentLexicalScope = savedCurrentScope; - currentClassHasParameterProperties = savedCurrentClassHasParameterProperties; return visited; } function onBeforeVisitNode(node) { @@ -191184,7 +191607,7 @@ function transformTypeScript(context) { } function visitPropertyNameOfClassElement(member) { const name = member.name; - if (isComputedPropertyName(name) && (!hasStaticModifier(member) && currentClassHasParameterProperties || hasDecorators(member) && legacyDecorators)) { + if (legacyDecorators && isComputedPropertyName(name) && hasDecorators(member)) { const expression = visitNode(name.expression, visitor, isExpression); Debug.assert(expression); const innerExpression = skipPartiallyEmittedExpressions(expression); @@ -191559,7 +191982,7 @@ function transformTypeScript(context) { return updated; } function visitParenthesizedExpression(node) { - const innerExpression = skipOuterExpressions(node.expression, ~6 /* Assertions */); + const innerExpression = skipOuterExpressions(node.expression, ~(6 /* Assertions */ | 16 /* ExpressionsWithTypeArguments */)); if (isAssertionExpression(innerExpression) || isSatisfiesExpression(innerExpression)) { const expression = visitNode(node.expression, visitor, isExpression); Debug.assert(expression); @@ -192365,8 +192788,6 @@ function transformClassFields(context) { return node; } switch (node.kind) { - case 129 /* AccessorKeyword */: - return Debug.fail("Use `modifierVisitor` instead."); case 263 /* ClassDeclaration */: return visitClassDeclaration(node); case 231 /* ClassExpression */: @@ -193779,6 +194200,7 @@ function transformClassFields(context) { addRange(statementsOut, visitNodes2(statementsIn, visitor, isStatement, statementOffset)); } function transformConstructorBody(node, constructor, isDerivedClass) { + var _a; const instanceProperties = getProperties( node, /*requireInitializer*/ @@ -193872,12 +194294,12 @@ function transformClassFields(context) { setTextRange( factory2.createNodeArray(statements), /*location*/ - constructor ? constructor.body.statements : node.members + ((_a = constructor == null ? void 0 : constructor.body) == null ? void 0 : _a.statements) ?? node.members ), multiLine ), /*location*/ - constructor ? constructor.body : void 0 + constructor == null ? void 0 : constructor.body ); } function addPropertyOrClassStaticBlockStatements(statements, properties, receiver) { @@ -200881,7 +201303,7 @@ function transformJsx(context) { const name = node.name; if (isIdentifier(name)) { const text = idText(name); - return /^[A-Za-z_]\w*$/.test(text) ? name : factory2.createStringLiteral(text); + return /^[A-Z_]\w*$/i.test(text) ? name : factory2.createStringLiteral(text); } return factory2.createStringLiteral(idText(name.namespace) + ":" + idText(name.name)); } @@ -203005,7 +203427,7 @@ function transformES2015(context) { statement, /*outermostLabeledStatement*/ node - ) : factory2.restoreEnclosingLabel(Debug.checkDefined(visitNode(statement, visitor, isStatement, factory2.liftToBlock)), node, convertedLoopState && resetLabel); + ) : factory2.restoreEnclosingLabel(visitNode(statement, visitor, isStatement, factory2.liftToBlock) ?? setTextRange(factory2.createEmptyStatement(), statement), node, convertedLoopState && resetLabel); } function visitIterationStatement(node, outermostLabeledStatement) { switch (node.kind) { @@ -206662,7 +207084,7 @@ function transformModule(context) { factory2.createExpressionStatement( reduceLeft( currentModuleInfo.exportedNames.slice(i, i + chunkSize), - (prev, nextId) => factory2.createAssignment(factory2.createPropertyAccessExpression(factory2.createIdentifier("exports"), factory2.createIdentifier(idText(nextId))), prev), + (prev, nextId) => nextId.kind === 11 /* StringLiteral */ ? factory2.createAssignment(factory2.createElementAccessExpression(factory2.createIdentifier("exports"), factory2.createStringLiteral(nextId.text)), prev) : factory2.createAssignment(factory2.createPropertyAccessExpression(factory2.createIdentifier("exports"), factory2.createIdentifier(idText(nextId))), prev), factory2.createVoidZero() ) ) @@ -206985,7 +207407,10 @@ function transformModule(context) { append(statements, createUnderscoreUnderscoreESModule()); } if (some(currentModuleInfo.exportedNames)) { - append(statements, factory2.createExpressionStatement(reduceLeft(currentModuleInfo.exportedNames, (prev, nextId) => factory2.createAssignment(factory2.createPropertyAccessExpression(factory2.createIdentifier("exports"), factory2.createIdentifier(idText(nextId))), prev), factory2.createVoidZero()))); + append( + statements, + factory2.createExpressionStatement(reduceLeft(currentModuleInfo.exportedNames, (prev, nextId) => nextId.kind === 11 /* StringLiteral */ ? factory2.createAssignment(factory2.createElementAccessExpression(factory2.createIdentifier("exports"), factory2.createStringLiteral(nextId.text)), prev) : factory2.createAssignment(factory2.createPropertyAccessExpression(factory2.createIdentifier("exports"), factory2.createIdentifier(idText(nextId))), prev), factory2.createVoidZero())) + ); } for (const f of currentModuleInfo.exportedFunctions) { appendExportsOfHoistedDeclaration(statements, f); @@ -207115,7 +207540,7 @@ function transformModule(context) { case 354 /* PartiallyEmittedExpression */: return visitPartiallyEmittedExpression(node, valueIsDiscarded); case 213 /* CallExpression */: - if (isImportCall(node) && currentSourceFile.impliedNodeFormat === void 0) { + if (isImportCall(node) && host.shouldTransformImportCall(currentSourceFile)) { return visitImportCallExpression(node); } break; @@ -207308,7 +207733,7 @@ function transformModule(context) { return factory2.updateLabeledStatement( node, node.label, - Debug.checkDefined(visitNode(node.statement, topLevelNestedVisitor, isStatement, factory2.liftToBlock)) + visitNode(node.statement, topLevelNestedVisitor, isStatement, factory2.liftToBlock) ?? setTextRange(factory2.createEmptyStatement(), node.statement) ); } function visitWithStatement(node) { @@ -207322,7 +207747,7 @@ function transformModule(context) { return factory2.updateIfStatement( node, visitNode(node.expression, visitor, isExpression), - Debug.checkDefined(visitNode(node.thenStatement, topLevelNestedVisitor, isStatement, factory2.liftToBlock)), + visitNode(node.thenStatement, topLevelNestedVisitor, isStatement, factory2.liftToBlock) ?? factory2.createBlock([]), visitNode(node.elseStatement, topLevelNestedVisitor, isStatement, factory2.liftToBlock) ); } @@ -207856,17 +208281,16 @@ function transformModule(context) { ); } for (const specifier of node.exportClause.elements) { - const exportNeedsImportDefault = !!getESModuleInterop(compilerOptions) && !(getInternalEmitFlags(node) & 2 /* NeverApplyImportHelper */) && idText(specifier.propertyName || specifier.name) === "default"; - const exportedValue = factory2.createPropertyAccessExpression( - exportNeedsImportDefault ? emitHelpers().createImportDefaultHelper(generatedName) : generatedName, - specifier.propertyName || specifier.name - ); + const specifierName = specifier.propertyName || specifier.name; + const exportNeedsImportDefault = !!getESModuleInterop(compilerOptions) && !(getInternalEmitFlags(node) & 2 /* NeverApplyImportHelper */) && moduleExportNameIsDefault(specifierName); + const target = exportNeedsImportDefault ? emitHelpers().createImportDefaultHelper(generatedName) : generatedName; + const exportedValue = specifierName.kind === 11 /* StringLiteral */ ? factory2.createElementAccessExpression(target, specifierName) : factory2.createPropertyAccessExpression(target, specifierName); statements.push( setOriginalNode( setTextRange( factory2.createExpressionStatement( createExportExpression( - factory2.getExportName(specifier), + specifier.name.kind === 11 /* StringLiteral */ ? factory2.cloneNode(specifier.name) : factory2.getExportName(specifier), exportedValue, /*location*/ void 0, @@ -207891,7 +208315,7 @@ function transformModule(context) { factory2.cloneNode(node.exportClause.name), getHelperExpressionForExport( node, - moduleKind !== 2 /* AMD */ ? createRequireCall2(node) : isExportNamespaceAsDefaultDeclaration(node) ? generatedName : factory2.createIdentifier(idText(node.exportClause.name)) + moduleKind !== 2 /* AMD */ ? createRequireCall2(node) : isExportNamespaceAsDefaultDeclaration(node) ? generatedName : node.exportClause.name.kind === 11 /* StringLiteral */ ? generatedName : factory2.createIdentifier(idText(node.exportClause.name)) ) ) ), @@ -208221,10 +208645,13 @@ function transformModule(context) { return statements; } function appendExportStatement(statements, seen, exportName, expression, location, allowComments, liveBinding) { - if (!seen.has(exportName)) { + if (exportName.kind !== 11 /* StringLiteral */) { + if (seen.has(exportName)) { + return statements; + } seen.set(exportName, true); - statements = append(statements, createExportStatement(exportName, expression, location, allowComments, liveBinding)); } + statements = append(statements, createExportStatement(exportName, expression, location, allowComments, liveBinding)); return statements; } function createUnderscoreUnderscoreESModule() { @@ -208294,7 +208721,10 @@ function transformModule(context) { ]) ] ) : factory2.createAssignment( - factory2.createPropertyAccessExpression( + name.kind === 11 /* StringLiteral */ ? factory2.createElementAccessExpression( + factory2.createIdentifier("exports"), + factory2.cloneNode(name) + ) : factory2.createPropertyAccessExpression( factory2.createIdentifier("exports"), factory2.cloneNode(name) ), @@ -208430,11 +208860,9 @@ function transformModule(context) { ); } else if (isImportSpecifier(importDeclaration)) { const name = importDeclaration.propertyName || importDeclaration.name; + const target = factory2.getGeneratedNameForNode(((_b = (_a = importDeclaration.parent) == null ? void 0 : _a.parent) == null ? void 0 : _b.parent) || importDeclaration); return setTextRange( - factory2.createPropertyAccessExpression( - factory2.getGeneratedNameForNode(((_b = (_a = importDeclaration.parent) == null ? void 0 : _a.parent) == null ? void 0 : _b.parent) || importDeclaration), - factory2.cloneNode(name) - ), + name.kind === 11 /* StringLiteral */ ? factory2.createElementAccessExpression(target, factory2.cloneNode(name)) : factory2.createPropertyAccessExpression(target, factory2.cloneNode(name)), /*location*/ node ); @@ -208722,7 +209150,7 @@ function transformSystemModule(context) { const exportedNames = []; if (moduleInfo.exportedNames) { for (const exportedLocalName of moduleInfo.exportedNames) { - if (exportedLocalName.escapedText === "default") { + if (moduleExportNameIsDefault(exportedLocalName)) { continue; } exportedNames.push( @@ -208900,10 +209328,10 @@ function transformSystemModule(context) { for (const e of entry.exportClause.elements) { properties.push( factory2.createPropertyAssignment( - factory2.createStringLiteral(idText(e.name)), + factory2.createStringLiteral(moduleExportNameTextUnescaped(e.name)), factory2.createElementAccessExpression( parameterName, - factory2.createStringLiteral(idText(e.propertyName || e.name)) + factory2.createStringLiteral(moduleExportNameTextUnescaped(e.propertyName || e.name)) ) ) ); @@ -208930,7 +209358,7 @@ function transformSystemModule(context) { /*typeArguments*/ void 0, [ - factory2.createStringLiteral(idText(entry.exportClause.name)), + factory2.createStringLiteral(moduleExportNameTextUnescaped(entry.exportClause.name)), parameterName ] ) @@ -209270,7 +209698,7 @@ function transformSystemModule(context) { const exportSpecifiers = moduleInfo.exportSpecifiers.get(name); if (exportSpecifiers) { for (const exportSpecifier of exportSpecifiers) { - if (exportSpecifier.name.escapedText !== excludeName) { + if (moduleExportNameTextUnescaped(exportSpecifier.name) !== excludeName) { statements = appendExportStatement(statements, exportSpecifier.name, name); } } @@ -209422,7 +209850,7 @@ function transformSystemModule(context) { return factory2.updateLabeledStatement( node, node.label, - Debug.checkDefined(visitNode(node.statement, topLevelNestedVisitor, isStatement, factory2.liftToBlock)) + visitNode(node.statement, topLevelNestedVisitor, isStatement, factory2.liftToBlock) ?? factory2.createExpressionStatement(factory2.createIdentifier("")) ); } function visitWithStatement(node) { @@ -209436,7 +209864,7 @@ function transformSystemModule(context) { return factory2.updateIfStatement( node, visitNode(node.expression, visitor, isExpression), - Debug.checkDefined(visitNode(node.thenStatement, topLevelNestedVisitor, isStatement, factory2.liftToBlock)), + visitNode(node.thenStatement, topLevelNestedVisitor, isStatement, factory2.liftToBlock) ?? factory2.createBlock([]), visitNode(node.elseStatement, topLevelNestedVisitor, isStatement, factory2.liftToBlock) ); } @@ -209691,13 +210119,12 @@ function transformSystemModule(context) { node ); } else if (isImportSpecifier(importDeclaration)) { + const importedName = importDeclaration.propertyName || importDeclaration.name; + const target = factory2.getGeneratedNameForNode(((_b = (_a = importDeclaration.parent) == null ? void 0 : _a.parent) == null ? void 0 : _b.parent) || importDeclaration); return setTextRange( factory2.createPropertyAssignment( factory2.cloneNode(name), - factory2.createPropertyAccessExpression( - factory2.getGeneratedNameForNode(((_b = (_a = importDeclaration.parent) == null ? void 0 : _a.parent) == null ? void 0 : _b.parent) || importDeclaration), - factory2.cloneNode(importDeclaration.propertyName || importDeclaration.name) - ) + importedName.kind === 11 /* StringLiteral */ ? factory2.createElementAccessExpression(target, factory2.cloneNode(importedName)) : factory2.createPropertyAccessExpression(target, factory2.cloneNode(importedName)) ), /*location*/ node @@ -209740,11 +210167,10 @@ function transformSystemModule(context) { node ); } else if (isImportSpecifier(importDeclaration)) { + const importedName = importDeclaration.propertyName || importDeclaration.name; + const target = factory2.getGeneratedNameForNode(((_b = (_a = importDeclaration.parent) == null ? void 0 : _a.parent) == null ? void 0 : _b.parent) || importDeclaration); return setTextRange( - factory2.createPropertyAccessExpression( - factory2.getGeneratedNameForNode(((_b = (_a = importDeclaration.parent) == null ? void 0 : _a.parent) == null ? void 0 : _b.parent) || importDeclaration), - factory2.cloneNode(importDeclaration.propertyName || importDeclaration.name) - ), + importedName.kind === 11 /* StringLiteral */ ? factory2.createElementAccessExpression(target, factory2.cloneNode(importedName)) : factory2.createPropertyAccessExpression(target, factory2.cloneNode(importedName)), /*location*/ node ); @@ -210110,8 +210536,8 @@ function transformECMAScriptModule(context) { } } -// src/compiler/transformers/module/node.ts -function transformNodeModule(context) { +// src/compiler/transformers/module/impliedNodeFormatDependent.ts +function transformImpliedNodeFormatDependentModule(context) { const previousOnSubstituteNode = context.onSubstituteNode; const previousOnEmitNode = context.onEmitNode; const esmTransform = transformECMAScriptModule(context); @@ -210122,6 +210548,7 @@ function transformNodeModule(context) { const cjsTransform = transformModule(context); const cjsOnSubstituteNode = context.onSubstituteNode; const cjsOnEmitNode = context.onEmitNode; + const getEmitModuleFormatOfFile2 = (file) => context.getEmitHost().getEmitModuleFormatOfFile(file); context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; context.enableSubstitution(307 /* SourceFile */); @@ -210136,7 +210563,7 @@ function transformNodeModule(context) { if (!currentSourceFile) { return previousOnSubstituteNode(hint, node); } - if (currentSourceFile.impliedNodeFormat === 99 /* ESNext */) { + if (getEmitModuleFormatOfFile2(currentSourceFile) >= 5 /* ES2015 */) { return esmOnSubstituteNode(hint, node); } return cjsOnSubstituteNode(hint, node); @@ -210149,13 +210576,13 @@ function transformNodeModule(context) { if (!currentSourceFile) { return previousOnEmitNode(hint, node, emitCallback); } - if (currentSourceFile.impliedNodeFormat === 99 /* ESNext */) { + if (getEmitModuleFormatOfFile2(currentSourceFile) >= 5 /* ES2015 */) { return esmOnEmitNode(hint, node, emitCallback); } return cjsOnEmitNode(hint, node, emitCallback); } function getModuleTransformForFile(file) { - return file.impliedNodeFormat === 99 /* ESNext */ ? esmTransform : cjsTransform; + return getEmitModuleFormatOfFile2(file) >= 5 /* ES2015 */ ? esmTransform : cjsTransform; } function transformSourceFile(node) { if (node.isDeclarationFile) { @@ -210577,7 +211004,11 @@ function createGetIsolatedDeclarationErrors(resolver) { if (isSetAccessor(node.parent)) { return createAccessorTypeError(node.parent); } - const addUndefined = resolver.requiresAddingImplicitUndefined(node); + const addUndefined = resolver.requiresAddingImplicitUndefined( + node, + /*enclosingDeclaration*/ + void 0 + ); if (!addUndefined && node.initializer) { return createExpressionError(node.initializer); } @@ -210632,19 +211063,19 @@ function createGetIsolatedDeclarationErrors(resolver) { function getDeclarationDiagnostics(host, resolver, file) { const compilerOptions = host.getCompilerOptions(); const files = filter(getSourceFilesToEmit(host, file), isSourceFileNotJson); - const result = transformNodes( + return contains(files, file) ? transformNodes( resolver, host, factory, compilerOptions, - file ? contains(files, file) ? [file] : emptyArray : files, + [file], [transformDeclarations], /*allowDtsFiles*/ false - ); - return result.diagnostics; + ).diagnostics : void 0; } -var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ | 2048 /* WriteClassExpressionAsTypeLiteral */ | 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 524288 /* AllowEmptyTuple */ | 1 /* AllowUnresolvedNames */ | 4 /* GenerateNamesForShadowedTypeParams */ | 1 /* NoTruncation */; +var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ | 2048 /* WriteClassExpressionAsTypeLiteral */ | 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 524288 /* AllowEmptyTuple */ | 4 /* GenerateNamesForShadowedTypeParams */ | 1 /* NoTruncation */; +var declarationEmitInternalNodeBuilderFlags = 8 /* AllowUnresolvedNames */; function transformDeclarations(context) { const throwDiagnostic = () => Debug.fail("Diagnostic emitted without context"); let getSymbolAccessibilityDiagnostic = throwDiagnostic; @@ -210741,7 +211172,10 @@ function transformDeclarations(context) { function reportPrivateInBaseOfClassExpression(propertyName) { if (errorNameNode || errorFallbackNode) { context.addDiagnostic( - createDiagnosticForNode(errorNameNode || errorFallbackNode, Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName) + addRelatedInfo( + createDiagnosticForNode(errorNameNode || errorFallbackNode, Diagnostics.Property_0_of_exported_anonymous_class_type_may_not_be_private_or_protected, propertyName), + ...isVariableDeclaration((errorNameNode || errorFallbackNode).parent) ? [createDiagnosticForNode(errorNameNode || errorFallbackNode, Diagnostics.Add_a_type_annotation_to_the_variable_0, errorDeclarationNameWithFallback())] : [] + ) ); } } @@ -210797,7 +211231,7 @@ function transformDeclarations(context) { diagnosticMessage: s.errorModuleName ? Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotation_may_unblock_declaration_emit : Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_declaration_emit, errorNode: s.errorNode || sourceFile }; - const result = resolver.getDeclarationStatementsForSourceFile(sourceFile, declarationEmitNodeBuilderFlags, symbolTracker); + const result = resolver.getDeclarationStatementsForSourceFile(sourceFile, declarationEmitNodeBuilderFlags, declarationEmitInternalNodeBuilderFlags, symbolTracker); getSymbolAccessibilityDiagnostic = oldDiag; return result; } @@ -211050,7 +211484,7 @@ function transformDeclarations(context) { if (shouldPrintWithInitializer(node)) { return; } - const shouldAddImplicitUndefined = node.kind === 169 /* Parameter */ && resolver.requiresAddingImplicitUndefined(node); + const shouldAddImplicitUndefined = node.kind === 169 /* Parameter */ && resolver.requiresAddingImplicitUndefined(node, enclosingDeclaration); if (type && !shouldAddImplicitUndefined) { return visitNode(type, visitDeclarationSubtree, isTypeNode); } @@ -211067,7 +211501,7 @@ function transformDeclarations(context) { case 172 /* PropertyDeclaration */: case 208 /* BindingElement */: case 260 /* VariableDeclaration */: - typeNode = resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker); + typeNode = resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, declarationEmitInternalNodeBuilderFlags, symbolTracker); break; case 262 /* FunctionDeclaration */: case 180 /* ConstructSignature */: @@ -211075,7 +211509,7 @@ function transformDeclarations(context) { case 174 /* MethodDeclaration */: case 177 /* GetAccessor */: case 179 /* CallSignature */: - typeNode = resolver.createReturnTypeOfSignatureDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker); + typeNode = resolver.createReturnTypeOfSignatureDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, declarationEmitInternalNodeBuilderFlags, symbolTracker); break; default: Debug.assertNever(node); @@ -211676,7 +212110,7 @@ function transformDeclarations(context) { newId, /*exclamationToken*/ void 0, - resolver.createTypeOfExpression(input.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), + resolver.createTypeOfExpression(input.expression, input, declarationEmitNodeBuilderFlags, declarationEmitInternalNodeBuilderFlags, symbolTracker), /*initializer*/ void 0 ); @@ -211802,7 +212236,7 @@ function transformDeclarations(context) { return void 0; } getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(p.valueDeclaration); - const type = resolver.createTypeOfDeclaration(p.valueDeclaration, fakespace, declarationEmitNodeBuilderFlags | -2147483648 /* NoSyntacticPrinter */, symbolTracker); + const type = resolver.createTypeOfDeclaration(p.valueDeclaration, fakespace, declarationEmitNodeBuilderFlags, declarationEmitInternalNodeBuilderFlags | 2 /* NoSyntacticPrinter */, symbolTracker); getSymbolAccessibilityDiagnostic = oldDiag; const isNonContextualKeywordName = isStringANonContextualKeyword(nameStr); const name = isNonContextualKeywordName ? factory2.getGeneratedNameForNode(p.valueDeclaration) : factory2.createIdentifier(nameStr); @@ -212005,7 +212439,7 @@ function transformDeclarations(context) { newId, /*exclamationToken*/ void 0, - resolver.createTypeOfExpression(extendsClause.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), + resolver.createTypeOfExpression(extendsClause.expression, input, declarationEmitNodeBuilderFlags, declarationEmitInternalNodeBuilderFlags, symbolTracker), /*initializer*/ void 0 ); @@ -212278,17 +212712,18 @@ function isProcessedComponent(node) { // src/compiler/transformer.ts function getModuleTransformer(moduleKind) { switch (moduleKind) { + case 200 /* Preserve */: + return transformECMAScriptModule; case 99 /* ESNext */: case 7 /* ES2022 */: case 6 /* ES2020 */: case 5 /* ES2015 */: - case 200 /* Preserve */: - return transformECMAScriptModule; - case 4 /* System */: - return transformSystemModule; case 100 /* Node16 */: case 199 /* NodeNext */: - return transformNodeModule; + case 1 /* CommonJS */: + return transformImpliedNodeFormatDependentModule; + case 4 /* System */: + return transformSystemModule; default: return transformModule; } @@ -212712,16 +213147,16 @@ function isBuildInfoFile(file) { function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, forceDtsEmit = false, onlyBuildInfo, includeBuildInfo) { const sourceFiles = isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile, forceDtsEmit); const options = host.getCompilerOptions(); - if (options.outFile) { - if (sourceFiles.length) { - const bundle = factory.createBundle(sourceFiles); - const result = action(getOutputPathsFor(bundle, host, forceDtsEmit), bundle); - if (result) { - return result; + if (!onlyBuildInfo) { + if (options.outFile) { + if (sourceFiles.length) { + const bundle = factory.createBundle(sourceFiles); + const result = action(getOutputPathsFor(bundle, host, forceDtsEmit), bundle); + if (result) { + return result; + } } - } - } else { - if (!onlyBuildInfo) { + } else { for (const sourceFile of sourceFiles) { const result = action(getOutputPathsFor(sourceFile, host, forceDtsEmit), sourceFile); if (result) { @@ -212729,19 +213164,19 @@ function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, forceDt } } } - if (includeBuildInfo) { - const buildInfoPath = getTsBuildInfoEmitOutputFilePath(options); - if (buildInfoPath) return action( - { buildInfoPath }, - /*sourceFileOrBundle*/ - void 0 - ); - } + } + if (includeBuildInfo) { + const buildInfoPath = getTsBuildInfoEmitOutputFilePath(options); + if (buildInfoPath) return action( + { buildInfoPath }, + /*sourceFileOrBundle*/ + void 0 + ); } } function getTsBuildInfoEmitOutputFilePath(options) { const configFile = options.configFilePath; - if (!isIncrementalCompilation(options)) return void 0; + if (!canEmitTsBuildInfo(options)) return void 0; if (options.tsBuildInfoFile) return options.tsBuildInfoFile; const outPath = options.outFile; let buildInfoExtensionLess; @@ -212759,14 +213194,16 @@ function getTsBuildInfoEmitOutputFilePath(options) { } return buildInfoExtensionLess + ".tsbuildinfo" /* TsBuildInfo */; } +function canEmitTsBuildInfo(options) { + return isIncrementalCompilation(options) || !!options.tscBuild; +} function getOutputPathsForBundle(options, forceDtsPaths) { const outPath = options.outFile; const jsFilePath = options.emitDeclarationOnly ? void 0 : outPath; const sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options); const declarationFilePath = forceDtsPaths || getEmitDeclarations(options) ? removeFileExtension(outPath) + ".d.ts" /* Dts */ : void 0; const declarationMapPath = declarationFilePath && getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : void 0; - const buildInfoPath = getTsBuildInfoEmitOutputFilePath(options); - return { jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, buildInfoPath }; + return { jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath }; } function getOutputPathsFor(sourceFile, host, forceDtsPaths) { const options = host.getCompilerOptions(); @@ -212780,7 +213217,7 @@ function getOutputPathsFor(sourceFile, host, forceDtsPaths) { const sourceMapFilePath = !jsFilePath || isJsonSourceFile(sourceFile) ? void 0 : getSourceMapFilePath(jsFilePath, options); const declarationFilePath = forceDtsPaths || getEmitDeclarations(options) && !isJsonFile ? getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : void 0; const declarationMapPath = declarationFilePath && getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : void 0; - return { jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, buildInfoPath: void 0 }; + return { jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath }; } } function getSourceMapFilePath(jsFilePath, options) { @@ -212829,7 +213266,7 @@ function createAddOutput() { } } function getSingleOutputFileNames(configFile, addOutput) { - const { jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, buildInfoPath } = getOutputPathsForBundle( + const { jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath } = getOutputPathsForBundle( configFile.options, /*forceDtsPaths*/ false @@ -212838,7 +213275,6 @@ function getSingleOutputFileNames(configFile, addOutput) { addOutput(sourceMapFilePath); addOutput(declarationFilePath); addOutput(declarationMapPath); - addOutput(buildInfoPath); } function getOwnOutputFileNames(configFile, inputFileName, ignoreCase, addOutput, getCommonSourceDirectory2) { if (isDeclarationFileName(inputFileName)) return; @@ -212889,8 +213325,8 @@ function getAllProjectOutputs(configFile, ignoreCase) { for (const inputFileName of configFile.fileNames) { getOwnOutputFileNames(configFile, inputFileName, ignoreCase, addOutput, getCommonSourceDirectory2); } - addOutput(getTsBuildInfoEmitOutputFilePath(configFile.options)); } + addOutput(getTsBuildInfoEmitOutputFilePath(configFile.options)); return getOutputs(); } function getOutputFileNames(commandLine, inputFileName, ignoreCase) { @@ -212930,7 +213366,7 @@ function getFirstProjectOutput(configFile, ignoreCase) { function emitResolverSkipsTypeChecking(emitOnly, forceDtsEmit) { return !!forceDtsEmit && !!emitOnly; } -function emitFiles(resolver, host, targetSourceFile, { scriptTransformers, declarationTransformers }, emitOnly, onlyBuildInfo, forceDtsEmit) { +function emitFiles(resolver, host, targetSourceFile, { scriptTransformers, declarationTransformers }, emitOnly, onlyBuildInfo, forceDtsEmit, skipBuildInfo) { var compilerOptions = host.getCompilerOptions(); var sourceMapDataList = compilerOptions.sourceMap || compilerOptions.inlineSourceMap || getAreDeclarationMapsEnabled(compilerOptions) ? [] : void 0; var emittedFilesList = compilerOptions.listEmittedFiles ? [] : void 0; @@ -212946,7 +213382,7 @@ function emitFiles(resolver, host, targetSourceFile, { scriptTransformers, decla getSourceFilesToEmit(host, targetSourceFile, forceDtsEmit), forceDtsEmit, onlyBuildInfo, - !targetSourceFile + !targetSourceFile && !skipBuildInfo ); exit(); return { @@ -212968,15 +213404,12 @@ function emitFiles(resolver, host, targetSourceFile, { scriptTransformers, decla (_f = tracing) == null ? void 0 : _f.pop(); } function emitBuildInfo(buildInfoPath) { - if (!buildInfoPath || targetSourceFile || emitSkipped) return; + if (!buildInfoPath || targetSourceFile) return; if (host.isEmitBlocked(buildInfoPath)) { emitSkipped = true; return; } - const buildInfo = host.getBuildInfo() || createBuildInfo( - /*program*/ - void 0 - ); + const buildInfo = host.getBuildInfo() || { version }; writeFile( host, emitterDiagnostics, @@ -213000,7 +213433,7 @@ function emitFiles(resolver, host, targetSourceFile, { scriptTransformers, decla } (isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : filter(sourceFileOrBundle.sourceFiles, isSourceFileNotJson)).forEach( (sourceFile) => { - if (compilerOptions.noCheck || !canIncludeBindAndCheckDiagnsotics(sourceFile, compilerOptions)) markLinkedReferences(sourceFile); + if (compilerOptions.noCheck || !canIncludeBindAndCheckDiagnostics(sourceFile, compilerOptions)) markLinkedReferences(sourceFile); } ); const transform2 = transformNodes( @@ -213018,6 +213451,7 @@ function emitFiles(resolver, host, targetSourceFile, { scriptTransformers, decla newLine: compilerOptions.newLine, noEmitHelpers: compilerOptions.noEmitHelpers, module: getEmitModuleKind(compilerOptions), + moduleResolution: getEmitModuleResolutionKind(compilerOptions), target: getEmitScriptTarget(compilerOptions), sourceMap: compilerOptions.sourceMap, inlineSourceMap: compilerOptions.inlineSourceMap, @@ -213052,7 +213486,7 @@ function emitFiles(resolver, host, targetSourceFile, { scriptTransformers, decla const filesForEmit = forceDtsEmit ? sourceFiles : filter(sourceFiles, isSourceFileNotJson); const inputListOrBundle = compilerOptions.outFile ? [factory.createBundle(filesForEmit)] : filesForEmit; filesForEmit.forEach((sourceFile) => { - if (emitOnly && !getEmitDeclarations(compilerOptions) || compilerOptions.noCheck || emitResolverSkipsTypeChecking(emitOnly, forceDtsEmit) || !canIncludeBindAndCheckDiagnsotics(sourceFile, compilerOptions)) { + if (emitOnly && !getEmitDeclarations(compilerOptions) || compilerOptions.noCheck || emitResolverSkipsTypeChecking(emitOnly, forceDtsEmit) || !canIncludeBindAndCheckDiagnostics(sourceFile, compilerOptions)) { collectLinkedAliases(sourceFile); } }); @@ -213080,6 +213514,7 @@ function emitFiles(resolver, host, targetSourceFile, { scriptTransformers, decla newLine: compilerOptions.newLine, noEmitHelpers: true, module: compilerOptions.module, + moduleResolution: compilerOptions.moduleResolution, target: compilerOptions.target, sourceMap: emitOnly !== 2 /* BuilderSignature */ && compilerOptions.declarationMap, inlineSourceMap: compilerOptions.inlineSourceMap, @@ -213095,7 +213530,7 @@ function emitFiles(resolver, host, targetSourceFile, { scriptTransformers, decla isEmitNotificationEnabled: declarationTransform.isEmitNotificationEnabled, substituteNode: declarationTransform.substituteNode }); - printSourceFileOrBundle( + const dtsWritten = printSourceFileOrBundle( declarationFilePath, declarationMapPath, declarationTransform, @@ -213109,7 +213544,7 @@ function emitFiles(resolver, host, targetSourceFile, { scriptTransformers, decla } ); if (emittedFilesList) { - emittedFilesList.push(declarationFilePath); + if (dtsWritten) emittedFilesList.push(declarationFilePath); if (declarationMapPath) { emittedFilesList.push(declarationMapPath); } @@ -213138,6 +213573,7 @@ function emitFiles(resolver, host, targetSourceFile, { scriptTransformers, decla forEachChild(node, collectLinkedAliases); } function markLinkedReferences(file) { + if (isSourceFileJS(file)) return; forEachChildRecursively(file, (n) => { if (isImportEqualsDeclaration(n) && !(getSyntacticModifierFlags(n) & 32 /* Export */)) return "skip"; if (isImportDeclaration(n)) return "skip"; @@ -213200,8 +213636,10 @@ function emitFiles(resolver, host, targetSourceFile, { scriptTransformers, decla writer.writeLine(); } const text = writer.getText(); - writeFile(host, emitterDiagnostics, jsFilePath, text, !!compilerOptions.emitBOM, sourceFiles, { sourceMapUrlPos, diagnostics: transform2.diagnostics }); + const data = { sourceMapUrlPos, diagnostics: transform2.diagnostics }; + writeFile(host, emitterDiagnostics, jsFilePath, text, !!compilerOptions.emitBOM, sourceFiles, data); writer.clear(); + return !data.skippedDtsWrite; } function shouldEmitSourceMaps(mapOptions, sourceFileOrBundle) { return (mapOptions.sourceMap || mapOptions.inlineSourceMap) && (sourceFileOrBundle.kind !== 307 /* SourceFile */ || !fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */)); @@ -213257,9 +213695,6 @@ function emitFiles(resolver, host, targetSourceFile, { scriptTransformers, decla return encodeURI(sourceMapFile); } } -function createBuildInfo(program) { - return { program, version }; -} function getBuildInfoText(buildInfo) { return JSON.stringify(buildInfo); } @@ -214122,7 +214557,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { } function getSortedEmitHelpers(node) { const helpers = getEmitHelpers(node); - return helpers && stableSort(helpers, compareEmitHelpers); + return helpers && toSorted(helpers, compareEmitHelpers); } function emitNumericOrBigIntLiteral(node) { emitLiteral( @@ -214132,7 +214567,13 @@ function createPrinter(printerOptions = {}, handlers = {}) { ); } function emitLiteral(node, jsxAttributeEscape) { - const text = getLiteralTextOfNode(node, printerOptions.neverAsciiEscape, jsxAttributeEscape); + const text = getLiteralTextOfNode( + node, + /*sourceFile*/ + void 0, + printerOptions.neverAsciiEscape, + jsxAttributeEscape + ); if ((printerOptions.sourceMap || printerOptions.inlineSourceMap) && (node.kind === 11 /* StringLiteral */ || isTemplateLiteralKind(node.kind))) { writeLiteral(text); } else { @@ -214613,6 +215054,8 @@ function createPrinter(printerOptions = {}, handlers = {}) { if (isNumericLiteral(expression)) { const text = getLiteralTextOfNode( expression, + /*sourceFile*/ + void 0, /*neverAsciiEscape*/ true, /*jsxAttributeEscape*/ @@ -215834,7 +216277,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { if (node.comment) { const text = getTextOfJSDocComment(node.comment); if (text) { - const lines = text.split(/\r\n?|\n/g); + const lines = text.split(/\r\n?|\n/); for (const line of lines) { writeLine(); writeSpace(); @@ -216261,7 +216704,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { if (isFunctionLike(parentNode) && parentNode.typeArguments) { return emitTypeArguments(parentNode, parentNode.typeArguments); } - emitList(parentNode, typeParameters, 53776 /* TypeParameters */); + emitList(parentNode, typeParameters, 53776 /* TypeParameters */ | (isArrowFunction(parentNode) ? 64 /* AllowTrailingComma */ : 0 /* None */)); } function emitParameters(parentNode, parameters) { emitList(parentNode, parameters, 2576 /* Parameters */); @@ -216529,7 +216972,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { } } function writeLines(text) { - const lines = text.split(/\r\n?|\n/g); + const lines = text.split(/\r\n?|\n/); const indentation = guessIndentation(lines); for (const lineText of lines) { const line = indentation ? lineText.slice(indentation) : lineText; @@ -216754,18 +217197,18 @@ function createPrinter(printerOptions = {}, handlers = {}) { } return getSourceTextOfNodeFromSourceFile(sourceFile, node, includeTrivia); } - function getLiteralTextOfNode(node, neverAsciiEscape, jsxAttributeEscape) { + function getLiteralTextOfNode(node, sourceFile = currentSourceFile, neverAsciiEscape, jsxAttributeEscape) { if (node.kind === 11 /* StringLiteral */ && node.textSourceNode) { const textSourceNode = node.textSourceNode; if (isIdentifier(textSourceNode) || isPrivateIdentifier(textSourceNode) || isNumericLiteral(textSourceNode) || isJsxNamespacedName(textSourceNode)) { const text = isNumericLiteral(textSourceNode) ? textSourceNode.text : getTextOfNode2(textSourceNode); return jsxAttributeEscape ? `"${escapeJsxAttributeString(text)}"` : neverAsciiEscape || getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? `"${escapeString(text)}"` : `"${escapeNonAsciiString(text)}"`; } else { - return getLiteralTextOfNode(textSourceNode, neverAsciiEscape, jsxAttributeEscape); + return getLiteralTextOfNode(textSourceNode, getSourceFileOfNode(textSourceNode), neverAsciiEscape, jsxAttributeEscape); } } const flags = (neverAsciiEscape ? 1 /* NeverAsciiEscape */ : 0) | (jsxAttributeEscape ? 2 /* JsxAttributeEscape */ : 0) | (printerOptions.terminateUnterminatedLiterals ? 4 /* TerminateUnterminatedLiterals */ : 0) | (printerOptions.target && printerOptions.target >= 8 /* ES2021 */ ? 8 /* AllowNumericSeparator */ : 0); - return getLiteralText(node, currentSourceFile, flags); + return getLiteralText(node, sourceFile, flags); } function pushNameGenerationScope(node) { privateNameTempFlagsStack.push(privateNameTempFlags); @@ -217766,7 +218209,7 @@ function createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensi } try { return createCachedFileSystemEntries(rootDir, rootDirPath); - } catch (_e) { + } catch { Debug.assert(!cachedReadDirectoryResult.has(ensureTrailingDirectorySeparator(rootDirPath))); return void 0; } @@ -217855,6 +218298,12 @@ function createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensi function realpath(s) { return host.realpath ? host.realpath(s) : s; } + function clearFirstAncestorEntry(fileOrDirectoryPath) { + forEachAncestorDirectory( + getDirectoryPath(fileOrDirectoryPath), + (ancestor) => cachedReadDirectoryResult.delete(ensureTrailingDirectorySeparator(ancestor)) ? true : void 0 + ); + } function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) { const existingResult = getCachedFileSystemEntries(fileOrDirectoryPath); if (existingResult !== void 0) { @@ -217863,6 +218312,7 @@ function createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensi } const parentResult = getCachedFileSystemEntriesForBaseDir(fileOrDirectoryPath); if (!parentResult) { + clearFirstAncestorEntry(fileOrDirectoryPath); return void 0; } if (!host.directoryExists) { @@ -217888,6 +218338,8 @@ function createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensi const parentResult = getCachedFileSystemEntriesForBaseDir(filePath); if (parentResult) { updateFilesOfFileSystemEntry(parentResult, getBaseNameOfFileName(fileName), eventKind === 0 /* Created */); + } else { + clearFirstAncestorEntry(filePath); } } function updateFilesOfFileSystemEntry(parentResult, baseName, fileExists2) { @@ -217914,7 +218366,6 @@ var ProgramUpdateLevel = /* @__PURE__ */ ((ProgramUpdateLevel2) => { ProgramUpdateLevel2[ProgramUpdateLevel2["Update"] = 0] = "Update"; ProgramUpdateLevel2[ProgramUpdateLevel2["RootNamesAndUpdate"] = 1] = "RootNamesAndUpdate"; ProgramUpdateLevel2[ProgramUpdateLevel2["Full"] = 2] = "Full"; - ProgramUpdateLevel2[ProgramUpdateLevel2["Resolutions"] = 3] = "Resolutions"; return ProgramUpdateLevel2; })(ProgramUpdateLevel || {}); function updateSharedExtendedConfigFileWatcher(projectPath, options, extendedConfigFilesMap, createExtendedConfigFileWatch, toPath3) { @@ -218047,7 +218498,7 @@ function isIgnoredFileFromWildCardWatching({ } return false; function hasSourceFile(file) { - return realProgram ? !!realProgram.getSourceFileByPath(file) : builderProgram ? builderProgram.getState().fileInfos.has(file) : !!find(program, (rootFile) => toPath3(rootFile) === file); + return realProgram ? !!realProgram.getSourceFileByPath(file) : builderProgram ? builderProgram.state.fileInfos.has(file) : !!find(program, (rootFile) => toPath3(rootFile) === file); } function isSupportedScriptKind() { if (!getScriptKind2) return false; @@ -218068,9 +218519,6 @@ function isIgnoredFileFromWildCardWatching({ } } } -function isBuilderProgram(program) { - return !!program.getState; -} function isEmittedFileOfProgram(program, file) { if (!program) { return false; @@ -218595,7 +219043,6 @@ function getModeForUsageLocation(file, usage, compilerOptions) { return getModeForUsageLocationWorker(file, usage, compilerOptions); } function getModeForUsageLocationWorker(file, usage, compilerOptions) { - var _a; if (isImportDeclaration(usage.parent) || isExportDeclaration(usage.parent) || isJSDocImportTag(usage.parent)) { const isTypeOnly = isExclusivelyTypeOnlyImportOrExport(usage.parent); if (isTypeOnly) { @@ -218611,19 +219058,28 @@ function getModeForUsageLocationWorker(file, usage, compilerOptions) { return override; } } - if (compilerOptions && getEmitModuleKind(compilerOptions) === 200 /* Preserve */) { - return usage.parent.parent && isImportEqualsDeclaration(usage.parent.parent) || isRequireCall( - usage.parent, - /*requireStringLiteralLikeArgument*/ - false - ) ? 1 /* CommonJS */ : 99 /* ESNext */; + if (compilerOptions && importSyntaxAffectsModuleResolution(compilerOptions)) { + return getEmitSyntaxForUsageLocationWorker(file, usage, compilerOptions); } - if (file.impliedNodeFormat === void 0) return void 0; - if (file.impliedNodeFormat !== 99 /* ESNext */) { - return isImportCall(walkUpParenthesizedExpressions(usage.parent)) ? 99 /* ESNext */ : 1 /* CommonJS */; +} +function getEmitSyntaxForUsageLocationWorker(file, usage, compilerOptions) { + var _a; + if (!compilerOptions) { + return void 0; } const exprParentParent = (_a = walkUpParenthesizedExpressions(usage.parent)) == null ? void 0 : _a.parent; - return exprParentParent && isImportEqualsDeclaration(exprParentParent) ? 1 /* CommonJS */ : 99 /* ESNext */; + if (exprParentParent && isImportEqualsDeclaration(exprParentParent) || isRequireCall( + usage.parent, + /*requireStringLiteralLikeArgument*/ + false + )) { + return 1 /* CommonJS */; + } + if (isImportCall(walkUpParenthesizedExpressions(usage.parent))) { + return shouldTransformImportCallWorker(file, compilerOptions) ? 1 /* CommonJS */ : 99 /* ESNext */; + } + const fileEmitMode = getEmitModuleFormatOfFileWorker(file, compilerOptions); + return fileEmitMode === 1 /* CommonJS */ ? 1 /* CommonJS */ : emitModuleKindIsNonNodeESM(fileEmitMode) || fileEmitMode === 200 /* Preserve */ ? 99 /* ESNext */ : void 0; } function getResolutionModeOverride(node, grammarErrorOnNode) { if (!node) return void 0; @@ -218680,7 +219136,7 @@ function getTypeReferenceResolutionName(entry) { } var typeReferenceResolutionNameAndModeGetter = { getName: getTypeReferenceResolutionName, - getMode: (entry, file) => getModeForFileReference(entry, file == null ? void 0 : file.impliedNodeFormat) + getMode: (entry, file, compilerOptions) => getModeForFileReference(entry, file && getDefaultResolutionModeForFileWorker(file, compilerOptions)) }; function createTypeReferenceResolutionLoader(containingFile, redirectedReference, options, host, cache) { return { @@ -218854,19 +219310,15 @@ function getImpliedNodeFormatForFile(fileName, packageJsonInfoCache, host, optio return typeof result === "object" ? result.impliedNodeFormat : result; } function getImpliedNodeFormatForFileWorker(fileName, packageJsonInfoCache, host, options) { - switch (getEmitModuleResolutionKind(options)) { - case 3 /* Node16 */: - case 99 /* NodeNext */: - return fileExtensionIsOneOf(fileName, [".d.mts" /* Dmts */, ".mts" /* Mts */, ".mjs" /* Mjs */]) ? 99 /* ESNext */ : fileExtensionIsOneOf(fileName, [".d.cts" /* Dcts */, ".cts" /* Cts */, ".cjs" /* Cjs */]) ? 1 /* CommonJS */ : fileExtensionIsOneOf(fileName, [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */, ".js" /* Js */, ".jsx" /* Jsx */]) ? lookupFromPackageJson() : void 0; - default: - return void 0; - } + const moduleResolution = getEmitModuleResolutionKind(options); + const shouldLookupFromPackageJson = 3 /* Node16 */ <= moduleResolution && moduleResolution <= 99 /* NodeNext */ || pathContainsNodeModules(fileName); + return fileExtensionIsOneOf(fileName, [".d.mts" /* Dmts */, ".mts" /* Mts */, ".mjs" /* Mjs */]) ? 99 /* ESNext */ : fileExtensionIsOneOf(fileName, [".d.cts" /* Dcts */, ".cts" /* Cts */, ".cjs" /* Cjs */]) ? 1 /* CommonJS */ : shouldLookupFromPackageJson && fileExtensionIsOneOf(fileName, [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */, ".js" /* Js */, ".jsx" /* Jsx */]) ? lookupFromPackageJson() : void 0; function lookupFromPackageJson() { const state = getTemporaryModuleResolutionState(packageJsonInfoCache, host, options); const packageJsonLocations = []; state.failedLookupLocations = packageJsonLocations; state.affectingLocations = packageJsonLocations; - const packageJsonScope = getPackageScopeForPath(fileName, state); + const packageJsonScope = getPackageScopeForPath(getDirectoryPath(fileName), state); const impliedNodeFormat = (packageJsonScope == null ? void 0 : packageJsonScope.contents.packageJsonContent.type) === "module" ? 99 /* ESNext */ : 1 /* CommonJS */; return { impliedNodeFormat, packageJsonLocations, packageJsonScope }; } @@ -219002,13 +219454,12 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config let commonSourceDirectory; let typeChecker; let classifiableNames; - const ambientModuleNameToUnmodifiedFileName = /* @__PURE__ */ new Map(); let fileReasons = createMultiMap(); let filesWithReferencesProcessed; let fileReasonsToChain; let reasonToRelatedInfo; - const cachedBindAndCheckDiagnosticsForFile = {}; - const cachedDeclarationDiagnosticsForFile = {}; + let cachedBindAndCheckDiagnosticsForFile; + let cachedDeclarationDiagnosticsForFile; let fileProcessingDiagnostics; let automaticTypeDirectiveNames; let automaticTypeDirectiveResolutions; @@ -219240,7 +219691,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config }); } } - files = stableSort(processingDefaultLibFiles, compareDefaultLibFiles).concat(processingOtherFiles); + files = toSorted(processingDefaultLibFiles, compareDefaultLibFiles).concat(processingOtherFiles); processingDefaultLibFiles = void 0; processingOtherFiles = void 0; filesWithReferencesProcessed = void 0; @@ -219251,7 +219702,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config const newFile = getSourceFileByPath(oldSourceFile.resolvedPath); if (shouldCreateNewSourceFile || !newFile || newFile.impliedNodeFormat !== oldSourceFile.impliedNodeFormat || // 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)); + host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions(), !!getSourceFileByPath(oldSourceFile.path), newFile); } } if (!host.getParsedCommandLine) { @@ -219261,7 +219712,9 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config resolvedProjectReference.sourceFile, oldProgram.getCompilerOptions(), /*hasSourceFileByPath*/ - false + false, + /*newSourceFileByResolvedPath*/ + void 0 ); } }); @@ -219319,6 +219772,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config isSourceFileFromExternalLibrary, isSourceFileDefaultLibrary, getModeForUsageLocation: getModeForUsageLocation2, + getEmitSyntaxForUsageLocation, getModeForResolutionAtIndex: getModeForResolutionAtIndex2, getSourceFileFromReference, getLibFileFromReference, @@ -219347,6 +219801,11 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config forEachResolvedProjectReference: forEachResolvedProjectReference2, isSourceOfProjectReferenceRedirect, getRedirectReferenceForResolutionFromSourceOfProject, + getCompilerOptionsForFile, + getDefaultResolutionModeForFile: getDefaultResolutionModeForFile2, + getEmitModuleFormatOfFile: getEmitModuleFormatOfFile2, + getImpliedNodeFormatForEmit: getImpliedNodeFormatForEmit2, + shouldTransformImportCall, emitBuildInfo, fileExists, readFile, @@ -219478,12 +219937,18 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config } function resolveModuleNamesWorker(moduleNames, containingFile, reusedNames) { var _a2, _b2; - if (!moduleNames.length) return emptyArray; const containingFileName = getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory); const redirectedReference = getRedirectReferenceForResolution(containingFile); (_a2 = tracing) == null ? void 0 : _a2.push(tracing.Phase.Program, "resolveModuleNamesWorker", { containingFileName }); mark("beforeResolveModule"); - const result = actualResolveModuleNamesWorker(moduleNames, containingFileName, redirectedReference, options, containingFile, reusedNames); + const result = actualResolveModuleNamesWorker( + moduleNames, + containingFileName, + redirectedReference, + options, + containingFile, + reusedNames + ); mark("afterResolveModule"); measure("ResolveModule", "beforeResolveModule", "afterResolveModule"); (_b2 = tracing) == null ? void 0 : _b2.pop(); @@ -219491,13 +219956,19 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config } function resolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFile, reusedNames) { var _a2, _b2; - if (!typeDirectiveNames.length) return []; const containingSourceFile = !isString(containingFile) ? containingFile : void 0; const containingFileName = !isString(containingFile) ? getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory) : containingFile; const redirectedReference = containingSourceFile && getRedirectReferenceForResolution(containingSourceFile); (_a2 = tracing) == null ? void 0 : _a2.push(tracing.Phase.Program, "resolveTypeReferenceDirectiveNamesWorker", { containingFileName }); mark("beforeResolveTypeReference"); - const result = actualResolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFileName, redirectedReference, options, containingSourceFile, reusedNames); + const result = actualResolveTypeReferenceDirectiveNamesWorker( + typeDirectiveNames, + containingFileName, + redirectedReference, + options, + containingSourceFile, + reusedNames + ); mark("afterResolveTypeReference"); measure("ResolveTypeReference", "beforeResolveTypeReference", "afterResolveTypeReference"); (_b2 = tracing) == null ? void 0 : _b2.pop(); @@ -219567,144 +220038,108 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config } return classifiableNames; } - function resolveModuleNamesReusingOldState(moduleNames, file) { - if (structureIsReused === 0 /* Not */ && !file.ambientModuleNames.length) { - return resolveModuleNamesWorker( - moduleNames, - file, + function resolveModuleNamesReusingOldState(moduleNames, containingFile) { + return resolveNamesReusingOldState({ + entries: moduleNames, + containingFile, + containingSourceFile: containingFile, + redirectedReference: getRedirectReferenceForResolution(containingFile), + nameAndModeGetter: moduleResolutionNameAndModeGetter, + resolutionWorker: resolveModuleNamesWorker, + getResolutionFromOldProgram: (name, mode) => oldProgram == null ? void 0 : oldProgram.getResolvedModule(containingFile, name, mode), + getResolved: getResolvedModuleFromResolution, + canReuseResolutionsInFile: () => containingFile === (oldProgram == null ? void 0 : oldProgram.getSourceFile(containingFile.fileName)) && !hasInvalidatedResolutions(containingFile.path), + resolveToOwnAmbientModule: true + }); + } + function resolveTypeReferenceDirectiveNamesReusingOldState(typeDirectiveNames, containingFile) { + const containingSourceFile = !isString(containingFile) ? containingFile : void 0; + return resolveNamesReusingOldState({ + entries: typeDirectiveNames, + containingFile, + containingSourceFile, + redirectedReference: containingSourceFile && getRedirectReferenceForResolution(containingSourceFile), + nameAndModeGetter: typeReferenceResolutionNameAndModeGetter, + resolutionWorker: resolveTypeReferenceDirectiveNamesWorker, + getResolutionFromOldProgram: (name, mode) => { + var _a2; + return containingSourceFile ? oldProgram == null ? void 0 : oldProgram.getResolvedTypeReferenceDirective(containingSourceFile, name, mode) : (_a2 = oldProgram == null ? void 0 : oldProgram.getAutomaticTypeDirectiveResolutions()) == null ? void 0 : _a2.get(name, mode); + }, + getResolved: getResolvedTypeReferenceDirectiveFromResolution, + canReuseResolutionsInFile: () => containingSourceFile ? containingSourceFile === (oldProgram == null ? void 0 : oldProgram.getSourceFile(containingSourceFile.fileName)) && !hasInvalidatedResolutions(containingSourceFile.path) : !hasInvalidatedResolutions(toPath3(containingFile)) + }); + } + function resolveNamesReusingOldState({ + entries, + containingFile, + containingSourceFile, + redirectedReference, + nameAndModeGetter, + resolutionWorker, + getResolutionFromOldProgram, + getResolved, + canReuseResolutionsInFile, + resolveToOwnAmbientModule + }) { + if (!entries.length) return emptyArray; + if (structureIsReused === 0 /* Not */ && (!resolveToOwnAmbientModule || !containingSourceFile.ambientModuleNames.length)) { + return resolutionWorker( + entries, + containingFile, /*reusedNames*/ void 0 ); } - let unknownModuleNames; + let unknownEntries; + let unknownEntryIndices; let result; let reusedNames; - const predictedToResolveToAmbientModuleMarker = emptyResolution; - const oldSourceFile = oldProgram && oldProgram.getSourceFile(file.fileName); - for (let i = 0; i < moduleNames.length; i++) { - const moduleName = moduleNames[i]; - if (file === oldSourceFile && !hasInvalidatedResolutions(file.path)) { - const oldResolution = oldProgram == null ? void 0 : oldProgram.getResolvedModule(file, moduleName.text, getModeForUsageLocation2(file, moduleName)); - if (oldResolution == null ? void 0 : oldResolution.resolvedModule) { + const reuseResolutions = canReuseResolutionsInFile(); + for (let i = 0; i < entries.length; i++) { + const entry = entries[i]; + if (reuseResolutions) { + const name = nameAndModeGetter.getName(entry); + const mode = nameAndModeGetter.getMode(entry, containingSourceFile, (redirectedReference == null ? void 0 : redirectedReference.commandLine.options) ?? options); + const oldResolution = getResolutionFromOldProgram(name, mode); + const oldResolved = oldResolution && getResolved(oldResolution); + if (oldResolved) { if (isTraceEnabled(options, host)) { trace( host, - oldResolution.resolvedModule.packageId ? Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package_ID_3 : Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2, - moduleName.text, - getNormalizedAbsolutePath(file.originalFileName, currentDirectory), - oldResolution.resolvedModule.resolvedFileName, - oldResolution.resolvedModule.packageId && packageIdToString(oldResolution.resolvedModule.packageId) + resolutionWorker === resolveModuleNamesWorker ? oldResolved.packageId ? Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package_ID_3 : Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2 : oldResolved.packageId ? Diagnostics.Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package_ID_3 : Diagnostics.Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved_to_2, + name, + containingSourceFile ? getNormalizedAbsolutePath(containingSourceFile.originalFileName, currentDirectory) : containingFile, + oldResolved.resolvedFileName, + oldResolved.packageId && packageIdToString(oldResolved.packageId) ); } - (result ?? (result = new Array(moduleNames.length)))[i] = oldResolution; - (reusedNames ?? (reusedNames = [])).push(moduleName); + (result ?? (result = new Array(entries.length)))[i] = oldResolution; + (reusedNames ?? (reusedNames = [])).push(entry); continue; } } - let resolvesToAmbientModuleInNonModifiedFile = false; - if (contains(file.ambientModuleNames, moduleName.text)) { - resolvesToAmbientModuleInNonModifiedFile = true; - if (isTraceEnabled(options, host)) { - trace(host, Diagnostics.Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1, moduleName.text, getNormalizedAbsolutePath(file.originalFileName, currentDirectory)); - } - } else { - resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName); - } - if (resolvesToAmbientModuleInNonModifiedFile) { - (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker; - } else { - (unknownModuleNames ?? (unknownModuleNames = [])).push(moduleName); - } - } - const resolutions = unknownModuleNames && unknownModuleNames.length ? resolveModuleNamesWorker(unknownModuleNames, file, reusedNames) : emptyArray; - if (!result) { - Debug.assert(resolutions.length === moduleNames.length); - return resolutions; - } - let j = 0; - for (let i = 0; i < result.length; i++) { - if (!result[i]) { - result[i] = resolutions[j]; - j++; - } - } - Debug.assert(j === resolutions.length); - return result; - function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName) { - var _a2; - const resolutionToFile = (_a2 = oldProgram == null ? void 0 : oldProgram.getResolvedModule(file, moduleName.text, getModeForUsageLocation2(file, moduleName))) == null ? void 0 : _a2.resolvedModule; - const resolvedFile = resolutionToFile && oldProgram.getSourceFile(resolutionToFile.resolvedFileName); - if (resolutionToFile && resolvedFile) { - return false; - } - const unmodifiedFile = ambientModuleNameToUnmodifiedFileName.get(moduleName.text); - if (!unmodifiedFile) { - return false; - } - if (isTraceEnabled(options, host)) { - trace(host, Diagnostics.Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified, moduleName.text, unmodifiedFile); - } - return true; - } - } - function resolveTypeReferenceDirectiveNamesReusingOldState(typeDirectiveNames, containingFile) { - var _a2; - if (structureIsReused === 0 /* Not */) { - return resolveTypeReferenceDirectiveNamesWorker( - typeDirectiveNames, - containingFile, - /*reusedNames*/ - void 0 - ); - } - let unknownTypeReferenceDirectiveNames; - let result; - let reusedNames; - const containingSourceFile = !isString(containingFile) ? containingFile : void 0; - const oldSourceFile = !isString(containingFile) ? oldProgram && oldProgram.getSourceFile(containingFile.fileName) : void 0; - const canReuseResolutions = !isString(containingFile) ? containingFile === oldSourceFile && !hasInvalidatedResolutions(containingFile.path) : !hasInvalidatedResolutions(toPath3(containingFile)); - for (let i = 0; i < typeDirectiveNames.length; i++) { - const entry = typeDirectiveNames[i]; - if (canReuseResolutions) { - const typeDirectiveName = getTypeReferenceResolutionName(entry); - const mode = getModeForFileReference(entry, containingSourceFile == null ? void 0 : containingSourceFile.impliedNodeFormat); - const oldResolution = !isString(containingFile) ? oldProgram == null ? void 0 : oldProgram.getResolvedTypeReferenceDirective(containingFile, typeDirectiveName, mode) : (_a2 = oldProgram == null ? void 0 : oldProgram.getAutomaticTypeDirectiveResolutions()) == null ? void 0 : _a2.get(typeDirectiveName, mode); - if (oldResolution == null ? void 0 : oldResolution.resolvedTypeReferenceDirective) { + if (resolveToOwnAmbientModule) { + const name = nameAndModeGetter.getName(entry); + if (contains(containingSourceFile.ambientModuleNames, name)) { if (isTraceEnabled(options, host)) { trace( host, - oldResolution.resolvedTypeReferenceDirective.packageId ? Diagnostics.Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package_ID_3 : Diagnostics.Reusing_resolution_of_type_reference_directive_0_from_1_of_old_program_it_was_successfully_resolved_to_2, - typeDirectiveName, - !isString(containingFile) ? getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory) : containingFile, - oldResolution.resolvedTypeReferenceDirective.resolvedFileName, - oldResolution.resolvedTypeReferenceDirective.packageId && packageIdToString(oldResolution.resolvedTypeReferenceDirective.packageId) + Diagnostics.Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1, + name, + getNormalizedAbsolutePath(containingSourceFile.originalFileName, currentDirectory) ); } - (result ?? (result = new Array(typeDirectiveNames.length)))[i] = oldResolution; - (reusedNames ?? (reusedNames = [])).push(entry); + (result ?? (result = new Array(entries.length)))[i] = emptyResolution; continue; } } - (unknownTypeReferenceDirectiveNames ?? (unknownTypeReferenceDirectiveNames = [])).push(entry); - } - if (!unknownTypeReferenceDirectiveNames) return result || emptyArray; - const resolutions = resolveTypeReferenceDirectiveNamesWorker( - unknownTypeReferenceDirectiveNames, - containingFile, - reusedNames - ); - if (!result) { - Debug.assert(resolutions.length === typeDirectiveNames.length); - return resolutions; - } - let j = 0; - for (let i = 0; i < result.length; i++) { - if (!result[i]) { - result[i] = resolutions[j]; - j++; - } + (unknownEntries ?? (unknownEntries = [])).push(entry); + (unknownEntryIndices ?? (unknownEntryIndices = [])).push(i); } - Debug.assert(j === resolutions.length); + if (!unknownEntries) return result; + const resolutions = resolutionWorker(unknownEntries, containingFile, reusedNames); + if (!result) return resolutions; + resolutions.forEach((resolution, index) => result[unknownEntryIndices[index]] = resolution); return result; } function canReuseProjectReferences() { @@ -219833,10 +220268,6 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config } else if (hasInvalidatedResolutions(oldSourceFile.path)) { structureIsReused = 1 /* SafeModules */; modifiedSourceFiles.push(newSourceFile); - } else { - for (const moduleName of oldSourceFile.ambientModuleNames) { - ambientModuleNameToUnmodifiedFileName.set(moduleName, oldSourceFile.fileName); - } } newSourceFiles.push(newSourceFile); } @@ -219929,6 +220360,10 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config getSymlinkCache, writeFile: writeFileCallback || writeFile2, isEmitBlocked, + shouldTransformImportCall, + getEmitModuleFormatOfFile: getEmitModuleFormatOfFile2, + getDefaultResolutionModeForFile: getDefaultResolutionModeForFile2, + getModeForResolutionAtIndex: getModeForResolutionAtIndex2, readFile: (f) => host.readFile(f), fileExists: (f) => { const path = toPath3(f); @@ -219955,7 +220390,6 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config } function emitBuildInfo(writeFileCallback) { var _a2, _b2; - Debug.assert(!options.outFile); (_a2 = tracing) == null ? void 0 : _a2.push( tracing.Phase.Emit, "emitBuildInfo", @@ -219997,20 +220431,23 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config if (file.hasNoDefaultLib) { return true; } - if (!options.noLib) { + if (options.noLib) { return false; } const equalityComparer = host.useCaseSensitiveFileNames() ? equateStringsCaseSensitive : equateStringsCaseInsensitive; if (!options.lib) { return equalityComparer(file.fileName, getDefaultLibraryFileName()); } else { - return some(options.lib, (libFileName) => equalityComparer(file.fileName, resolvedLibReferences.get(libFileName).actual)); + return some(options.lib, (libFileName) => { + const resolvedLib = resolvedLibReferences.get(libFileName); + return !!resolvedLib && equalityComparer(file.fileName, resolvedLib.actual); + }); } } function getTypeChecker() { return typeChecker || (typeChecker = createTypeChecker(program)); } - function emit(sourceFile, writeFileCallback, cancellationToken, emitOnly, transformers, forceDtsEmit) { + function emit(sourceFile, writeFileCallback, cancellationToken, emitOnly, transformers, forceDtsEmit, skipBuildInfo) { var _a2, _b2; (_a2 = tracing) == null ? void 0 : _a2.push( tracing.Phase.Emit, @@ -220019,14 +220456,25 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config /*separateBeginAndEnd*/ true ); - const result = runWithCancellationToken(() => emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnly, transformers, forceDtsEmit)); + const result = runWithCancellationToken( + () => emitWorker( + program, + sourceFile, + writeFileCallback, + cancellationToken, + emitOnly, + transformers, + forceDtsEmit, + skipBuildInfo + ) + ); (_b2 = tracing) == null ? void 0 : _b2.pop(); return result; } function isEmitBlocked(emitFileName) { return hasEmitBlockingDiagnostics.has(toPath3(emitFileName)); } - function emitWorker(program2, sourceFile, writeFileCallback, cancellationToken, emitOnly, customTransformers, forceDtsEmit) { + function emitWorker(program2, sourceFile, writeFileCallback, cancellationToken, emitOnly, customTransformers, forceDtsEmit, skipBuildInfo) { if (!forceDtsEmit) { const result = handleNoEmitOptions(program2, sourceFile, writeFileCallback, cancellationToken); if (result) return result; @@ -220048,7 +220496,8 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config emitOnly, /*onlyBuildInfo*/ false, - forceDtsEmit + forceDtsEmit, + skipBuildInfo ) ); mark("afterEmit"); @@ -220075,15 +220524,23 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config function getSyntacticDiagnostics(sourceFile, cancellationToken) { return getDiagnosticsHelper(sourceFile, getSyntacticDiagnosticsForFile, cancellationToken); } - function getSemanticDiagnostics(sourceFile, cancellationToken) { - return getDiagnosticsHelper(sourceFile, getSemanticDiagnosticsForFile, cancellationToken); + function getSemanticDiagnostics(sourceFile, cancellationToken, nodesToCheck) { + return getDiagnosticsHelper( + sourceFile, + (sourceFile2, cancellationToken2) => getSemanticDiagnosticsForFile(sourceFile2, cancellationToken2, nodesToCheck), + cancellationToken + ); } function getCachedSemanticDiagnostics(sourceFile) { - var _a2; - return sourceFile ? (_a2 = cachedBindAndCheckDiagnosticsForFile.perFile) == null ? void 0 : _a2.get(sourceFile.path) : cachedBindAndCheckDiagnosticsForFile.allDiagnostics; + return cachedBindAndCheckDiagnosticsForFile == null ? void 0 : cachedBindAndCheckDiagnosticsForFile.get(sourceFile.path); } function getBindAndCheckDiagnostics(sourceFile, cancellationToken) { - return getBindAndCheckDiagnosticsForFile(sourceFile, cancellationToken); + return getBindAndCheckDiagnosticsForFile( + sourceFile, + cancellationToken, + /*nodesToCheck*/ + void 0 + ); } function getProgramDiagnostics(sourceFile) { var _a2; @@ -220097,12 +220554,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config return getDiagnosticsWithPrecedingDirectives(sourceFile, sourceFile.commentDirectives, programDiagnosticsInFile).diagnostics; } function getDeclarationDiagnostics2(sourceFile, cancellationToken) { - const options2 = program.getCompilerOptions(); - if (!sourceFile || options2.outFile) { - return getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); - } else { - return getDiagnosticsHelper(sourceFile, getDeclarationDiagnosticsForFile, cancellationToken); - } + return getDiagnosticsHelper(sourceFile, getDeclarationDiagnosticsForFile, cancellationToken); } function getSyntacticDiagnosticsForFile(sourceFile) { if (isSourceFileJS(sourceFile)) { @@ -220123,16 +220575,26 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config throw e; } } - function getSemanticDiagnosticsForFile(sourceFile, cancellationToken) { + function getSemanticDiagnosticsForFile(sourceFile, cancellationToken, nodesToCheck) { return concatenate( - filterSemanticDiagnostics(getBindAndCheckDiagnosticsForFile(sourceFile, cancellationToken), options), + filterSemanticDiagnostics(getBindAndCheckDiagnosticsForFile(sourceFile, cancellationToken, nodesToCheck), options), getProgramDiagnostics(sourceFile) ); } - function getBindAndCheckDiagnosticsForFile(sourceFile, cancellationToken) { - return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedBindAndCheckDiagnosticsForFile, getBindAndCheckDiagnosticsForFileNoCache); + function getBindAndCheckDiagnosticsForFile(sourceFile, cancellationToken, nodesToCheck) { + if (nodesToCheck) { + return getBindAndCheckDiagnosticsForFileNoCache(sourceFile, cancellationToken, nodesToCheck); + } + let result = cachedBindAndCheckDiagnosticsForFile == null ? void 0 : cachedBindAndCheckDiagnosticsForFile.get(sourceFile.path); + if (!result) { + (cachedBindAndCheckDiagnosticsForFile ?? (cachedBindAndCheckDiagnosticsForFile = /* @__PURE__ */ new Map())).set( + sourceFile.path, + result = getBindAndCheckDiagnosticsForFileNoCache(sourceFile, cancellationToken) + ); + } + return result; } - function getBindAndCheckDiagnosticsForFileNoCache(sourceFile, cancellationToken) { + function getBindAndCheckDiagnosticsForFileNoCache(sourceFile, cancellationToken, nodesToCheck) { return runWithCancellationToken(() => { if (skipTypeChecking(sourceFile, options, program)) { return emptyArray; @@ -220140,24 +220602,34 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config const typeChecker2 = getTypeChecker(); Debug.assert(!!sourceFile.bindDiagnostics); const isJs = sourceFile.scriptKind === 1 /* JS */ || sourceFile.scriptKind === 2 /* JSX */; - const isCheckJs = isJs && isCheckJsEnabledForFile(sourceFile, options); const isPlainJs = isPlainJsFile(sourceFile, options.checkJs); + const isCheckJs = isJs && isCheckJsEnabledForFile(sourceFile, options); let bindDiagnostics = sourceFile.bindDiagnostics; - let checkDiagnostics = typeChecker2.getDiagnostics(sourceFile, cancellationToken); + let checkDiagnostics = typeChecker2.getDiagnostics(sourceFile, cancellationToken, nodesToCheck); if (isPlainJs) { bindDiagnostics = filter(bindDiagnostics, (d) => plainJSErrors.has(d.code)); checkDiagnostics = filter(checkDiagnostics, (d) => plainJSErrors.has(d.code)); } - return getMergedBindAndCheckDiagnostics(sourceFile, !isPlainJs, bindDiagnostics, checkDiagnostics, isCheckJs ? sourceFile.jsDocDiagnostics : void 0); + return getMergedBindAndCheckDiagnostics( + sourceFile, + !isPlainJs, + !!nodesToCheck, + bindDiagnostics, + checkDiagnostics, + isCheckJs ? sourceFile.jsDocDiagnostics : void 0 + ); }); } - function getMergedBindAndCheckDiagnostics(sourceFile, includeBindAndCheckDiagnostics, ...allDiagnostics) { + function getMergedBindAndCheckDiagnostics(sourceFile, includeBindAndCheckDiagnostics, partialCheck, ...allDiagnostics) { var _a2; const flatDiagnostics = flatten(allDiagnostics); if (!includeBindAndCheckDiagnostics || !((_a2 = sourceFile.commentDirectives) == null ? void 0 : _a2.length)) { return flatDiagnostics; } const { diagnostics, directives } = getDiagnosticsWithPrecedingDirectives(sourceFile, sourceFile.commentDirectives, flatDiagnostics); + if (partialCheck) { + return diagnostics; + } for (const errorExpectation of directives.getUnusedExpectations()) { diagnostics.push(createDiagnosticForRange(sourceFile, errorExpectation.range, Diagnostics.Unused_ts_expect_error_directive)); } @@ -220185,7 +220657,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config return line; } const lineText = file.text.slice(lineStarts[line], lineStarts[line + 1]).trim(); - if (lineText !== "" && !/^(\s*)\/\/(.*)$/.test(lineText)) { + if (lineText !== "" && !/^\s*\/\/.*$/.test(lineText)) { return -1; } line--; @@ -220408,7 +220880,14 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config }); } function getDeclarationDiagnosticsWorker(sourceFile, cancellationToken) { - return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedDeclarationDiagnosticsForFile, getDeclarationDiagnosticsForFileNoCache); + let result = cachedDeclarationDiagnosticsForFile == null ? void 0 : cachedDeclarationDiagnosticsForFile.get(sourceFile.path); + if (!result) { + (cachedDeclarationDiagnosticsForFile ?? (cachedDeclarationDiagnosticsForFile = /* @__PURE__ */ new Map())).set( + sourceFile.path, + result = getDeclarationDiagnosticsForFileNoCache(sourceFile, cancellationToken) + ); + } + return result; } function getDeclarationDiagnosticsForFileNoCache(sourceFile, cancellationToken) { return runWithCancellationToken(() => { @@ -220416,22 +220895,8 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config return getDeclarationDiagnostics(getEmitHost(noop), resolver, sourceFile) || emptyArray; }); } - function getAndCacheDiagnostics(sourceFile, cancellationToken, cache, getDiagnostics2) { - var _a2; - const cachedResult = sourceFile ? (_a2 = cache.perFile) == null ? void 0 : _a2.get(sourceFile.path) : cache.allDiagnostics; - if (cachedResult) { - return cachedResult; - } - const result = getDiagnostics2(sourceFile, cancellationToken); - if (sourceFile) { - (cache.perFile || (cache.perFile = /* @__PURE__ */ new Map())).set(sourceFile.path, result); - } else { - cache.allDiagnostics = result; - } - return result; - } function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) { - return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); + return sourceFile.isDeclarationFile ? emptyArray : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken); } function getOptionsDiagnostics() { return sortAndDeduplicateDiagnostics(concatenate( @@ -220978,10 +221443,14 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config const resolvedTypeReferenceDirective = resolutions[index]; const fileName = ref.fileName; resolutionsInFile.set(fileName, getModeForFileReference(ref, file.impliedNodeFormat), resolvedTypeReferenceDirective); - const mode = ref.resolutionMode || file.impliedNodeFormat; + const mode = ref.resolutionMode || getDefaultResolutionModeForFile2(file); processTypeReferenceDirective(fileName, mode, resolvedTypeReferenceDirective, { kind: 5 /* TypeReferenceDirective */, file: file.path, index }); } } + function getCompilerOptionsForFile(file) { + var _a2; + return ((_a2 = getRedirectReferenceForResolution(file)) == null ? void 0 : _a2.commandLine.options) || options; + } function processTypeReferenceDirective(typeReferenceDirective, mode, resolution, reason) { var _a2, _b2; (_a2 = tracing) == null ? void 0 : _a2.push(tracing.Phase.Program, "processTypeReferenceDirective", { directive: typeReferenceDirective, hasResolved: !!resolution.resolvedTypeReferenceDirective, refKind: reason.kind, refPath: isReferencedFile(reason) ? reason.file : void 0 }); @@ -221082,13 +221551,12 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config return host.getCanonicalFileName(fileName); } function processImportedModules(file) { - var _a2; collectExternalModuleReferences(file); if (file.imports.length || file.moduleAugmentations.length) { const moduleNames = getModuleNames(file); const resolutions = (resolvedModulesProcessing == null ? void 0 : resolvedModulesProcessing.get(file.path)) || resolveModuleNamesReusingOldState(moduleNames, file); Debug.assert(resolutions.length === moduleNames.length); - const optionsForFile = ((_a2 = getRedirectReferenceForResolution(file)) == null ? void 0 : _a2.commandLine.options) || options; + const optionsForFile = getCompilerOptionsForFile(file); const resolutionsInFile = createModeAwareCache(); (resolvedModules ?? (resolvedModules = /* @__PURE__ */ new Map())).set(file.path, resolutionsInFile); for (let index = 0; index < moduleNames.length; index++) { @@ -221253,8 +221721,8 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config } const outputFile = options.outFile; if (options.tsBuildInfoFile) { - if (!isIncrementalCompilation(options)) { - createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "tsBuildInfoFile", "incremental", "composite"); + if (!canEmitTsBuildInfo(options)) { + createDiagnosticForOptionName(Diagnostics.Option_tsBuildInfoFile_cannot_be_specified_without_specifying_option_incremental_or_composite_or_if_not_running_tsc_b, "tsBuildInfoFile"); } } else if (options.incremental && !outputFile && !options.configFilePath) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified)); @@ -221393,14 +221861,6 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config if (!getEmitDeclarations(options)) { createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "emitDeclarationOnly", "declaration", "composite"); } - if (options.noEmit) { - createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit"); - } - } - if (options.noCheck) { - if (options.noEmit) { - createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_with_option_1, "noCheck", "noEmit"); - } } if (options.emitDecoratorMetadata && !options.experimentalDecorators) { createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators"); @@ -221512,7 +221972,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config } return Version.zero; } - function checkDeprecations(deprecatedIn, stopsWorkingIn, removedIn, createDiagnostic, fn) { + function checkDeprecations(deprecatedIn, removedIn, createDiagnostic, fn) { const deprecatedInVersion = new Version(deprecatedIn); const removedInVersion = new Version(removedIn); const typescriptVersion = new Version(typeScriptVersion3 || versionMajorMinor); @@ -221529,9 +221989,9 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config } } else { if (value === void 0) { - createDiagnostic(name, value, useInstead, Diagnostics.Option_0_is_deprecated_and_will_stop_functioning_in_TypeScript_1_Specify_compilerOption_ignoreDeprecations_Colon_2_to_silence_this_error, name, stopsWorkingIn, deprecatedIn); + createDiagnostic(name, value, useInstead, Diagnostics.Option_0_is_deprecated_and_will_stop_functioning_in_TypeScript_1_Specify_compilerOption_ignoreDeprecations_Colon_2_to_silence_this_error, name, removedIn, deprecatedIn); } else { - createDiagnostic(name, value, useInstead, Diagnostics.Option_0_1_is_deprecated_and_will_stop_functioning_in_TypeScript_2_Specify_compilerOption_ignoreDeprecations_Colon_3_to_silence_this_error, name, value, stopsWorkingIn, deprecatedIn); + createDiagnostic(name, value, useInstead, Diagnostics.Option_0_1_is_deprecated_and_will_stop_functioning_in_TypeScript_2_Specify_compilerOption_ignoreDeprecations_Colon_3_to_silence_this_error, name, value, removedIn, deprecatedIn); } } }); @@ -221567,7 +222027,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config ); } } - checkDeprecations("5.0", "5.5", "6.0", createDiagnostic, (createDeprecatedDiagnostic) => { + checkDeprecations("5.0", "5.5", createDiagnostic, (createDeprecatedDiagnostic) => { if (options.target === 0 /* ES3 */) { createDeprecatedDiagnostic("target", "ES3"); } @@ -221619,7 +222079,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config function createDiagnostic(_name, _value, _useInstead, message, ...args) { createDiagnosticForReference(parentFile, index, message, ...args); } - checkDeprecations("5.0", "5.5", "6.0", createDiagnostic, (createDeprecatedDiagnostic) => { + checkDeprecations("5.0", "5.5", createDiagnostic, (createDeprecatedDiagnostic) => { if (ref.prepend) { createDeprecatedDiagnostic("prepend"); } @@ -221645,7 +222105,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config redirectInfo = cachedChain.redirectInfo; } else { reasons == null ? void 0 : reasons.forEach(processReason); - redirectInfo = file && explainIfFileIsRedirectAndImpliedFormat(file); + redirectInfo = file && explainIfFileIsRedirectAndImpliedFormat(file, getCompilerOptionsForFile(file)); } if (fileProcessingReason) processReason(fileProcessingReason); const processedExtraReason = (seenReasons == null ? void 0 : seenReasons.size) !== (reasons == null ? void 0 : reasons.length); @@ -222003,13 +222463,53 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config return symlinks; } function getModeForUsageLocation2(file, usage) { - var _a2; - const optionsForFile = ((_a2 = getRedirectReferenceForResolution(file)) == null ? void 0 : _a2.commandLine.options) || options; - return getModeForUsageLocationWorker(file, usage, optionsForFile); + return getModeForUsageLocationWorker(file, usage, getCompilerOptionsForFile(file)); + } + function getEmitSyntaxForUsageLocation(file, usage) { + return getEmitSyntaxForUsageLocationWorker(file, usage, getCompilerOptionsForFile(file)); } function getModeForResolutionAtIndex2(file, index) { return getModeForUsageLocation2(file, getModuleNameStringLiteralAt(file, index)); } + function getDefaultResolutionModeForFile2(sourceFile) { + return getDefaultResolutionModeForFileWorker(sourceFile, getCompilerOptionsForFile(sourceFile)); + } + function getImpliedNodeFormatForEmit2(sourceFile) { + return getImpliedNodeFormatForEmitWorker(sourceFile, getCompilerOptionsForFile(sourceFile)); + } + function getEmitModuleFormatOfFile2(sourceFile) { + return getEmitModuleFormatOfFileWorker(sourceFile, getCompilerOptionsForFile(sourceFile)); + } + function shouldTransformImportCall(sourceFile) { + return shouldTransformImportCallWorker(sourceFile, getCompilerOptionsForFile(sourceFile)); + } +} +function shouldTransformImportCallWorker(sourceFile, options) { + const moduleKind = getEmitModuleKind(options); + if (100 /* Node16 */ <= moduleKind && moduleKind <= 199 /* NodeNext */ || moduleKind === 200 /* Preserve */) { + return false; + } + return getEmitModuleFormatOfFileWorker(sourceFile, options) < 5 /* ES2015 */; +} +function getEmitModuleFormatOfFileWorker(sourceFile, options) { + return getImpliedNodeFormatForEmitWorker(sourceFile, options) ?? getEmitModuleKind(options); +} +function getImpliedNodeFormatForEmitWorker(sourceFile, options) { + var _a, _b; + const moduleKind = getEmitModuleKind(options); + if (100 /* Node16 */ <= moduleKind && moduleKind <= 199 /* NodeNext */) { + return sourceFile.impliedNodeFormat; + } + if (sourceFile.impliedNodeFormat === 1 /* CommonJS */ && (((_a = sourceFile.packageJsonScope) == null ? void 0 : _a.contents.packageJsonContent.type) === "commonjs" || fileExtensionIsOneOf(sourceFile.fileName, [".cjs" /* Cjs */, ".cts" /* Cts */]))) { + return 1 /* CommonJS */; + } + if (sourceFile.impliedNodeFormat === 99 /* ESNext */ && (((_b = sourceFile.packageJsonScope) == null ? void 0 : _b.contents.packageJsonContent.type) === "module" || fileExtensionIsOneOf(sourceFile.fileName, [".mjs" /* Mjs */, ".mts" /* Mts */]))) { + return 99 /* ESNext */; + } + return void 0; +} +function getDefaultResolutionModeForFileWorker(sourceFile, options) { + return importSyntaxAffectsModuleResolution(options) ? getImpliedNodeFormatForEmitWorker(sourceFile, options) : void 0; } function updateHostForUseSourceOfProjectReferenceRedirect(host) { let setOfDeclarationDirectories; @@ -222137,8 +222637,7 @@ var emitSkippedWithNoDiagnostics = { diagnostics: emptyArray, sourceMaps: void 0 function handleNoEmitOptions(program, sourceFile, writeFile2, cancellationToken) { const options = program.getCompilerOptions(); if (options.noEmit) { - program.getSemanticDiagnostics(sourceFile, cancellationToken); - return sourceFile || options.outFile ? emitSkippedWithNoDiagnostics : program.emitBuildInfo(writeFile2, cancellationToken); + return sourceFile ? emitSkippedWithNoDiagnostics : program.emitBuildInfo(writeFile2, cancellationToken); } if (!options.noEmitOnError) return void 0; let diagnostics = [ @@ -222156,7 +222655,7 @@ function handleNoEmitOptions(program, sourceFile, writeFile2, cancellationToken) } if (!diagnostics.length) return void 0; let emittedFiles; - if (!sourceFile && !options.outFile) { + if (!sourceFile) { const emitResult = program.emitBuildInfo(writeFile2, cancellationToken); if (emitResult.diagnostics) diagnostics = [...diagnostics, ...emitResult.diagnostics]; emittedFiles = emitResult.emittedFiles; @@ -222621,20 +223120,30 @@ var BuilderFileEmit = /* @__PURE__ */ ((BuilderFileEmit2) => { BuilderFileEmit2[BuilderFileEmit2["Js"] = 1] = "Js"; BuilderFileEmit2[BuilderFileEmit2["JsMap"] = 2] = "JsMap"; BuilderFileEmit2[BuilderFileEmit2["JsInlineMap"] = 4] = "JsInlineMap"; - BuilderFileEmit2[BuilderFileEmit2["Dts"] = 8] = "Dts"; - BuilderFileEmit2[BuilderFileEmit2["DtsMap"] = 16] = "DtsMap"; + BuilderFileEmit2[BuilderFileEmit2["DtsErrors"] = 8] = "DtsErrors"; + BuilderFileEmit2[BuilderFileEmit2["DtsEmit"] = 16] = "DtsEmit"; + BuilderFileEmit2[BuilderFileEmit2["DtsMap"] = 32] = "DtsMap"; + BuilderFileEmit2[BuilderFileEmit2["Dts"] = 24] = "Dts"; BuilderFileEmit2[BuilderFileEmit2["AllJs"] = 7] = "AllJs"; - BuilderFileEmit2[BuilderFileEmit2["AllDts"] = 24] = "AllDts"; - BuilderFileEmit2[BuilderFileEmit2["All"] = 31] = "All"; + BuilderFileEmit2[BuilderFileEmit2["AllDtsEmit"] = 48] = "AllDtsEmit"; + BuilderFileEmit2[BuilderFileEmit2["AllDts"] = 56] = "AllDts"; + BuilderFileEmit2[BuilderFileEmit2["All"] = 63] = "All"; return BuilderFileEmit2; })(BuilderFileEmit || {}); +function isBuilderProgramStateWithDefinedProgram(state) { + return state.program !== void 0; +} +function toBuilderProgramStateWithDefinedProgram(state) { + Debug.assert(isBuilderProgramStateWithDefinedProgram(state)); + return state; +} function getBuilderFileEmit(options) { let result = 1 /* Js */; if (options.sourceMap) result = result | 2 /* JsMap */; if (options.inlineSourceMap) result = result | 4 /* JsInlineMap */; - if (getEmitDeclarations(options)) result = result | 8 /* Dts */; - if (options.declarationMap) result = result | 16 /* DtsMap */; - if (options.emitDeclarationOnly) result = result & 24 /* AllDts */; + if (getEmitDeclarations(options)) result = result | 24 /* Dts */; + if (options.declarationMap) result = result | 32 /* DtsMap */; + if (options.emitDeclarationOnly) result = result & 56 /* AllDts */; return result; } function getPendingEmitKind(optionsOrEmitKind, oldOptionsOrEmitKind) { @@ -222645,7 +223154,8 @@ function getPendingEmitKind(optionsOrEmitKind, oldOptionsOrEmitKind) { const diff = oldEmitKind ^ emitKind; let result = 0 /* None */; if (diff & 7 /* AllJs */) result = emitKind & 7 /* AllJs */; - if (diff & 24 /* AllDts */) result = result | emitKind & 24 /* AllDts */; + if (diff & 8 /* DtsErrors */) result = result | emitKind & 8 /* DtsErrors */; + if (diff & 48 /* AllDtsEmit */) result = result | emitKind & 48 /* AllDtsEmit */; return result; } function hasSameKeys(map1, map2) { @@ -222663,17 +223173,18 @@ function createBuilderProgramState(newProgram, oldState) { const compilerOptions = newProgram.getCompilerOptions(); state.compilerOptions = compilerOptions; const outFilePath = compilerOptions.outFile; - if (!outFilePath) { - state.semanticDiagnosticsPerFile = /* @__PURE__ */ new Map(); - } else if (compilerOptions.composite && (oldState == null ? void 0 : oldState.outSignature) && outFilePath === oldState.compilerOptions.outFile) { + state.semanticDiagnosticsPerFile = /* @__PURE__ */ new Map(); + if (outFilePath && compilerOptions.composite && (oldState == null ? void 0 : oldState.outSignature) && outFilePath === oldState.compilerOptions.outFile) { state.outSignature = oldState.outSignature && getEmitSignatureFromOldSignature(compilerOptions, oldState.compilerOptions, oldState.outSignature); } state.changedFilesSet = /* @__PURE__ */ new Set(); state.latestChangedDtsFile = compilerOptions.composite ? oldState == null ? void 0 : oldState.latestChangedDtsFile : void 0; + state.checkPending = state.compilerOptions.noCheck ? true : void 0; const useOldState = BuilderState.canReuseOldState(state.referencedMap, oldState); const oldCompilerOptions = useOldState ? oldState.compilerOptions : void 0; - const canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile && !compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldCompilerOptions); + let canCopySemanticDiagnostics = useOldState && !compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldCompilerOptions); const canCopyEmitSignatures = compilerOptions.composite && (oldState == null ? void 0 : oldState.emitSignatures) && !outFilePath && !compilerOptionsAffectDeclarationPath(compilerOptions, oldState.compilerOptions); + let canCopyEmitDiagnostics = true; if (useOldState) { (_a = oldState.changedFilesSet) == null ? void 0 : _a.forEach((value) => state.changedFilesSet.add(value)); if (!outFilePath && ((_b = oldState.affectedFilesPendingEmit) == null ? void 0 : _b.size)) { @@ -222681,8 +223192,13 @@ function createBuilderProgramState(newProgram, oldState) { state.seenAffectedFiles = /* @__PURE__ */ new Set(); } state.programEmitPending = oldState.programEmitPending; + if (outFilePath && state.changedFilesSet.size) { + canCopySemanticDiagnostics = false; + canCopyEmitDiagnostics = false; + } + state.hasErrorsFromOldState = oldState.hasErrors; } else { - state.buildInfoEmitPending = true; + state.buildInfoEmitPending = isIncrementalCompilation(compilerOptions); } const referencedMap = state.referencedMap; const oldReferencedMap = useOldState ? oldState.referencedMap : void 0; @@ -222698,10 +223214,10 @@ function createBuilderProgramState(newProgram, oldState) { oldInfo.impliedFormat !== info.impliedFormat || // Referenced files changed !hasSameKeys(newReferences = referencedMap && referencedMap.getValues(sourceFilePath), oldReferencedMap && oldReferencedMap.getValues(sourceFilePath)) || // Referenced file was deleted in the new program newReferences && forEachKey(newReferences, (path) => !state.fileInfos.has(path) && oldState.fileInfos.has(path))) { - addFileToChangeSet(state, sourceFilePath); + addFileToChangeSet(sourceFilePath); } else { const sourceFile = newProgram.getSourceFileByPath(sourceFilePath); - const emitDiagnostics = (_a2 = oldState.emitDiagnosticsPerFile) == null ? void 0 : _a2.get(sourceFilePath); + const emitDiagnostics = canCopyEmitDiagnostics ? (_a2 = oldState.emitDiagnosticsPerFile) == null ? void 0 : _a2.get(sourceFilePath) : void 0; if (emitDiagnostics) { (state.emitDiagnosticsPerFile ?? (state.emitDiagnosticsPerFile = /* @__PURE__ */ new Map())).set( sourceFilePath, @@ -222730,16 +223246,16 @@ function createBuilderProgramState(newProgram, oldState) { }); if (useOldState && forEachEntry(oldState.fileInfos, (info, sourceFilePath) => { if (state.fileInfos.has(sourceFilePath)) return false; - if (outFilePath || info.affectsGlobalScope) return true; + if (info.affectsGlobalScope) return true; state.buildInfoEmitPending = true; - return false; + return !!outFilePath; })) { BuilderState.getAllFilesExcludingDefaultLibraryFile( state, newProgram, /*firstSourceFile*/ void 0 - ).forEach((file) => addFileToChangeSet(state, file.resolvedPath)); + ).forEach((file) => addFileToChangeSet(file.resolvedPath)); } else if (oldCompilerOptions) { const pendingEmitKind = compilerOptionsAffectEmit(compilerOptions, oldCompilerOptions) ? getBuilderFileEmit(compilerOptions) : getPendingEmitKind(compilerOptions, oldCompilerOptions); if (pendingEmitKind !== 0 /* None */) { @@ -222755,18 +223271,26 @@ function createBuilderProgramState(newProgram, oldState) { }); Debug.assert(!state.seenAffectedFiles || !state.seenAffectedFiles.size); state.seenAffectedFiles = state.seenAffectedFiles || /* @__PURE__ */ new Set(); - state.buildInfoEmitPending = true; - } else { + } else if (!state.changedFilesSet.size) { state.programEmitPending = state.programEmitPending ? state.programEmitPending | pendingEmitKind : pendingEmitKind; } + state.buildInfoEmitPending = true; } } + if (useOldState && state.semanticDiagnosticsPerFile.size !== state.fileInfos.size && oldState.checkPending !== state.checkPending) state.buildInfoEmitPending = true; return state; -} -function addFileToChangeSet(state, path) { - state.changedFilesSet.add(path); - state.buildInfoEmitPending = true; - state.programEmitPending = void 0; + function addFileToChangeSet(path) { + state.changedFilesSet.add(path); + if (outFilePath) { + canCopySemanticDiagnostics = false; + canCopyEmitDiagnostics = false; + state.semanticDiagnosticsFromOldState = void 0; + state.semanticDiagnosticsPerFile.clear(); + state.emitDiagnosticsPerFile = void 0; + } + state.buildInfoEmitPending = true; + state.programEmitPending = void 0; + } } function getEmitSignatureFromOldSignature(options, oldOptions, oldEmitSignature) { return !!options.declarationMap === !!oldOptions.declarationMap ? ( @@ -222790,7 +223314,12 @@ function repopulateDiagnostics(diagnostics, newProgram) { } function convertOrRepopulateDiagnosticMessageChain(chain, sourceFile, newProgram, repopulateInfo) { const info = repopulateInfo(chain); - if (info) { + if (info === true) { + return { + ...createModeMismatchDetails(sourceFile), + next: convertOrRepopulateDiagnosticMessageChainArray(chain.next, sourceFile, newProgram, repopulateInfo) + }; + } else if (info) { return { ...createModuleNotFoundChain(sourceFile, newProgram, info.moduleReference, info.mode, info.packageName || info.moduleReference), next: convertOrRepopulateDiagnosticMessageChainArray(chain.next, sourceFile, newProgram, repopulateInfo) @@ -222833,34 +223362,6 @@ function releaseCache(state) { BuilderState.releaseCache(state); state.program = void 0; } -function backupBuilderProgramEmitState(state) { - const outFilePath = state.compilerOptions.outFile; - Debug.assert(!state.changedFilesSet.size || outFilePath); - return { - affectedFilesPendingEmit: state.affectedFilesPendingEmit && new Map(state.affectedFilesPendingEmit), - seenEmittedFiles: state.seenEmittedFiles && new Map(state.seenEmittedFiles), - programEmitPending: state.programEmitPending, - emitSignatures: state.emitSignatures && new Map(state.emitSignatures), - outSignature: state.outSignature, - latestChangedDtsFile: state.latestChangedDtsFile, - hasChangedEmitSignature: state.hasChangedEmitSignature, - changedFilesSet: outFilePath ? new Set(state.changedFilesSet) : void 0, - buildInfoEmitPending: state.buildInfoEmitPending, - emitDiagnosticsPerFile: state.emitDiagnosticsPerFile && new Map(state.emitDiagnosticsPerFile) - }; -} -function restoreBuilderProgramEmitState(state, savedEmitState) { - state.affectedFilesPendingEmit = savedEmitState.affectedFilesPendingEmit; - state.seenEmittedFiles = savedEmitState.seenEmittedFiles; - state.programEmitPending = savedEmitState.programEmitPending; - state.emitSignatures = savedEmitState.emitSignatures; - state.outSignature = savedEmitState.outSignature; - state.latestChangedDtsFile = savedEmitState.latestChangedDtsFile; - state.hasChangedEmitSignature = savedEmitState.hasChangedEmitSignature; - state.buildInfoEmitPending = savedEmitState.buildInfoEmitPending; - state.emitDiagnosticsPerFile = savedEmitState.emitDiagnosticsPerFile; - if (savedEmitState.changedFilesSet) state.changedFilesSet = savedEmitState.changedFilesSet; -} function assertSourceFileOkWithoutNextAffectedCall(state, sourceFile) { Debug.assert(!sourceFile || !state.affectedFiles || state.affectedFiles[state.affectedFilesIndex - 1] !== sourceFile || !state.semanticDiagnosticsPerFile.has(sourceFile.resolvedPath)); } @@ -222875,7 +223376,11 @@ function getNextAffectedFile(state, cancellationToken, host) { const affectedFile = affectedFiles[affectedFilesIndex]; if (!seenAffectedFiles.has(affectedFile.resolvedPath)) { state.affectedFilesIndex = affectedFilesIndex; - addToAffectedFilesPendingEmit(state, affectedFile.resolvedPath, getBuilderFileEmit(state.compilerOptions)); + addToAffectedFilesPendingEmit( + state, + affectedFile.resolvedPath, + getBuilderFileEmit(state.compilerOptions) + ); handleDtsMayChangeOfAffectedFile( state, affectedFile, @@ -222895,15 +223400,11 @@ function getNextAffectedFile(state, cancellationToken, host) { if (nextKey.done) { return void 0; } - const program = Debug.checkDefined(state.program); - const compilerOptions = program.getCompilerOptions(); - if (compilerOptions.outFile) { - Debug.assert(!state.semanticDiagnosticsPerFile); - return program; - } + const compilerOptions = state.program.getCompilerOptions(); + if (compilerOptions.outFile) return state.program; state.affectedFiles = BuilderState.getFilesAffectedByWithOldState( state, - program, + state.program, nextKey.value, cancellationToken, host @@ -222913,17 +223414,34 @@ function getNextAffectedFile(state, cancellationToken, host) { if (!state.seenAffectedFiles) state.seenAffectedFiles = /* @__PURE__ */ new Set(); } } -function clearAffectedFilesPendingEmit(state, emitOnlyDtsFiles) { - var _a; - if (!((_a = state.affectedFilesPendingEmit) == null ? void 0 : _a.size)) return; - if (!emitOnlyDtsFiles) return state.affectedFilesPendingEmit = void 0; - state.affectedFilesPendingEmit.forEach((emitKind, path) => { - const pending = emitKind & 7 /* AllJs */; +function clearAffectedFilesPendingEmit(state, emitOnlyDtsFiles, isForDtsErrors) { + var _a, _b; + if (!((_a = state.affectedFilesPendingEmit) == null ? void 0 : _a.size) && !state.programEmitPending) return; + if (!emitOnlyDtsFiles && !isForDtsErrors) { + state.affectedFilesPendingEmit = void 0; + state.programEmitPending = void 0; + } + (_b = state.affectedFilesPendingEmit) == null ? void 0 : _b.forEach((emitKind, path) => { + const pending = !isForDtsErrors ? emitKind & 7 /* AllJs */ : emitKind & (7 /* AllJs */ | 48 /* AllDtsEmit */); if (!pending) state.affectedFilesPendingEmit.delete(path); else state.affectedFilesPendingEmit.set(path, pending); }); + if (state.programEmitPending) { + const pending = !isForDtsErrors ? state.programEmitPending & 7 /* AllJs */ : state.programEmitPending & (7 /* AllJs */ | 48 /* AllDtsEmit */); + if (!pending) state.programEmitPending = void 0; + else state.programEmitPending = pending; + } +} +function getPendingEmitKindWithSeen(optionsOrEmitKind, seenOldOptionsOrEmitKind, emitOnlyDtsFiles, isForDtsErrors) { + let pendingKind = getPendingEmitKind(optionsOrEmitKind, seenOldOptionsOrEmitKind); + if (emitOnlyDtsFiles) pendingKind = pendingKind & 56 /* AllDts */; + if (isForDtsErrors) pendingKind = pendingKind & 8 /* DtsErrors */; + return pendingKind; +} +function getBuilderFileEmitAllDts(isForDtsErrors) { + return !isForDtsErrors ? 56 /* AllDts */ : 8 /* DtsErrors */; } -function getNextAffectedFilePendingEmit(state, emitOnlyDtsFiles) { +function getNextAffectedFilePendingEmit(state, emitOnlyDtsFiles, isForDtsErrors) { var _a; if (!((_a = state.affectedFilesPendingEmit) == null ? void 0 : _a.size)) return void 0; return forEachEntry(state.affectedFilesPendingEmit, (emitKind, path) => { @@ -222934,12 +223452,16 @@ function getNextAffectedFilePendingEmit(state, emitOnlyDtsFiles) { return void 0; } const seenKind = (_a2 = state.seenEmittedFiles) == null ? void 0 : _a2.get(affectedFile.resolvedPath); - let pendingKind = getPendingEmitKind(emitKind, seenKind); - if (emitOnlyDtsFiles) pendingKind = pendingKind & 24 /* AllDts */; + const pendingKind = getPendingEmitKindWithSeen( + emitKind, + seenKind, + emitOnlyDtsFiles, + isForDtsErrors + ); if (pendingKind) return { affectedFile, emitKind: pendingKind }; }); } -function getNextPendingEmitDiagnosticsFile(state) { +function getNextPendingEmitDiagnosticsFile(state, isForDtsErrors) { var _a; if (!((_a = state.emitDiagnosticsPerFile) == null ? void 0 : _a.size)) return void 0; return forEachEntry(state.emitDiagnosticsPerFile, (diagnostics, path) => { @@ -222950,15 +223472,14 @@ function getNextPendingEmitDiagnosticsFile(state) { return void 0; } const seenKind = ((_a2 = state.seenEmittedFiles) == null ? void 0 : _a2.get(affectedFile.resolvedPath)) || 0 /* None */; - if (!(seenKind & 24 /* AllDts */)) return { affectedFile, diagnostics, seenKind }; + if (!(seenKind & getBuilderFileEmitAllDts(isForDtsErrors))) return { affectedFile, diagnostics, seenKind }; }); } function removeDiagnosticsOfLibraryFiles(state) { if (!state.cleanedDiagnosticsOfLibFiles) { state.cleanedDiagnosticsOfLibFiles = true; - const program = Debug.checkDefined(state.program); - const options = program.getCompilerOptions(); - forEach(program.getSourceFiles(), (f) => program.isSourceFileDefaultLibrary(f) && !skipTypeChecking(f, options, program) && removeSemanticDiagnosticsOf(state, f.resolvedPath)); + const options = state.program.getCompilerOptions(); + forEach(state.program.getSourceFiles(), (f) => state.program.isSourceFileDefaultLibrary(f) && !skipTypeCheckingIgnoringNoCheck(f, options, state.program) && removeSemanticDiagnosticsOf(state, f.resolvedPath)); } } function handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, host) { @@ -222967,7 +223488,7 @@ function handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken removeDiagnosticsOfLibraryFiles(state); BuilderState.updateShapeSignature( state, - Debug.checkDefined(state.program), + state.program, affectedFile, cancellationToken, host @@ -222985,12 +223506,11 @@ function handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken function handleDtsMayChangeOf(state, path, invalidateJsFiles, cancellationToken, host) { removeSemanticDiagnosticsOf(state, path); if (!state.changedFilesSet.has(path)) { - const program = Debug.checkDefined(state.program); - const sourceFile = program.getSourceFileByPath(path); + const sourceFile = state.program.getSourceFileByPath(path); if (sourceFile) { BuilderState.updateShapeSignature( state, - program, + state.program, sourceFile, cancellationToken, host, @@ -222998,9 +223518,17 @@ function handleDtsMayChangeOf(state, path, invalidateJsFiles, cancellationToken, true ); if (invalidateJsFiles) { - addToAffectedFilesPendingEmit(state, path, getBuilderFileEmit(state.compilerOptions)); + addToAffectedFilesPendingEmit( + state, + path, + getBuilderFileEmit(state.compilerOptions) + ); } else if (getEmitDeclarations(state.compilerOptions)) { - addToAffectedFilesPendingEmit(state, path, state.compilerOptions.declarationMap ? 24 /* AllDts */ : 8 /* Dts */); + addToAffectedFilesPendingEmit( + state, + path, + state.compilerOptions.declarationMap ? 56 /* AllDts */ : 24 /* Dts */ + ); } } } @@ -223067,7 +223595,7 @@ function handleDtsMayChangeOfReferencingExportOfAffectedFile(state, affectedFile host ); if (isChangedSignature(state, currentPath)) { - const currentSourceFile = Debug.checkDefined(state.program).getSourceFileByPath(currentPath); + const currentSourceFile = state.program.getSourceFileByPath(currentPath); queue.push(...BuilderState.getReferencedByPaths(state, currentSourceFile.resolvedPath)); } } @@ -223113,38 +223641,79 @@ function handleDtsMayChangeOfFileAndExportsOfFile(state, filePath, invalidateJsF ); return void 0; } -function getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken) { +function getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken, semanticDiagnosticsPerFile) { + if (state.compilerOptions.noCheck) return emptyArray; return concatenate( - getBinderAndCheckerDiagnosticsOfFile(state, sourceFile, cancellationToken), - Debug.checkDefined(state.program).getProgramDiagnostics(sourceFile) + getBinderAndCheckerDiagnosticsOfFile(state, sourceFile, cancellationToken, semanticDiagnosticsPerFile), + state.program.getProgramDiagnostics(sourceFile) ); } -function getBinderAndCheckerDiagnosticsOfFile(state, sourceFile, cancellationToken) { +function getBinderAndCheckerDiagnosticsOfFile(state, sourceFile, cancellationToken, semanticDiagnosticsPerFile) { + semanticDiagnosticsPerFile ?? (semanticDiagnosticsPerFile = state.semanticDiagnosticsPerFile); const path = sourceFile.resolvedPath; - if (state.semanticDiagnosticsPerFile) { - const cachedDiagnostics = state.semanticDiagnosticsPerFile.get(path); - if (cachedDiagnostics) { - return filterSemanticDiagnostics(cachedDiagnostics, state.compilerOptions); - } - } - const diagnostics = Debug.checkDefined(state.program).getBindAndCheckDiagnostics(sourceFile, cancellationToken); - if (state.semanticDiagnosticsPerFile) { - state.semanticDiagnosticsPerFile.set(path, diagnostics); + const cachedDiagnostics = semanticDiagnosticsPerFile.get(path); + if (cachedDiagnostics) { + return filterSemanticDiagnostics(cachedDiagnostics, state.compilerOptions); } + const diagnostics = state.program.getBindAndCheckDiagnostics(sourceFile, cancellationToken); + semanticDiagnosticsPerFile.set(path, diagnostics); + state.buildInfoEmitPending = true; return filterSemanticDiagnostics(diagnostics, state.compilerOptions); } -function isProgramBundleEmitBuildInfo(info) { +function isIncrementalBundleEmitBuildInfo(info) { var _a; return !!((_a = info.options) == null ? void 0 : _a.outFile); } +function isIncrementalBuildInfo(info) { + return !!info.fileNames; +} +function isNonIncrementalBuildInfo(info) { + return !isIncrementalBuildInfo(info) && !!info.root; +} +function ensureHasErrorsForState(state) { + if (state.hasErrors !== void 0) return; + if (isIncrementalCompilation(state.compilerOptions)) { + state.hasErrors = !some(state.program.getSourceFiles(), (f) => { + var _a, _b; + const bindAndCheckDiagnostics = state.semanticDiagnosticsPerFile.get(f.resolvedPath); + return bindAndCheckDiagnostics === void 0 || // Missing semantic diagnostics in cache will be encoded in buildInfo + !!bindAndCheckDiagnostics.length || // cached semantic diagnostics will be encoded in buildInfo + !!((_b = (_a = state.emitDiagnosticsPerFile) == null ? void 0 : _a.get(f.resolvedPath)) == null ? void 0 : _b.length); + }) && (hasSyntaxOrGlobalErrors(state) || some(state.program.getSourceFiles(), (f) => !!state.program.getProgramDiagnostics(f).length)); + } else { + state.hasErrors = some(state.program.getSourceFiles(), (f) => { + var _a, _b; + const bindAndCheckDiagnostics = state.semanticDiagnosticsPerFile.get(f.resolvedPath); + return !!(bindAndCheckDiagnostics == null ? void 0 : bindAndCheckDiagnostics.length) || // If has semantic diagnostics + !!((_b = (_a = state.emitDiagnosticsPerFile) == null ? void 0 : _a.get(f.resolvedPath)) == null ? void 0 : _b.length); + }) || hasSyntaxOrGlobalErrors(state); + } +} +function hasSyntaxOrGlobalErrors(state) { + return !!state.program.getConfigFileParsingDiagnostics().length || !!state.program.getSyntacticDiagnostics().length || !!state.program.getOptionsDiagnostics().length || !!state.program.getGlobalDiagnostics().length; +} +function getBuildInfoEmitPending(state) { + ensureHasErrorsForState(state); + return state.buildInfoEmitPending ?? (state.buildInfoEmitPending = !!state.hasErrorsFromOldState !== !!state.hasErrors); +} function getBuildInfo2(state) { var _a, _b; - const currentDirectory = Debug.checkDefined(state.program).getCurrentDirectory(); + const currentDirectory = state.program.getCurrentDirectory(); const buildInfoDirectory = getDirectoryPath(getNormalizedAbsolutePath(getTsBuildInfoEmitOutputFilePath(state.compilerOptions), currentDirectory)); const latestChangedDtsFile = state.latestChangedDtsFile ? relativeToBuildInfoEnsuringAbsolutePath(state.latestChangedDtsFile) : void 0; const fileNames = []; const fileNameToFileId = /* @__PURE__ */ new Map(); const rootFileNames = new Set(state.program.getRootFileNames().map((f) => toPath(f, currentDirectory, state.program.getCanonicalFileName))); + ensureHasErrorsForState(state); + if (!isIncrementalCompilation(state.compilerOptions)) { + const buildInfo2 = { + root: arrayFrom(rootFileNames, (r) => relativeToBuildInfo(r)), + errors: state.hasErrors ? true : void 0, + checkPending: state.checkPending, + version + }; + return buildInfo2; + } const root = []; if (state.compilerOptions.outFile) { const fileInfos2 = arrayFrom(state.fileInfos.entries(), ([key, value]) => { @@ -223152,12 +223721,15 @@ function getBuildInfo2(state) { tryAddRoot(key, fileId); return value.impliedFormat ? { version: value.version, impliedFormat: value.impliedFormat, signature: void 0, affectsGlobalScope: void 0 } : value.version; }); - const program2 = { + const buildInfo2 = { fileNames, fileInfos: fileInfos2, root, resolvedRoot: toResolvedRoot(), - options: convertToProgramBuildInfoCompilerOptions(state.compilerOptions), + options: toIncrementalBuildInfoCompilerOptions(state.compilerOptions), + semanticDiagnosticsPerFile: !state.changedFilesSet.size ? toIncrementalBuildInfoDiagnostics() : void 0, + emitDiagnosticsPerFile: toIncrementalBuildInfoEmitDiagnostics(), + changeFileSet: toChangeFileSet(), outSignature: state.outSignature, latestChangedDtsFile, pendingEmit: !state.programEmitPending ? void 0 : ( @@ -223166,10 +223738,13 @@ function getBuildInfo2(state) { // Pending emit is same as deteremined by compilerOptions state.programEmitPending ) - ) + ), // Actual value + errors: state.hasErrors ? true : void 0, + checkPending: state.checkPending, + version }; - return createBuildInfo(program2); + return buildInfo2; } let fileIdsList; let fileNamesToFileIdListId; @@ -223224,7 +223799,7 @@ function getBuildInfo2(state) { toFileIdListId(state.referencedMap.getValues(key)) ]); } - const semanticDiagnosticsPerFile = convertToProgramBuildInfoDiagnostics(); + const semanticDiagnosticsPerFile = toIncrementalBuildInfoDiagnostics(); let affectedFilesPendingEmit; if ((_b = state.affectedFilesPendingEmit) == null ? void 0 : _b.size) { const fullEmitForOptions = getBuilderFileEmit(state.compilerOptions); @@ -223238,7 +223813,7 @@ function getBuildInfo2(state) { affectedFilesPendingEmit, pendingEmit === fullEmitForOptions ? fileId : ( // Pending full emit per options - pendingEmit === 8 /* Dts */ ? [fileId] : ( + pendingEmit === 24 /* Dts */ ? [fileId] : ( // Pending on Dts only [fileId, pendingEmit] ) @@ -223248,29 +223823,25 @@ function getBuildInfo2(state) { } } } - let changeFileSet; - if (state.changedFilesSet.size) { - for (const path of arrayFrom(state.changedFilesSet.keys()).sort(compareStringsCaseSensitive)) { - changeFileSet = append(changeFileSet, toFileId(path)); - } - } - const emitDiagnosticsPerFile = convertToProgramBuildInfoEmitDiagnostics(); - const program = { + const buildInfo = { fileNames, + fileIdsList, fileInfos, root, resolvedRoot: toResolvedRoot(), - options: convertToProgramBuildInfoCompilerOptions(state.compilerOptions), - fileIdsList, + options: toIncrementalBuildInfoCompilerOptions(state.compilerOptions), referencedMap, semanticDiagnosticsPerFile, - emitDiagnosticsPerFile, + emitDiagnosticsPerFile: toIncrementalBuildInfoEmitDiagnostics(), + changeFileSet: toChangeFileSet(), affectedFilesPendingEmit, - changeFileSet, emitSignatures, - latestChangedDtsFile + latestChangedDtsFile, + errors: state.hasErrors ? true : void 0, + checkPending: state.checkPending, + version }; - return createBuildInfo(program); + return buildInfo; function relativeToBuildInfoEnsuringAbsolutePath(path) { return relativeToBuildInfo(getNormalizedAbsolutePath(path, currentDirectory)); } @@ -223318,13 +223889,13 @@ function getBuildInfo2(state) { }); return result; } - function convertToProgramBuildInfoCompilerOptions(options) { + function toIncrementalBuildInfoCompilerOptions(options) { let result; const { optionsNameMap } = getOptionsNameMap(); for (const name of getOwnKeys(options).sort(compareStringsCaseSensitive)) { const optionInfo = optionsNameMap.get(name.toLowerCase()); if (optionInfo == null ? void 0 : optionInfo.affectsBuildInfo) { - (result || (result = {}))[name] = convertToReusableCompilerOptionValue( + (result || (result = {}))[name] = toReusableCompilerOptionValue( optionInfo, options[name] ); @@ -223332,7 +223903,7 @@ function getBuildInfo2(state) { } return result; } - function convertToReusableCompilerOptionValue(option, value) { + function toReusableCompilerOptionValue(option, value) { if (option) { Debug.assert(option.type !== "listOrElement"); if (option.type === "list") { @@ -223346,23 +223917,22 @@ function getBuildInfo2(state) { } return value; } - function convertToProgramBuildInfoDiagnostics() { + function toIncrementalBuildInfoDiagnostics() { let result; state.fileInfos.forEach((_value, key) => { - var _a2; - const value = (_a2 = state.semanticDiagnosticsPerFile) == null ? void 0 : _a2.get(key); + const value = state.semanticDiagnosticsPerFile.get(key); if (!value) { if (!state.changedFilesSet.has(key)) result = append(result, toFileId(key)); } else if (value.length) { result = append(result, [ toFileId(key), - convertToReusableDiagnostics(value, key) + toReusableDiagnostic(value, key) ]); } }); return result; } - function convertToProgramBuildInfoEmitDiagnostics() { + function toIncrementalBuildInfoEmitDiagnostics() { var _a2; let result; if (!((_a2 = state.emitDiagnosticsPerFile) == null ? void 0 : _a2.size)) return result; @@ -223370,55 +223940,64 @@ function getBuildInfo2(state) { const value = state.emitDiagnosticsPerFile.get(key); result = append(result, [ toFileId(key), - convertToReusableDiagnostics(value, key) + toReusableDiagnostic(value, key) ]); } return result; } - function convertToReusableDiagnostics(diagnostics, diagnosticFilePath) { + function toReusableDiagnostic(diagnostics, diagnosticFilePath) { Debug.assert(!!diagnostics.length); return diagnostics.map((diagnostic) => { - const result = convertToReusableDiagnosticRelatedInformation(diagnostic, diagnosticFilePath); + const result = toReusableDiagnosticRelatedInformation(diagnostic, diagnosticFilePath); result.reportsUnnecessary = diagnostic.reportsUnnecessary; result.reportDeprecated = diagnostic.reportsDeprecated; result.source = diagnostic.source; result.skippedOn = diagnostic.skippedOn; const { relatedInformation } = diagnostic; - result.relatedInformation = relatedInformation ? relatedInformation.length ? relatedInformation.map((r) => convertToReusableDiagnosticRelatedInformation(r, diagnosticFilePath)) : [] : void 0; + result.relatedInformation = relatedInformation ? relatedInformation.length ? relatedInformation.map((r) => toReusableDiagnosticRelatedInformation(r, diagnosticFilePath)) : [] : void 0; return result; }); } - function convertToReusableDiagnosticRelatedInformation(diagnostic, diagnosticFilePath) { + function toReusableDiagnosticRelatedInformation(diagnostic, diagnosticFilePath) { const { file } = diagnostic; return { ...diagnostic, file: file ? file.resolvedPath === diagnosticFilePath ? void 0 : relativeToBuildInfo(file.resolvedPath) : false, - messageText: isString(diagnostic.messageText) ? diagnostic.messageText : convertToReusableDiagnosticMessageChain(diagnostic.messageText) + messageText: isString(diagnostic.messageText) ? diagnostic.messageText : toReusableDiagnosticMessageChain(diagnostic.messageText) }; } - function convertToReusableDiagnosticMessageChain(chain) { + function toReusableDiagnosticMessageChain(chain) { if (chain.repopulateInfo) { return { info: chain.repopulateInfo(), - next: convertToReusableDiagnosticMessageChainArray(chain.next) + next: toReusableDiagnosticMessageChainArray(chain.next) }; } - const next = convertToReusableDiagnosticMessageChainArray(chain.next); + const next = toReusableDiagnosticMessageChainArray(chain.next); return next === chain.next ? chain : { ...chain, next }; } - function convertToReusableDiagnosticMessageChainArray(array) { + function toReusableDiagnosticMessageChainArray(array) { if (!array) return array; return forEach(array, (chain, index) => { - const reusable = convertToReusableDiagnosticMessageChain(chain); + const reusable = toReusableDiagnosticMessageChain(chain); if (chain === reusable) return void 0; const result = index > 0 ? array.slice(0, index - 1) : []; result.push(reusable); for (let i = index + 1; i < array.length; i++) { - result.push(convertToReusableDiagnosticMessageChain(array[i])); + result.push(toReusableDiagnosticMessageChain(array[i])); } return result; }) || array; } + function toChangeFileSet() { + let changeFileSet; + if (state.changedFilesSet.size) { + for (const path of arrayFrom(state.changedFilesSet.keys()).sort(compareStringsCaseSensitive)) { + changeFileSet = append(changeFileSet, toFileId(path)); + } + } + return changeFileSet; + } } var BuilderProgramKind = /* @__PURE__ */ ((BuilderProgramKind2) => { BuilderProgramKind2[BuilderProgramKind2["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram"; @@ -223482,25 +224061,27 @@ function computeSignature(text, host, data) { return (host.createHash ?? generateDjb2Hash)(getTextHandlingSourceMapForSignature(text, data)); } function createBuilderProgram(kind, { newProgram, host, oldProgram, configFileParsingDiagnostics }) { - let oldState = oldProgram && oldProgram.getState(); + let oldState = oldProgram && oldProgram.state; if (oldState && newProgram === oldState.program && configFileParsingDiagnostics === newProgram.getConfigFileParsingDiagnostics()) { newProgram = void 0; oldState = void 0; return oldProgram; } const state = createBuilderProgramState(newProgram, oldState); - newProgram.getBuildInfo = () => getBuildInfo2(state); + newProgram.getBuildInfo = () => getBuildInfo2(toBuilderProgramStateWithDefinedProgram(state)); newProgram = void 0; oldProgram = void 0; oldState = void 0; - const getState = () => state; - const builderProgram = createRedirectedBuilderProgram(getState, configFileParsingDiagnostics); - builderProgram.getState = getState; - builderProgram.saveEmitState = () => backupBuilderProgramEmitState(state); - builderProgram.restoreEmitState = (saved) => restoreBuilderProgramEmitState(state, saved); + const builderProgram = createRedirectedBuilderProgram(state, configFileParsingDiagnostics); + builderProgram.state = state; builderProgram.hasChangedEmitSignature = () => !!state.hasChangedEmitSignature; - builderProgram.getAllDependencies = (sourceFile) => BuilderState.getAllDependencies(state, Debug.checkDefined(state.program), sourceFile); + builderProgram.getAllDependencies = (sourceFile) => BuilderState.getAllDependencies( + state, + Debug.checkDefined(state.program), + sourceFile + ); builderProgram.getSemanticDiagnostics = getSemanticDiagnostics; + builderProgram.getDeclarationDiagnostics = getDeclarationDiagnostics2; builderProgram.emit = emit; builderProgram.releaseProgram = () => releaseCache(state); if (kind === 0 /* SemanticDiagnosticsBuilderProgram */) { @@ -223514,76 +224095,145 @@ function createBuilderProgram(kind, { newProgram, host, oldProgram, configFilePa } return builderProgram; function emitBuildInfo(writeFile2, cancellationToken) { - if (state.buildInfoEmitPending) { - const result = Debug.checkDefined(state.program).emitBuildInfo(writeFile2 || maybeBind(host, host.writeFile), cancellationToken); + Debug.assert(isBuilderProgramStateWithDefinedProgram(state)); + if (getBuildInfoEmitPending(state)) { + const result = state.program.emitBuildInfo( + writeFile2 || maybeBind(host, host.writeFile), + cancellationToken + ); state.buildInfoEmitPending = false; return result; } return emitSkippedWithNoDiagnostics; } - function emitNextAffectedFile(writeFile2, cancellationToken, emitOnlyDtsFiles, customTransformers) { - var _a, _b, _c; + function emitNextAffectedFileOrDtsErrors(writeFile2, cancellationToken, emitOnlyDtsFiles, customTransformers, isForDtsErrors) { + var _a, _b, _c, _d; + Debug.assert(isBuilderProgramStateWithDefinedProgram(state)); let affected = getNextAffectedFile(state, cancellationToken, host); const programEmitKind = getBuilderFileEmit(state.compilerOptions); - let emitKind = emitOnlyDtsFiles ? programEmitKind & 24 /* AllDts */ : programEmitKind; + let emitKind = !isForDtsErrors ? emitOnlyDtsFiles ? programEmitKind & 56 /* AllDts */ : programEmitKind : 8 /* DtsErrors */; if (!affected) { if (!state.compilerOptions.outFile) { - const pendingAffectedFile = getNextAffectedFilePendingEmit(state, emitOnlyDtsFiles); - if (!pendingAffectedFile) { - const pendingForDiagnostics = getNextPendingEmitDiagnosticsFile(state); + const pendingAffectedFile = getNextAffectedFilePendingEmit( + state, + emitOnlyDtsFiles, + isForDtsErrors + ); + if (pendingAffectedFile) { + ({ affectedFile: affected, emitKind } = pendingAffectedFile); + } else { + const pendingForDiagnostics = getNextPendingEmitDiagnosticsFile( + state, + isForDtsErrors + ); if (pendingForDiagnostics) { - (state.seenEmittedFiles ?? (state.seenEmittedFiles = /* @__PURE__ */ new Map())).set(pendingForDiagnostics.affectedFile.resolvedPath, pendingForDiagnostics.seenKind | 24 /* AllDts */); + (state.seenEmittedFiles ?? (state.seenEmittedFiles = /* @__PURE__ */ new Map())).set( + pendingForDiagnostics.affectedFile.resolvedPath, + pendingForDiagnostics.seenKind | getBuilderFileEmitAllDts(isForDtsErrors) + ); return { result: { emitSkipped: true, diagnostics: pendingForDiagnostics.diagnostics }, affected: pendingForDiagnostics.affectedFile }; } - if (!state.buildInfoEmitPending) return void 0; - const affected2 = state.program; - const result2 = affected2.emitBuildInfo(writeFile2 || maybeBind(host, host.writeFile), cancellationToken); - state.buildInfoEmitPending = false; - return { result: result2, affected: affected2 }; } - ({ affectedFile: affected, emitKind } = pendingAffectedFile); } else { - if (!state.programEmitPending) return void 0; - emitKind = state.programEmitPending; - if (emitOnlyDtsFiles) emitKind = emitKind & 24 /* AllDts */; - if (!emitKind) return void 0; - affected = state.program; + if (state.programEmitPending) { + emitKind = getPendingEmitKindWithSeen( + state.programEmitPending, + state.seenProgramEmit, + emitOnlyDtsFiles, + isForDtsErrors + ); + if (emitKind) affected = state.program; + } + if (!affected && ((_a = state.emitDiagnosticsPerFile) == null ? void 0 : _a.size)) { + const seenKind = state.seenProgramEmit || 0 /* None */; + if (!(seenKind & getBuilderFileEmitAllDts(isForDtsErrors))) { + state.seenProgramEmit = getBuilderFileEmitAllDts(isForDtsErrors) | seenKind; + const diagnostics = []; + state.emitDiagnosticsPerFile.forEach((d) => addRange(diagnostics, d)); + return { + result: { emitSkipped: true, diagnostics }, + affected: state.program + }; + } + } + } + if (!affected) { + if (isForDtsErrors || !getBuildInfoEmitPending(state)) return void 0; + const affected2 = state.program; + const result2 = affected2.emitBuildInfo( + writeFile2 || maybeBind(host, host.writeFile), + cancellationToken + ); + state.buildInfoEmitPending = false; + return { result: result2, affected: affected2 }; } } let emitOnly; if (emitKind & 7 /* AllJs */) emitOnly = 0 /* Js */; - if (emitKind & 24 /* AllDts */) emitOnly = emitOnly === void 0 ? 1 /* Dts */ : void 0; - if (affected === state.program) { - state.programEmitPending = state.changedFilesSet.size ? getPendingEmitKind(programEmitKind, emitKind) : state.programEmitPending ? getPendingEmitKind(state.programEmitPending, emitKind) : void 0; - } - const result = state.program.emit( + if (emitKind & 56 /* AllDts */) emitOnly = emitOnly === void 0 ? 1 /* Dts */ : void 0; + const result = !isForDtsErrors ? state.program.emit( affected === state.program ? void 0 : affected, getWriteFileCallback(writeFile2, customTransformers), cancellationToken, emitOnly, - customTransformers - ); + customTransformers, + /*forceDtsEmit*/ + void 0, + /*skipBuildInfo*/ + true + ) : { + emitSkipped: true, + diagnostics: state.program.getDeclarationDiagnostics( + affected === state.program ? void 0 : affected, + cancellationToken + ) + }; if (affected !== state.program) { const affectedSourceFile = affected; state.seenAffectedFiles.add(affectedSourceFile.resolvedPath); if (state.affectedFilesIndex !== void 0) state.affectedFilesIndex++; state.buildInfoEmitPending = true; - const existing = ((_a = state.seenEmittedFiles) == null ? void 0 : _a.get(affectedSourceFile.resolvedPath)) || 0 /* None */; + const existing = ((_b = state.seenEmittedFiles) == null ? void 0 : _b.get(affectedSourceFile.resolvedPath)) || 0 /* None */; (state.seenEmittedFiles ?? (state.seenEmittedFiles = /* @__PURE__ */ new Map())).set(affectedSourceFile.resolvedPath, emitKind | existing); - const existingPending = ((_b = state.affectedFilesPendingEmit) == null ? void 0 : _b.get(affectedSourceFile.resolvedPath)) || programEmitKind; + const existingPending = ((_c = state.affectedFilesPendingEmit) == null ? void 0 : _c.get(affectedSourceFile.resolvedPath)) || programEmitKind; const pendingKind = getPendingEmitKind(existingPending, emitKind | existing); if (pendingKind) (state.affectedFilesPendingEmit ?? (state.affectedFilesPendingEmit = /* @__PURE__ */ new Map())).set(affectedSourceFile.resolvedPath, pendingKind); - else (_c = state.affectedFilesPendingEmit) == null ? void 0 : _c.delete(affectedSourceFile.resolvedPath); + else (_d = state.affectedFilesPendingEmit) == null ? void 0 : _d.delete(affectedSourceFile.resolvedPath); if (result.diagnostics.length) (state.emitDiagnosticsPerFile ?? (state.emitDiagnosticsPerFile = /* @__PURE__ */ new Map())).set(affectedSourceFile.resolvedPath, result.diagnostics); } else { state.changedFilesSet.clear(); + state.programEmitPending = state.changedFilesSet.size ? getPendingEmitKind(programEmitKind, emitKind) : state.programEmitPending ? getPendingEmitKind(state.programEmitPending, emitKind) : void 0; + state.seenProgramEmit = emitKind | (state.seenProgramEmit || 0 /* None */); + setEmitDiagnosticsPerFile(result.diagnostics); + state.buildInfoEmitPending = true; } return { result, affected }; } + function setEmitDiagnosticsPerFile(diagnostics) { + let emitDiagnosticsPerFile; + diagnostics.forEach((d) => { + if (!d.file) return; + let diagnostics2 = emitDiagnosticsPerFile == null ? void 0 : emitDiagnosticsPerFile.get(d.file.resolvedPath); + if (!diagnostics2) (emitDiagnosticsPerFile ?? (emitDiagnosticsPerFile = /* @__PURE__ */ new Map())).set(d.file.resolvedPath, diagnostics2 = []); + diagnostics2.push(d); + }); + if (emitDiagnosticsPerFile) state.emitDiagnosticsPerFile = emitDiagnosticsPerFile; + } + function emitNextAffectedFile(writeFile2, cancellationToken, emitOnlyDtsFiles, customTransformers) { + return emitNextAffectedFileOrDtsErrors( + writeFile2, + cancellationToken, + emitOnlyDtsFiles, + customTransformers, + /*isForDtsErrors*/ + false + ); + } function getWriteFileCallback(writeFile2, customTransformers) { + Debug.assert(isBuilderProgramStateWithDefinedProgram(state)); if (!getEmitDeclarations(state.compilerOptions)) return writeFile2 || maybeBind(host, host.writeFile); return (fileName, text, writeByteOrderMark, onError, sourceFiles, data) => { var _a, _b, _c; @@ -223618,7 +224268,7 @@ function createBuilderProgram(kind, { newProgram, host, oldProgram, configFilePa if (state.compilerOptions.composite) { const filePath = sourceFiles[0].resolvedPath; emitSignature = handleNewSignature((_c = state.emitSignatures) == null ? void 0 : _c.get(filePath), emitSignature); - if (!emitSignature) return; + if (!emitSignature) return data.skippedDtsWrite = true; (state.emitSignatures ?? (state.emitSignatures = /* @__PURE__ */ new Map())).set(filePath, emitSignature); } } else if (state.compilerOptions.composite) { @@ -223627,7 +224277,7 @@ function createBuilderProgram(kind, { newProgram, host, oldProgram, configFilePa /*newSignature*/ void 0 ); - if (!newSignature) return; + if (!newSignature) return data.skippedDtsWrite = true; state.outSignature = newSignature; } } @@ -223650,6 +224300,7 @@ function createBuilderProgram(kind, { newProgram, host, oldProgram, configFilePa }; } function emit(targetSourceFile, writeFile2, cancellationToken, emitOnlyDtsFiles, customTransformers) { + Debug.assert(isBuilderProgramStateWithDefinedProgram(state)); if (kind === 1 /* EmitAndSemanticDiagnosticsBuilderProgram */) { assertSourceFileOkWithoutNextAffectedCall(state, targetSourceFile); } @@ -223662,7 +224313,12 @@ function createBuilderProgram(kind, { newProgram, host, oldProgram, configFilePa let diagnostics; let emittedFiles = []; let affectedEmitResult; - while (affectedEmitResult = emitNextAffectedFile(writeFile2, cancellationToken, emitOnlyDtsFiles, customTransformers)) { + while (affectedEmitResult = emitNextAffectedFile( + writeFile2, + cancellationToken, + emitOnlyDtsFiles, + customTransformers + )) { emitSkipped = emitSkipped || affectedEmitResult.result.emitSkipped; diagnostics = addRange(diagnostics, affectedEmitResult.result.diagnostics); emittedFiles = addRange(emittedFiles, affectedEmitResult.result.emittedFiles); @@ -223675,23 +224331,82 @@ function createBuilderProgram(kind, { newProgram, host, oldProgram, configFilePa sourceMaps }; } else { - clearAffectedFilesPendingEmit(state, emitOnlyDtsFiles); + clearAffectedFilesPendingEmit( + state, + emitOnlyDtsFiles, + /*isForDtsErrors*/ + false + ); } } - return Debug.checkDefined(state.program).emit( + const emitResult = state.program.emit( targetSourceFile, getWriteFileCallback(writeFile2, customTransformers), cancellationToken, emitOnlyDtsFiles, customTransformers ); + handleNonEmitBuilderWithEmitOrDtsErrors( + targetSourceFile, + emitOnlyDtsFiles, + /*isForDtsErrors*/ + false, + emitResult.diagnostics + ); + return emitResult; + } + function handleNonEmitBuilderWithEmitOrDtsErrors(targetSourceFile, emitOnlyDtsFiles, isForDtsErrors, diagnostics) { + if (!targetSourceFile && kind !== 1 /* EmitAndSemanticDiagnosticsBuilderProgram */) { + clearAffectedFilesPendingEmit(state, emitOnlyDtsFiles, isForDtsErrors); + setEmitDiagnosticsPerFile(diagnostics); + } + } + function getDeclarationDiagnostics2(sourceFile, cancellationToken) { + var _a; + Debug.assert(isBuilderProgramStateWithDefinedProgram(state)); + if (kind === 1 /* EmitAndSemanticDiagnosticsBuilderProgram */) { + assertSourceFileOkWithoutNextAffectedCall(state, sourceFile); + let affectedEmitResult; + let diagnostics; + while (affectedEmitResult = emitNextAffectedFileOrDtsErrors( + /*writeFile*/ + void 0, + cancellationToken, + /*emitOnlyDtsFiles*/ + void 0, + /*customTransformers*/ + void 0, + /*isForDtsErrors*/ + true + )) { + if (!sourceFile) diagnostics = addRange(diagnostics, affectedEmitResult.result.diagnostics); + } + return (!sourceFile ? diagnostics : (_a = state.emitDiagnosticsPerFile) == null ? void 0 : _a.get(sourceFile.resolvedPath)) || emptyArray; + } else { + const result = state.program.getDeclarationDiagnostics(sourceFile, cancellationToken); + handleNonEmitBuilderWithEmitOrDtsErrors( + sourceFile, + /*emitOnlyDtsFiles*/ + void 0, + /*isForDtsErrors*/ + true, + result + ); + return result; + } } function getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile) { + Debug.assert(isBuilderProgramStateWithDefinedProgram(state)); while (true) { const affected = getNextAffectedFile(state, cancellationToken, host); let result; - if (!affected) return void 0; - else if (affected !== state.program) { + if (!affected) { + if (state.checkPending && !state.compilerOptions.noCheck) { + state.checkPending = void 0; + state.buildInfoEmitPending = true; + } + return void 0; + } else if (affected !== state.program) { const affectedSourceFile = affected; if (!ignoreSourceFile || !ignoreSourceFile(affectedSourceFile)) { result = getSemanticDiagnosticsOfFile(state, affectedSourceFile, cancellationToken); @@ -223701,33 +224416,48 @@ function createBuilderProgram(kind, { newProgram, host, oldProgram, configFilePa state.buildInfoEmitPending = true; if (!result) continue; } else { - result = state.program.getSemanticDiagnostics( - /*sourceFile*/ - void 0, - cancellationToken + let diagnostics; + const semanticDiagnosticsPerFile = /* @__PURE__ */ new Map(); + state.program.getSourceFiles().forEach( + (sourceFile) => diagnostics = addRange( + diagnostics, + getSemanticDiagnosticsOfFile( + state, + sourceFile, + cancellationToken, + semanticDiagnosticsPerFile + ) + ) ); + state.semanticDiagnosticsPerFile = semanticDiagnosticsPerFile; + result = diagnostics || emptyArray; state.changedFilesSet.clear(); state.programEmitPending = getBuilderFileEmit(state.compilerOptions); + if (!state.compilerOptions.noCheck) state.checkPending = void 0; + state.buildInfoEmitPending = true; } return { result, affected }; } } function getSemanticDiagnostics(sourceFile, cancellationToken) { + Debug.assert(isBuilderProgramStateWithDefinedProgram(state)); assertSourceFileOkWithoutNextAffectedCall(state, sourceFile); - const compilerOptions = Debug.checkDefined(state.program).getCompilerOptions(); - if (compilerOptions.outFile) { - Debug.assert(!state.semanticDiagnosticsPerFile); - return Debug.checkDefined(state.program).getSemanticDiagnostics(sourceFile, cancellationToken); - } if (sourceFile) { return getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken); } - while (getSemanticDiagnosticsOfNextAffectedFile(cancellationToken)) { + while (true) { + const affectedResult = getSemanticDiagnosticsOfNextAffectedFile(cancellationToken); + if (!affectedResult) break; + if (affectedResult.affected === state.program) return affectedResult.result; } let diagnostics; - for (const sourceFile2 of Debug.checkDefined(state.program).getSourceFiles()) { + for (const sourceFile2 of state.program.getSourceFiles()) { diagnostics = addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile2, cancellationToken)); } + if (state.checkPending && !state.compilerOptions.noCheck) { + state.checkPending = void 0; + state.buildInfoEmitPending = true; + } return diagnostics || emptyArray; } } @@ -223741,44 +224471,49 @@ function toBuilderStateFileInfoForMultiEmit(fileInfo) { return isString(fileInfo) ? { version: fileInfo, signature: fileInfo, affectsGlobalScope: void 0, impliedFormat: void 0 } : isString(fileInfo.signature) ? fileInfo : { version: fileInfo.version, signature: fileInfo.signature === false ? void 0 : fileInfo.version, affectsGlobalScope: fileInfo.affectsGlobalScope, impliedFormat: fileInfo.impliedFormat }; } function toBuilderFileEmit(value, fullEmitForOptions) { - return isNumber(value) ? fullEmitForOptions : value[1] || 8 /* Dts */; + return isNumber(value) ? fullEmitForOptions : value[1] || 24 /* Dts */; } function toProgramEmitPending(value, options) { return !value ? getBuilderFileEmit(options || {}) : value; } -function createBuilderProgramUsingProgramBuildInfo(buildInfo, buildInfoPath, host) { +function createBuilderProgramUsingIncrementalBuildInfo(buildInfo, buildInfoPath, host) { var _a, _b, _c, _d; - const program = buildInfo.program; const buildInfoDirectory = getDirectoryPath(getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory())); const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames()); let state; - const filePaths = (_a = program.fileNames) == null ? void 0 : _a.map(toPathInBuildInfoDirectory); + const filePaths = (_a = buildInfo.fileNames) == null ? void 0 : _a.map(toPathInBuildInfoDirectory); let filePathsSetList; - const latestChangedDtsFile = program.latestChangedDtsFile ? toAbsolutePath(program.latestChangedDtsFile) : void 0; - if (isProgramBundleEmitBuildInfo(program)) { - const fileInfos = /* @__PURE__ */ new Map(); - program.fileInfos.forEach((fileInfo, index) => { + const latestChangedDtsFile = buildInfo.latestChangedDtsFile ? toAbsolutePath(buildInfo.latestChangedDtsFile) : void 0; + const fileInfos = /* @__PURE__ */ new Map(); + const changedFilesSet = new Set(map(buildInfo.changeFileSet, toFilePath)); + if (isIncrementalBundleEmitBuildInfo(buildInfo)) { + buildInfo.fileInfos.forEach((fileInfo, index) => { const path = toFilePath(index + 1); fileInfos.set(path, isString(fileInfo) ? { version: fileInfo, signature: void 0, affectsGlobalScope: void 0, impliedFormat: void 0 } : fileInfo); }); state = { fileInfos, - compilerOptions: program.options ? convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath) : {}, + compilerOptions: buildInfo.options ? convertToOptionsWithAbsolutePaths(buildInfo.options, toAbsolutePath) : {}, + semanticDiagnosticsPerFile: toPerFileSemanticDiagnostics(buildInfo.semanticDiagnosticsPerFile), + emitDiagnosticsPerFile: toPerFileEmitDiagnostics(buildInfo.emitDiagnosticsPerFile), + hasReusableDiagnostic: true, + changedFilesSet, latestChangedDtsFile, - outSignature: program.outSignature, - programEmitPending: program.pendingEmit === void 0 ? void 0 : toProgramEmitPending(program.pendingEmit, program.options) + outSignature: buildInfo.outSignature, + programEmitPending: buildInfo.pendingEmit === void 0 ? void 0 : toProgramEmitPending(buildInfo.pendingEmit, buildInfo.options), + hasErrors: buildInfo.errors, + checkPending: buildInfo.checkPending }; } else { - filePathsSetList = (_b = program.fileIdsList) == null ? void 0 : _b.map((fileIds) => new Set(fileIds.map(toFilePath))); - const fileInfos = /* @__PURE__ */ new Map(); - const emitSignatures = ((_c = program.options) == null ? void 0 : _c.composite) && !program.options.outFile ? /* @__PURE__ */ new Map() : void 0; - program.fileInfos.forEach((fileInfo, index) => { + filePathsSetList = (_b = buildInfo.fileIdsList) == null ? void 0 : _b.map((fileIds) => new Set(fileIds.map(toFilePath))); + const emitSignatures = ((_c = buildInfo.options) == null ? void 0 : _c.composite) && !buildInfo.options.outFile ? /* @__PURE__ */ new Map() : void 0; + buildInfo.fileInfos.forEach((fileInfo, index) => { const path = toFilePath(index + 1); const stateFileInfo = toBuilderStateFileInfoForMultiEmit(fileInfo); fileInfos.set(path, stateFileInfo); if (emitSignatures && stateFileInfo.signature) emitSignatures.set(path, stateFileInfo.signature); }); - (_d = program.emitSignatures) == null ? void 0 : _d.forEach((value) => { + (_d = buildInfo.emitSignatures) == null ? void 0 : _d.forEach((value) => { if (isNumber(value)) emitSignatures.delete(toFilePath(value)); else { const key = toFilePath(value[0]); @@ -223791,25 +224526,24 @@ function createBuilderProgramUsingProgramBuildInfo(buildInfo, buildInfoPath, hos ); } }); - const changedFilesSet = new Set(map(program.changeFileSet, toFilePath)); - const fullEmitForOptions = program.affectedFilesPendingEmit ? getBuilderFileEmit(program.options || {}) : void 0; + const fullEmitForOptions = buildInfo.affectedFilesPendingEmit ? getBuilderFileEmit(buildInfo.options || {}) : void 0; state = { fileInfos, - compilerOptions: program.options ? convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath) : {}, - referencedMap: toManyToManyPathMap(program.referencedMap, program.options ?? {}), - semanticDiagnosticsPerFile: toPerFileSemanticDiagnostics(program.semanticDiagnosticsPerFile, fileInfos, changedFilesSet), - emitDiagnosticsPerFile: toPerFileEmitDiagnostics(program.emitDiagnosticsPerFile), + compilerOptions: buildInfo.options ? convertToOptionsWithAbsolutePaths(buildInfo.options, toAbsolutePath) : {}, + referencedMap: toManyToManyPathMap(buildInfo.referencedMap, buildInfo.options ?? {}), + semanticDiagnosticsPerFile: toPerFileSemanticDiagnostics(buildInfo.semanticDiagnosticsPerFile), + emitDiagnosticsPerFile: toPerFileEmitDiagnostics(buildInfo.emitDiagnosticsPerFile), hasReusableDiagnostic: true, - affectedFilesPendingEmit: program.affectedFilesPendingEmit && arrayToMap(program.affectedFilesPendingEmit, (value) => toFilePath(isNumber(value) ? value : value[0]), (value) => toBuilderFileEmit(value, fullEmitForOptions)), changedFilesSet, + affectedFilesPendingEmit: buildInfo.affectedFilesPendingEmit && arrayToMap(buildInfo.affectedFilesPendingEmit, (value) => toFilePath(isNumber(value) ? value : value[0]), (value) => toBuilderFileEmit(value, fullEmitForOptions)), latestChangedDtsFile, - emitSignatures: (emitSignatures == null ? void 0 : emitSignatures.size) ? emitSignatures : void 0 + emitSignatures: (emitSignatures == null ? void 0 : emitSignatures.size) ? emitSignatures : void 0, + hasErrors: buildInfo.errors, + checkPending: buildInfo.checkPending }; } return { - getState: () => state, - saveEmitState: noop, - restoreEmitState: noop, + state, getProgram: notImplemented, getProgramOrUndefined: returnUndefined, releaseProgram: noop, @@ -223849,7 +224583,7 @@ function createBuilderProgramUsingProgramBuildInfo(buildInfo, buildInfoPath, hos referenceMap.forEach(([fileId, fileIdListId]) => map2.set(toFilePath(fileId), toFilePathsSet(fileIdListId))); return map2; } - function toPerFileSemanticDiagnostics(diagnostics, fileInfos, changedFilesSet) { + function toPerFileSemanticDiagnostics(diagnostics) { const semanticDiagnostics = new Map( mapDefinedIterator( fileInfos.keys(), @@ -223860,7 +224594,7 @@ function createBuilderProgramUsingProgramBuildInfo(buildInfo, buildInfoPath, hos if (isNumber(value)) semanticDiagnostics.delete(toFilePath(value)); else semanticDiagnostics.set(toFilePath(value[0]), value[1]); }); - return semanticDiagnostics.size ? semanticDiagnostics : void 0; + return semanticDiagnostics; } function toPerFileEmitDiagnostics(diagnostics) { return diagnostics && arrayToMap(diagnostics, (value) => toFilePath(value[0]), (value) => value[1]); @@ -223901,15 +224635,19 @@ function getBuildInfoFileVersionMap(program, buildInfoPath, host) { } } } -function createRedirectedBuilderProgram(getState, configFileParsingDiagnostics) { +function getNonIncrementalBuildInfoRoots(buildInfo, buildInfoPath, host) { + if (!isNonIncrementalBuildInfo(buildInfo)) return void 0; + const buildInfoDirectory = getDirectoryPath(getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory())); + const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + return buildInfo.root.map((r) => toPath(r, buildInfoDirectory, getCanonicalFileName)); +} +function createRedirectedBuilderProgram(state, configFileParsingDiagnostics) { return { - getState: notImplemented, - saveEmitState: noop, - restoreEmitState: noop, + state: void 0, getProgram, - getProgramOrUndefined: () => getState().program, - releaseProgram: () => getState().program = void 0, - getCompilerOptions: () => getState().compilerOptions, + getProgramOrUndefined: () => state.program, + releaseProgram: () => state.program = void 0, + getCompilerOptions: () => state.compilerOptions, getSourceFile: (fileName) => getProgram().getSourceFile(fileName), getSourceFiles: () => getProgram().getSourceFiles(), getOptionsDiagnostics: (cancellationToken) => getProgram().getOptionsDiagnostics(cancellationToken), @@ -223925,20 +224663,50 @@ function createRedirectedBuilderProgram(getState, configFileParsingDiagnostics) close: noop }; function getProgram() { - return Debug.checkDefined(getState().program); + return Debug.checkDefined(state.program); } } // src/compiler/builderPublic.ts function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { - return createBuilderProgram(0 /* SemanticDiagnosticsBuilderProgram */, getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); + return createBuilderProgram( + 0 /* SemanticDiagnosticsBuilderProgram */, + getBuilderCreationParameters( + newProgramOrRootNames, + hostOrOptions, + oldProgramOrHost, + configFileParsingDiagnosticsOrOldProgram, + configFileParsingDiagnostics, + projectReferences + ) + ); } function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { - return createBuilderProgram(1 /* EmitAndSemanticDiagnosticsBuilderProgram */, getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); + return createBuilderProgram( + 1 /* EmitAndSemanticDiagnosticsBuilderProgram */, + getBuilderCreationParameters( + newProgramOrRootNames, + hostOrOptions, + oldProgramOrHost, + configFileParsingDiagnosticsOrOldProgram, + configFileParsingDiagnostics, + projectReferences + ) + ); } function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { - const { newProgram, configFileParsingDiagnostics: newConfigFileParsingDiagnostics } = getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences); - return createRedirectedBuilderProgram(() => ({ program: newProgram, compilerOptions: newProgram.getCompilerOptions() }), newConfigFileParsingDiagnostics); + const { newProgram, configFileParsingDiagnostics: newConfigFileParsingDiagnostics } = getBuilderCreationParameters( + newProgramOrRootNames, + hostOrOptions, + oldProgramOrHost, + configFileParsingDiagnosticsOrOldProgram, + configFileParsingDiagnostics, + projectReferences + ); + return createRedirectedBuilderProgram( + { program: newProgram, compilerOptions: newProgram.getCompilerOptions() }, + newConfigFileParsingDiagnostics + ); } // src/compiler/resolutionCache.ts @@ -223951,9 +224719,9 @@ function removeIgnoredPath(path) { function perceivedOsRootLengthForWatching(pathComponents2, length2) { if (length2 <= 1) return 1; let indexAfterOsRoot = 1; - let isDosStyle = pathComponents2[0].search(/[a-zA-Z]:/) === 0; + let isDosStyle = pathComponents2[0].search(/[a-z]:/i) === 0; if (pathComponents2[0] !== directorySeparator && !isDosStyle && // Non dos style paths - pathComponents2[1].search(/[a-zA-Z]\$$/) === 0) { + pathComponents2[1].search(/[a-z]\$$/i) === 0) { if (length2 === 2) return 2; indexAfterOsRoot = 2; isDosStyle = true; @@ -223988,7 +224756,7 @@ function canWatchAffectedPackageJsonOrNodeModulesOfAtTypes(fileOrDirPath) { function canWatchAffectingLocation(filePath) { return canWatchAffectedPackageJsonOrNodeModulesOfAtTypes(filePath); } -function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath, rootDir, rootPath, rootPathComponents, getCurrentDirectory) { +function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath, rootDir, rootPath, rootPathComponents, getCurrentDirectory, preferNonRecursiveWatch) { const failedLookupPathComponents = getPathComponents(failedLookupLocationPath); failedLookupLocation = isRootedDiskPath(failedLookupLocation) ? normalizePath(failedLookupLocation) : getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); const failedLookupComponents = getPathComponents(failedLookupLocation); @@ -224020,10 +224788,11 @@ function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLoo perceivedOsRootLength, nodeModulesIndex, rootPathComponents, - lastNodeModulesIndex + lastNodeModulesIndex, + preferNonRecursiveWatch ); } -function getDirectoryToWatchFromFailedLookupLocationDirectory(dirComponents, dirPathComponents, dirPathComponentsLength, perceivedOsRootLength, nodeModulesIndex, rootPathComponents, lastNodeModulesIndex) { +function getDirectoryToWatchFromFailedLookupLocationDirectory(dirComponents, dirPathComponents, dirPathComponentsLength, perceivedOsRootLength, nodeModulesIndex, rootPathComponents, lastNodeModulesIndex, preferNonRecursiveWatch) { if (nodeModulesIndex !== -1) { return getDirectoryOfFailedLookupWatch( dirComponents, @@ -224034,11 +224803,13 @@ function getDirectoryToWatchFromFailedLookupLocationDirectory(dirComponents, dir } let nonRecursive = true; let length2 = dirPathComponentsLength; - for (let i = 0; i < dirPathComponentsLength; i++) { - if (dirPathComponents[i] !== rootPathComponents[i]) { - nonRecursive = false; - length2 = Math.max(i + 1, perceivedOsRootLength + 1); - break; + if (!preferNonRecursiveWatch) { + for (let i = 0; i < dirPathComponentsLength; i++) { + if (dirPathComponents[i] !== rootPathComponents[i]) { + nonRecursive = false; + length2 = Math.max(i + 1, perceivedOsRootLength + 1); + break; + } } } return getDirectoryOfFailedLookupWatch( @@ -224066,7 +224837,7 @@ function getDirectoryOfFailedLookupWatch(dirComponents, dirPathComponents, lengt packageDirPath: packageDirLength !== void 0 ? getPathFromPathComponents(dirPathComponents, packageDirLength) : void 0 }; } -function getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath, rootPath, rootPathComponents, getCurrentDirectory, filterCustomPath) { +function getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath, rootPath, rootPathComponents, getCurrentDirectory, preferNonRecursiveWatch, filterCustomPath) { const typeRootPathComponents = getPathComponents(typeRootPath); if (isInDirectoryPath(rootPathComponents, typeRootPathComponents)) { return rootPath; @@ -224079,7 +224850,8 @@ function getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootP perceivedOsRootLengthForWatching(typeRootPathComponents, typeRootPathComponents.length), typeRootPathComponents.indexOf("node_modules"), rootPathComponents, - typeRootPathComponents.lastIndexOf("node_modules") + typeRootPathComponents.lastIndexOf("node_modules"), + preferNonRecursiveWatch ); return toWatch && filterCustomPath(toWatch.dirPath) ? toWatch.dirPath : void 0; } @@ -224087,9 +224859,6 @@ function getRootDirectoryOfResolutionCache(rootDirForResolution, getCurrentDirec const normalized = getNormalizedAbsolutePath(rootDirForResolution, getCurrentDirectory()); return !isDiskPathRoot(normalized) ? removeTrailingDirectorySeparator(normalized) : normalized; } -function getRootPathSplitLength(rootPath) { - return rootPath.split(directorySeparator).length - (hasTrailingDirectorySeparator(rootPath) ? 1 : 0); -} function getModuleResolutionHost(resolutionHost) { var _a; return ((_a = resolutionHost.getCompilerHost) == null ? void 0 : _a.call(resolutionHost)) || resolutionHost; @@ -224138,7 +224907,7 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW let filesWithChangedSetOfUnresolvedImports; let filesWithInvalidatedResolutions; let filesWithInvalidatedNonRelativeUnresolvedImports; - const nonRelativeExternalModuleResolutions = createMultiMap(); + const nonRelativeExternalModuleResolutions = /* @__PURE__ */ new Set(); const resolutionsWithFailedLookups = /* @__PURE__ */ new Set(); const resolutionsWithOnlyAffectingLocations = /* @__PURE__ */ new Set(); const resolvedFileToResolution = /* @__PURE__ */ new Map(); @@ -224219,12 +224988,6 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW clear: clear2, onChangesAffectModuleResolution }; - function getResolvedModule(resolution) { - return resolution.resolvedModule; - } - function getResolvedTypeReferenceDirective(resolution) { - return resolution.resolvedTypeReferenceDirective; - } function clear2() { clearMap(directoryWatchesOfFailedLookups, closeFileWatcherOf); clearMap(fileWatchesOfAffectingLocations, closeFileWatcherOf); @@ -224295,8 +225058,7 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW moduleResolutionCache.clearAllExceptPackageJsonInfoCache(); typeReferenceDirectiveResolutionCache.clearAllExceptPackageJsonInfoCache(); libraryResolutionCache.clearAllExceptPackageJsonInfoCache(); - nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); - nonRelativeExternalModuleResolutions.clear(); + watchFailedLookupLocationOfNonRelativeModuleResolutions(); isSymlinkCache.clear(); } function cleanupLibResolutionWatching(newProgram) { @@ -224306,7 +225068,7 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW stopWatchFailedLookupLocationOfResolution( resolution, resolutionHost.toPath(getInferredLibraryNameResolveFrom(resolutionHost.getCompilationSettings(), getCurrentDirectory(), libFileName)), - getResolvedModule + getResolvedModuleFromResolution ); resolvedLibraries.delete(libFileName); } @@ -224315,13 +225077,12 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW function finishCachingPerDirectoryResolution(newProgram, oldProgram) { filesWithInvalidatedNonRelativeUnresolvedImports = void 0; allModuleAndTypeResolutionsAreInvalidated = false; - nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); - nonRelativeExternalModuleResolutions.clear(); + watchFailedLookupLocationOfNonRelativeModuleResolutions(); if (newProgram !== oldProgram) { cleanupLibResolutionWatching(newProgram); newProgram == null ? void 0 : newProgram.getSourceFiles().forEach((newFile) => { var _a; - const expected = isExternalOrCommonJsModule(newFile) ? ((_a = newFile.packageJsonLocations) == null ? void 0 : _a.length) ?? 0 : 0; + const expected = ((_a = newFile.packageJsonLocations) == null ? void 0 : _a.length) ?? 0; const existing = impliedFormatPackageJsons.get(newFile.resolvedPath) ?? emptyArray; for (let i = existing.length; i < expected; i++) { createFileWatcherOfAffectingLocation( @@ -224486,7 +225247,7 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW getModuleResolutionHost(resolutionHost), typeReferenceDirectiveResolutionCache ), - getResolutionWithResolvedFileName: getResolvedTypeReferenceDirective, + getResolutionWithResolvedFileName: getResolvedTypeReferenceDirectiveFromResolution, shouldRetryResolution: (resolution) => resolution.resolvedTypeReferenceDirective === void 0, deferWatchingNonRelativeResolution: false }); @@ -224507,7 +225268,7 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW resolutionHost, moduleResolutionCache ), - getResolutionWithResolvedFileName: getResolvedModule, + getResolutionWithResolvedFileName: getResolvedModuleFromResolution, shouldRetryResolution: (resolution) => !resolution.resolvedModule || !resolutionExtensionIsTSOrJson(resolution.resolvedModule.extension), logChanges: logChangesWhenResolvingModule, deferWatchingNonRelativeResolution: true @@ -224525,17 +225286,17 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW libraryName, resolution, path, - getResolvedModule, + getResolvedModuleFromResolution, /*deferWatchingNonRelativeResolution*/ false ); resolvedLibraries.set(libFileName, resolution); if (existingResolution) { - stopWatchFailedLookupLocationOfResolution(existingResolution, path, getResolvedModule); + stopWatchFailedLookupLocationOfResolution(existingResolution, path, getResolvedModuleFromResolution); } } else { if (isTraceEnabled(options, host)) { - const resolved = getResolvedModule(resolution); + const resolved = getResolvedModuleFromResolution(resolution); trace( host, (resolved == null ? void 0 : resolved.resolvedFileName) ? resolved.packageId ? Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2_with_Package_ID_3 : Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_successfully_resolved_to_2 : Diagnostics.Reusing_resolution_of_module_0_from_1_of_old_program_it_was_not_resolved, @@ -224574,27 +225335,20 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW return endsWith(dirPath, "/node_modules/@types"); } function watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, filePath, getResolutionWithResolvedFileName, deferWatchingNonRelativeResolution) { - var _a; - if (resolution.refCount) { - resolution.refCount++; - Debug.assertIsDefined(resolution.files); + (resolution.files ?? (resolution.files = /* @__PURE__ */ new Set())).add(filePath); + if (resolution.files.size !== 1) return; + if (!deferWatchingNonRelativeResolution || isExternalModuleNameRelative(name)) { + watchFailedLookupLocationOfResolution(resolution); } else { - resolution.refCount = 1; - Debug.assert(!((_a = resolution.files) == null ? void 0 : _a.size)); - if (!deferWatchingNonRelativeResolution || isExternalModuleNameRelative(name)) { - watchFailedLookupLocationOfResolution(resolution); - } else { - nonRelativeExternalModuleResolutions.add(name, resolution); - } - const resolved = getResolutionWithResolvedFileName(resolution); - if (resolved && resolved.resolvedFileName) { - const key = resolutionHost.toPath(resolved.resolvedFileName); - let resolutions = resolvedFileToResolution.get(key); - if (!resolutions) resolvedFileToResolution.set(key, resolutions = /* @__PURE__ */ new Set()); - resolutions.add(resolution); - } + nonRelativeExternalModuleResolutions.add(resolution); + } + const resolved = getResolutionWithResolvedFileName(resolution); + if (resolved && resolved.resolvedFileName) { + const key = resolutionHost.toPath(resolved.resolvedFileName); + let resolutions = resolvedFileToResolution.get(key); + if (!resolutions) resolvedFileToResolution.set(key, resolutions = /* @__PURE__ */ new Set()); + resolutions.add(resolution); } - (resolution.files ?? (resolution.files = /* @__PURE__ */ new Set())).add(filePath); } function watchFailedLookupLocation(failedLookupLocation, setAtRoot) { const failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); @@ -224604,7 +225358,8 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW rootDir, rootPath, rootPathComponents, - getCurrentDirectory + getCurrentDirectory, + resolutionHost.preferNonRecursiveWatch ); if (toWatch) { const { dir, dirPath, nonRecursive, packageDir, packageDirPath } = toWatch; @@ -224619,7 +225374,8 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW return setAtRoot; } function watchFailedLookupLocationOfResolution(resolution) { - Debug.assert(!!resolution.refCount); + var _a; + Debug.assert(!!((_a = resolution.files) == null ? void 0 : _a.size)); const { failedLookupLocations, affectingLocations, alternateResult } = resolution; if (!(failedLookupLocations == null ? void 0 : failedLookupLocations.length) && !(affectingLocations == null ? void 0 : affectingLocations.length) && !alternateResult) return; if ((failedLookupLocations == null ? void 0 : failedLookupLocations.length) || alternateResult) resolutionsWithFailedLookups.add(resolution); @@ -224645,7 +225401,8 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW watchAffectingLocationsOfResolution(resolution, !(failedLookupLocations == null ? void 0 : failedLookupLocations.length) && !alternateResult); } function watchAffectingLocationsOfResolution(resolution, addToResolutionsWithOnlyAffectingLocations) { - Debug.assert(!!resolution.refCount); + var _a; + Debug.assert(!!((_a = resolution.files) == null ? void 0 : _a.size)); const { affectingLocations } = resolution; if (!(affectingLocations == null ? void 0 : affectingLocations.length)) return; if (addToResolutionsWithOnlyAffectingLocations) resolutionsWithOnlyAffectingLocations.add(resolution); @@ -224719,17 +225476,9 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW (_a = watcher == null ? void 0 : watcher.symlinks) == null ? void 0 : _a.forEach((path2) => invalidateAffectingFileWatcher(path2, packageJsonMap)); packageJsonMap == null ? void 0 : packageJsonMap.delete(resolutionHost.toPath(path)); } - function watchFailedLookupLocationOfNonRelativeModuleResolutions(resolutions, name) { - const program = resolutionHost.getCurrentProgram(); - if (!program || !program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(name)) { - resolutions.forEach(watchFailedLookupLocationOfResolution); - } else { - resolutions.forEach((resolution) => watchAffectingLocationsOfResolution( - resolution, - /*addToResolutionsWithOnlyAffectingLocations*/ - true - )); - } + function watchFailedLookupLocationOfNonRelativeModuleResolutions() { + nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfResolution); + nonRelativeExternalModuleResolutions.clear(); } function createDirectoryWatcherForPackageDir(dir, dirPath, packageDir, packageDirPath, nonRecursive) { Debug.assert(!nonRecursive); @@ -224749,11 +225498,7 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW ); } else if (packageDirWatcher.isSymlink !== isSymlink) { packageDirWatcher.dirPathToWatcher.forEach((watcher) => { - removeDirectoryWatcher( - packageDirWatcher.isSymlink ? packageDirPath : dirPath, - /*syncDirWatcherRemove*/ - false - ); + removeDirectoryWatcher(packageDirWatcher.isSymlink ? packageDirPath : dirPath); watcher.watcher = createDirPathToWatcher(); }); packageDirWatcher.isSymlink = isSymlink; @@ -224793,7 +225538,7 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW } return dirWatcher; } - function stopWatchFailedLookupLocation(failedLookupLocation, removeAtRoot, syncDirWatcherRemove) { + function stopWatchFailedLookupLocation(failedLookupLocation, removeAtRoot) { const failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); const toWatch = getDirectoryToWatchFailedLookupLocation( failedLookupLocation, @@ -224801,7 +225546,8 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW rootDir, rootPath, rootPathComponents, - getCurrentDirectory + getCurrentDirectory, + resolutionHost.preferNonRecursiveWatch ); if (toWatch) { const { dirPath, packageDirPath } = toWatch; @@ -224812,7 +225558,7 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW const forDirPath = packageDirWatcher.dirPathToWatcher.get(dirPath); forDirPath.refCount--; if (forDirPath.refCount === 0) { - removeDirectoryWatcher(packageDirWatcher.isSymlink ? packageDirPath : dirPath, syncDirWatcherRemove); + removeDirectoryWatcher(packageDirWatcher.isSymlink ? packageDirPath : dirPath); packageDirWatcher.dirPathToWatcher.delete(dirPath); if (packageDirWatcher.isSymlink) { const refCount = dirPathToSymlinkPackageRefCount.get(dirPath) - 1; @@ -224822,20 +225568,17 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW dirPathToSymlinkPackageRefCount.set(dirPath, refCount); } } - if (syncDirWatcherRemove) closePackageDirWatcher(packageDirWatcher, packageDirPath); } } else { - removeDirectoryWatcher(dirPath, syncDirWatcherRemove); + removeDirectoryWatcher(dirPath); } } return removeAtRoot; } - function stopWatchFailedLookupLocationOfResolution(resolution, filePath, getResolutionWithResolvedFileName, syncDirWatcherRemove) { + function stopWatchFailedLookupLocationOfResolution(resolution, filePath, getResolutionWithResolvedFileName) { Debug.checkDefined(resolution.files).delete(filePath); - resolution.refCount--; - if (resolution.refCount) { - return; - } + if (resolution.files.size) return; + resolution.files = void 0; const resolved = getResolutionWithResolvedFileName(resolution); if (resolved && resolved.resolvedFileName) { const key = resolutionHost.toPath(resolved.resolvedFileName); @@ -224847,11 +225590,11 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW let removeAtRoot = false; if (failedLookupLocations) { for (const failedLookupLocation of failedLookupLocations) { - removeAtRoot = stopWatchFailedLookupLocation(failedLookupLocation, removeAtRoot, syncDirWatcherRemove); + removeAtRoot = stopWatchFailedLookupLocation(failedLookupLocation, removeAtRoot); } } - if (alternateResult) removeAtRoot = stopWatchFailedLookupLocation(alternateResult, removeAtRoot, syncDirWatcherRemove); - if (removeAtRoot) removeDirectoryWatcher(rootPath, syncDirWatcherRemove); + if (alternateResult) removeAtRoot = stopWatchFailedLookupLocation(alternateResult, removeAtRoot); + if (removeAtRoot) removeDirectoryWatcher(rootPath); } else if (affectingLocations == null ? void 0 : affectingLocations.length) { resolutionsWithOnlyAffectingLocations.delete(resolution); } @@ -224859,14 +225602,12 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW for (const affectingLocation of affectingLocations) { const watcher = fileWatchesOfAffectingLocations.get(affectingLocation); watcher.resolutions--; - if (syncDirWatcherRemove) closeFileWatcherOfAffectingLocation(watcher, affectingLocation); } } } - function removeDirectoryWatcher(dirPath, syncDirWatcherRemove) { + function removeDirectoryWatcher(dirPath) { const dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); dirWatcher.refCount--; - if (syncDirWatcherRemove) closeDirectoryWatchesOfFailedLookup(dirWatcher, dirPath); } function createDirectoryWatcher(directory, dirPath, nonRecursive) { return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, (fileOrDirectory) => { @@ -224877,15 +225618,14 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW scheduleInvalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath); }, nonRecursive ? 0 /* None */ : 1 /* Recursive */); } - function removeResolutionsOfFileFromCache(cache, filePath, getResolutionWithResolvedFileName, syncDirWatcherRemove) { + function removeResolutionsOfFileFromCache(cache, filePath, getResolutionWithResolvedFileName) { const resolutions = cache.get(filePath); if (resolutions) { resolutions.forEach( (resolution) => stopWatchFailedLookupLocationOfResolution( resolution, filePath, - getResolutionWithResolvedFileName, - syncDirWatcherRemove + getResolutionWithResolvedFileName ) ); cache.delete(filePath); @@ -224899,9 +225639,9 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW if (!resolvedProjectReference) return; resolvedProjectReference.commandLine.fileNames.forEach((f) => removeResolutionsOfFile(resolutionHost.toPath(f))); } - function removeResolutionsOfFile(filePath, syncDirWatcherRemove) { - removeResolutionsOfFileFromCache(resolvedModuleNames, filePath, getResolvedModule, syncDirWatcherRemove); - removeResolutionsOfFileFromCache(resolvedTypeReferenceDirectives, filePath, getResolvedTypeReferenceDirective, syncDirWatcherRemove); + function removeResolutionsOfFile(filePath) { + removeResolutionsOfFileFromCache(resolvedModuleNames, filePath, getResolvedModuleFromResolution); + removeResolutionsOfFileFromCache(resolvedTypeReferenceDirectives, filePath, getResolvedTypeReferenceDirectiveFromResolution); } function invalidateResolutions(resolutions, canInvalidate) { if (!resolutions) return false; @@ -225031,6 +225771,7 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW rootPath, rootPathComponents, getCurrentDirectory, + resolutionHost.preferNonRecursiveWatch, (dirPath2) => directoryWatchesOfFailedLookups.has(dirPath2) || dirPathToSymlinkPackageRefCount.has(dirPath2) ); if (dirPath) { @@ -225196,7 +225937,7 @@ function createTabularErrorsDisplay(filesInError, host) { if (distinctFiles.length === 0) return ""; const numberLength = (num) => Math.log(num) * Math.LOG10E + 1; const fileToErrorCount = distinctFiles.map((file) => [file, countWhere(filesInError, (fileInError) => fileInError.fileName === file.fileName)]); - const maxErrors = fileToErrorCount.reduce((acc, value) => Math.max(acc, value[1] || 0), 0); + const maxErrors = maxBy(fileToErrorCount, 0, (value) => value[1]); const headerRow = Diagnostics.Errors_Files.message; const leftColumnHeadingLength = headerRow.split(" ")[0].length; const leftPaddingGoal = Math.max(leftColumnHeadingLength, numberLength(maxErrors)); @@ -225213,13 +225954,13 @@ function createTabularErrorsDisplay(filesInError, host) { }); return tabularData; } -function isBuilderProgram2(program) { - return !!program.getState; +function isBuilderProgram(program) { + return !!program.state; } function listFiles(program, write) { const options = program.getCompilerOptions(); if (options.explainFiles) { - explainFiles(isBuilderProgram2(program) ? program.getProgram() : program, write); + explainFiles(isBuilderProgram(program) ? program.getProgram() : program, write); } else if (options.listFiles || options.listFilesOnly) { forEach(program.getSourceFiles(), (file) => { write(file.fileName); @@ -225233,10 +225974,10 @@ function explainFiles(program, write) { for (const file of program.getSourceFiles()) { write(`${toFileName(file, relativeFileName)}`); (_a = reasons.get(file.path)) == null ? void 0 : _a.forEach((reason) => write(` ${fileIncludeReasonToDiagnostics(program, reason, relativeFileName).messageText}`)); - (_b = explainIfFileIsRedirectAndImpliedFormat(file, relativeFileName)) == null ? void 0 : _b.forEach((d) => write(` ${d.messageText}`)); + (_b = explainIfFileIsRedirectAndImpliedFormat(file, program.getCompilerOptionsForFile(file), relativeFileName)) == null ? void 0 : _b.forEach((d) => write(` ${d.messageText}`)); } } -function explainIfFileIsRedirectAndImpliedFormat(file, fileNameConvertor) { +function explainIfFileIsRedirectAndImpliedFormat(file, options, fileNameConvertor) { var _a; let result; if (file.path !== file.resolvedPath) { @@ -225256,7 +225997,7 @@ function explainIfFileIsRedirectAndImpliedFormat(file, fileNameConvertor) { )); } if (isExternalOrCommonJsModule(file)) { - switch (file.impliedNodeFormat) { + switch (getImpliedNodeFormatForEmitWorker(file, options)) { case 99 /* ESNext */: if (file.packageJsonScope) { (result ?? (result = [])).push(chainDiagnosticMessages( @@ -225424,7 +226165,7 @@ function toFileName(file, fileNameConvertor) { return fileNameConvertor ? fileNameConvertor(fileName) : fileName; } function emitFilesAndReportErrors(program, reportDiagnostic, write, reportSummary, writeFile2, cancellationToken, emitOnlyDtsFiles, customTransformers) { - const isListFilesOnly = !!program.getCompilerOptions().listFilesOnly; + const options = program.getCompilerOptions(); const allDiagnostics = program.getConfigFileParsingDiagnostics().slice(); const configFileParsingDiagnosticsLength = allDiagnostics.length; addRange(allDiagnostics, program.getSyntacticDiagnostics( @@ -225434,7 +226175,7 @@ function emitFilesAndReportErrors(program, reportDiagnostic, write, reportSummar )); if (allDiagnostics.length === configFileParsingDiagnosticsLength) { addRange(allDiagnostics, program.getOptionsDiagnostics(cancellationToken)); - if (!isListFilesOnly) { + if (!options.listFilesOnly) { addRange(allDiagnostics, program.getGlobalDiagnostics(cancellationToken)); if (allDiagnostics.length === configFileParsingDiagnosticsLength) { addRange(allDiagnostics, program.getSemanticDiagnostics( @@ -225443,9 +226184,16 @@ function emitFilesAndReportErrors(program, reportDiagnostic, write, reportSummar cancellationToken )); } + if (options.noEmit && getEmitDeclarations(options) && allDiagnostics.length === configFileParsingDiagnosticsLength) { + addRange(allDiagnostics, program.getDeclarationDiagnostics( + /*sourceFile*/ + void 0, + cancellationToken + )); + } } } - const emitResult = isListFilesOnly ? { emitSkipped: true, diagnostics: emptyArray } : program.emit( + const emitResult = options.listFilesOnly ? { emitSkipped: true, diagnostics: emptyArray } : program.emit( /*targetSourceFile*/ void 0, writeFile2, @@ -225453,13 +226201,12 @@ function emitFilesAndReportErrors(program, reportDiagnostic, write, reportSummar emitOnlyDtsFiles, customTransformers ); - const { emittedFiles, diagnostics: emitDiagnostics } = emitResult; - addRange(allDiagnostics, emitDiagnostics); + addRange(allDiagnostics, emitResult.diagnostics); const diagnostics = sortAndDeduplicateDiagnostics(allDiagnostics); diagnostics.forEach(reportDiagnostic); if (write) { const currentDir = program.getCurrentDirectory(); - forEach(emittedFiles, (file) => { + forEach(emitResult.emittedFiles, (file) => { const filepath = getNormalizedAbsolutePath(file, currentDir); write(`TSFILE: ${filepath}`); }); @@ -225500,7 +226247,8 @@ function createWatchHost(system = sys, reportWatchStatus2) { watchFile: maybeBind(system, system.watchFile) || returnNoopFileWatcher, watchDirectory: maybeBind(system, system.watchDirectory) || returnNoopFileWatcher, setTimeout: maybeBind(system, system.setTimeout) || noop, - clearTimeout: maybeBind(system, system.clearTimeout) || noop + clearTimeout: maybeBind(system, system.clearTimeout) || noop, + preferNonRecursiveWatch: system.preferNonRecursiveWatch }; } var WatchType = { @@ -225719,8 +226467,8 @@ function readBuilderProgram(compilerOptions, host) { if (!content) return void 0; buildInfo = getBuildInfo(buildInfoPath, content); } - if (!buildInfo || buildInfo.version !== version || !buildInfo.program) return void 0; - return createBuilderProgramUsingProgramBuildInfo(buildInfo, buildInfoPath, host); + if (!buildInfo || buildInfo.version !== version || !isIncrementalBuildInfo(buildInfo)) return void 0; + return createBuilderProgramUsingIncrementalBuildInfo(buildInfo, buildInfoPath, host); } function createIncrementalCompilerHost(options, system = sys) { const host = createCompilerHostWorker( @@ -225819,11 +226567,6 @@ function createWatchProgram(host) { if (configFileName) { configFileWatcher = watchFile2(configFileName, scheduleProgramReload, 2e3 /* High */, watchOptions, WatchType.ConfigFile); } - let pnpFileWatcher; - const pnpApiPath = getPnpApiPath(__filename); - if (pnpApiPath) { - pnpFileWatcher = watchFile2(pnpApiPath, scheduleResolutionReload, 2e3 /* High */, watchOptions, WatchType.ConfigFile); - } const compilerHost = createCompilerHostFromProgramHost(host, () => compilerOptions, directoryStructureHost); setGetSourceFileAsHashVersioned(compilerHost); const getNewSourceFile = compilerHost.getSourceFile; @@ -225836,6 +226579,7 @@ function createWatchProgram(host) { compilerHost.toPath = toPath3; compilerHost.getCompilationSettings = () => compilerOptions; compilerHost.useSourceOfProjectReferenceRedirect = maybeBind(host, host.useSourceOfProjectReferenceRedirect); + compilerHost.preferNonRecursiveWatch = host.preferNonRecursiveWatch; compilerHost.watchDirectoryOfFailedLookupLocation = (dir, cb, flags) => watchDirectory(dir, cb, flags, watchOptions, WatchType.FailedLookupLocations); compilerHost.watchAffectingFileLocation = (file, cb) => watchFile2(file, cb, 2e3 /* High */, watchOptions, WatchType.AffectingFileLocation); compilerHost.watchTypeRootsDirectory = (dir, cb, flags) => watchDirectory(dir, cb, flags, watchOptions, WatchType.TypeRoots); @@ -225886,10 +226630,6 @@ function createWatchProgram(host) { configFileWatcher.close(); configFileWatcher = void 0; } - if (pnpFileWatcher) { - pnpFileWatcher.close(); - pnpFileWatcher = void 0; - } extendedConfigCache == null ? void 0 : extendedConfigCache.clear(); extendedConfigCache = void 0; if (sharedExtendedConfigFileWatchers) { @@ -225925,7 +226665,7 @@ function createWatchProgram(host) { function getCurrentProgram() { return builderProgram && builderProgram.getProgramOrUndefined(); } - function synchronizeProgram(forceAllFilesAsInvalidated = false) { + function synchronizeProgram() { writeLog(`Synchronizing program`); Debug.assert(compilerOptions); Debug.assert(rootFileNames); @@ -225937,7 +226677,7 @@ function createWatchProgram(host) { resolutionCache.onChangesAffectModuleResolution(); } } - const { hasInvalidatedResolutions, hasInvalidatedLibResolutions } = resolutionCache.createHasInvalidatedResolutions(forceAllFilesAsInvalidated ? returnTrue : customHasInvalidatedResolutions, customHasInvalidLibResolutions); + const { hasInvalidatedResolutions, hasInvalidatedLibResolutions } = resolutionCache.createHasInvalidatedResolutions(customHasInvalidatedResolutions, customHasInvalidLibResolutions); const { originalReadFile, originalFileExists, @@ -226145,41 +226885,23 @@ function createWatchProgram(host) { updateLevel = 2 /* Full */; scheduleProgramUpdate(); } - function scheduleResolutionReload() { - writeLog("Clearing resolutions"); - resolutionCache.clear(); - updateLevel = 3 /* Resolutions */; - scheduleProgramUpdate(); - } function updateProgramWithWatchStatus() { timerToUpdateProgram = void 0; reportFileChangeDetectedOnCreateProgram = true; updateProgram(); } function updateProgram() { - var _a, _b, _c, _d, _e; switch (updateLevel) { case 1 /* RootNamesAndUpdate */: - (_a = perfLogger) == null ? void 0 : _a.logStartUpdateProgram("PartialConfigReload"); reloadFileNamesFromConfigFile(); break; case 2 /* Full */: - (_b = perfLogger) == null ? void 0 : _b.logStartUpdateProgram("FullConfigReload"); reloadConfigFile(); break; - case 3 /* Resolutions */: - (_c = perfLogger) == null ? void 0 : _c.logStartUpdateProgram("SynchronizeProgramWithResolutions"); - synchronizeProgram( - /*forceAllFilesAsInvalidated*/ - true - ); - break; default: - (_d = perfLogger) == null ? void 0 : _d.logStartUpdateProgram("SynchronizeProgram"); synchronizeProgram(); break; } - (_e = perfLogger) == null ? void 0 : _e.logStopUpdateProgram("Done"); return getCurrentBuilderProgram(); } function reloadFileNamesFromConfigFile() { @@ -226461,16 +227183,17 @@ var UpToDateStatusType = /* @__PURE__ */ ((UpToDateStatusType2) => { UpToDateStatusType2[UpToDateStatusType2["ErrorReadingFile"] = 4] = "ErrorReadingFile"; UpToDateStatusType2[UpToDateStatusType2["OutOfDateWithSelf"] = 5] = "OutOfDateWithSelf"; UpToDateStatusType2[UpToDateStatusType2["OutOfDateWithUpstream"] = 6] = "OutOfDateWithUpstream"; - UpToDateStatusType2[UpToDateStatusType2["OutOfDateBuildInfo"] = 7] = "OutOfDateBuildInfo"; - UpToDateStatusType2[UpToDateStatusType2["OutOfDateOptions"] = 8] = "OutOfDateOptions"; - UpToDateStatusType2[UpToDateStatusType2["OutOfDateRoots"] = 9] = "OutOfDateRoots"; - UpToDateStatusType2[UpToDateStatusType2["UpstreamOutOfDate"] = 10] = "UpstreamOutOfDate"; - UpToDateStatusType2[UpToDateStatusType2["UpstreamBlocked"] = 11] = "UpstreamBlocked"; - UpToDateStatusType2[UpToDateStatusType2["ComputingUpstream"] = 12] = "ComputingUpstream"; - UpToDateStatusType2[UpToDateStatusType2["TsVersionOutputOfDate"] = 13] = "TsVersionOutputOfDate"; - UpToDateStatusType2[UpToDateStatusType2["UpToDateWithInputFileText"] = 14] = "UpToDateWithInputFileText"; - UpToDateStatusType2[UpToDateStatusType2["ContainerOnly"] = 15] = "ContainerOnly"; - UpToDateStatusType2[UpToDateStatusType2["ForceBuild"] = 16] = "ForceBuild"; + UpToDateStatusType2[UpToDateStatusType2["OutOfDateBuildInfoWithPendingEmit"] = 7] = "OutOfDateBuildInfoWithPendingEmit"; + UpToDateStatusType2[UpToDateStatusType2["OutOfDateBuildInfoWithErrors"] = 8] = "OutOfDateBuildInfoWithErrors"; + UpToDateStatusType2[UpToDateStatusType2["OutOfDateOptions"] = 9] = "OutOfDateOptions"; + UpToDateStatusType2[UpToDateStatusType2["OutOfDateRoots"] = 10] = "OutOfDateRoots"; + UpToDateStatusType2[UpToDateStatusType2["UpstreamOutOfDate"] = 11] = "UpstreamOutOfDate"; + UpToDateStatusType2[UpToDateStatusType2["UpstreamBlocked"] = 12] = "UpstreamBlocked"; + UpToDateStatusType2[UpToDateStatusType2["ComputingUpstream"] = 13] = "ComputingUpstream"; + UpToDateStatusType2[UpToDateStatusType2["TsVersionOutputOfDate"] = 14] = "TsVersionOutputOfDate"; + UpToDateStatusType2[UpToDateStatusType2["UpToDateWithInputFileText"] = 15] = "UpToDateWithInputFileText"; + UpToDateStatusType2[UpToDateStatusType2["ContainerOnly"] = 16] = "ContainerOnly"; + UpToDateStatusType2[UpToDateStatusType2["ForceBuild"] = 17] = "ForceBuild"; return UpToDateStatusType2; })(UpToDateStatusType || {}); function resolveConfigFileProjectName(project) { @@ -226482,7 +227205,6 @@ function resolveConfigFileProjectName(project) { // src/compiler/tsbuildPublic.ts var minimumDate = /* @__PURE__ */ new Date(-864e13); -var maximumDate = /* @__PURE__ */ new Date(864e13); function getOrCreateValueFromConfigFileMap(configFileMap, resolved, createT) { const existingValue = configFileMap.get(resolved); let newValue; @@ -226537,6 +227259,7 @@ function getCompilerOptionsOfBuildOptions(buildOptions) { commonOptionsWithBuild.forEach((option) => { if (hasProperty(buildOptions, option.name)) result[option.name] = buildOptions[option.name]; }); + result.tscBuild = true; return result; } function createSolutionBuilder(host, rootNames, defaultOptions) { @@ -226940,7 +227663,7 @@ function createUpdateOutputFileStampsProject(state, project, projectPath, config } }; } -function createBuildOrUpdateInvalidedProject(state, project, projectPath, projectIndex, config, buildOrder) { +function createBuildOrUpdateInvalidedProject(state, project, projectPath, projectIndex, config, status, buildOrder) { let step = 0 /* CreateProgram */; let program; let buildResult; @@ -226991,17 +227714,13 @@ function createBuildOrUpdateInvalidedProject(state, project, projectPath, projec } ); } - executeSteps(2 /* SemanticDiagnostics */, cancellationToken); - if (step === 4 /* EmitBuildInfo */) { - return emitBuildInfo(writeFile2, cancellationToken); - } - if (step !== 3 /* Emit */) return void 0; + executeSteps(0 /* CreateProgram */, cancellationToken); return emit(writeFile2, cancellationToken, customTransformers); }, done }; function done(cancellationToken, writeFile2, customTransformers) { - executeSteps(6 /* Done */, cancellationToken, writeFile2, customTransformers); + executeSteps(3 /* Done */, cancellationToken, writeFile2, customTransformers); mark("SolutionBuilder::Projects built"); return doneInvalidatedProject(state, projectPath); } @@ -227018,14 +227737,14 @@ function createBuildOrUpdateInvalidedProject(state, project, projectPath, projec if (state.options.dry) { reportStatus(state, Diagnostics.A_non_dry_build_would_build_project_0, project); buildResult = 1 /* Success */; - step = 5 /* QueueReferencingProjects */; + step = 2 /* QueueReferencingProjects */; return; } if (state.options.verbose) reportStatus(state, Diagnostics.Building_project_0, project); if (config.fileNames.length === 0) { reportAndStoreErrors(state, projectPath, getConfigFileParsingDiagnostics(config)); buildResult = 0 /* None */; - step = 5 /* QueueReferencingProjects */; + step = 2 /* QueueReferencingProjects */; return; } const { host, compilerHost } = state; @@ -227053,185 +227772,97 @@ function createBuildOrUpdateInvalidedProject(state, project, projectPath, projec } step++; } - function handleDiagnostics(diagnostics, errorFlags, errorType) { - if (diagnostics.length) { - ({ buildResult, step } = buildErrors( - state, - projectPath, - program, - config, - diagnostics, - errorFlags, - errorType - )); - } else { - step++; - } - } - function getSyntaxDiagnostics(cancellationToken) { - Debug.assertIsDefined(program); - handleDiagnostics( - [ - ...program.getConfigFileParsingDiagnostics(), - ...program.getOptionsDiagnostics(cancellationToken), - ...program.getGlobalDiagnostics(cancellationToken), - ...program.getSyntacticDiagnostics( - /*sourceFile*/ - void 0, - cancellationToken - ) - ], - 8 /* SyntaxErrors */, - "Syntactic" - ); - } - function getSemanticDiagnostics(cancellationToken) { - handleDiagnostics( - Debug.checkDefined(program).getSemanticDiagnostics( - /*sourceFile*/ - void 0, - cancellationToken - ), - 16 /* TypeErrors */, - "Semantic" - ); - } function emit(writeFileCallback, cancellationToken, customTransformers) { var _a, _b, _c; Debug.assertIsDefined(program); - Debug.assert(step === 3 /* Emit */); - const saved = program.saveEmitState(); - let declDiagnostics; - const reportDeclarationDiagnostics = (d) => (declDiagnostics || (declDiagnostics = [])).push(d); - const outputFiles = []; - const { emitResult } = emitFilesAndReportErrors( + Debug.assert(step === 1 /* Emit */); + const { host, compilerHost } = state; + const emittedOutputs = /* @__PURE__ */ new Map(); + const options = program.getCompilerOptions(); + const isIncremental = isIncrementalCompilation(options); + let outputTimeStampMap; + let now; + const { emitResult, diagnostics } = emitFilesAndReportErrors( program, - reportDeclarationDiagnostics, - /*write*/ - void 0, + (d) => host.reportDiagnostic(d), + state.write, /*reportSummary*/ void 0, - (name, text, writeByteOrderMark, _onError, _sourceFiles, data) => outputFiles.push({ name, text, writeByteOrderMark, data }), + (name, text, writeByteOrderMark, onError, sourceFiles, data) => { + var _a2; + const path = toPath2(state, name); + emittedOutputs.set(toPath2(state, name), name); + if (data == null ? void 0 : data.buildInfo) { + now || (now = getCurrentTime(state.host)); + const isChangedSignature2 = (_a2 = program.hasChangedEmitSignature) == null ? void 0 : _a2.call(program); + const existing = getBuildInfoCacheEntry(state, name, projectPath); + if (existing) { + existing.buildInfo = data.buildInfo; + existing.modifiedTime = now; + if (isChangedSignature2) existing.latestChangedDtsTime = now; + } else { + state.buildInfoCache.set(projectPath, { + path: toPath2(state, name), + buildInfo: data.buildInfo, + modifiedTime: now, + latestChangedDtsTime: isChangedSignature2 ? now : void 0 + }); + } + } + const modifiedTime = (data == null ? void 0 : data.differsOnlyInMap) ? getModifiedTime(state.host, name) : void 0; + (writeFileCallback || compilerHost.writeFile)( + name, + text, + writeByteOrderMark, + onError, + sourceFiles, + data + ); + if (data == null ? void 0 : data.differsOnlyInMap) state.host.setModifiedTime(name, modifiedTime); + else if (!isIncremental && state.watch) { + (outputTimeStampMap || (outputTimeStampMap = getOutputTimeStampMap(state, projectPath))).set(path, now || (now = getCurrentTime(state.host))); + } + }, cancellationToken, /*emitOnlyDtsFiles*/ - false, + void 0, customTransformers || ((_b = (_a = state.host).getCustomTransformers) == null ? void 0 : _b.call(_a, project)) ); - if (declDiagnostics) { - program.restoreEmitState(saved); - ({ buildResult, step } = buildErrors( - state, - projectPath, - program, - config, - declDiagnostics, - 32 /* DeclarationEmitErrors */, - "Declaration file" - )); - return { - emitSkipped: true, - diagnostics: emitResult.diagnostics - }; + if ((!options.noEmitOnError || !diagnostics.length) && (emittedOutputs.size || status.type !== 8 /* OutOfDateBuildInfoWithErrors */)) { + updateOutputTimestampsWorker(state, config, projectPath, Diagnostics.Updating_unchanged_output_timestamps_of_project_0, emittedOutputs); } - const { host, compilerHost } = state; - const resultFlags = ((_c = program.hasChangedEmitSignature) == null ? void 0 : _c.call(program)) ? 0 /* None */ : 2 /* DeclarationOutputUnchanged */; - const emitterDiagnostics = createDiagnosticCollection(); - const emittedOutputs = /* @__PURE__ */ new Map(); - const options = program.getCompilerOptions(); - const isIncremental = isIncrementalCompilation(options); - let outputTimeStampMap; - let now; - outputFiles.forEach(({ name, text, writeByteOrderMark, data }) => { - const path = toPath2(state, name); - emittedOutputs.set(toPath2(state, name), name); - if (data == null ? void 0 : data.buildInfo) setBuildInfo(state, data.buildInfo, projectPath, options, resultFlags); - const modifiedTime = (data == null ? void 0 : data.differsOnlyInMap) ? getModifiedTime(state.host, name) : void 0; - writeFile(writeFileCallback ? { writeFile: writeFileCallback } : compilerHost, emitterDiagnostics, name, text, writeByteOrderMark); - if (data == null ? void 0 : data.differsOnlyInMap) state.host.setModifiedTime(name, modifiedTime); - else if (!isIncremental && state.watch) { - (outputTimeStampMap || (outputTimeStampMap = getOutputTimeStampMap(state, projectPath))).set(path, now || (now = getCurrentTime(state.host))); - } - }); - finishEmit( - emitterDiagnostics, - emittedOutputs, - outputFiles.length ? outputFiles[0].name : getFirstProjectOutput(config, !host.useCaseSensitiveFileNames()), - resultFlags - ); - return emitResult; - } - function emitBuildInfo(writeFileCallback, cancellationToken) { - Debug.assertIsDefined(program); - Debug.assert(step === 4 /* EmitBuildInfo */); - const emitResult = program.emitBuildInfo((name, text, writeByteOrderMark, onError, sourceFiles, data) => { - if (data == null ? void 0 : data.buildInfo) setBuildInfo(state, data.buildInfo, projectPath, program.getCompilerOptions(), 2 /* DeclarationOutputUnchanged */); - if (writeFileCallback) writeFileCallback(name, text, writeByteOrderMark, onError, sourceFiles, data); - else state.compilerHost.writeFile(name, text, writeByteOrderMark, onError, sourceFiles, data); - }, cancellationToken); - if (emitResult.diagnostics.length) { - reportErrors(state, emitResult.diagnostics); - state.diagnostics.set(projectPath, [...state.diagnostics.get(projectPath), ...emitResult.diagnostics]); - buildResult = 64 /* EmitErrors */ & buildResult; - } - if (emitResult.emittedFiles && state.write) { - emitResult.emittedFiles.forEach((name) => listEmittedFile(state, config, name)); + state.projectErrorsReported.set(projectPath, true); + buildResult = ((_c = program.hasChangedEmitSignature) == null ? void 0 : _c.call(program)) ? 0 /* None */ : 2 /* DeclarationOutputUnchanged */; + if (!diagnostics.length) { + state.diagnostics.delete(projectPath); + state.projectStatus.set(projectPath, { + type: 1 /* UpToDate */, + oldestOutputFileName: firstOrUndefinedIterator(emittedOutputs.values()) ?? getFirstProjectOutput(config, !host.useCaseSensitiveFileNames()) + }); + } else { + state.diagnostics.set(projectPath, diagnostics); + state.projectStatus.set(projectPath, { type: 0 /* Unbuildable */, reason: `it had errors` }); + buildResult |= 4 /* AnyErrors */; } afterProgramDone(state, program); - step = 5 /* QueueReferencingProjects */; + step = 2 /* QueueReferencingProjects */; return emitResult; } - function finishEmit(emitterDiagnostics, emittedOutputs, oldestOutputFileName, resultFlags) { - const emitDiagnostics = emitterDiagnostics.getDiagnostics(); - if (emitDiagnostics.length) { - ({ buildResult, step } = buildErrors( - state, - projectPath, - program, - config, - emitDiagnostics, - 64 /* EmitErrors */, - "Emit" - )); - return emitDiagnostics; - } - if (state.write) { - emittedOutputs.forEach((name) => listEmittedFile(state, config, name)); - } - updateOutputTimestampsWorker(state, config, projectPath, Diagnostics.Updating_unchanged_output_timestamps_of_project_0, emittedOutputs); - state.diagnostics.delete(projectPath); - state.projectStatus.set(projectPath, { - type: 1 /* UpToDate */, - oldestOutputFileName - }); - afterProgramDone(state, program); - step = 5 /* QueueReferencingProjects */; - buildResult = resultFlags; - return emitDiagnostics; - } function executeSteps(till, cancellationToken, writeFile2, customTransformers) { - while (step <= till && step < 6 /* Done */) { + while (step <= till && step < 3 /* Done */) { const currentStep = step; switch (step) { case 0 /* CreateProgram */: createProgram2(); break; - case 1 /* SyntaxDiagnostics */: - getSyntaxDiagnostics(cancellationToken); - break; - case 2 /* SemanticDiagnostics */: - getSemanticDiagnostics(cancellationToken); - break; - case 3 /* Emit */: + case 1 /* Emit */: emit(writeFile2, cancellationToken, customTransformers); break; - case 4 /* EmitBuildInfo */: - emitBuildInfo(writeFile2, cancellationToken); - break; - case 5 /* QueueReferencingProjects */: + case 2 /* QueueReferencingProjects */: queueReferencingProjects(state, project, projectPath, projectIndex, config, buildOrder, Debug.checkDefined(buildResult)); step++; break; - case 6 /* Done */: + case 3 /* Done */: default: assertType(step); } @@ -227281,7 +227912,7 @@ function getNextInvalidatedProjectCreateInfo(state, buildOrder, reportQueue) { } continue; } - if (status.type === 2 /* UpToDateWithUpstreamTypes */ || status.type === 14 /* UpToDateWithInputFileText */) { + if (status.type === 2 /* UpToDateWithUpstreamTypes */ || status.type === 15 /* UpToDateWithInputFileText */) { reportAndStoreErrors(state, projectPath, getConfigFileParsingDiagnostics(config)); return { kind: 1 /* UpdateOutputFileStamps */, @@ -227293,7 +227924,7 @@ function getNextInvalidatedProjectCreateInfo(state, buildOrder, reportQueue) { }; } } - if (status.type === 11 /* UpstreamBlocked */) { + if (status.type === 12 /* UpstreamBlocked */) { verboseReportProjectStatus(state, project, status); reportAndStoreErrors(state, projectPath, getConfigFileParsingDiagnostics(config)); projectPendingBuild.delete(projectPath); @@ -227307,7 +227938,7 @@ function getNextInvalidatedProjectCreateInfo(state, buildOrder, reportQueue) { } continue; } - if (status.type === 15 /* ContainerOnly */) { + if (status.type === 16 /* ContainerOnly */) { verboseReportProjectStatus(state, project, status); reportAndStoreErrors(state, projectPath, getConfigFileParsingDiagnostics(config)); projectPendingBuild.delete(projectPath); @@ -227332,6 +227963,7 @@ function createInvalidatedProjectWithInfo(state, info, buildOrder) { info.projectPath, info.projectIndex, info.config, + info.status, buildOrder ) : createUpdateOutputFileStampsProject( state, @@ -227346,11 +227978,6 @@ function getNextInvalidatedProject(state, buildOrder, reportQueue) { if (!info) return info; return createInvalidatedProjectWithInfo(state, info, buildOrder); } -function listEmittedFile({ write }, proj, file) { - if (write && proj.options.listEmittedFiles) { - write(`TSFILE: ${file}`); - } -} function getOldProgram({ options, builderPrograms, compilerHost }, proj, parsed) { if (options.force) return void 0; const value = builderPrograms.get(proj); @@ -227359,7 +227986,6 @@ function getOldProgram({ options, builderPrograms, compilerHost }, proj, parsed) } function afterProgramDone(state, program) { if (program) { - if (state.write) listFiles(program, state.write); if (state.host.afterProgramEmitAndDiagnostics) { state.host.afterProgramEmitAndDiagnostics(program); } @@ -227367,14 +227993,6 @@ function afterProgramDone(state, program) { } state.projectCompilerOptions = state.baseCompilerOptions; } -function buildErrors(state, resolvedPath, program, config, diagnostics, buildResult, errorType) { - const canEmitBuildInfo = program && !program.getCompilerOptions().outFile; - reportAndStoreErrors(state, resolvedPath, diagnostics); - state.projectStatus.set(resolvedPath, { type: 0 /* Unbuildable */, reason: `${errorType} errors` }); - if (canEmitBuildInfo) return { buildResult, step: 4 /* EmitBuildInfo */ }; - afterProgramDone(state, program); - return { buildResult, step: 5 /* QueueReferencingProjects */ }; -} function isFileWatcherWithModifiedTime(value) { return !!value.watcher; } @@ -227432,23 +228050,6 @@ function getOutputTimeStampMap(state, resolvedConfigFilePath) { if (!result) state.outputTimeStamps.set(resolvedConfigFilePath, result = /* @__PURE__ */ new Map()); return result; } -function setBuildInfo(state, buildInfo, resolvedConfigPath, options, resultFlags) { - const buildInfoPath = getTsBuildInfoEmitOutputFilePath(options); - const existing = getBuildInfoCacheEntry(state, buildInfoPath, resolvedConfigPath); - const modifiedTime = getCurrentTime(state.host); - if (existing) { - existing.buildInfo = buildInfo; - existing.modifiedTime = modifiedTime; - if (!(resultFlags & 2 /* DeclarationOutputUnchanged */)) existing.latestChangedDtsTime = modifiedTime; - } else { - state.buildInfoCache.set(resolvedConfigPath, { - path: toPath2(state, buildInfoPath), - buildInfo, - modifiedTime, - latestChangedDtsTime: resultFlags & 2 /* DeclarationOutputUnchanged */ ? void 0 : modifiedTime - }); - } -} function getBuildInfoCacheEntry(state, buildInfoPath, resolvedConfigPath) { const path = toPath2(state, buildInfoPath); const existing = state.buildInfoCache.get(resolvedConfigPath); @@ -227476,99 +228077,107 @@ function checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, } } function getUpToDateStatusWorker(state, project, resolvedPath) { - var _a, _b, _c, _d; + var _a, _b, _c, _d, _e; if (!project.fileNames.length && !canJsonReportNoInputFiles(project.raw)) { return { - type: 15 /* ContainerOnly */ + type: 16 /* ContainerOnly */ }; } let referenceStatuses; const force = !!state.options.force; if (project.projectReferences) { - state.projectStatus.set(resolvedPath, { type: 12 /* ComputingUpstream */ }); + state.projectStatus.set(resolvedPath, { type: 13 /* ComputingUpstream */ }); for (const ref of project.projectReferences) { const resolvedRef = resolveProjectReferencePath(ref); const resolvedRefPath = toResolvedConfigFilePath(state, resolvedRef); const resolvedConfig = parseConfigFile(state, resolvedRef, resolvedRefPath); const refStatus = getUpToDateStatus(state, resolvedConfig, resolvedRefPath); - if (refStatus.type === 12 /* ComputingUpstream */ || refStatus.type === 15 /* ContainerOnly */) { + if (refStatus.type === 13 /* ComputingUpstream */ || refStatus.type === 16 /* ContainerOnly */) { continue; } - if (refStatus.type === 0 /* Unbuildable */ || refStatus.type === 11 /* UpstreamBlocked */) { + if (state.options.stopBuildOnErrors && (refStatus.type === 0 /* Unbuildable */ || refStatus.type === 12 /* UpstreamBlocked */)) { return { - type: 11 /* UpstreamBlocked */, + type: 12 /* UpstreamBlocked */, upstreamProjectName: ref.path, - upstreamProjectBlocked: refStatus.type === 11 /* UpstreamBlocked */ - }; - } - if (refStatus.type !== 1 /* UpToDate */) { - return { - type: 10 /* UpstreamOutOfDate */, - upstreamProjectName: ref.path + upstreamProjectBlocked: refStatus.type === 12 /* UpstreamBlocked */ }; } if (!force) (referenceStatuses || (referenceStatuses = [])).push({ ref, refStatus, resolvedRefPath, resolvedConfig }); } } - if (force) return { type: 16 /* ForceBuild */ }; + if (force) return { type: 17 /* ForceBuild */ }; const { host } = state; const buildInfoPath = getTsBuildInfoEmitOutputFilePath(project.options); - let oldestOutputFileName; - let oldestOutputFileTime = maximumDate; - let buildInfoTime; - let buildInfoProgram; - let buildInfoVersionMap; - if (buildInfoPath) { - const buildInfoCacheEntry2 = getBuildInfoCacheEntry(state, buildInfoPath, resolvedPath); - buildInfoTime = (buildInfoCacheEntry2 == null ? void 0 : buildInfoCacheEntry2.modifiedTime) || getModifiedTime(host, buildInfoPath); - if (buildInfoTime === missingFileModifiedTime) { - if (!buildInfoCacheEntry2) { - state.buildInfoCache.set(resolvedPath, { - path: toPath2(state, buildInfoPath), - buildInfo: false, - modifiedTime: buildInfoTime - }); - } + const isIncremental = isIncrementalCompilation(project.options); + let buildInfoCacheEntry = getBuildInfoCacheEntry(state, buildInfoPath, resolvedPath); + const buildInfoTime = (buildInfoCacheEntry == null ? void 0 : buildInfoCacheEntry.modifiedTime) || getModifiedTime(host, buildInfoPath); + if (buildInfoTime === missingFileModifiedTime) { + if (!buildInfoCacheEntry) { + state.buildInfoCache.set(resolvedPath, { + path: toPath2(state, buildInfoPath), + buildInfo: false, + modifiedTime: buildInfoTime + }); + } + return { + type: 3 /* OutputMissing */, + missingOutputFileName: buildInfoPath + }; + } + const buildInfo = getBuildInfo3(state, buildInfoPath, resolvedPath, buildInfoTime); + if (!buildInfo) { + return { + type: 4 /* ErrorReadingFile */, + fileName: buildInfoPath + }; + } + const incrementalBuildInfo = isIncremental && isIncrementalBuildInfo(buildInfo) ? buildInfo : void 0; + if ((incrementalBuildInfo || !isIncremental) && buildInfo.version !== version) { + return { + type: 14 /* TsVersionOutputOfDate */, + version: buildInfo.version + }; + } + if (!project.options.noCheck && (buildInfo.errors || // TODO: syntax errors???? + buildInfo.checkPending)) { + return { + type: 8 /* OutOfDateBuildInfoWithErrors */, + buildInfoFile: buildInfoPath + }; + } + if (incrementalBuildInfo) { + if (!project.options.noCheck && (((_a = incrementalBuildInfo.changeFileSet) == null ? void 0 : _a.length) || ((_b = incrementalBuildInfo.semanticDiagnosticsPerFile) == null ? void 0 : _b.length) || getEmitDeclarations(project.options) && ((_c = incrementalBuildInfo.emitDiagnosticsPerFile) == null ? void 0 : _c.length))) { return { - type: 3 /* OutputMissing */, - missingOutputFileName: buildInfoPath + type: 8 /* OutOfDateBuildInfoWithErrors */, + buildInfoFile: buildInfoPath }; } - const buildInfo = getBuildInfo3(state, buildInfoPath, resolvedPath, buildInfoTime); - if (!buildInfo) { + if (!project.options.noEmit && (((_d = incrementalBuildInfo.changeFileSet) == null ? void 0 : _d.length) || ((_e = incrementalBuildInfo.affectedFilesPendingEmit) == null ? void 0 : _e.length) || incrementalBuildInfo.pendingEmit !== void 0)) { return { - type: 4 /* ErrorReadingFile */, - fileName: buildInfoPath + type: 7 /* OutOfDateBuildInfoWithPendingEmit */, + buildInfoFile: buildInfoPath }; } - if (buildInfo.program && buildInfo.version !== version) { + if ((!project.options.noEmit || project.options.noEmit && getEmitDeclarations(project.options)) && getPendingEmitKindWithSeen( + project.options, + incrementalBuildInfo.options || {}, + /*emitOnlyDtsFiles*/ + void 0, + !!project.options.noEmit + )) { return { - type: 13 /* TsVersionOutputOfDate */, - version: buildInfo.version + type: 9 /* OutOfDateOptions */, + buildInfoFile: buildInfoPath }; } - if (buildInfo.program) { - if (((_a = buildInfo.program.changeFileSet) == null ? void 0 : _a.length) || (!project.options.noEmit ? ((_b = buildInfo.program.affectedFilesPendingEmit) == null ? void 0 : _b.length) || ((_c = buildInfo.program.emitDiagnosticsPerFile) == null ? void 0 : _c.length) : (_d = buildInfo.program.semanticDiagnosticsPerFile) == null ? void 0 : _d.length)) { - return { - type: 7 /* OutOfDateBuildInfo */, - buildInfoFile: buildInfoPath - }; - } - if (!project.options.noEmit && getPendingEmitKind(project.options, buildInfo.program.options || {})) { - return { - type: 8 /* OutOfDateOptions */, - buildInfoFile: buildInfoPath - }; - } - buildInfoProgram = buildInfo.program; - } - oldestOutputFileTime = buildInfoTime; - oldestOutputFileName = buildInfoPath; } + let oldestOutputFileTime = buildInfoTime; + let oldestOutputFileName = buildInfoPath; let newestInputFileName = void 0; let newestInputFileTime = minimumDate; let pseudoInputUpToDate = false; const seenRoots = /* @__PURE__ */ new Set(); + let buildInfoVersionMap; for (const inputFile of project.fileNames) { const inputTime = getModifiedTime2(state, inputFile); if (inputTime === missingFileModifiedTime) { @@ -227577,12 +228186,12 @@ function getUpToDateStatusWorker(state, project, resolvedPath) { reason: `${inputFile} does not exist` }; } - const inputPath = buildInfoProgram ? toPath2(state, inputFile) : void 0; - if (buildInfoTime && buildInfoTime < inputTime) { + const inputPath = toPath2(state, inputFile); + if (buildInfoTime < inputTime) { let version2; let currentVersion; - if (buildInfoProgram) { - if (!buildInfoVersionMap) buildInfoVersionMap = getBuildInfoFileVersionMap(buildInfoProgram, buildInfoPath, host); + if (incrementalBuildInfo) { + if (!buildInfoVersionMap) buildInfoVersionMap = getBuildInfoFileVersionMap(incrementalBuildInfo, buildInfoPath, host); const resolvedInputPath = buildInfoVersionMap.roots.get(inputPath); version2 = buildInfoVersionMap.fileInfos.get(resolvedInputPath ?? inputPath); const text = version2 ? state.readFileWithCache(resolvedInputPath ?? inputFile) : void 0; @@ -227601,27 +228210,34 @@ function getUpToDateStatusWorker(state, project, resolvedPath) { newestInputFileName = inputFile; newestInputFileTime = inputTime; } - if (buildInfoProgram) seenRoots.add(inputPath); + seenRoots.add(inputPath); } - if (buildInfoProgram) { - if (!buildInfoVersionMap) buildInfoVersionMap = getBuildInfoFileVersionMap(buildInfoProgram, buildInfoPath, host); - const existingRoot = forEachEntry( + let existingRoot; + if (incrementalBuildInfo) { + if (!buildInfoVersionMap) buildInfoVersionMap = getBuildInfoFileVersionMap(incrementalBuildInfo, buildInfoPath, host); + existingRoot = forEachEntry( buildInfoVersionMap.roots, // File was root file when project was built but its not any more (_resolved, existingRoot2) => !seenRoots.has(existingRoot2) ? existingRoot2 : void 0 ); - if (existingRoot) { - return { - type: 9 /* OutOfDateRoots */, - buildInfoFile: buildInfoPath, - inputFile: existingRoot - }; - } + } else { + existingRoot = forEach( + getNonIncrementalBuildInfoRoots(buildInfo, buildInfoPath, host), + (root) => !seenRoots.has(root) ? root : void 0 + ); } - if (!buildInfoPath) { + if (existingRoot) { + return { + type: 10 /* OutOfDateRoots */, + buildInfoFile: buildInfoPath, + inputFile: existingRoot + }; + } + if (!isIncremental) { const outputs = getAllProjectOutputs(project, !host.useCaseSensitiveFileNames()); const outputTimeStampMap = getOutputTimeStampMap(state, resolvedPath); for (const output of outputs) { + if (output === buildInfoPath) continue; const path = toPath2(state, output); let outputTime = outputTimeStampMap == null ? void 0 : outputTimeStampMap.get(path); if (!outputTime) { @@ -227647,14 +228263,13 @@ function getUpToDateStatusWorker(state, project, resolvedPath) { } } } - const buildInfoCacheEntry = state.buildInfoCache.get(resolvedPath); let pseudoUpToDate = false; if (referenceStatuses) { for (const { ref, refStatus, resolvedConfig, resolvedRefPath } of referenceStatuses) { if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) { continue; } - if (buildInfoCacheEntry && hasSameBuildInfo(state, buildInfoCacheEntry, resolvedRefPath)) { + if (hasSameBuildInfo(state, buildInfoCacheEntry ?? (buildInfoCacheEntry = state.buildInfoCache.get(resolvedPath)), resolvedRefPath)) { return { type: 6 /* OutOfDateWithUpstream */, outOfDateOutputFileName: buildInfoPath, @@ -227685,7 +228300,7 @@ function getUpToDateStatusWorker(state, project, resolvedPath) { ); if (dependentPackageFileStatus) return dependentPackageFileStatus; return { - type: pseudoUpToDate ? 2 /* UpToDateWithUpstreamTypes */ : pseudoInputUpToDate ? 14 /* UpToDateWithInputFileText */ : 1 /* UpToDate */, + type: pseudoUpToDate ? 2 /* UpToDateWithUpstreamTypes */ : pseudoInputUpToDate ? 15 /* UpToDateWithInputFileText */ : 1 /* UpToDate */, newestInputFileTime, newestInputFileName, oldestOutputFileName @@ -227697,7 +228312,7 @@ function hasSameBuildInfo(state, buildInfoCacheEntry, resolvedRefPath) { } function getUpToDateStatus(state, project, resolvedPath) { if (project === void 0) { - return { type: 0 /* Unbuildable */, reason: "File deleted mid-build" }; + return { type: 0 /* Unbuildable */, reason: "config file deleted mid-build" }; } const prior = state.projectStatus.get(resolvedPath); if (prior !== void 0) { @@ -227714,7 +228329,8 @@ function updateOutputTimestampsWorker(state, proj, projectPath, verboseMessage, if (proj.options.noEmit) return; let now; const buildInfoPath = getTsBuildInfoEmitOutputFilePath(proj.options); - if (buildInfoPath) { + const isIncremental = isIncrementalCompilation(proj.options); + if (buildInfoPath && isIncremental) { if (!(skipOutputs == null ? void 0 : skipOutputs.has(toPath2(state, buildInfoPath)))) { if (!!state.options.verbose) reportStatus(state, verboseMessage, proj.options.configFilePath); state.host.setModifiedTime(buildInfoPath, now = getCurrentTime(state.host)); @@ -227737,7 +228353,8 @@ function updateOutputTimestampsWorker(state, proj, projectPath, verboseMessage, reportStatus(state, verboseMessage, proj.options.configFilePath); } host.setModifiedTime(file, now || (now = getCurrentTime(state.host))); - if (outputTimeStampMap) { + if (file === buildInfoPath) getBuildInfoCacheEntry(state, buildInfoPath, projectPath).modifiedTime = now; + else if (outputTimeStampMap) { outputTimeStampMap.set(path, now); modifiedOutputs.add(path); } @@ -227751,7 +228368,7 @@ function getLatestChangedDtsTime(state, options, resolvedConfigPath) { if (!options.composite) return void 0; const entry = Debug.checkDefined(state.buildInfoCache.get(resolvedConfigPath)); if (entry.latestChangedDtsTime !== void 0) return entry.latestChangedDtsTime || void 0; - const latestChangedDtsTime = entry.buildInfo && entry.buildInfo.program && entry.buildInfo.program.latestChangedDtsFile ? state.host.getModifiedTime(getNormalizedAbsolutePath(entry.buildInfo.program.latestChangedDtsFile, getDirectoryPath(entry.path))) : void 0; + const latestChangedDtsTime = entry.buildInfo && isIncrementalBuildInfo(entry.buildInfo) && entry.buildInfo.latestChangedDtsFile ? state.host.getModifiedTime(getNormalizedAbsolutePath(entry.buildInfo.latestChangedDtsFile, getDirectoryPath(entry.path))) : void 0; entry.latestChangedDtsTime = latestChangedDtsTime || false; return latestChangedDtsTime; } @@ -227766,7 +228383,7 @@ function updateOutputTimestamps(state, proj, resolvedPath) { }); } function queueReferencingProjects(state, project, projectPath, projectIndex, config, buildOrder, buildResult) { - if (buildResult & 124 /* AnyErrors */) return; + if (state.options.stopBuildOnErrors && buildResult & 4 /* AnyErrors */) return; if (!config.options.composite) return; for (let index = projectIndex + 1; index < buildOrder.length; index++) { const nextProject = buildOrder[index]; @@ -227785,7 +228402,7 @@ function queueReferencingProjects(state, project, projectPath, projectIndex, con status.type = 2 /* UpToDateWithUpstreamTypes */; break; } - case 14 /* UpToDateWithInputFileText */: + case 15 /* UpToDateWithInputFileText */: case 2 /* UpToDateWithUpstreamTypes */: if (!(buildResult & 2 /* DeclarationOutputUnchanged */)) { state.projectStatus.set(nextProjectPath, { @@ -227795,7 +228412,7 @@ function queueReferencingProjects(state, project, projectPath, projectIndex, con }); } break; - case 11 /* UpstreamBlocked */: + case 12 /* UpstreamBlocked */: if (toResolvedConfigFilePath(state, resolveProjectName(state, status.upstreamProjectName)) === projectPath) { clearProjectStatus(state, nextProjectPath); } @@ -228214,21 +228831,28 @@ function reportUpToDateStatus(state, configFileName, status) { relName(state, configFileName), relName(state, status.fileName) ); - case 7 /* OutOfDateBuildInfo */: + case 7 /* OutOfDateBuildInfoWithPendingEmit */: return reportStatus( state, Diagnostics.Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_some_of_the_changes_were_not_emitted, relName(state, configFileName), relName(state, status.buildInfoFile) ); - case 8 /* OutOfDateOptions */: + case 8 /* OutOfDateBuildInfoWithErrors */: + return reportStatus( + state, + Diagnostics.Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_program_needs_to_report_errors, + relName(state, configFileName), + relName(state, status.buildInfoFile) + ); + case 9 /* OutOfDateOptions */: return reportStatus( state, Diagnostics.Project_0_is_out_of_date_because_buildinfo_file_1_indicates_there_is_change_in_compilerOptions, relName(state, configFileName), relName(state, status.buildInfoFile) ); - case 9 /* OutOfDateRoots */: + case 10 /* OutOfDateRoots */: return reportStatus( state, Diagnostics.Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_file_2_was_root_file_of_compilation_but_not_any_more, @@ -228253,20 +228877,20 @@ function reportUpToDateStatus(state, configFileName, status) { Diagnostics.Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies, relName(state, configFileName) ); - case 14 /* UpToDateWithInputFileText */: + case 15 /* UpToDateWithInputFileText */: return reportStatus( state, Diagnostics.Project_0_is_up_to_date_but_needs_to_update_timestamps_of_output_files_that_are_older_than_input_files, relName(state, configFileName) ); - case 10 /* UpstreamOutOfDate */: + case 11 /* UpstreamOutOfDate */: return reportStatus( state, Diagnostics.Project_0_is_out_of_date_because_its_dependency_1_is_out_of_date, relName(state, configFileName), relName(state, status.upstreamProjectName) ); - case 11 /* UpstreamBlocked */: + case 12 /* UpstreamBlocked */: return reportStatus( state, status.upstreamProjectBlocked ? Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_was_not_built : Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_has_errors, @@ -228276,11 +228900,11 @@ function reportUpToDateStatus(state, configFileName, status) { case 0 /* Unbuildable */: return reportStatus( state, - Diagnostics.Failed_to_parse_file_0_Colon_1, + Diagnostics.Project_0_is_out_of_date_because_1, relName(state, configFileName), status.reason ); - case 13 /* TsVersionOutputOfDate */: + case 14 /* TsVersionOutputOfDate */: return reportStatus( state, Diagnostics.Project_0_is_out_of_date_because_output_for_it_was_generated_with_version_1_that_differs_with_current_version_2, @@ -228288,14 +228912,14 @@ function reportUpToDateStatus(state, configFileName, status) { status.version, version ); - case 16 /* ForceBuild */: + case 17 /* ForceBuild */: return reportStatus( state, Diagnostics.Project_0_is_being_forcibly_rebuilt, relName(state, configFileName) ); - case 15 /* ContainerOnly */: - case 12 /* ComputingUpstream */: + case 16 /* ContainerOnly */: + case 13 /* ComputingUpstream */: break; default: assertType(status); @@ -228367,7 +228991,7 @@ function shouldBePretty(sys2, options) { return options.pretty; } function getOptionsForHelp(commandLine) { - return !!commandLine.options.all ? sort(optionDeclarations, (a, b) => compareStringsCaseInsensitive(a.name, b.name)) : filter(optionDeclarations.slice(), (v) => !!v.showInSimplifiedHelpView); + return !!commandLine.options.all ? toSorted(optionDeclarations, (a, b) => compareStringsCaseInsensitive(a.name, b.name)) : filter(optionDeclarations.slice(), (v) => !!v.showInSimplifiedHelpView); } function printVersion(sys2) { sys2.write(getDiagnosticText(Diagnostics.Version_0, version) + sys2.newLine); @@ -229540,7 +230164,7 @@ function createSyntacticTypeNodeBuilder(options, resolver) { return typeFromAccessor(parent2, context); } const declaredType = getEffectiveTypeAnnotationNode(node); - const addUndefined = resolver.requiresAddingImplicitUndefined(node); + const addUndefined = resolver.requiresAddingImplicitUndefined(node, context.enclosingDeclaration); let resultType; if (declaredType) { resultType = serializeExistingTypeAnnotation(declaredType, addUndefined); @@ -229848,7 +230472,6 @@ __export(ts_JsTyping_exports, { nodeCoreModuleList: () => nodeCoreModuleList, nodeCoreModules: () => nodeCoreModules, nonRelativeModuleNameForTypingCache: () => nonRelativeModuleNameForTypingCache, - prefixedNodeCoreModuleList: () => prefixedNodeCoreModuleList, renderPackageNameValidationFailure: () => renderPackageNameValidationFailure, validatePackageName: () => validatePackageName }); @@ -231946,7 +232569,9 @@ function createModuleSpecifierResolutionHost(program, host) { isSourceOfProjectReferenceRedirect: (fileName) => program.isSourceOfProjectReferenceRedirect(fileName), getNearestAncestorDirectoryWithPackageJson: maybeBind(host, host.getNearestAncestorDirectoryWithPackageJson), getFileIncludeReasons: () => program.getFileIncludeReasons(), - getCommonSourceDirectory: () => program.getCommonSourceDirectory() + getCommonSourceDirectory: () => program.getCommonSourceDirectory(), + getDefaultResolutionModeForFile: (file) => program.getDefaultResolutionModeForFile(file), + getModeForResolutionAtIndex: (file, index) => program.getModeForResolutionAtIndex(file, index) }; } function getModuleSpecifierResolverHost(program, host) { @@ -232045,7 +232670,7 @@ function insertImports(changes, sourceFile, imports, blankLineBetween, preferenc const importKindPredicate = decl.kind === 243 /* VariableStatement */ ? isRequireVariableStatement : isAnyImportSyntax; const existingImportStatements = filter(sourceFile.statements, importKindPredicate); const { comparer, isSorted } = ts_OrganizeImports_exports.getOrganizeImportsStringComparerWithDetection(existingImportStatements, preferences); - const sortedNewImports = isArray(imports) ? stableSort(imports, (a, b) => ts_OrganizeImports_exports.compareImportsOrRequireStatements(a, b, comparer)) : [imports]; + const sortedNewImports = isArray(imports) ? toSorted(imports, (a, b) => ts_OrganizeImports_exports.compareImportsOrRequireStatements(a, b, comparer)) : [imports]; if (!(existingImportStatements == null ? void 0 : existingImportStatements.length)) { if (isFullSourceFile(sourceFile)) { changes.insertNodesAtTopOfFile(sourceFile, sortedNewImports, blankLineBetween); @@ -232408,13 +233033,6 @@ function signatureToDisplayParts(typechecker, signature, enclosingDeclaration, f ); }); } -function nodeToDisplayParts(node, enclosingDeclaration) { - const file = enclosingDeclaration.getSourceFile(); - return mapToDisplayParts((writer) => { - const printer = createPrinterWithRemoveCommentsOmitTrailingSemicolon(); - printer.writeNode(4 /* Unspecified */, node, file, writer); - }); -} function isImportOrExportSpecifierName(location) { return !!location.parent && isImportOrExportSpecifier(location.parent) && location.parent.propertyName === location; } @@ -232655,7 +233273,7 @@ function getTypeNodeIfAccessible(type, enclosingScope, program, host) { const checker = program.getTypeChecker(); let typeIsAccessible = true; const notAccessible = () => typeIsAccessible = false; - const res = checker.typeToTypeNode(type, enclosingScope, 1 /* NoTruncation */, { + const res = checker.typeToTypeNode(type, enclosingScope, 1 /* NoTruncation */, 8 /* AllowUnresolvedNames */, { trackSymbol: (symbol, declaration, meaning) => { typeIsAccessible = typeIsAccessible && checker.isSymbolAccessible( symbol, @@ -232884,7 +233502,7 @@ function createPackageJsonImportFilter(fromFile, preferences, host) { let sourceFileCache; return { allowsImportingAmbientModule, - allowsImportingSourceFile, + getSourceFileInfo, allowsImportingSpecifier }; function moduleSpecifierIsCoveredByPackageJson(specifier) { @@ -232923,9 +233541,9 @@ function createPackageJsonImportFilter(fromFile, preferences, host) { ambientModuleCache.set(moduleSymbol, result); return result; } - function allowsImportingSourceFile(sourceFile, moduleSpecifierResolutionHost) { + function getSourceFileInfo(sourceFile, moduleSpecifierResolutionHost) { if (!packageJsons.length) { - return true; + return { importable: true, packageName: void 0 }; } if (!sourceFileCache) { sourceFileCache = /* @__PURE__ */ new Map(); @@ -232935,12 +233553,14 @@ function createPackageJsonImportFilter(fromFile, preferences, host) { return cached; } } - const moduleSpecifier = getNodeModulesPackageNameFromFileName(sourceFile.fileName, moduleSpecifierResolutionHost); - if (!moduleSpecifier) { - sourceFileCache.set(sourceFile, true); - return true; + const packageName = getNodeModulesPackageNameFromFileName(sourceFile.fileName, moduleSpecifierResolutionHost); + if (!packageName) { + const result2 = { importable: true, packageName }; + sourceFileCache.set(sourceFile, result2); + return result2; } - const result = moduleSpecifierIsCoveredByPackageJson(moduleSpecifier); + const importable = moduleSpecifierIsCoveredByPackageJson(packageName); + const result = { importable, packageName }; sourceFileCache.set(sourceFile, result); return result; } @@ -232965,14 +233585,7 @@ function createPackageJsonImportFilter(fromFile, preferences, host) { return false; } function getNodeModulesPackageNameFromFileName(importedFileName, moduleSpecifierResolutionHost) { - const pnpapi = getPnpApi(importedFileName); - if (pnpapi) { - const fromLocator = pnpapi.findPackageLocator(fromFile.fileName); - const toLocator = pnpapi.findPackageLocator(importedFileName); - if (!(fromLocator && toLocator)) { - return void 0; - } - } else if (!importedFileName.includes("node_modules")) { + if (!importedFileName.includes("node_modules")) { return void 0; } const specifier = ts_moduleSpecifiers_exports.getNodeModulesPackageName( @@ -233057,36 +233670,12 @@ function mapOneOrMany(valueOrArray, f, resultSelector = identity) { function firstOrOnly(valueOrArray) { return isArray(valueOrArray) ? first(valueOrArray) : valueOrArray; } -function getNamesForExportedSymbol(symbol, scriptTarget) { - if (needsNameFromDeclaration(symbol)) { - const fromDeclaration = getDefaultLikeExportNameFromDeclaration(symbol); - if (fromDeclaration) return fromDeclaration; - const fileNameCase = moduleSymbolToValidIdentifier( - getSymbolParentOrFail(symbol), - scriptTarget, - /*forceCapitalize*/ - false - ); - const capitalized = moduleSymbolToValidIdentifier( - getSymbolParentOrFail(symbol), - scriptTarget, - /*forceCapitalize*/ - true - ); - if (fileNameCase === capitalized) return fileNameCase; - return [fileNameCase, capitalized]; - } - return symbol.name; -} function getNameForExportedSymbol(symbol, scriptTarget, preferCapitalized) { - if (needsNameFromDeclaration(symbol)) { + if (symbol.escapedName === "export=" /* ExportEquals */ || symbol.escapedName === "default" /* Default */) { return getDefaultLikeExportNameFromDeclaration(symbol) || moduleSymbolToValidIdentifier(getSymbolParentOrFail(symbol), scriptTarget, !!preferCapitalized); } return symbol.name; } -function needsNameFromDeclaration(symbol) { - return !(symbol.flags & 33554432 /* Transient */) && (symbol.escapedName === "export=" /* ExportEquals */ || symbol.escapedName === "default" /* Default */); -} function getDefaultLikeExportNameFromDeclaration(symbol) { return firstDefined(symbol.declarations, (d) => { var _a, _b, _c; @@ -233154,16 +233743,6 @@ function stringContainsAt(haystack, needle, startIndex) { function startsWithUnderscore(name) { return name.charCodeAt(0) === 95 /* _ */; } -function isGlobalDeclaration(declaration) { - return !isNonGlobalDeclaration(declaration); -} -function isNonGlobalDeclaration(declaration) { - const sourceFile = declaration.getSourceFile(); - if (!sourceFile.externalModuleIndicator && !sourceFile.commonJsModuleIndicator) { - return false; - } - return isInJSFile(declaration) || !findAncestor(declaration, (d) => isModuleDeclaration(d) && isGlobalScopeAugmentation(d)); -} function isDeprecatedDeclaration(decl) { return !!(getCombinedNodeFlagsAlwaysIncludeJSDoc(decl) & 65536 /* Deprecated */); } @@ -233259,9 +233838,13 @@ function fileShouldUseJavaScriptRequire(file, program, host, preferRequire) { if (!hasJSFileExtension(fileName)) { return false; } - const compilerOptions = program.getCompilerOptions(); + const compilerOptions = typeof file === "string" ? program.getCompilerOptions() : program.getCompilerOptionsForFile(file); const moduleKind = getEmitModuleKind(compilerOptions); - const impliedNodeFormat = typeof file === "string" ? getImpliedNodeFormatForFile(toPath(file, host.getCurrentDirectory(), hostGetCanonicalFileName(host)), (_a = program.getPackageJsonInfoCache) == null ? void 0 : _a.call(program), host, compilerOptions) : file.impliedNodeFormat; + const sourceFileLike = typeof file === "string" ? { + fileName: file, + impliedNodeFormat: getImpliedNodeFormatForFile(toPath(file, host.getCurrentDirectory(), hostGetCanonicalFileName(host)), (_a = program.getPackageJsonInfoCache) == null ? void 0 : _a.call(program), host, compilerOptions) + } : file; + const impliedNodeFormat = getImpliedNodeFormatForEmitWorker(sourceFileLike, compilerOptions); if (impliedNodeFormat === 99 /* ESNext */) { return false; } @@ -233373,6 +233956,7 @@ function createCacheableExportInfoMap(host) { const namedSymbol = isDefault && getLocalSymbolForExportDefault(symbol) || symbol; const names = exportKind === 0 /* Named */ || isExternalModuleSymbol(namedSymbol) ? unescapeLeadingUnderscores(symbolTableKey) : getNamesForExportedSymbol( namedSymbol, + checker, /*scriptTarget*/ void 0 ); @@ -233522,7 +234106,7 @@ function isImportableFile(program, from, to, preferences, packageJsonFilter, mod if (from === to) return false; const cachedResult = moduleSpecifierCache == null ? void 0 : moduleSpecifierCache.get(from.path, to.path, preferences, {}); if ((cachedResult == null ? void 0 : cachedResult.isBlockedByPackageJsonDependencies) !== void 0) { - return !cachedResult.isBlockedByPackageJsonDependencies; + return !cachedResult.isBlockedByPackageJsonDependencies || !!cachedResult.packageName && fileContainsPackageImport(from, cachedResult.packageName); } const getCanonicalFileName = hostGetCanonicalFileName(moduleSpecifierResolutionHost); const globalTypingsCache = (_a = moduleSpecifierResolutionHost.getGlobalTypingsCacheLocation) == null ? void 0 : _a.call(moduleSpecifierResolutionHost); @@ -233538,16 +234122,16 @@ function isImportableFile(program, from, to, preferences, packageJsonFilter, mod } ); if (packageJsonFilter) { - const isAutoImportable = hasImportablePath && packageJsonFilter.allowsImportingSourceFile(to, moduleSpecifierResolutionHost); - moduleSpecifierCache == null ? void 0 : moduleSpecifierCache.setBlockedByPackageJsonDependencies(from.path, to.path, preferences, {}, !isAutoImportable); - return isAutoImportable; + const importInfo = hasImportablePath ? packageJsonFilter.getSourceFileInfo(to, moduleSpecifierResolutionHost) : void 0; + moduleSpecifierCache == null ? void 0 : moduleSpecifierCache.setBlockedByPackageJsonDependencies(from.path, to.path, preferences, {}, importInfo == null ? void 0 : importInfo.packageName, !(importInfo == null ? void 0 : importInfo.importable)); + return !!(importInfo == null ? void 0 : importInfo.importable) || !!(importInfo == null ? void 0 : importInfo.packageName) && fileContainsPackageImport(from, importInfo.packageName); } return hasImportablePath; } +function fileContainsPackageImport(sourceFile, packageName) { + return sourceFile.imports && sourceFile.imports.some((i) => i.text === packageName || i.text.startsWith(packageName + "/")); +} function isImportablePath(fromPath, toPath3, getCanonicalFileName, globalCachePath) { - if (getPnpApi(fromPath)) { - return isImportablePathPnp(fromPath, toPath3); - } const toNodeModules = forEachAncestorDirectory(toPath3, (ancestor) => getBaseFileName(ancestor) === "node_modules" ? ancestor : void 0); const toNodeModulesParent = toNodeModules && getDirectoryPath(getCanonicalFileName(toNodeModules)); return toNodeModulesParent === void 0 || startsWith(getCanonicalFileName(fromPath), toNodeModulesParent) || !!globalCachePath && startsWith(getCanonicalFileName(globalCachePath), toNodeModulesParent); @@ -233555,10 +234139,7 @@ function isImportablePath(fromPath, toPath3, getCanonicalFileName, globalCachePa function forEachExternalModuleToImportFrom(program, host, preferences, useAutoImportProvider, cb) { var _a, _b; const useCaseSensitiveFileNames2 = hostUsesCaseSensitiveFileNames(host); - const excludePatterns = preferences.autoImportFileExcludePatterns && mapDefined(preferences.autoImportFileExcludePatterns, (spec) => { - const pattern = getSubPatternFromSpec(spec, "", "exclude"); - return pattern ? getRegexFromPattern(pattern, useCaseSensitiveFileNames2) : void 0; - }); + const excludePatterns = preferences.autoImportFileExcludePatterns && getIsExcludedPatterns(preferences, useCaseSensitiveFileNames2); forEachExternalModule(program.getTypeChecker(), program.getSourceFiles(), excludePatterns, host, (module2, file) => cb( module2, file, @@ -233591,25 +234172,17 @@ function forEachExternalModuleToImportFrom(program, host, preferences, useAutoIm (_b = host.log) == null ? void 0 : _b.call(host, `forEachExternalModuleToImportFrom autoImportProvider: ${timestamp() - start}`); } } -function forEachExternalModule(checker, allSourceFiles, excludePatterns, host, cb) { - var _a, _b; - const realpathsWithSymlinks = (_a = host.getSymlinkCache) == null ? void 0 : _a.call(host).getSymlinkedDirectoriesByRealpath(); - const isExcluded = excludePatterns && (({ fileName, path }) => { - if (excludePatterns.some((p) => p.test(fileName))) return true; - if ((realpathsWithSymlinks == null ? void 0 : realpathsWithSymlinks.size) && pathContainsNodeModules(fileName)) { - let dir = getDirectoryPath(fileName); - return forEachAncestorDirectory(getDirectoryPath(path), (dirPath) => { - const symlinks = realpathsWithSymlinks.get(ensureTrailingDirectorySeparator(dirPath)); - if (symlinks) { - return symlinks.some((s) => excludePatterns.some((p) => p.test(fileName.replace(dir, s)))); - } - dir = getDirectoryPath(dir); - }) ?? false; - } - return false; +function getIsExcludedPatterns(preferences, useCaseSensitiveFileNames2) { + return mapDefined(preferences.autoImportFileExcludePatterns, (spec) => { + const pattern = getSubPatternFromSpec(spec, "", "exclude"); + return pattern ? getRegexFromPattern(pattern, useCaseSensitiveFileNames2) : void 0; }); +} +function forEachExternalModule(checker, allSourceFiles, excludePatterns, host, cb) { + var _a; + const isExcluded = excludePatterns && getIsExcluded(excludePatterns, host); for (const ambient of checker.getAmbientModules()) { - if (!ambient.name.includes("*") && !(excludePatterns && ((_b = ambient.declarations) == null ? void 0 : _b.every((d) => isExcluded(d.getSourceFile()))))) { + if (!ambient.name.includes("*") && !(excludePatterns && ((_a = ambient.declarations) == null ? void 0 : _a.every((d) => isExcluded(d.getSourceFile()))))) { cb( ambient, /*sourceFile*/ @@ -233623,6 +234196,28 @@ function forEachExternalModule(checker, allSourceFiles, excludePatterns, host, c } } } +function getIsExcluded(excludePatterns, host) { + var _a; + const realpathsWithSymlinks = (_a = host.getSymlinkCache) == null ? void 0 : _a.call(host).getSymlinkedDirectoriesByRealpath(); + return ({ fileName, path }) => { + if (excludePatterns.some((p) => p.test(fileName))) return true; + if ((realpathsWithSymlinks == null ? void 0 : realpathsWithSymlinks.size) && pathContainsNodeModules(fileName)) { + let dir = getDirectoryPath(fileName); + return forEachAncestorDirectory(getDirectoryPath(path), (dirPath) => { + const symlinks = realpathsWithSymlinks.get(ensureTrailingDirectorySeparator(dirPath)); + if (symlinks) { + return symlinks.some((s) => excludePatterns.some((p) => p.test(fileName.replace(dir, s)))); + } + dir = getDirectoryPath(dir); + }) ?? false; + } + return false; + }; +} +function getIsFileExcluded(host, preferences) { + if (!preferences.autoImportFileExcludePatterns) return () => false; + return getIsExcluded(getIsExcludedPatterns(preferences, hostUsesCaseSensitiveFileNames(host)), host); +} function getExportInfoMap(importingFile, host, program, preferences, cancellationToken) { var _a, _b, _c, _d, _e; const start = timestamp(); @@ -233700,7 +234295,15 @@ function getDefaultLikeExportInfo(moduleSymbol, checker) { function isImportableSymbol(symbol, checker) { return !checker.isUndefinedSymbol(symbol) && !checker.isUnknownSymbol(symbol) && !isKnownSymbol(symbol) && !isPrivateIdentifierSymbol(symbol); } -function forEachNameOfDefaultExport(defaultExport, checker, compilerOptions, preferCapitalizedNames, cb) { +function getNamesForExportedSymbol(defaultExport, checker, scriptTarget) { + let names; + forEachNameOfDefaultExport(defaultExport, checker, scriptTarget, (name, capitalizedName) => { + names = capitalizedName ? [name, capitalizedName] : name; + return true; + }); + return Debug.checkDefined(names); +} +function forEachNameOfDefaultExport(defaultExport, checker, scriptTarget, cb) { let chain; let current = defaultExport; const seen = /* @__PURE__ */ new Map(); @@ -233720,7 +234323,20 @@ function forEachNameOfDefaultExport(defaultExport, checker, compilerOptions, pre } for (const symbol of chain ?? emptyArray) { if (symbol.parent && isExternalModuleSymbol(symbol.parent)) { - const final = cb(moduleSymbolToValidIdentifier(symbol.parent, getEmitScriptTarget(compilerOptions), preferCapitalizedNames)); + const final = cb( + moduleSymbolToValidIdentifier( + symbol.parent, + scriptTarget, + /*forceCapitalize*/ + false + ), + moduleSymbolToValidIdentifier( + symbol.parent, + scriptTarget, + /*forceCapitalize*/ + true + ) + ); if (final) return final; } } @@ -234386,8 +235002,8 @@ function getEncodedSyntacticClassifications(cancellationToken, sourceFile, span) } } function tryClassifyTripleSlashComment(start, width) { - const tripleSlashXMLCommentRegEx = /^(\/\/\/\s*)(<)(?:(\S+)((?:[^/]|\/[^>])*)(\/>)?)?/im; - const attributeRegex = /(\s)(\S+)(\s*)(=)(\s*)('[^']+'|"[^"]+")/img; + const tripleSlashXMLCommentRegEx = /^(\/\/\/\s*)(<)(?:(\S+)((?:[^/]|\/[^>])*)(\/>)?)?/m; + const attributeRegex = /(\s)(\S+)(\s*)(=)(\s*)('[^']+'|"[^"]+")/g; const text = sourceFile.text.substr(start, width); const match = tripleSlashXMLCommentRegEx.exec(text); if (!match) { @@ -234818,10 +235434,8 @@ var DocumentHighlights; return [...nodes, container]; } return nodes; - case 210 /* ObjectLiteralExpression */: - return void 0; default: - Debug.assertNever(container, "Invalid container kind."); + return void 0; } } function pushKeywordIf(keywordList, token, ...expected) { @@ -236102,7 +236716,7 @@ function preProcessFile(sourceText, readImportFiles = true, detectJavaScriptImpo } // src/services/sourcemaps.ts -var base64UrlRegExp = /^data:(?:application\/json(?:;charset=[uU][tT][fF]-8);base64,([A-Za-z0-9+/=]+)$)?/; +var base64UrlRegExp = /^data:(?:application\/json;charset=[uU][tT][fF]-8;base64,([A-Za-z0-9+/=]+)$)?/; function getSourceMapper(host) { const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames()); const currentDirectory = host.getCurrentDirectory(); @@ -236246,7 +236860,7 @@ function computeSuggestionDiagnostics(sourceFile, program, cancellationToken) { program.getSemanticDiagnostics(sourceFile, cancellationToken); const diags = []; const checker = program.getTypeChecker(); - const isCommonJSFile = sourceFile.impliedNodeFormat === 1 /* CommonJS */ || fileExtensionIsOneOf(sourceFile.fileName, [".cts" /* Cts */, ".cjs" /* Cjs */]); + const isCommonJSFile = program.getImpliedNodeFormatForEmit(sourceFile) === 1 /* CommonJS */ || fileExtensionIsOneOf(sourceFile.fileName, [".cts" /* Cts */, ".cjs" /* Cjs */]); if (!isCommonJSFile && sourceFile.commonJsModuleIndicator && (programContainsEsModules(program) || compilerOptionsIndicateEsModules(program.getCompilerOptions())) && containsTopLevelCommonjs(sourceFile)) { diags.push(createDiagnosticForNode(getErrorNodeFromCommonJsIndicator(sourceFile.commonJsModuleIndicator), Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module)); } @@ -236267,7 +236881,8 @@ function computeSuggestionDiagnostics(sourceFile, program, cancellationToken) { } addRange(diags, sourceFile.bindSuggestionDiagnostics); addRange(diags, program.getSuggestionDiagnostics(sourceFile, cancellationToken)); - return diags.sort((d1, d2) => d1.start - d2.start); + diags.sort((d1, d2) => d1.start - d2.start); + return diags; function check(node) { if (isJsFile) { if (canBeConvertedToClass(node, checker)) { @@ -236513,6 +237128,7 @@ function transpileWorker(input, transpileOptions, declaration) { options.isolatedDeclarations = true; } else { options.declaration = false; + options.declarationMap = false; } const newLine = getNewLineCharacter(options); const compilerHost = { @@ -236708,7 +237324,8 @@ function getContainers(declaration) { } container = getContainerNode(container); } - return containers.reverse(); + containers.reverse(); + return containers; } function compareNavigateToItems(i1, i2) { return compareValues(i1.matchKind, i2.matchKind) || compareStringsCaseSensitiveUI(i1.name, i2.name); @@ -237488,13 +238105,12 @@ function isFunctionOrClassExpression(node) { } function cleanText(text) { text = text.length > maxLength ? text.substring(0, maxLength) + "..." : text; - return text.replace(/\\?(\r?\n|\r|\u2028|\u2029)/g, ""); + return text.replace(/\\?(?:\r?\n|[\r\u2028\u2029])/g, ""); } // src/services/_namespaces/ts.refactor.ts var ts_refactor_exports = {}; __export(ts_refactor_exports, { - addExportToChanges: () => addExportToChanges, addExportsInOldFile: () => addExportsInOldFile, addImportsForMovedSymbols: () => addImportsForMovedSymbols, addNewFileToTsconfig: () => addNewFileToTsconfig, @@ -237506,13 +238122,8 @@ __export(ts_refactor_exports, { convertStringOrTemplateLiteral: () => ts_refactor_convertStringOrTemplateLiteral_exports, convertToOptionalChainExpression: () => ts_refactor_convertToOptionalChainExpression_exports, createNewFileName: () => createNewFileName, - deleteMovedStatements: () => deleteMovedStatements, - deleteUnusedImports: () => deleteUnusedImports, - deleteUnusedOldImports: () => deleteUnusedOldImports, doChangeNamedToNamespaceOrDefault: () => doChangeNamedToNamespaceOrDefault, extractSymbol: () => ts_refactor_extractSymbol_exports, - filterImport: () => filterImport, - forEachImportInStatement: () => forEachImportInStatement, generateGetAccessorAndSetAccessor: () => ts_refactor_generateGetAccessorAndSetAccessor_exports, getApplicableRefactors: () => getApplicableRefactors, getEditsForRefactor: () => getEditsForRefactor, @@ -237520,16 +238131,11 @@ __export(ts_refactor_exports, { getIdentifierForNode: () => getIdentifierForNode, getNewStatementsAndRemoveFromOldFile: () => getNewStatementsAndRemoveFromOldFile, getStatementsToMove: () => getStatementsToMove, - getTopLevelDeclarationStatement: () => getTopLevelDeclarationStatement, getUsageInfo: () => getUsageInfo, inferFunctionReturnType: () => ts_refactor_inferFunctionReturnType_exports, isRefactorErrorInfo: () => isRefactorErrorInfo, - isTopLevelDeclaration: () => isTopLevelDeclaration, - moduleSpecifierFromImport: () => moduleSpecifierFromImport, - nameOfTopLevelDeclaration: () => nameOfTopLevelDeclaration, refactorKindBeginsWith: () => refactorKindBeginsWith, - registerRefactor: () => registerRefactor, - updateImportsInOtherFiles: () => updateImportsInOtherFiles + registerRefactor: () => registerRefactor }); // src/services/refactorProvider.ts @@ -237963,9 +238569,9 @@ function doChangeNamedToNamespaceOrDefault(sourceFile, program, changes, toConve const namespaceImportName = namespaceNameConflicts ? getUniqueName(preferredName, sourceFile) : preferredName; const neededNamedImports = /* @__PURE__ */ new Set(); for (const element of toConvert.elements) { - const propertyName = (element.propertyName || element.name).text; + const propertyName = element.propertyName || element.name; ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, (id) => { - const access = factory.createPropertyAccessExpression(factory.createIdentifier(namespaceImportName), propertyName); + const access = propertyName.kind === 11 /* StringLiteral */ ? factory.createElementAccessExpression(factory.createIdentifier(namespaceImportName), factory.cloneNode(propertyName)) : factory.createPropertyAccessExpression(factory.createIdentifier(namespaceImportName), factory.cloneNode(propertyName)); if (isShorthandPropertyAssignment(id.parent)) { changes.replaceNode(sourceFile, id.parent, factory.createPropertyAssignment(id.text, access)); } else if (isExportSpecifier(id.parent)) { @@ -237981,7 +238587,7 @@ function doChangeNamedToNamespaceOrDefault(sourceFile, program, changes, toConve shouldUseDefault ? factory.createIdentifier(namespaceImportName) : factory.createNamespaceImport(factory.createIdentifier(namespaceImportName)) ); if (neededNamedImports.size && isImportDeclaration(importDecl)) { - const newNamedImports = arrayFrom(neededNamedImports.values(), (element) => factory.createImportSpecifier(element.isTypeOnly, element.propertyName && factory.createIdentifier(element.propertyName.text), factory.createIdentifier(element.name.text))); + const newNamedImports = arrayFrom(neededNamedImports.values(), (element) => factory.createImportSpecifier(element.isTypeOnly, element.propertyName && factory.cloneNode(element.propertyName), factory.cloneNode(element.name))); changes.insertNodeAfter(sourceFile, toConvert.parent.parent, createImport( importDecl, /*defaultImportName*/ @@ -238532,7 +239138,7 @@ function updateImportsInOtherFiles(changes, program, host, oldFile, movedSymbols deleteUnusedImports(sourceFile, importNode, changes, shouldMove); const pathToTargetFileWithExtension = resolvePath(getDirectoryPath(getNormalizedAbsolutePath(oldFile.fileName, program.getCurrentDirectory())), targetFileName); if (getStringComparer(!program.useCaseSensitiveFileNames())(pathToTargetFileWithExtension, sourceFile.fileName) === 0 /* EqualTo */) return; - const newModuleSpecifier = getModuleSpecifier(program.getCompilerOptions(), sourceFile, sourceFile.fileName, pathToTargetFileWithExtension, createModuleSpecifierResolutionHost(program, host)); + const newModuleSpecifier = ts_moduleSpecifiers_exports.getModuleSpecifier(program.getCompilerOptions(), sourceFile, sourceFile.fileName, pathToTargetFileWithExtension, createModuleSpecifierResolutionHost(program, host)); const newImportDeclaration = filterImport(importNode, makeStringLiteral(newModuleSpecifier, quotePreference), shouldMove); if (newImportDeclaration) changes.insertNodeAfter(sourceFile, statement, newImportDeclaration); const ns = getNamespaceLikeImport(importNode); @@ -238943,7 +239549,7 @@ function isPureImport(node) { return false; } } -function getUsageInfo(oldFile, toMove, checker, existingTargetLocals = /* @__PURE__ */ new Set()) { +function getUsageInfo(oldFile, toMove, checker, existingTargetLocals = /* @__PURE__ */ new Set(), enclosingRange) { var _a; const movedSymbols = /* @__PURE__ */ new Set(); const oldImportsNeededByTargetFile = /* @__PURE__ */ new Map(); @@ -238959,7 +239565,7 @@ function getUsageInfo(oldFile, toMove, checker, existingTargetLocals = /* @__PUR } const unusedImportsFromOldFile = /* @__PURE__ */ new Set(); for (const statement of toMove) { - forEachReference(statement, checker, (symbol, isValidTypeOnlyUseSite) => { + forEachReference(statement, checker, enclosingRange, (symbol, isValidTypeOnlyUseSite) => { if (!symbol.declarations || isGlobalType(checker, symbol)) { return; } @@ -238989,7 +239595,7 @@ function getUsageInfo(oldFile, toMove, checker, existingTargetLocals = /* @__PUR if (jsxNamespaceSymbol && !!(statement.transformFlags & 2 /* ContainsJsx */)) { unusedImportsFromOldFile.delete(jsxNamespaceSymbol); } - forEachReference(statement, checker, (symbol, isValidTypeOnlyUseSite) => { + forEachReference(statement, checker, enclosingRange, (symbol, isValidTypeOnlyUseSite) => { if (movedSymbols.has(symbol)) oldFileImportsFromTargetFile.set(symbol, isValidTypeOnlyUseSite); unusedImportsFromOldFile.delete(symbol); }); @@ -239031,9 +239637,12 @@ function makeUniqueFilename(proposedFilename, extension, inDirectory, host) { function inferNewFileName(importsFromNewFile, movedSymbols) { return forEachKey(importsFromNewFile, symbolNameNoDefault) || forEachKey(movedSymbols, symbolNameNoDefault) || "newFile"; } -function forEachReference(node, checker, onReference) { +function forEachReference(node, checker, enclosingRange, onReference) { node.forEachChild(function cb(node2) { if (isIdentifier(node2) && !isDeclarationName(node2)) { + if (enclosingRange && !rangeContainsRange(enclosingRange, node2)) { + return; + } const sym = checker.getSymbolAtLocation(node2); if (sym) onReference(sym, isValidTypeOnlyAliasUseSite(node2)); } else { @@ -239196,12 +239805,18 @@ function getExistingLocals(sourceFile, statements, checker) { } } for (const statement of statements) { - forEachReference(statement, checker, (s) => { - const symbol = skipAlias(s, checker); - if (symbol.valueDeclaration && getSourceFileOfNode(symbol.valueDeclaration).path === sourceFile.path) { - existingLocals.add(symbol); + forEachReference( + statement, + checker, + /*enclosingRange*/ + void 0, + (s) => { + const symbol = skipAlias(s, checker); + if (symbol.valueDeclaration && getSourceFileOfNode(symbol.valueDeclaration).path === sourceFile.path) { + existingLocals.add(symbol); + } } - }); + ); } return existingLocals; } @@ -239293,7 +239908,12 @@ registerRefactor(refactorName4, { const { references, declaration, replacement } = info; const edits = ts_textChanges_exports.ChangeTracker.with(context, (tracker) => { for (const node of references) { - tracker.replaceNode(file, node, getReplacementExpression(node, replacement)); + const closestStringIdentifierParent = isStringLiteral(replacement) && isIdentifier(node) && walkUpParenthesizedExpressions(node.parent); + if (closestStringIdentifierParent && isTemplateSpan(closestStringIdentifierParent) && !isTaggedTemplateExpression(closestStringIdentifierParent.parent.parent)) { + replaceTemplateStringVariableWithLiteral(tracker, file, closestStringIdentifierParent, replacement); + } else { + tracker.replaceNode(file, node, getReplacementExpression(node, replacement)); + } } tracker.delete(file, declaration); }); @@ -239382,6 +240002,19 @@ function getReplacementExpression(reference, replacement) { } return replacement; } +function replaceTemplateStringVariableWithLiteral(tracker, sourceFile, reference, replacement) { + const templateExpression = reference.parent; + const index = templateExpression.templateSpans.indexOf(reference); + const prevNode = index === 0 ? templateExpression.head : templateExpression.templateSpans[index - 1]; + tracker.replaceRangeWithText( + sourceFile, + { + pos: prevNode.getEnd() - 2, + end: reference.literal.getStart() + 1 + }, + replacement.text.replace(/\\/g, "\\\\").replace(/`/g, "\\`") + ); +} // src/services/refactors/moveToNewFile.ts var refactorName5 = "Move to a new file"; @@ -241590,7 +242223,7 @@ function extractFunctionInScope(node, scope, { usages: usagesInScope, typeParame if (!isJS) { let type = checker.getTypeOfSymbolAtLocation(usage.symbol, usage.node); type = checker.getBaseTypeOfLiteralType(type); - typeNode = ts_codefix_exports.typeToAutoImportableTypeNode(checker, importAdder, type, scope, scriptTarget, 1 /* NoTruncation */); + typeNode = ts_codefix_exports.typeToAutoImportableTypeNode(checker, importAdder, type, scope, scriptTarget, 1 /* NoTruncation */, 8 /* AllowUnresolvedNames */); } const paramDecl = factory.createParameterDeclaration( /*modifiers*/ @@ -241610,8 +242243,8 @@ function extractFunctionInScope(node, scope, { usages: usagesInScope, typeParame callArguments.push(factory.createIdentifier(name)); }); const typeParametersAndDeclarations = arrayFrom(typeParameterUsages.values(), (type) => ({ type, declaration: getFirstDeclarationBeforePosition(type, context.startPosition) })); - const sortedTypeParametersAndDeclarations = typeParametersAndDeclarations.sort(compareTypesByDeclarationOrder); - const typeParameters = sortedTypeParametersAndDeclarations.length === 0 ? void 0 : mapDefined(sortedTypeParametersAndDeclarations, ({ declaration }) => declaration); + typeParametersAndDeclarations.sort(compareTypesByDeclarationOrder); + const typeParameters = typeParametersAndDeclarations.length === 0 ? void 0 : mapDefined(typeParametersAndDeclarations, ({ declaration }) => declaration); const callTypeArguments = typeParameters !== void 0 ? typeParameters.map((decl) => factory.createTypeReferenceNode( decl.name, /*typeArguments*/ @@ -241619,7 +242252,7 @@ function extractFunctionInScope(node, scope, { usages: usagesInScope, typeParame )) : void 0; if (isExpression(node) && !isJS) { const contextualType = checker.getContextualType(node); - returnType = checker.typeToTypeNode(contextualType, scope, 1 /* NoTruncation */); + returnType = checker.typeToTypeNode(contextualType, scope, 1 /* NoTruncation */, 8 /* AllowUnresolvedNames */); } const { body, returnValueProperty } = transformFunctionBody(node, exposedVariableDeclarations, writes, substitutions, !!(range.facts & 1 /* HasReturn */)); suppressLeadingAndTrailingTrivia(body); @@ -241659,7 +242292,8 @@ function extractFunctionInScope(node, scope, { usages: usagesInScope, typeParame checker.typeToTypeNode( checker.getTypeAtLocation(range.thisNode), scope, - 1 /* NoTruncation */ + 1 /* NoTruncation */, + 8 /* AllowUnresolvedNames */ ), /*initializer*/ void 0 @@ -241756,7 +242390,8 @@ function extractFunctionInScope(node, scope, { usages: usagesInScope, typeParame const variableType = checker.typeToTypeNode( checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), scope, - 1 /* NoTruncation */ + 1 /* NoTruncation */, + 8 /* AllowUnresolvedNames */ ); typeElements.push(factory.createPropertySignature( /*modifiers*/ @@ -241887,7 +242522,7 @@ function extractConstantInScope(node, scope, { substitutions }, rangeFacts, cont const file = scope.getSourceFile(); const localNameText = getIdentifierForNode(node, scope, checker, file); const isJS = isInJSFile(scope); - let variableType = isJS || !checker.isContextSensitive(node) ? void 0 : checker.typeToTypeNode(checker.getContextualType(node), scope, 1 /* NoTruncation */); + let variableType = isJS || !checker.isContextSensitive(node) ? void 0 : checker.typeToTypeNode(checker.getContextualType(node), scope, 1 /* NoTruncation */, 8 /* AllowUnresolvedNames */); let initializer = transformConstantInitializer(skipParentheses(node), substitutions); ({ variableType, initializer } = transformFunctionInitializerAndType(variableType, initializer)); suppressLeadingAndTrailingTrivia(initializer); @@ -242012,13 +242647,13 @@ function extractConstantInScope(node, scope, { substitutions }, rangeFacts, cont } else { const paramType = checker.getTypeAtLocation(p); if (paramType === checker.getAnyType()) hasAny = true; - parameters.push(factory.updateParameterDeclaration(p, p.modifiers, p.dotDotDotToken, p.name, p.questionToken, p.type || checker.typeToTypeNode(paramType, scope, 1 /* NoTruncation */), p.initializer)); + parameters.push(factory.updateParameterDeclaration(p, p.modifiers, p.dotDotDotToken, p.name, p.questionToken, p.type || checker.typeToTypeNode(paramType, scope, 1 /* NoTruncation */, 8 /* AllowUnresolvedNames */), p.initializer)); } } if (hasAny) return { variableType: variableType2, initializer: initializer2 }; variableType2 = void 0; if (isArrowFunction(initializer2)) { - initializer2 = factory.updateArrowFunction(initializer2, canHaveModifiers(node) ? getModifiers(node) : void 0, initializer2.typeParameters, parameters, initializer2.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, 1 /* NoTruncation */), initializer2.equalsGreaterThanToken, initializer2.body); + initializer2 = factory.updateArrowFunction(initializer2, canHaveModifiers(node) ? getModifiers(node) : void 0, initializer2.typeParameters, parameters, initializer2.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, 1 /* NoTruncation */, 8 /* AllowUnresolvedNames */), initializer2.equalsGreaterThanToken, initializer2.body); } else { if (functionSignature && !!functionSignature.thisParameter) { const firstParameter = firstOrUndefined(parameters); @@ -242035,7 +242670,7 @@ function extractConstantInScope(node, scope, { substitutions }, rangeFacts, cont "this", /*questionToken*/ void 0, - checker.typeToTypeNode(thisType, scope, 1 /* NoTruncation */) + checker.typeToTypeNode(thisType, scope, 1 /* NoTruncation */, 8 /* AllowUnresolvedNames */) ) ); } @@ -242644,11 +243279,31 @@ function getInfo4(context) { return { error: getLocaleSpecificMessage(Diagnostics.Return_type_must_be_inferred_from_a_function) }; } const typeChecker = context.program.getTypeChecker(); - const returnType = tryGetReturnType(typeChecker, declaration); + let returnType; + if (typeChecker.isImplementationOfOverload(declaration)) { + const signatures = typeChecker.getTypeAtLocation(declaration).getCallSignatures(); + if (signatures.length > 1) { + returnType = typeChecker.getUnionType(mapDefined(signatures, (s) => s.getReturnType())); + } + } + if (!returnType) { + const signature = typeChecker.getSignatureFromDeclaration(declaration); + if (signature) { + const typePredicate = typeChecker.getTypePredicateOfSignature(signature); + if (typePredicate && typePredicate.type) { + const typePredicateTypeNode = typeChecker.typePredicateToTypePredicateNode(typePredicate, declaration, 1 /* NoTruncation */, 8 /* AllowUnresolvedNames */); + if (typePredicateTypeNode) { + return { declaration, returnTypeNode: typePredicateTypeNode }; + } + } else { + returnType = typeChecker.getReturnTypeOfSignature(signature); + } + } + } if (!returnType) { return { error: getLocaleSpecificMessage(Diagnostics.Could_not_determine_function_return_type) }; } - const returnTypeNode = typeChecker.typeToTypeNode(returnType, declaration, 1 /* NoTruncation */); + const returnTypeNode = typeChecker.typeToTypeNode(returnType, declaration, 1 /* NoTruncation */, 8 /* AllowUnresolvedNames */); if (returnTypeNode) { return { declaration, returnTypeNode }; } @@ -242664,18 +243319,6 @@ function isConvertibleDeclaration(node) { return false; } } -function tryGetReturnType(typeChecker, node) { - if (typeChecker.isImplementationOfOverload(node)) { - const signatures = typeChecker.getTypeAtLocation(node).getCallSignatures(); - if (signatures.length > 1) { - return typeChecker.getUnionType(mapDefined(signatures, (s) => s.getReturnType())); - } - } - const signature = typeChecker.getSignatureFromDeclaration(node); - if (signature) { - return typeChecker.getReturnTypeOfSignature(signature); - } -} // src/services/classifier2020.ts var TokenEncodingConsts = /* @__PURE__ */ ((TokenEncodingConsts2) => { @@ -243995,13 +244638,18 @@ function createLanguageService(host, documentRegistry = createDocumentRegistry(h if (host.getParsedCommandLine) { (_a3 = host.onReleaseParsedCommandLine) == null ? void 0 : _a3.call(host, configFileName, oldResolvedRef, oldOptions); } else if (oldResolvedRef) { - onReleaseOldSourceFile(oldResolvedRef.sourceFile, oldOptions); + releaseOldSourceFile(oldResolvedRef.sourceFile, oldOptions); } } - function onReleaseOldSourceFile(oldSourceFile, oldOptions) { + function releaseOldSourceFile(oldSourceFile, oldOptions) { const oldSettingsKey = documentRegistry.getKeyForCompilationSettings(oldOptions); documentRegistry.releaseDocumentWithKey(oldSourceFile.resolvedPath, oldSettingsKey, oldSourceFile.scriptKind, oldSourceFile.impliedNodeFormat); } + function onReleaseOldSourceFile(oldSourceFile, oldOptions, hasSourceFileByPath, newSourceFileByResolvedPath) { + var _a3; + releaseOldSourceFile(oldSourceFile, oldOptions); + (_a3 = host.onReleaseOldSourceFile) == null ? void 0 : _a3.call(host, oldSourceFile, oldOptions, hasSourceFileByPath, newSourceFileByResolvedPath); + } function getOrCreateSourceFile(fileName, languageVersionOrOptions, onError, shouldCreateNewSourceFile) { return getOrCreateSourceFileByPath(fileName, toPath(fileName, currentDirectory, getCanonicalFileName), languageVersionOrOptions, onError, shouldCreateNewSourceFile); } @@ -244112,6 +244760,108 @@ function createLanguageService(host, documentRegistry = createDocumentRegistry(h const declarationDiagnostics = program.getDeclarationDiagnostics(targetSourceFile, cancellationToken); return [...semanticDiagnostics, ...declarationDiagnostics]; } + function getRegionSemanticDiagnostics(fileName, ranges) { + synchronizeHostData(); + const sourceFile = getValidSourceFile(fileName); + const options = program.getCompilerOptions(); + if (skipTypeChecking(sourceFile, options, program) || !canIncludeBindAndCheckDiagnostics(sourceFile, options) || program.getCachedSemanticDiagnostics(sourceFile)) { + return void 0; + } + const nodes = getNodesForRanges(sourceFile, ranges); + if (!nodes) { + return void 0; + } + const checkedSpans = normalizeSpans(nodes.map((node) => createTextSpanFromBounds(node.getFullStart(), node.getEnd()))); + const semanticDiagnostics = program.getSemanticDiagnostics(sourceFile, cancellationToken, nodes); + return { + diagnostics: semanticDiagnostics.slice(), + spans: checkedSpans + }; + } + function getNodesForRanges(file, ranges) { + const nodes = []; + const spans = normalizeSpans(ranges.map((range) => createTextSpanFromRange(range))); + for (const span of spans) { + const nodesForSpan = getNodesForSpan(file, span); + if (!nodesForSpan) { + return void 0; + } + nodes.push(...nodesForSpan); + } + if (!nodes.length) { + return void 0; + } + return nodes; + } + function getNodesForSpan(file, span) { + if (textSpanContainsTextRange(span, file)) { + return void 0; + } + const endToken = findTokenOnLeftOfPosition(file, textSpanEnd(span)) || file; + const enclosingNode = findAncestor(endToken, (node) => textRangeContainsTextSpan(node, span)); + const nodes = []; + chooseOverlappingNodes(span, enclosingNode, nodes); + if (file.end === span.start + span.length) { + nodes.push(file.endOfFileToken); + } + if (some(nodes, isSourceFile)) { + return void 0; + } + return nodes; + } + function chooseOverlappingNodes(span, node, result) { + if (!nodeOverlapsWithSpan(node, span)) { + return false; + } + if (textSpanContainsTextRange(span, node)) { + addSourceElement(node, result); + return true; + } + if (isBlockLike(node)) { + return chooseOverlappingBlockLike(span, node, result); + } + if (isClassLike(node)) { + return chooseOverlappingClassLike(span, node, result); + } + addSourceElement(node, result); + return true; + } + function nodeOverlapsWithSpan(node, span) { + const spanEnd = span.start + span.length; + return node.pos < spanEnd && node.end > span.start; + } + function addSourceElement(node, result) { + while (node.parent && !isSourceElement(node)) { + node = node.parent; + } + result.push(node); + } + function chooseOverlappingBlockLike(span, node, result) { + const childResult = []; + const stmts = node.statements.filter((stmt) => chooseOverlappingNodes(span, stmt, childResult)); + if (stmts.length === node.statements.length) { + addSourceElement(node, result); + return true; + } + result.push(...childResult); + return false; + } + function chooseOverlappingClassLike(span, node, result) { + var _a2, _b, _c; + const overlaps = (n) => textRangeIntersectsWithTextSpan(n, span); + if (((_a2 = node.modifiers) == null ? void 0 : _a2.some(overlaps)) || node.name && overlaps(node.name) || ((_b = node.typeParameters) == null ? void 0 : _b.some(overlaps)) || ((_c = node.heritageClauses) == null ? void 0 : _c.some(overlaps))) { + addSourceElement(node, result); + return true; + } + const childResult = []; + const members = node.members.filter((member) => chooseOverlappingNodes(span, member, childResult)); + if (members.length === node.members.length) { + addSourceElement(node, result); + return true; + } + result.push(...childResult); + return false; + } function getSuggestionDiagnostics(fileName) { synchronizeHostData(); return computeSuggestionDiagnostics(getValidSourceFile(fileName), program, cancellationToken); @@ -244466,6 +245216,7 @@ function createLanguageService(host, documentRegistry = createDocumentRegistry(h synchronizeHostData(); Debug.assert(args.type === "file"); const sourceFile = getValidSourceFile(args.fileName); + if (containsParseError(sourceFile)) return emptyArray; const formatContext = ts_formatting_exports.getFormatContext(formatOptions, host); const mode = args.mode ?? (args.skipDestructiveCodeActions ? "SortAndCombine" /* SortAndCombine */ : "All" /* All */); return ts_OrganizeImports_exports.organizeImports(sourceFile, formatContext, host, program, preferences, mode); @@ -244808,7 +245559,7 @@ function createLanguageService(host, documentRegistry = createDocumentRegistry(h return str.replace(/[-[\]/{}()*+?.\\^$|]/g, "\\$&"); } function getTodoCommentsRegExp() { - const singleLineCommentStart = /(?:\/\/+\s*)/.source; + const singleLineCommentStart = /(?:\/{2,}\s*)/.source; const multiLineCommentStart = /(?:\/\*+\s*)/.source; const anyNumberOfSpacesAndAsterisksAtStartOfLine = /(?:^(?:\s|\*)*)/.source; const preamble = "(" + anyNumberOfSpacesAndAsterisksAtStartOfLine + "|" + singleLineCommentStart + "|" + multiLineCommentStart + ")"; @@ -244926,6 +245677,7 @@ function createLanguageService(host, documentRegistry = createDocumentRegistry(h cleanupSemanticCache, getSyntacticDiagnostics, getSemanticDiagnostics, + getRegionSemanticDiagnostics, getSuggestionDiagnostics, getCompilerOptionsDiagnostics, getSyntacticClassifications: getSyntacticClassifications2, @@ -246088,19 +246840,16 @@ __export(ts_codefix_exports, { createFileTextChanges: () => createFileTextChanges, createImportAdder: () => createImportAdder, createImportSpecifierResolver: () => createImportSpecifierResolver, - createJsonPropertyAssignment: () => createJsonPropertyAssignment, createMissingMemberNodes: () => createMissingMemberNodes, createSignatureDeclarationFromCallExpression: () => createSignatureDeclarationFromCallExpression, createSignatureDeclarationFromSignature: () => createSignatureDeclarationFromSignature, createStubbedBody: () => createStubbedBody, eachDiagnostic: () => eachDiagnostic, findAncestorMatchingSpan: () => findAncestorMatchingSpan, - findJsonProperty: () => findJsonProperty, generateAccessorFromProperty: () => generateAccessorFromProperty, getAccessorConvertiblePropertyAtPosition: () => getAccessorConvertiblePropertyAtPosition, getAllFixes: () => getAllFixes, getAllSupers: () => getAllSupers, - getArgumentTypesAndTypeParameters: () => getArgumentTypesAndTypeParameters, getFixes: () => getFixes, getImportCompletionAction: () => getImportCompletionAction, getImportKind: () => getImportKind, @@ -246115,6 +246864,7 @@ __export(ts_codefix_exports, { setJsonCompilerOptionValue: () => setJsonCompilerOptionValue, setJsonCompilerOptionValues: () => setJsonCompilerOptionValues, tryGetAutoImportableReferenceFromTypeNode: () => tryGetAutoImportableReferenceFromTypeNode, + typePredicateToAutoImportableTypeNode: () => typePredicateToAutoImportableTypeNode, typeToAutoImportableTypeNode: () => typeToAutoImportableTypeNode }); @@ -246501,7 +247251,7 @@ function isInsideAwaitableBody(node) { function makeChange3(changeTracker, errorCode, sourceFile, checker, insertionSite, fixedDeclarations) { if (isForOfStatement(insertionSite.parent) && !insertionSite.parent.awaitModifier) { const exprType = checker.getTypeAtLocation(insertionSite); - const asyncIter = checker.getAsyncIterableType(); + const asyncIter = checker.getAnyAsyncIterableType(); if (asyncIter && checker.isTypeAssignableTo(exprType, asyncIter)) { const forOf = insertionSite.parent; changeTracker.replaceNode(sourceFile, forOf, factory.updateForOfStatement(forOf, factory.createToken(135 /* AwaitKeyword */), forOf.initializer, forOf.expression, forOf.statement)); @@ -248858,7 +249608,7 @@ function getLeftAndRightSiblings(typedefNode) { function findEndOfTextBetween(jsDocComment, from, to) { const comment = jsDocComment.getText().substring(from - jsDocComment.getStart(), to - jsDocComment.getStart()); for (let i = comment.length; i > 0; i--) { - if (!/[*/\s]/g.test(comment.substring(i - 1, i))) { + if (!/[*/\s]/.test(comment.substring(i - 1, i))) { return from + i; } } @@ -249065,6 +249815,8 @@ function addMissingDeclarations(context, implementedTypeNode, sourceFile, classD classDeclaration, /*flags*/ void 0, + /*internalFlags*/ + void 0, getNoopSymbolTrackerWithResolver(context) )); } @@ -249184,7 +249936,7 @@ function createImportAdderWorker(sourceFile, program, useAutoImportProvider, pre addImport(first(info)); } function addImportFromExportedSymbol(exportedSymbol, isValidTypeOnlyUseSite, referenceImport) { - var _a; + var _a, _b; const moduleSymbol = Debug.checkDefined(exportedSymbol.parent); const symbolName2 = getNameForExportedSymbol(exportedSymbol, getEmitScriptTarget(compilerOptions)); const checker = program.getTypeChecker(); @@ -249201,10 +249953,14 @@ function createImportAdderWorker(sourceFile, program, useAutoImportProvider, pre preferences, cancellationToken ); + if (!exportInfo) { + Debug.assert((_a = preferences.autoImportFileExcludePatterns) == null ? void 0 : _a.length); + return; + } const useRequire = shouldUseRequire(sourceFile, program); let fix = getImportFixForSymbol( sourceFile, - Debug.checkDefined(exportInfo), + exportInfo, program, /*position*/ void 0, @@ -249214,7 +249970,7 @@ function createImportAdderWorker(sourceFile, program, useAutoImportProvider, pre preferences ); if (fix) { - const localName = ((_a = tryCast(referenceImport == null ? void 0 : referenceImport.name, isIdentifier)) == null ? void 0 : _a.text) ?? symbolName2; + const localName = ((_b = tryCast(referenceImport == null ? void 0 : referenceImport.name, isIdentifier)) == null ? void 0 : _b.text) ?? symbolName2; if (referenceImport && isTypeOnlyImportDeclaration(referenceImport) && (fix.kind === 3 /* AddNew */ || fix.kind === 2 /* AddToExisting */) && fix.addAsTypeOnly === 1 /* Allowed */) { fix = { ...fix, addAsTypeOnly: 2 /* Required */ }; } @@ -249251,9 +250007,10 @@ function createImportAdderWorker(sourceFile, program, useAutoImportProvider, pre sourceFile, exportingFileName, compilerOptions, - createModuleSpecifierResolutionHost(program, host) + createModuleSpecifierResolutionHost(program, host), + preferences ); - const importKind = getImportKind(futureExportingSourceFile, exportKind, compilerOptions); + const importKind = getImportKind(futureExportingSourceFile, exportKind, program); const addAsTypeOnly = getAddAsTypeOnly( isImportUsageValidAsTypeOnly, /*isForNewImportDeclaration*/ @@ -249593,7 +250350,7 @@ function createImportAdderWorker(sourceFile, program, useAutoImportProvider, pre } function createImportSpecifierResolver(importingFile, program, host, preferences) { const packageJsonImportFilter = createPackageJsonImportFilter(importingFile, preferences, host); - const importMap = createExistingImportMap(program.getTypeChecker(), importingFile, program.getCompilerOptions()); + const importMap = createExistingImportMap(importingFile, program); return { getModuleSpecifierForBestExportInfo }; function getModuleSpecifierForBestExportInfo(exportInfo, position, isValidTypeOnlyUseSite, fromCacheOnly) { const { fixes, computedWithoutCacheCount } = getImportFixes( @@ -249663,8 +250420,12 @@ function codeFixActionToCodeAction({ description: description3, changes, command } function getAllExportInfoForSymbol(importingFile, symbol, symbolName2, moduleSymbol, preferCapitalized, program, host, preferences, cancellationToken) { const getChecker = createGetChecker(program, host); + const isFileExcluded = preferences.autoImportFileExcludePatterns && getIsFileExcluded(host, preferences); + const mergedModuleSymbol = program.getTypeChecker().getMergedSymbol(moduleSymbol); + const moduleSourceFile = isFileExcluded && mergedModuleSymbol.declarations && getDeclarationOfKind(mergedModuleSymbol, 307 /* SourceFile */); + const moduleSymbolExcluded = moduleSourceFile && isFileExcluded(moduleSourceFile); return getExportInfoMap(importingFile, host, program, preferences, cancellationToken).search(importingFile.path, preferCapitalized, (name) => name === symbolName2, (info) => { - if (skipAlias(info[0].symbol, getChecker(info[0].isFromPackageJson)) === symbol && info.some((i) => i.moduleSymbol === moduleSymbol || i.symbol.parent === moduleSymbol)) { + if (getChecker(info[0].isFromPackageJson).getMergedSymbol(skipAlias(info[0].symbol, getChecker(info[0].isFromPackageJson))) === symbol && (moduleSymbolExcluded || info.some((i) => i.moduleSymbol === moduleSymbol || i.symbol.parent === moduleSymbol))) { return info; } }); @@ -249696,7 +250457,7 @@ function getSingleExportInfoForSymbol(symbol, symbolName2, moduleSymbol, program } } } -function getImportFixes(exportInfos, usagePosition, isValidTypeOnlyUseSite, useRequire, program, sourceFile, host, preferences, importMap = isFullSourceFile(sourceFile) ? createExistingImportMap(program.getTypeChecker(), sourceFile, program.getCompilerOptions()) : void 0, fromCacheOnly) { +function getImportFixes(exportInfos, usagePosition, isValidTypeOnlyUseSite, useRequire, program, sourceFile, host, preferences, importMap = isFullSourceFile(sourceFile) ? createExistingImportMap(sourceFile, program) : void 0, fromCacheOnly) { const checker = program.getTypeChecker(); const existingImports = importMap ? flatMap(exportInfos, importMap.getImportsForExportInfo) : emptyArray; const useNamespace = usagePosition !== void 0 && tryUseExistingNamespaceImport(existingImports, usagePosition); @@ -249811,7 +250572,8 @@ function tryAddToExistingImport(existingImports, isValidTypeOnlyUseSite, checker }; } } -function createExistingImportMap(checker, importingFile, compilerOptions) { +function createExistingImportMap(importingFile, program) { + const checker = program.getTypeChecker(); let importMap; for (const moduleSpecifier of importingFile.imports) { const i = importFromModuleSpecifier(moduleSpecifier); @@ -249832,7 +250594,7 @@ function createExistingImportMap(checker, importingFile, compilerOptions) { const matchingDeclarations = importMap == null ? void 0 : importMap.get(getSymbolId(moduleSymbol)); if (!matchingDeclarations) return emptyArray; if (isSourceFileJS(importingFile) && !(targetFlags & 111551 /* Value */) && !every(matchingDeclarations, isJSDocImportTag)) return emptyArray; - const importKind = getImportKind(importingFile, exportKind, compilerOptions); + const importKind = getImportKind(importingFile, exportKind, program); return matchingDeclarations.map((declaration) => ({ declaration, importKind, symbol, targetFlags })); } }; @@ -249847,8 +250609,8 @@ function shouldUseRequire(sourceFile, program) { if (compilerOptions.configFile) { return getEmitModuleKind(compilerOptions) < 5 /* ES2015 */; } - if (sourceFile.impliedNodeFormat === 1 /* CommonJS */) return true; - if (sourceFile.impliedNodeFormat === 99 /* ESNext */) return false; + if (getImpliedNodeFormatForEmit(sourceFile, program) === 1 /* CommonJS */) return true; + if (getImpliedNodeFormatForEmit(sourceFile, program) === 99 /* ESNext */) return false; for (const otherFile of program.getSourceFiles()) { if (otherFile === sourceFile || !isSourceFileJS(otherFile) || program.isSourceFileFromExternalLibrary(otherFile)) continue; if (otherFile.commonJsModuleIndicator && !otherFile.externalModuleIndicator) return true; @@ -249900,20 +250662,13 @@ function getNewImportFixes(program, sourceFile, usagePosition, isValidTypeOnlyUs if (!importedSymbolHasValueMeaning && isJs && usagePosition !== void 0) { return { kind: 1 /* JsdocTypeImport */, moduleSpecifierKind, moduleSpecifier, usagePosition, exportInfo: exportInfo2, isReExport: i > 0 }; } - const importKind = getImportKind(sourceFile, exportInfo2.exportKind, compilerOptions); + const importKind = getImportKind(sourceFile, exportInfo2.exportKind, program); let qualification; if (usagePosition !== void 0 && importKind === 3 /* CommonJS */ && exportInfo2.exportKind === 0 /* Named */) { const exportEquals = checker.resolveExternalModuleSymbol(exportInfo2.moduleSymbol); let namespacePrefix; if (exportEquals !== exportInfo2.moduleSymbol) { - namespacePrefix = forEachNameOfDefaultExport( - exportEquals, - checker, - compilerOptions, - /*preferCapitalizedNames*/ - false, - identity - ); + namespacePrefix = forEachNameOfDefaultExport(exportEquals, checker, getEmitScriptTarget(compilerOptions), identity); } namespacePrefix || (namespacePrefix = moduleSymbolToValidIdentifier( exportInfo2.moduleSymbol, @@ -249977,7 +250732,7 @@ function getFixInfos(context, errorCode, pos, useAutoImportProvider) { } function sortFixInfo(fixes, sourceFile, program, packageJsonImportFilter, host, preferences) { const _toPath = (fileName) => toPath(fileName, host.getCurrentDirectory(), hostGetCanonicalFileName(host)); - return sort(fixes, (a, b) => compareBooleans(!!a.isJsxNamespaceFix, !!b.isJsxNamespaceFix) || compareValues(a.fix.kind, b.fix.kind) || compareModuleSpecifiers(a.fix, b.fix, sourceFile, program, preferences, packageJsonImportFilter.allowsImportingSpecifier, _toPath)); + return toSorted(fixes, (a, b) => compareBooleans(!!a.isJsxNamespaceFix, !!b.isJsxNamespaceFix) || compareValues(a.fix.kind, b.fix.kind) || compareModuleSpecifiers(a.fix, b.fix, sourceFile, program, preferences, packageJsonImportFilter.allowsImportingSpecifier, _toPath)); } function getFixInfosWithoutDiagnostic(context, symbolToken, useAutoImportProvider) { const info = getFixesInfoForNonUMDImport(context, symbolToken, useAutoImportProvider); @@ -250086,8 +250841,8 @@ function getUmdSymbol(token, checker) { } return void 0; } -function getImportKind(importingFile, exportKind, compilerOptions, forceImportKeyword) { - if (compilerOptions.verbatimModuleSyntax && (getEmitModuleKind(compilerOptions) === 1 /* CommonJS */ || importingFile.impliedNodeFormat === 1 /* CommonJS */)) { +function getImportKind(importingFile, exportKind, program, forceImportKeyword) { + if (program.getCompilerOptions().verbatimModuleSyntax && getEmitModuleFormatOfFile(importingFile, program) === 1 /* CommonJS */) { return 3 /* CommonJS */; } switch (exportKind) { @@ -250096,18 +250851,18 @@ function getImportKind(importingFile, exportKind, compilerOptions, forceImportKe case 1 /* Default */: return 1 /* Default */; case 2 /* ExportEquals */: - return getExportEqualsImportKind(importingFile, compilerOptions, !!forceImportKeyword); + return getExportEqualsImportKind(importingFile, program.getCompilerOptions(), !!forceImportKeyword); case 3 /* UMD */: - return getUmdImportKind(importingFile, compilerOptions, !!forceImportKeyword); + return getUmdImportKind(importingFile, program, !!forceImportKeyword); default: return Debug.assertNever(exportKind); } } -function getUmdImportKind(importingFile, compilerOptions, forceImportKeyword) { - if (getAllowSyntheticDefaultImports(compilerOptions)) { +function getUmdImportKind(importingFile, program, forceImportKeyword) { + if (getAllowSyntheticDefaultImports(program.getCompilerOptions())) { return 1 /* Default */; } - const moduleKind = getEmitModuleKind(compilerOptions); + const moduleKind = getEmitModuleKind(program.getCompilerOptions()); switch (moduleKind) { case 2 /* AMD */: case 1 /* CommonJS */: @@ -250126,7 +250881,7 @@ function getUmdImportKind(importingFile, compilerOptions, forceImportKeyword) { return 2 /* Namespace */; case 100 /* Node16 */: case 199 /* NodeNext */: - return importingFile.impliedNodeFormat === 99 /* ESNext */ ? 2 /* Namespace */ : 3 /* CommonJS */; + return getImpliedNodeFormatForEmit(importingFile, program) === 99 /* ESNext */ ? 2 /* Namespace */ : 3 /* CommonJS */; default: return Debug.assertNever(moduleKind, `Unexpected moduleKind ${moduleKind}`); } @@ -250199,7 +250954,7 @@ function getExportInfos(symbolName2, isJsxTagName, currentTokenMeaning, cancella }); function addSymbol(moduleSymbol, toFile, exportedSymbol, exportKind, program2, isFromPackageJson) { const moduleSpecifierResolutionHost = getModuleSpecifierResolutionHost(isFromPackageJson); - if (toFile && isImportableFile(program2, fromFile, toFile, preferences, packageJsonFilter, moduleSpecifierResolutionHost, moduleSpecifierCache) || !toFile && packageJsonFilter.allowsImportingAmbientModule(moduleSymbol, moduleSpecifierResolutionHost)) { + if (toFile && isImportableFile(program2, fromFile, toFile, preferences, packageJsonFilter, moduleSpecifierResolutionHost, moduleSpecifierCache) || (!toFile && packageJsonFilter.allowsImportingAmbientModule(moduleSymbol, moduleSpecifierResolutionHost) || fileContainsPackageImport(fromFile, stripQuotes(moduleSymbol.name)))) { const checker = program2.getTypeChecker(); originalSymbolToExportInfos.add(getUniqueSymbolId(exportedSymbol, checker).toString(), { symbol: exportedSymbol, moduleSymbol, moduleFileName: toFile == null ? void 0 : toFile.fileName, exportKind, targetFlags: skipAlias(exportedSymbol, checker).flags, isFromPackageJson }); } @@ -250209,7 +250964,7 @@ function getExportInfos(symbolName2, isJsxTagName, currentTokenMeaning, cancella cancellationToken.throwIfCancellationRequested(); const compilerOptions = program2.getCompilerOptions(); const defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker); - if (defaultInfo && symbolFlagsHaveMeaning(checker.getSymbolFlags(defaultInfo.symbol), currentTokenMeaning) && forEachNameOfDefaultExport(defaultInfo.symbol, checker, compilerOptions, isJsxTagName, (name) => name === symbolName2)) { + if (defaultInfo && symbolFlagsHaveMeaning(checker.getSymbolFlags(defaultInfo.symbol), currentTokenMeaning) && forEachNameOfDefaultExport(defaultInfo.symbol, checker, getEmitScriptTarget(compilerOptions), (name, capitalizedName) => (isJsxTagName ? capitalizedName ?? name : name) === symbolName2)) { addSymbol(moduleSymbol, sourceFile, defaultInfo.symbol, defaultInfo.exportKind, program2, isFromPackageJson); } const exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(symbolName2, moduleSymbol); @@ -250423,7 +251178,7 @@ function doAddExistingFix(changes, sourceFile, clause, defaultImport, namedImpor } if (namedImports.length) { const { specifierComparer, isSorted } = ts_OrganizeImports_exports.getNamedImportSpecifierComparerWithDetection(clause.parent, preferences, sourceFile); - const newSpecifiers = stableSort( + const newSpecifiers = toSorted( namedImports.map( (namedImport) => factory.createImportSpecifier( (!clause.isTypeOnly || promoteFromTypeOnly2) && shouldUseTypeOnly(namedImport, preferences), @@ -250440,7 +251195,7 @@ function doAddExistingFix(changes, sourceFile, clause, defaultImport, namedImpor clause.namedBindings, factory.updateNamedImports( clause.namedBindings, - stableSort([...existingSpecifiers.filter((s) => !removeExistingImportSpecifiers.has(s)), ...newSpecifiers], specifierComparer) + toSorted([...existingSpecifiers.filter((s) => !removeExistingImportSpecifiers.has(s)), ...newSpecifiers], specifierComparer) ) ); } else if ((existingSpecifiers == null ? void 0 : existingSpecifiers.length) && isSorted !== false) { @@ -250610,6 +251365,12 @@ function createConstEqualsRequireDeclaration(name, quotedModuleSpecifier) { function symbolFlagsHaveMeaning(flags, meaning) { return meaning === 7 /* All */ ? true : meaning & 1 /* Value */ ? !!(flags & 111551 /* Value */) : meaning & 2 /* Type */ ? !!(flags & 788968 /* Type */) : meaning & 4 /* Namespace */ ? !!(flags & 1920 /* Namespace */) : false; } +function getImpliedNodeFormatForEmit(file, program) { + return isFullSourceFile(file) ? program.getImpliedNodeFormatForEmit(file) : getImpliedNodeFormatForEmitWorker(file, program.getCompilerOptions()); +} +function getEmitModuleFormatOfFile(file, program) { + return isFullSourceFile(file) ? program.getEmitModuleFormatOfFile(file) : getEmitModuleFormatOfFileWorker(file, program.getCompilerOptions()); +} // src/services/codefixes/fixAddMissingConstraint.ts var fixId17 = "addMissingConstraint"; @@ -250688,6 +251449,8 @@ function addMissingConstraint(changes, program, preferences, host, sourceFile, i scriptTarget, /*flags*/ void 0, + /*internalFlags*/ + void 0, tracker ); if (typeNode) { @@ -251695,7 +252458,7 @@ function getInfo10(sourceFile, tokenPos, errorCode, checker, program) { const moduleDeclaration = find(symbol.declarations, isModuleDeclaration); const moduleDeclarationSourceFile = moduleDeclaration == null ? void 0 : moduleDeclaration.getSourceFile(); if (moduleDeclaration && moduleDeclarationSourceFile && !isSourceFileFromLibrary(program, moduleDeclarationSourceFile)) { - return { kind: 2 /* Function */, token, call: parent2.parent, sourceFile, modifierFlags: 32 /* Export */, parentDeclaration: moduleDeclaration }; + return { kind: 2 /* Function */, token, call: parent2.parent, sourceFile: moduleDeclarationSourceFile, modifierFlags: 32 /* Export */, parentDeclaration: moduleDeclaration }; } const moduleSourceFile = find(symbol.declarations, isSourceFile); if (sourceFile.commonJsModuleIndicator) return void 0; @@ -251795,14 +252558,15 @@ function getTypeNode2(checker, node, token) { const binaryExpression = token.parent.parent; const otherExpression = token.parent === binaryExpression.left ? binaryExpression.right : binaryExpression.left; const widenedType = checker.getWidenedType(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(otherExpression))); - typeNode = checker.typeToTypeNode(widenedType, node, 1 /* NoTruncation */); + typeNode = checker.typeToTypeNode(widenedType, node, 1 /* NoTruncation */, 8 /* AllowUnresolvedNames */); } else { const contextualType = checker.getContextualType(token.parent); typeNode = contextualType ? checker.typeToTypeNode( contextualType, /*enclosingDeclaration*/ void 0, - 1 /* NoTruncation */ + 1 /* NoTruncation */, + 8 /* AllowUnresolvedNames */ ) : void 0; } return typeNode || factory.createKeywordTypeNode(133 /* AnyKeyword */); @@ -252124,7 +252888,9 @@ function createPropertyNameFromSymbol(symbol, target, quotePreference, checker) 111551 /* Value */, /*enclosingDeclaration*/ void 0, - 1073741824 /* WriteComputedProps */ + /*flags*/ + void 0, + 1 /* WriteComputedProps */ ); if (prop && isComputedPropertyName(prop)) return prop; } @@ -252297,7 +253063,7 @@ function tryGetName2(node) { } } function typeToTypeNode(checker, type, enclosingDeclaration) { - return checker.typeToTypeNode(checker.getWidenedType(type), enclosingDeclaration, 1 /* NoTruncation */) ?? factory.createKeywordTypeNode(159 /* UnknownKeyword */); + return checker.typeToTypeNode(checker.getWidenedType(type), enclosingDeclaration, 1 /* NoTruncation */, 8 /* AllowUnresolvedNames */) ?? factory.createKeywordTypeNode(159 /* UnknownKeyword */); } function doChange19(changes, program, preferences, host, declarations, newParameters) { const scriptTarget = getEmitScriptTarget(program.getCompilerOptions()); @@ -253600,7 +254366,8 @@ var canHaveTypeAnnotation = /* @__PURE__ */ new Set([ 206 /* ObjectBindingPattern */, 207 /* ArrayBindingPattern */ ]); -var declarationEmitNodeBuilderFlags2 = 1024 /* MultilineObjectLiterals */ | 2048 /* WriteClassExpressionAsTypeLiteral */ | 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 524288 /* AllowEmptyTuple */ | 4 /* GenerateNamesForShadowedTypeParams */ | 1 /* NoTruncation */ | 1073741824 /* WriteComputedProps */; +var declarationEmitNodeBuilderFlags2 = 1024 /* MultilineObjectLiterals */ | 2048 /* WriteClassExpressionAsTypeLiteral */ | 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 524288 /* AllowEmptyTuple */ | 4 /* GenerateNamesForShadowedTypeParams */ | 1 /* NoTruncation */; +var declarationEmitInternalNodeBuilderFlags2 = 1 /* WriteComputedProps */; registerCodeFix({ errorCodes: errorCodes47, fixIds: [fixId36], @@ -254193,7 +254960,25 @@ function withContext(context, typePrintMode, cb) { if (typePrintMode === 1 /* Relative */) { return relativeType(node); } - let type = isValueSignatureDeclaration(node) ? tryGetReturnType2(node) : typeChecker.getTypeAtLocation(node); + let type; + if (isValueSignatureDeclaration(node)) { + const signature = typeChecker.getSignatureFromDeclaration(node); + if (signature) { + const typePredicate = typeChecker.getTypePredicateOfSignature(signature); + if (typePredicate) { + if (!typePredicate.type) { + return emptyInferenceResult; + } + return { + typeNode: typePredicateToTypeNode(typePredicate, findAncestor(node, isDeclaration) ?? sourceFile, getFlags(typePredicate.type)), + mutatedTarget: false + }; + } + type = typeChecker.getReturnTypeOfSignature(signature); + } + } else { + type = typeChecker.getTypeAtLocation(node); + } if (!type) { return emptyInferenceResult; } @@ -254207,14 +254992,17 @@ function withContext(context, typePrintMode, cb) { } type = widenedType; } - if (isParameter(node) && typeChecker.requiresAddingImplicitUndefined(node)) { + const enclosingDeclaration = findAncestor(node, isDeclaration) ?? sourceFile; + if (isParameter(node) && typeChecker.requiresAddingImplicitUndefined(node, enclosingDeclaration)) { type = typeChecker.getUnionType([typeChecker.getUndefinedType(), type], 0 /* None */); } - const flags = (isVariableDeclaration(node) || isPropertyDeclaration(node) && hasSyntacticModifier(node, 256 /* Static */ | 8 /* Readonly */)) && type.flags & 8192 /* UniqueESSymbol */ ? 1048576 /* AllowUniqueESSymbolType */ : 0 /* None */; return { - typeNode: typeToTypeNode2(type, findAncestor(node, isDeclaration) ?? sourceFile, flags), + typeNode: typeToTypeNode2(type, enclosingDeclaration, getFlags(type)), mutatedTarget: false }; + function getFlags(type2) { + return (isVariableDeclaration(node) || isPropertyDeclaration(node) && hasSyntacticModifier(node, 256 /* Static */ | 8 /* Readonly */)) && type2.flags & 8192 /* UniqueESSymbol */ ? 1048576 /* AllowUniqueESSymbolType */ : 0 /* None */; + } } function createTypeOfFromEntityNameExpression(node) { return factory.createTypeQueryNode(getSynthesizedDeepClone(node)); @@ -254366,7 +255154,7 @@ function withContext(context, typePrintMode, cb) { } function typeToTypeNode2(type, enclosingDeclaration, flags = 0 /* None */) { let isTruncated = false; - const result2 = typeToAutoImportableTypeNode(typeChecker, importAdder, type, enclosingDeclaration, scriptTarget, declarationEmitNodeBuilderFlags2 | flags, { + const result2 = typeToAutoImportableTypeNode(typeChecker, importAdder, type, enclosingDeclaration, scriptTarget, declarationEmitNodeBuilderFlags2 | flags, declarationEmitInternalNodeBuilderFlags2, { moduleResolverHost: program, trackSymbol() { return true; @@ -254377,11 +255165,18 @@ function withContext(context, typePrintMode, cb) { }); return isTruncated ? factory.createKeywordTypeNode(133 /* AnyKeyword */) : result2; } - function tryGetReturnType2(node) { - const signature = typeChecker.getSignatureFromDeclaration(node); - if (signature) { - return typeChecker.getReturnTypeOfSignature(signature); - } + function typePredicateToTypeNode(typePredicate, enclosingDeclaration, flags = 0 /* None */) { + let isTruncated = false; + const result2 = typePredicateToAutoImportableTypeNode(typeChecker, importAdder, typePredicate, enclosingDeclaration, scriptTarget, declarationEmitNodeBuilderFlags2 | flags, declarationEmitInternalNodeBuilderFlags2, { + moduleResolverHost: program, + trackSymbol() { + return true; + }, + reportTruncationError() { + isTruncated = true; + } + }); + return isTruncated ? factory.createKeywordTypeNode(133 /* AnyKeyword */) : result2; } function addTypeToVariableLike(decl) { const { typeNode } = inferType(decl); @@ -255699,7 +256494,7 @@ function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, sourceFile, con case 172 /* PropertyDeclaration */: let flags = 1 /* NoTruncation */; flags |= quotePreference === 0 /* Single */ ? 268435456 /* UseSingleQuotesForStringLiteralType */ : 0; - let typeNode = checker.typeToTypeNode(type, enclosingDeclaration, flags, getNoopSymbolTrackerWithResolver(context)); + let typeNode = checker.typeToTypeNode(type, enclosingDeclaration, flags, 8 /* AllowUnresolvedNames */, getNoopSymbolTrackerWithResolver(context)); if (importAdder) { const importableReference = tryGetAutoImportableReferenceFromTypeNode(typeNode, scriptTarget); if (importableReference) { @@ -255724,6 +256519,8 @@ function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, sourceFile, con enclosingDeclaration, /*flags*/ void 0, + /*internalFlags*/ + void 0, getNoopSymbolTrackerWithResolver(context) ); const allAccessors = getAllAccessorDeclarations(declarations, declaration); @@ -255779,6 +256576,9 @@ function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, sourceFile, con break; } for (const signature of signatures) { + if (signature.declaration && signature.declaration.flags & 33554432 /* Ambient */) { + continue; + } outputMethod(quotePreference, signature, modifiers, createName(declarationName)); } if (!ambient) { @@ -255853,7 +256653,7 @@ function createSignatureDeclarationFromSignature(kind, context, quotePreference, const scriptTarget = getEmitScriptTarget(program.getCompilerOptions()); const isJs = isInJSFile(enclosingDeclaration); const flags = 1 /* NoTruncation */ | 256 /* SuppressAnyReturnType */ | 524288 /* AllowEmptyTuple */ | (quotePreference === 0 /* Single */ ? 268435456 /* UseSingleQuotesForStringLiteralType */ : 0 /* None */); - const signatureDeclaration = checker.signatureToSignatureDeclaration(signature, kind, enclosingDeclaration, flags, getNoopSymbolTrackerWithResolver(context)); + const signatureDeclaration = checker.signatureToSignatureDeclaration(signature, kind, enclosingDeclaration, flags, 8 /* AllowUnresolvedNames */, getNoopSymbolTrackerWithResolver(context)); if (!signatureDeclaration) { return void 0; } @@ -255954,6 +256754,7 @@ function createSignatureDeclarationFromCallExpression(kind, context, importAdder contextNode, scriptTarget, 1 /* NoTruncation */, + 8 /* AllowUnresolvedNames */, tracker ); const modifiers = modifierFlags ? factory.createNodeArray(factory.createModifiersFromModifierFlags(modifierFlags)) : void 0; @@ -255972,6 +256773,8 @@ function createSignatureDeclarationFromCallExpression(kind, context, importAdder contextNode, /*flags*/ void 0, + /*internalFlags*/ + void 0, tracker ); switch (kind) { @@ -256041,8 +256844,8 @@ function createTypeParametersForArguments(checker, argumentTypeParameters, typeA function createTypeParameterName(index) { return 84 /* T */ + index <= 90 /* Z */ ? String.fromCharCode(84 /* T */ + index) : `T${index}`; } -function typeToAutoImportableTypeNode(checker, importAdder, type, contextNode, scriptTarget, flags, tracker) { - let typeNode = checker.typeToTypeNode(type, contextNode, flags, tracker); +function typeToAutoImportableTypeNode(checker, importAdder, type, contextNode, scriptTarget, flags, internalFlags, tracker) { + let typeNode = checker.typeToTypeNode(type, contextNode, flags, internalFlags, tracker); if (typeNode && isImportTypeNode(typeNode)) { const importableReference = tryGetAutoImportableReferenceFromTypeNode(typeNode, scriptTarget); if (importableReference) { @@ -256052,13 +256855,24 @@ function typeToAutoImportableTypeNode(checker, importAdder, type, contextNode, s } return getSynthesizedDeepClone(typeNode); } +function typePredicateToAutoImportableTypeNode(checker, importAdder, typePredicate, contextNode, scriptTarget, flags, internalFlags, tracker) { + let typePredicateNode = checker.typePredicateToTypePredicateNode(typePredicate, contextNode, flags, internalFlags, tracker); + if ((typePredicateNode == null ? void 0 : typePredicateNode.type) && isImportTypeNode(typePredicateNode.type)) { + const importableReference = tryGetAutoImportableReferenceFromTypeNode(typePredicateNode.type, scriptTarget); + if (importableReference) { + importSymbols(importAdder, importableReference.symbols); + typePredicateNode = factory.updateTypePredicateNode(typePredicateNode, typePredicateNode.assertsModifier, typePredicateNode.parameterName, importableReference.typeNode); + } + } + return getSynthesizedDeepClone(typePredicateNode); +} function typeContainsTypeParameter(type) { if (type.isUnionOrIntersection()) { return type.types.some(typeContainsTypeParameter); } return type.flags & 262144 /* TypeParameter */; } -function getArgumentTypesAndTypeParameters(checker, importAdder, instanceTypes, contextNode, scriptTarget, flags, tracker) { +function getArgumentTypesAndTypeParameters(checker, importAdder, instanceTypes, contextNode, scriptTarget, flags, internalFlags, tracker) { const argumentTypeNodes = []; const argumentTypeParameters = /* @__PURE__ */ new Map(); for (let i = 0; i < instanceTypes.length; i += 1) { @@ -256070,13 +256884,13 @@ function getArgumentTypesAndTypeParameters(checker, importAdder, instanceTypes, continue; } const widenedInstanceType = checker.getBaseTypeOfLiteralType(instanceType); - const argumentTypeNode = typeToAutoImportableTypeNode(checker, importAdder, widenedInstanceType, contextNode, scriptTarget, flags, tracker); + const argumentTypeNode = typeToAutoImportableTypeNode(checker, importAdder, widenedInstanceType, contextNode, scriptTarget, flags, internalFlags, tracker); if (!argumentTypeNode) { continue; } argumentTypeNodes.push(argumentTypeNode); const argumentTypeParameter = getFirstTypeParameterName(instanceType); - const instanceTypeConstraint = instanceType.isTypeParameter() && instanceType.constraint && !isAnonymousObjectConstraintType(instanceType.constraint) ? typeToAutoImportableTypeNode(checker, importAdder, instanceType.constraint, contextNode, scriptTarget, flags, tracker) : void 0; + const instanceTypeConstraint = instanceType.isTypeParameter() && instanceType.constraint && !isAnonymousObjectConstraintType(instanceType.constraint) ? typeToAutoImportableTypeNode(checker, importAdder, instanceType.constraint, contextNode, scriptTarget, flags, internalFlags, tracker) : void 0; if (argumentTypeParameter) { argumentTypeParameters.set(argumentTypeParameter, { argumentType: instanceType, constraint: instanceTypeConstraint }); } @@ -256176,7 +256990,7 @@ function createMethodImplementingSignatures(checker, context, enclosingDeclarati function getReturnTypeFromSignatures(signatures, checker, context, enclosingDeclaration) { if (length(signatures)) { const type = checker.getUnionType(map(signatures, checker.getReturnTypeOfSignature)); - return checker.typeToTypeNode(type, enclosingDeclaration, 1 /* NoTruncation */, getNoopSymbolTrackerWithResolver(context)); + return checker.typeToTypeNode(type, enclosingDeclaration, 1 /* NoTruncation */, 8 /* AllowUnresolvedNames */, getNoopSymbolTrackerWithResolver(context)); } } function createStubbedMethod(modifiers, name, optional, typeParameters, parameters, returnType, quotePreference, body) { @@ -256774,7 +257588,7 @@ var errorCodes54 = [Diagnostics.require_call_may_be_converted_to_an_import.code] registerCodeFix({ errorCodes: errorCodes54, getCodeActions(context) { - const info = getInfo18(context.sourceFile, context.program, context.span.start); + const info = getInfo18(context.sourceFile, context.program, context.span.start, context.preferences); if (!info) { return void 0; } @@ -256783,14 +257597,14 @@ registerCodeFix({ }, fixIds: [fixId42], getAllCodeActions: (context) => codeFixAll(context, errorCodes54, (changes, diag2) => { - const info = getInfo18(diag2.file, context.program, diag2.start); + const info = getInfo18(diag2.file, context.program, diag2.start, context.preferences); if (info) { doChange35(changes, context.sourceFile, info); } }) }); function doChange35(changes, sourceFile, info) { - const { allowSyntheticDefaults, defaultImportName, namedImports, statement, required } = info; + const { allowSyntheticDefaults, defaultImportName, namedImports, statement, moduleSpecifier } = info; changes.replaceNode( sourceFile, statement, @@ -256800,7 +257614,7 @@ function doChange35(changes, sourceFile, info) { /*isTypeOnly*/ false, defaultImportName, - factory.createExternalModuleReference(required) + factory.createExternalModuleReference(moduleSpecifier) ) : factory.createImportDeclaration( /*modifiers*/ void 0, @@ -256810,13 +257624,13 @@ function doChange35(changes, sourceFile, info) { defaultImportName, namedImports ), - required, + moduleSpecifier, /*attributes*/ void 0 ) ); } -function getInfo18(sourceFile, program, pos) { +function getInfo18(sourceFile, program, pos, preferences) { const { parent: parent2 } = getTokenAtPosition(sourceFile, pos); if (!isRequireCall( parent2, @@ -256826,15 +257640,17 @@ function getInfo18(sourceFile, program, pos) { Debug.failBadSyntaxKind(parent2); } const decl = cast(parent2.parent, isVariableDeclaration); + const quotePreference = getQuotePreference(sourceFile, preferences); const defaultImportName = tryCast(decl.name, isIdentifier); const namedImports = isObjectBindingPattern(decl.name) ? tryCreateNamedImportsFromObjectBindingPattern(decl.name) : void 0; if (defaultImportName || namedImports) { + const moduleSpecifier = first(parent2.arguments); return { allowSyntheticDefaults: getAllowSyntheticDefaultImports(program.getCompilerOptions()), defaultImportName, namedImports, statement: cast(decl.parent.parent, isVariableStatement), - required: first(parent2.arguments) + moduleSpecifier: isNoSubstitutionTemplateLiteral(moduleSpecifier) ? factory.createStringLiteral(moduleSpecifier.text, quotePreference === 0 /* Single */) : moduleSpecifier }; } } @@ -257368,6 +258184,7 @@ __export(ts_Completions_exports, { getCompletionEntryDetails: () => getCompletionEntryDetails, getCompletionEntrySymbol: () => getCompletionEntrySymbol, getCompletionsAtPosition: () => getCompletionsAtPosition, + getDefaultCommitCharacters: () => getDefaultCommitCharacters, getPropertiesForObjectExpression: () => getPropertiesForObjectExpression, moduleSpecifierResolutionCacheAttemptLimit: () => moduleSpecifierResolutionCacheAttemptLimit, moduleSpecifierResolutionLimit: () => moduleSpecifierResolutionLimit @@ -257459,9 +258276,9 @@ function originIsComputedPropertyName(origin) { return !!(origin && origin.kind & 512 /* ComputedPropertyName */); } function resolvingModuleSpecifiers(logPrefix, host, resolver, program, position, preferences, isForImportStatementCompletion, isValidTypeOnlyUseSite, cb) { - var _a, _b, _c; + var _a, _b, _c, _d; const start = timestamp(); - const needsFullResolution = isForImportStatementCompletion || moduleResolutionSupportsPackageJsonExportsAndImports(getEmitModuleResolutionKind(program.getCompilerOptions())); + const needsFullResolution = isForImportStatementCompletion || getResolvePackageJsonExports(program.getCompilerOptions()) || ((_a = preferences.autoImportSpecifierExcludeRegexes) == null ? void 0 : _a.length); let skippedAny = false; let ambientCount = 0; let resolvedCount = 0; @@ -257474,9 +258291,9 @@ function resolvingModuleSpecifiers(logPrefix, host, resolver, program, position, resolvedBeyondLimit: () => resolvedCount > moduleSpecifierResolutionLimit }); const hitRateMessage = cacheAttemptCount ? ` (${(resolvedFromCacheCount / cacheAttemptCount * 100).toFixed(1)}% hit rate)` : ""; - (_a = host.log) == null ? void 0 : _a.call(host, `${logPrefix}: resolved ${resolvedCount} module specifiers, plus ${ambientCount} ambient and ${resolvedFromCacheCount} from cache${hitRateMessage}`); - (_b = host.log) == null ? void 0 : _b.call(host, `${logPrefix}: response is ${skippedAny ? "incomplete" : "complete"}`); - (_c = host.log) == null ? void 0 : _c.call(host, `${logPrefix}: ${timestamp() - start}`); + (_b = host.log) == null ? void 0 : _b.call(host, `${logPrefix}: resolved ${resolvedCount} module specifiers, plus ${ambientCount} ambient and ${resolvedFromCacheCount} from cache${hitRateMessage}`); + (_c = host.log) == null ? void 0 : _c.call(host, `${logPrefix}: response is ${skippedAny ? "incomplete" : "complete"}`); + (_d = host.log) == null ? void 0 : _d.call(host, `${logPrefix}: ${timestamp() - start}`); return result; function tryResolve(exportInfo, isFromAmbientModule) { if (isFromAmbientModule) { @@ -257500,6 +258317,12 @@ function resolvingModuleSpecifiers(logPrefix, host, resolver, program, position, return result2 || (needsFullResolution ? "failed" : "skipped"); } } +function getDefaultCommitCharacters(isNewIdentifierLocation) { + if (isNewIdentifierLocation) { + return []; + } + return [".", ",", ";"]; +} function getCompletionsAtPosition(host, program, log, sourceFile, position, preferences, triggerCharacter, completionKind, cancellationToken, formatContext, includeSymbol = false) { var _a; const { previousToken } = getRelevantTokens(position, sourceFile); @@ -257508,7 +258331,17 @@ function getCompletionsAtPosition(host, program, log, sourceFile, position, pref } if (triggerCharacter === " ") { if (preferences.includeCompletionsForImportStatements && preferences.includeCompletionsWithInsertText) { - return { isGlobalCompletion: true, isMemberCompletion: false, isNewIdentifierLocation: true, isIncomplete: true, entries: [] }; + return { + isGlobalCompletion: true, + isMemberCompletion: false, + isNewIdentifierLocation: true, + isIncomplete: true, + entries: [], + defaultCommitCharacters: getDefaultCommitCharacters( + /*isNewIdentifierLocation*/ + true + ) + }; } return void 0; } @@ -257662,7 +258495,16 @@ function continuePreviousIncompleteResponse(cache, file, location, program, host return previousResponse; } function jsdocCompletionInfo(entries) { - return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries }; + return { + isGlobalCompletion: false, + isMemberCompletion: false, + isNewIdentifierLocation: false, + entries, + defaultCommitCharacters: getDefaultCommitCharacters( + /*isNewIdentifierLocation*/ + false + ) + }; } function getJSDocParameterCompletions(sourceFile, position, checker, options, preferences, tagNameOnly) { const currentToken = getTokenAtPosition(sourceFile, position); @@ -257890,10 +258732,12 @@ function getJSDocParamAnnotation(paramName, initializer, dotDotDotToken, isJs, i const printer = isSnippet ? createSnippetPrinter({ removeComments: true, module: options.module, + moduleResolution: options.moduleResolution, target: options.target }) : createPrinter({ removeComments: true, module: options.module, + moduleResolution: options.moduleResolution, target: options.target }); setEmitFlags(typeNode, 1 /* SingleLine */); @@ -257933,7 +258777,8 @@ function specificKeywordCompletionInfo(entries, isNewIdentifierLocation) { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation, - entries: entries.slice() + entries: entries.slice(), + defaultCommitCharacters: getDefaultCommitCharacters(isNewIdentifierLocation) }; } function keywordCompletionData(keywordFilters, filterOutTsOnlyKeywords, isNewIdentifierLocation) { @@ -258091,7 +258936,8 @@ function completionInfoFromData(sourceFile, host, program, compilerOptions, log, isMemberCompletion: isMemberCompletionKind(completionKind), isNewIdentifierLocation, optionalReplacementSpan: getOptionalReplacementSpan(location), - entries + entries, + defaultCommitCharacters: getDefaultCommitCharacters(isNewIdentifierLocation) }; } function isCheckedFile(sourceFile, compilerOptions) { @@ -258149,6 +258995,7 @@ function getExhaustiveCaseSnippets(caseBlock, sourceFile, preferences, options, const printer = createSnippetPrinter({ removeComments: true, module: options.module, + moduleResolution: options.moduleResolution, target: options.target, newLine: getNewLineKind(newLineChar) }); @@ -258256,7 +259103,17 @@ function getJsxClosingTagCompletion(location, sourceFile) { kindModifiers: void 0, sortText: SortText.LocationPriority }; - return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: false, optionalReplacementSpan: replacementSpan, entries: [entry] }; + return { + isGlobalCompletion: false, + isMemberCompletion: true, + isNewIdentifierLocation: false, + optionalReplacementSpan: replacementSpan, + entries: [entry], + defaultCommitCharacters: getDefaultCommitCharacters( + /*isNewIdentifierLocation*/ + false + ) + }; } return; } @@ -258273,7 +259130,8 @@ function getJSCompletionEntries(sourceFile, position, uniqueNames, target, entri kind: "warning" /* warning */, kindModifiers: "", sortText: SortText.JavascriptIdentifiers, - isFromUncheckedFile: true + isFromUncheckedFile: true, + commitCharacters: [] }, compareCompletionEntries); } }); @@ -258282,7 +259140,13 @@ function completionNameForLiteral(sourceFile, preferences, literal) { return typeof literal === "object" ? pseudoBigIntToString(literal) + "n" : isString(literal) ? quote(sourceFile, preferences, literal) : JSON.stringify(literal); } function createCompletionEntryForLiteral(sourceFile, preferences, literal) { - return { name: completionNameForLiteral(sourceFile, preferences, literal), kind: "string" /* string */, kindModifiers: "" /* none */, sortText: SortText.LocationPriority }; + return { + name: completionNameForLiteral(sourceFile, preferences, literal), + kind: "string" /* string */, + kindModifiers: "" /* none */, + sortText: SortText.LocationPriority, + commitCharacters: [] + }; } function createCompletionEntry(symbol, sortText, replacementToken, contextToken, location, position, sourceFile, host, program, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, importStatementCompletion, useSemicolons, options, preferences, completionKind, formatContext, isJsxIdentifierExpected, isRightOfOpenTag, includeSymbol) { var _a, _b; @@ -258335,7 +259199,7 @@ function createCompletionEntry(symbol, sortText, replacementToken, contextToken, if (originIsResolvedExport(origin)) { sourceDisplay = [textPart(origin.moduleSpecifier)]; if (importStatementCompletion) { - ({ insertText, replacementSpan } = getInsertTextAndReplacementSpanForImportCompletion(name, importStatementCompletion, origin, useSemicolons, sourceFile, options, preferences)); + ({ insertText, replacementSpan } = getInsertTextAndReplacementSpanForImportCompletion(name, importStatementCompletion, origin, useSemicolons, sourceFile, program, preferences)); isSnippet = preferences.includeCompletionsWithSnippetText ? true : void 0; } } @@ -258405,15 +259269,25 @@ function createCompletionEntry(symbol, sortText, replacementToken, contextToken, hasAction = !importStatementCompletion; } const parentNamedImportOrExport = findAncestor(location, isNamedImportsOrExports); - if ((parentNamedImportOrExport == null ? void 0 : parentNamedImportOrExport.kind) === 275 /* NamedImports */) { - const possibleToken = stringToToken(name); - if (parentNamedImportOrExport && possibleToken && (possibleToken === 135 /* AwaitKeyword */ || isNonContextualKeyword(possibleToken))) { - insertText = `${name} as ${name}_`; + if (parentNamedImportOrExport) { + const languageVersion = getEmitScriptTarget(host.getCompilationSettings()); + if (!isIdentifierText(name, languageVersion)) { + insertText = JSON.stringify(name); + if (parentNamedImportOrExport.kind === 275 /* NamedImports */) { + insertText += " as " + generateIdentifierForArbitraryString(name, languageVersion); + } + } else if (parentNamedImportOrExport.kind === 275 /* NamedImports */) { + const possibleToken = stringToToken(name); + if (possibleToken && (possibleToken === 135 /* AwaitKeyword */ || isNonContextualKeyword(possibleToken))) { + insertText = `${name} as ${name}_`; + } } } + const kind = ts_SymbolDisplay_exports.getSymbolKind(typeChecker, symbol, location); + const commitCharacters = kind === "warning" /* warning */ || kind === "string" /* string */ ? [] : void 0; return { name, - kind: ts_SymbolDisplay_exports.getSymbolKind(typeChecker, symbol, location), + kind, kindModifiers: ts_SymbolDisplay_exports.getSymbolModifiers(typeChecker, symbol), sortText, source, @@ -258428,9 +259302,27 @@ function createCompletionEntry(symbol, sortText, replacementToken, contextToken, isPackageJsonImport: originIsPackageJsonImport(origin) || void 0, isImportStatementCompletion: !!importStatementCompletion || void 0, data, + commitCharacters, ...includeSymbol ? { symbol } : void 0 }; } +function generateIdentifierForArbitraryString(text, languageVersion) { + let needsUnderscore = false; + let identifier = ""; + let ch; + for (let i = 0; i < text.length; i += ch !== void 0 && ch >= 65536 ? 2 : 1) { + ch = text.codePointAt(i); + if (ch !== void 0 && (i === 0 ? isIdentifierStart(ch, languageVersion) : isIdentifierPart(ch, languageVersion))) { + if (needsUnderscore) identifier += "_"; + identifier += String.fromCodePoint(ch); + needsUnderscore = false; + } else { + needsUnderscore = true; + } + } + if (needsUnderscore) identifier += "_"; + return identifier || "_"; +} function isClassLikeMemberCompletion(symbol, location, sourceFile) { if (isInJSFile(location)) { return false; @@ -258451,6 +259343,7 @@ function getEntryForMemberCompletion(host, program, options, preferences, name, const printer = createSnippetPrinter({ removeComments: true, module: options.module, + moduleResolution: options.moduleResolution, target: options.target, omitTrailingSemicolon: false, newLine: getNewLineKind(getNewLineOrDefaultFromHost(host, formatContext == null ? void 0 : formatContext.options)) @@ -258601,6 +259494,7 @@ function getEntryForObjectLiteralMethodCompletion(symbol, name, enclosingDeclara const printer = createSnippetPrinter({ removeComments: true, module: options.module, + moduleResolution: options.moduleResolution, target: options.target, omitTrailingSemicolon: false, newLine: getNewLineKind(getNewLineOrDefaultFromHost(host, formatContext == null ? void 0 : formatContext.options)) @@ -258621,6 +259515,7 @@ function getEntryForObjectLiteralMethodCompletion(symbol, name, enclosingDeclara const signaturePrinter = createPrinter({ removeComments: true, module: options.module, + moduleResolution: options.moduleResolution, target: options.target, omitTrailingSemicolon: true }); @@ -258670,7 +259565,14 @@ function createObjectLiteralMethod(symbol, enclosingDeclaration, sourceFile, pro if (signatures.length !== 1) { return void 0; } - const typeNode = checker.typeToTypeNode(effectiveType, enclosingDeclaration, builderFlags, ts_codefix_exports.getNoopSymbolTrackerWithResolver({ program, host })); + const typeNode = checker.typeToTypeNode( + effectiveType, + enclosingDeclaration, + builderFlags, + /*internalFlags*/ + void 0, + ts_codefix_exports.getNoopSymbolTrackerWithResolver({ program, host }) + ); if (!typeNode || !isFunctionTypeNode(typeNode)) { return void 0; } @@ -258790,7 +259692,7 @@ function createSnippetPrinter(printerOptions) { { ...formatContext, options: formatOptions } ); }); - const allChanges = escapes ? stableSort(concatenate(changes, escapes), (a, b) => compareTextSpans(a.span, b.span)) : changes; + const allChanges = escapes ? toSorted(concatenate(changes, escapes), (a, b) => compareTextSpans(a.span, b.span)) : changes; return ts_textChanges_exports.applyChanges(syntheticFile.text, allChanges); } function printNode(hint, node, sourceFile) { @@ -258826,7 +259728,7 @@ function createSnippetPrinter(printerOptions) { 0, { ...formatContext, options: formatOptions } ); - const allChanges = escapes ? stableSort(concatenate(changes, escapes), (a, b) => compareTextSpans(a.span, b.span)) : changes; + const allChanges = escapes ? toSorted(concatenate(changes, escapes), (a, b) => compareTextSpans(a.span, b.span)) : changes; return ts_textChanges_exports.applyChanges(syntheticFile.text, allChanges); } } @@ -258882,7 +259784,7 @@ function completionEntryDataToSymbolOriginInfo(data, completionName, moduleSymbo }; return unresolvedOrigin; } -function getInsertTextAndReplacementSpanForImportCompletion(name, importStatementCompletion, origin, useSemicolons, sourceFile, options, preferences) { +function getInsertTextAndReplacementSpanForImportCompletion(name, importStatementCompletion, origin, useSemicolons, sourceFile, program, preferences) { const replacementSpan = importStatementCompletion.replacementSpan; const quotedModuleSpecifier = escapeSnippetText(quote(sourceFile, preferences, origin.moduleSpecifier)); const exportKind = origin.isDefaultExport ? 1 /* Default */ : origin.exportName === "export=" /* ExportEquals */ ? 2 /* ExportEquals */ : 0 /* Named */; @@ -258890,7 +259792,7 @@ function getInsertTextAndReplacementSpanForImportCompletion(name, importStatemen const importKind = ts_codefix_exports.getImportKind( sourceFile, exportKind, - options, + program, /*forceImportKeyword*/ true ); @@ -259038,7 +259940,16 @@ function getCompletionEntriesFromSymbols(symbols, entries, replacementToken, con function getLabelCompletionAtPosition(node) { const entries = getLabelStatementCompletions(node); if (entries.length) { - return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries }; + return { + isGlobalCompletion: false, + isMemberCompletion: false, + isNewIdentifierLocation: false, + entries, + defaultCommitCharacters: getDefaultCommitCharacters( + /*isNewIdentifierLocation*/ + false + ) + }; } } function getLabelStatementCompletions(node) { @@ -260017,7 +260928,7 @@ function getCompletionData(program, log, sourceFile, compilerOptions, position, if (ts_JsTyping_exports.nodeCoreModules.has(moduleName) && startsWith(moduleName, "node:") !== shouldUseUriStyleNodeCoreModules(sourceFile, program)) { return false; } - return packageJsonFilter ? packageJsonFilter.allowsImportingAmbientModule(info.moduleSymbol, getModuleSpecifierResolutionHost(info.isFromPackageJson)) : true; + return ((packageJsonFilter == null ? void 0 : packageJsonFilter.allowsImportingAmbientModule(info.moduleSymbol, getModuleSpecifierResolutionHost(info.isFromPackageJson))) ?? true) || fileContainsPackageImport(sourceFile, moduleName); } return isImportableFile( info.isFromPackageJson ? packageJsonAutoImportProvider : program, @@ -260259,7 +261170,7 @@ function getCompletionData(program, log, sourceFile, compilerOptions, position, completionKind = 3 /* MemberLike */; isNewIdentifierLocation = false; const exports2 = typeChecker.getExportsAndPropertiesOfModule(moduleSpecifierSymbol); - const existing = new Set(namedImportsOrExports.elements.filter((n) => !isCurrentlyEditingNode(n)).map((n) => (n.propertyName || n.name).escapedText)); + const existing = new Set(namedImportsOrExports.elements.filter((n) => !isCurrentlyEditingNode(n)).map((n) => moduleExportNameTextEscaped(n.propertyName || n.name))); const uniques = exports2.filter((e) => e.escapedName !== "default" /* Default */ && !existing.has(e.escapedName)); symbols = concatenate(symbols, uniques); if (!uniques.length) { @@ -260750,6 +261661,9 @@ function getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind, js if (isIdentifierText(name, target, jsxIdentifierExpected ? 1 /* JSX */ : 0 /* Standard */) || symbol.valueDeclaration && isPrivateIdentifierClassElementDeclaration(symbol.valueDeclaration)) { return validNameResult; } + if (symbol.flags & 2097152 /* Alias */) { + return { name, needsConvertPropertyAccess: true }; + } switch (kind) { case 3 /* MemberLike */: return originIsComputedPropertyName(origin) ? { name: origin.symbolName, needsConvertPropertyAccess: false } : void 0; @@ -260891,7 +261805,13 @@ function getJsDocTagAtPosition(node, position) { } function getPropertiesForObjectExpression(contextualType, completionsType, obj, checker) { const hasCompletionsType = completionsType && completionsType !== contextualType; - const type = hasCompletionsType && !(completionsType.flags & 3 /* AnyOrUnknown */) ? checker.getUnionType([contextualType, completionsType]) : contextualType; + const promiseFilteredContextualType = checker.getUnionType( + filter( + contextualType.flags & 1048576 /* Union */ ? contextualType.types : [contextualType], + (t) => !checker.getPromisedTypeOfPromise(t) + ) + ); + const type = hasCompletionsType && !(completionsType.flags & 3 /* AnyOrUnknown */) ? checker.getUnionType([promiseFilteredContextualType, completionsType]) : promiseFilteredContextualType; const properties = getApparentProperties(type, obj, checker); return type.isClass() && containsNonPublicProperties(properties) ? [] : hasCompletionsType ? filter(properties, hasDeclarationOtherThanSelf) : properties; function hasDeclarationOtherThanSelf(member) { @@ -261266,7 +262186,7 @@ function createNameAndKindSet() { } function getStringLiteralCompletions(sourceFile, position, contextToken, options, host, program, log, preferences, includeSymbol) { if (isInReferenceComment(sourceFile, position)) { - const entries = getTripleSlashReferenceCompletion(sourceFile, position, options, host); + const entries = getTripleSlashReferenceCompletion(sourceFile, position, program, host); return entries && convertPathCompletions(entries); } if (isInString(sourceFile, position, contextToken)) { @@ -261324,7 +262244,14 @@ function convertStringLiteralCompletions(completion, contextToken, sourceFile, h void 0, includeSymbol ); - return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, optionalReplacementSpan, entries }; + return { + isGlobalCompletion: false, + isMemberCompletion: true, + isNewIdentifierLocation: completion.hasIndexSignature, + optionalReplacementSpan, + entries, + defaultCommitCharacters: getDefaultCommitCharacters(completion.hasIndexSignature) + }; } case 2 /* Types */: { const quoteChar = contextToken.kind === 15 /* NoSubstitutionTemplateLiteral */ ? 96 /* backtick */ : startsWith(getTextOfNode(contextToken), "'") ? 39 /* singleQuote */ : 34 /* doubleQuote */; @@ -261333,9 +262260,17 @@ function convertStringLiteralCompletions(completion, contextToken, sourceFile, h kindModifiers: "" /* none */, kind: "string" /* string */, sortText: SortText.LocationPriority, - replacementSpan: getReplacementSpanForContextToken(contextToken, position) + replacementSpan: getReplacementSpanForContextToken(contextToken, position), + commitCharacters: [] })); - return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: completion.isNewIdentifier, optionalReplacementSpan, entries }; + return { + isGlobalCompletion: false, + isMemberCompletion: false, + isNewIdentifierLocation: completion.isNewIdentifier, + optionalReplacementSpan, + entries, + defaultCommitCharacters: getDefaultCommitCharacters(completion.isNewIdentifier) + }; } default: return Debug.assertNever(completion); @@ -261366,7 +262301,13 @@ function convertPathCompletions(pathCompletions) { const isGlobalCompletion = false; const isNewIdentifierLocation = true; const entries = pathCompletions.map(({ name, kind, span, extension }) => ({ name, kind, kindModifiers: kindModifiersFromExtension(extension), sortText: SortText.LocationPriority, replacementSpan: span })); - return { isGlobalCompletion, isMemberCompletion: false, isNewIdentifierLocation, entries }; + return { + isGlobalCompletion, + isMemberCompletion: false, + isNewIdentifierLocation, + entries, + defaultCommitCharacters: getDefaultCommitCharacters(isNewIdentifierLocation) + }; } function kindModifiersFromExtension(extension) { switch (extension) { @@ -261445,6 +262386,21 @@ function getStringLiteralCompletionEntries(sourceFile, node, position, program, } const literals = contextualTypes.types.filter((literal) => !tracker.hasValue(literal.value)); return { kind: 2 /* Types */, types: literals, isNewIdentifier: false }; + case 276 /* ImportSpecifier */: + case 281 /* ExportSpecifier */: + const specifier = parent2; + if (specifier.propertyName && node !== specifier.propertyName) { + return; + } + const namedImportsOrExports = specifier.parent; + const { moduleSpecifier } = namedImportsOrExports.kind === 275 /* NamedImports */ ? namedImportsOrExports.parent.parent : namedImportsOrExports.parent; + if (!moduleSpecifier) return; + const moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(moduleSpecifier); + if (!moduleSpecifierSymbol) return; + const exports2 = typeChecker.getExportsAndPropertiesOfModule(moduleSpecifierSymbol); + const existing = new Set(namedImportsOrExports.elements.map((n) => moduleExportNameTextEscaped(n.propertyName || n.name))); + const uniques = exports2.filter((e) => e.escapedName !== "default" /* Default */ && !existing.has(e.escapedName)); + return { kind: 1 /* Properties */, symbols: uniques, hasIndexSignature: false }; default: return fromContextualType() || fromContextualType(0 /* None */); } @@ -261574,7 +262530,7 @@ function getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, prog const compilerOptions = program.getCompilerOptions(); const typeChecker = program.getTypeChecker(); const extensionOptions = getExtensionOptions(compilerOptions, 1 /* ModuleSpecifier */, sourceFile, typeChecker, preferences, mode); - return isPathRelativeToScript(literalValue) || !compilerOptions.baseUrl && !compilerOptions.paths && (isRootedDiskPath(literalValue) || isUrl(literalValue)) ? getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath, extensionOptions) : getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, mode, compilerOptions, host, extensionOptions, typeChecker); + return isPathRelativeToScript(literalValue) || !compilerOptions.baseUrl && !compilerOptions.paths && (isRootedDiskPath(literalValue) || isUrl(literalValue)) ? getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, program, host, scriptPath, extensionOptions) : getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, mode, program, host, extensionOptions); } function getExtensionOptions(compilerOptions, referenceKind, importingSourceFile, typeChecker, preferences, resolutionMode) { return { @@ -261585,14 +262541,15 @@ function getExtensionOptions(compilerOptions, referenceKind, importingSourceFile resolutionMode }; } -function getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, compilerOptions, host, scriptPath, extensionOptions) { +function getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, program, host, scriptPath, extensionOptions) { + const compilerOptions = program.getCompilerOptions(); if (compilerOptions.rootDirs) { return getCompletionEntriesForDirectoryFragmentWithRootDirs( compilerOptions.rootDirs, literalValue, scriptDirectory, extensionOptions, - compilerOptions, + program, host, scriptPath ); @@ -261601,6 +262558,7 @@ function getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, c literalValue, scriptDirectory, extensionOptions, + program, host, /*moduleSpecifierIsRelative*/ true, @@ -261627,7 +262585,8 @@ function getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptDirectory, ign compareStringsCaseSensitive ); } -function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptDirectory, extensionOptions, compilerOptions, host, exclude) { +function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptDirectory, extensionOptions, program, host, exclude) { + const compilerOptions = program.getCompilerOptions(); const basePath = compilerOptions.project || host.getCurrentDirectory(); const ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); const baseDirectories = getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptDirectory, ignoreCase); @@ -261636,6 +262595,7 @@ function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment fragment, baseDirectory, extensionOptions, + program, host, /*moduleSpecifierIsRelative*/ true, @@ -261644,7 +262604,7 @@ function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment (itemA, itemB) => itemA.name === itemB.name && itemA.kind === itemB.kind && itemA.extension === itemB.extension ); } -function getCompletionEntriesForDirectoryFragment(fragment, scriptDirectory, extensionOptions, host, moduleSpecifierIsRelative, exclude, result = createNameAndKindSet()) { +function getCompletionEntriesForDirectoryFragment(fragment, scriptDirectory, extensionOptions, program, host, moduleSpecifierIsRelative, exclude, result = createNameAndKindSet()) { var _a; if (fragment === void 0) { fragment = ""; @@ -261669,7 +262629,7 @@ function getCompletionEntriesForDirectoryFragment(fragment, scriptDirectory, ext if (versionPaths) { const packageDirectory = getDirectoryPath(packageJsonPath); const pathInPackage = absolutePath.slice(ensureTrailingDirectorySeparator(packageDirectory).length); - if (addCompletionEntriesFromPaths(result, pathInPackage, packageDirectory, extensionOptions, host, versionPaths)) { + if (addCompletionEntriesFromPaths(result, pathInPackage, packageDirectory, extensionOptions, program, host, versionPaths)) { return result; } } @@ -261695,7 +262655,7 @@ function getCompletionEntriesForDirectoryFragment(fragment, scriptDirectory, ext } const { name, extension } = getFilenameWithExtensionOption( getBaseFileName(filePath), - host.getCompilationSettings(), + program, extensionOptions, /*isExportsWildcard*/ false @@ -261714,7 +262674,7 @@ function getCompletionEntriesForDirectoryFragment(fragment, scriptDirectory, ext } return result; } -function getFilenameWithExtensionOption(name, compilerOptions, extensionOptions, isExportsWildcard) { +function getFilenameWithExtensionOption(name, program, extensionOptions, isExportsWildcard) { const nonJsResult = ts_moduleSpecifiers_exports.tryGetRealFileNameForNonJsDeclarationFileName(name); if (nonJsResult) { return { name: nonJsResult, extension: tryGetExtensionFromPath2(nonJsResult) }; @@ -261722,9 +262682,10 @@ function getFilenameWithExtensionOption(name, compilerOptions, extensionOptions, if (extensionOptions.referenceKind === 0 /* Filename */) { return { name, extension: tryGetExtensionFromPath2(name) }; } - let allowedEndings = getModuleSpecifierPreferences( + let allowedEndings = ts_moduleSpecifiers_exports.getModuleSpecifierPreferences( { importModuleSpecifierEnding: extensionOptions.endingPreference }, - compilerOptions, + program, + program.getCompilerOptions(), extensionOptions.importingSourceFile ).getAllowedEndingsInPreferredOrder(extensionOptions.resolutionMode); if (isExportsWildcard) { @@ -261734,16 +262695,16 @@ function getFilenameWithExtensionOption(name, compilerOptions, extensionOptions, if (fileExtensionIsOneOf(name, supportedTSImplementationExtensions)) { return { name, extension: tryGetExtensionFromPath2(name) }; } - const outputExtension2 = ts_moduleSpecifiers_exports.tryGetJSExtensionForFile(name, compilerOptions); + const outputExtension2 = ts_moduleSpecifiers_exports.tryGetJSExtensionForFile(name, program.getCompilerOptions()); return outputExtension2 ? { name: changeExtension(name, outputExtension2), extension: outputExtension2 } : { name, extension: tryGetExtensionFromPath2(name) }; } if (!isExportsWildcard && (allowedEndings[0] === 0 /* Minimal */ || allowedEndings[0] === 1 /* Index */) && fileExtensionIsOneOf(name, [".js" /* Js */, ".jsx" /* Jsx */, ".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */])) { return { name: removeFileExtension(name), extension: tryGetExtensionFromPath2(name) }; } - const outputExtension = ts_moduleSpecifiers_exports.tryGetJSExtensionForFile(name, compilerOptions); + const outputExtension = ts_moduleSpecifiers_exports.tryGetJSExtensionForFile(name, program.getCompilerOptions()); return outputExtension ? { name: changeExtension(name, outputExtension), extension: outputExtension } : { name, extension: tryGetExtensionFromPath2(name) }; } -function addCompletionEntriesFromPaths(result, fragment, baseDirectory, extensionOptions, host, paths) { +function addCompletionEntriesFromPaths(result, fragment, baseDirectory, extensionOptions, program, host, paths) { const getPatternsForKey = (key) => paths[key]; const comparePaths2 = (a, b) => { const patternA = tryParsePattern(a); @@ -261759,13 +262720,14 @@ function addCompletionEntriesFromPaths(result, fragment, baseDirectory, extensio fragment, baseDirectory, extensionOptions, + program, host, getOwnKeys(paths), getPatternsForKey, comparePaths2 ); } -function addCompletionEntriesFromPathsOrExports(result, isExports, fragment, baseDirectory, extensionOptions, host, keys, getPatternsForKey, comparePaths2) { +function addCompletionEntriesFromPathsOrExports(result, isExports, fragment, baseDirectory, extensionOptions, program, host, keys, getPatternsForKey, comparePaths2) { let pathResults = []; let matchedPath; for (const key of keys) { @@ -261784,7 +262746,7 @@ function addCompletionEntriesFromPathsOrExports(result, isExports, fragment, bas if (typeof pathPattern === "string" || matchedPath === void 0 || comparePaths2(key, matchedPath) !== 1 /* GreaterThan */) { pathResults.push({ matchedPattern: isMatch, - results: getCompletionsForPathMapping(keyWithoutLeadingDotSlash, patterns, fragment, baseDirectory, extensionOptions, isExports && isMatch, host).map(({ name, kind, extension }) => nameAndKind(name, kind, extension)) + results: getCompletionsForPathMapping(keyWithoutLeadingDotSlash, patterns, fragment, baseDirectory, extensionOptions, isExports && isMatch, program, host).map(({ name, kind, extension }) => nameAndKind(name, kind, extension)) }); } } @@ -261792,7 +262754,9 @@ function addCompletionEntriesFromPathsOrExports(result, isExports, fragment, bas pathResults.forEach((pathResult) => pathResult.results.forEach((r) => result.add(r))); return matchedPath !== void 0; } -function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, mode, compilerOptions, host, extensionOptions, typeChecker) { +function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, mode, program, host, extensionOptions) { + const typeChecker = program.getTypeChecker(); + const compilerOptions = program.getCompilerOptions(); const { baseUrl, paths } = compilerOptions; const result = createNameAndKindSet(); const moduleResolution = getEmitModuleResolutionKind(compilerOptions); @@ -261802,6 +262766,7 @@ function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, mode, c fragment, absolute, extensionOptions, + program, host, /*moduleSpecifierIsRelative*/ false, @@ -261812,7 +262777,7 @@ function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, mode, c } if (paths) { const absolute = getPathsBasePath(compilerOptions, host); - addCompletionEntriesFromPaths(result, fragment, absolute, extensionOptions, host, paths); + addCompletionEntriesFromPaths(result, fragment, absolute, extensionOptions, program, host, paths); } const fragmentDirectory = getFragmentDirectory(fragment); for (const ambientName of getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker)) { @@ -261823,7 +262788,7 @@ function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, mode, c void 0 )); } - getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, fragmentDirectory, extensionOptions, result); + getCompletionEntriesFromTypings(host, program, scriptPath, fragmentDirectory, extensionOptions, result); if (moduleResolutionUsesNodeModules(moduleResolution)) { let foundGlobal = false; if (fragmentDirectory === void 0) { @@ -261848,6 +262813,7 @@ function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, mode, c fragment, nodeModules, extensionOptions, + program, host, /*moduleSpecifierIsRelative*/ false, @@ -261857,33 +262823,7 @@ function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, mode, c ); } }; - const checkExports = (packageFile, packageDirectory, fragmentSubpath) => { - const packageJson = readJson(packageFile, host); - const exports2 = packageJson.exports; - if (exports2) { - if (typeof exports2 !== "object" || exports2 === null) { - return true; - } - const keys = getOwnKeys(exports2); - const conditions = getConditions(compilerOptions, mode); - addCompletionEntriesFromPathsOrExports( - result, - /*isExports*/ - true, - fragmentSubpath, - packageDirectory, - extensionOptions, - host, - keys, - (key) => singleElementArray(getPatternFromFirstMatchingCondition(exports2[key], conditions)), - comparePatternKeys - ); - return true; - } - return false; - }; - const shouldCheckExports = fragmentDirectory && getResolvePackageJsonExports(compilerOptions); - if (shouldCheckExports) { + if (fragmentDirectory && getResolvePackageJsonExports(compilerOptions)) { const nodeModulesDirectoryLookup = ancestorLookup; ancestorLookup = (ancestor) => { const components = getPathComponents(fragment); @@ -261902,52 +262842,35 @@ function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, mode, c const packageDirectory = combinePaths(ancestor, "node_modules", packagePath); const packageFile = combinePaths(packageDirectory, "package.json"); if (tryFileExists(host, packageFile)) { - const fragmentSubpath = components.join("/") + (components.length && hasTrailingDirectorySeparator(fragment) ? "/" : ""); - if (checkExports(packageFile, packageDirectory, fragmentSubpath)) { - return; - } - } - return nodeModulesDirectoryLookup(ancestor); - }; - } - const pnpApi = getPnpApi(scriptPath); - if (pnpApi) { - const pathRegExp = /^(?![a-zA-Z]:[\\/]|\\\\|\.{0,2}(?:\/|$))((?:@[^/]+\/)?[^/]+)\/*(.*|)$/; - const dependencyNameMatch = fragment.match(pathRegExp); - if (dependencyNameMatch) { - const [, dependencyName, subPath] = dependencyNameMatch; - let unqualified; - try { - unqualified = pnpApi.resolveToUnqualified(dependencyName, scriptPath, { considerBuiltins: false }); - } catch { - } - if (unqualified) { - const packageDirectory = normalizePath(unqualified); - let shouldGetCompletions = true; - if (shouldCheckExports) { - const packageFile = combinePaths(packageDirectory, "package.json"); - if (tryFileExists(host, packageFile) && checkExports(packageFile, packageDirectory, subPath)) { - shouldGetCompletions = false; + const packageJson = readJson(packageFile, host); + const exports2 = packageJson.exports; + if (exports2) { + if (typeof exports2 !== "object" || exports2 === null) { + return; } - } - if (shouldGetCompletions) { - getCompletionEntriesForDirectoryFragment( - subPath, + const keys = getOwnKeys(exports2); + const fragmentSubpath = components.join("/") + (components.length && hasTrailingDirectorySeparator(fragment) ? "/" : ""); + const conditions = getConditions(compilerOptions, mode); + addCompletionEntriesFromPathsOrExports( + result, + /*isExports*/ + true, + fragmentSubpath, packageDirectory, extensionOptions, + program, host, - /*moduleSpecifierIsRelative*/ - false, - /*exclude*/ - void 0, - result + keys, + (key) => singleElementArray(getPatternFromFirstMatchingCondition(exports2[key], conditions)), + comparePatternKeys ); + return; } } - } - } else { - forEachAncestorDirectory(scriptPath, ancestorLookup); + return nodeModulesDirectoryLookup(ancestor); + }; } + forEachAncestorDirectory(scriptPath, ancestorLookup); } } return arrayFrom(result.values()); @@ -261968,7 +262891,7 @@ function getPatternFromFirstMatchingCondition(target, conditions) { function getFragmentDirectory(fragment) { return containsSlash(fragment) ? hasTrailingDirectorySeparator(fragment) ? fragment : getDirectoryPath(fragment) : void 0; } -function getCompletionsForPathMapping(path, patterns, fragment, packageDirectory, extensionOptions, isExportsWildcard, host) { +function getCompletionsForPathMapping(path, patterns, fragment, packageDirectory, extensionOptions, isExportsWildcard, program, host) { if (!endsWith(path, "*")) { return !path.includes("*") ? justPathMappingName(path, "script" /* scriptElement */) : emptyArray; } @@ -261978,15 +262901,15 @@ function getCompletionsForPathMapping(path, patterns, fragment, packageDirectory const starIsFullPathComponent = path[path.length - 2] === "/"; return starIsFullPathComponent ? justPathMappingName(pathPrefix, "directory" /* directory */) : flatMap(patterns, (pattern) => { var _a; - return (_a = getModulesForPathsPattern("", packageDirectory, pattern, extensionOptions, isExportsWildcard, host)) == null ? void 0 : _a.map(({ name, ...rest }) => ({ name: pathPrefix + name, ...rest })); + return (_a = getModulesForPathsPattern("", packageDirectory, pattern, extensionOptions, isExportsWildcard, program, host)) == null ? void 0 : _a.map(({ name, ...rest }) => ({ name: pathPrefix + name, ...rest })); }); } - return flatMap(patterns, (pattern) => getModulesForPathsPattern(remainingFragment, packageDirectory, pattern, extensionOptions, isExportsWildcard, host)); + return flatMap(patterns, (pattern) => getModulesForPathsPattern(remainingFragment, packageDirectory, pattern, extensionOptions, isExportsWildcard, program, host)); function justPathMappingName(name, kind) { return startsWith(name, fragment) ? [{ name: removeTrailingDirectorySeparator(name), kind, extension: void 0 }] : emptyArray; } } -function getModulesForPathsPattern(fragment, packageDirectory, pattern, extensionOptions, isExportsWildcard, host) { +function getModulesForPathsPattern(fragment, packageDirectory, pattern, extensionOptions, isExportsWildcard, program, host) { if (!host.readDirectory) { return void 0; } @@ -262019,7 +262942,7 @@ function getModulesForPathsPattern(fragment, packageDirectory, pattern, extensio if (containsSlash(trimmedWithPattern)) { return directoryResult(getPathComponents(removeLeadingDirectorySeparator(trimmedWithPattern))[1]); } - const { name, extension } = getFilenameWithExtensionOption(trimmedWithPattern, host.getCompilationSettings(), extensionOptions, isExportsWildcard); + const { name, extension } = getFilenameWithExtensionOption(trimmedWithPattern, program, extensionOptions, isExportsWildcard); return nameAndKind(name, "script" /* scriptElement */, extension); } }); @@ -262047,7 +262970,8 @@ function getAmbientModuleCompletions(fragment, fragmentDirectory, checker) { } return nonRelativeModuleNames; } -function getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host) { +function getTripleSlashReferenceCompletion(sourceFile, position, program, host) { + const compilerOptions = program.getCompilerOptions(); const token = getTokenAtPosition(sourceFile, position); const commentRanges = getLeadingCommentRanges(sourceFile.text, token.pos); const range = commentRanges && find(commentRanges, (commentRange) => position >= commentRange.pos && position <= commentRange.end); @@ -262065,28 +262989,24 @@ function getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions toComplete, scriptPath, getExtensionOptions(compilerOptions, 0 /* Filename */, sourceFile), + program, host, /*moduleSpecifierIsRelative*/ true, sourceFile.path - ) : kind === "types" ? getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, getFragmentDirectory(toComplete), getExtensionOptions(compilerOptions, 1 /* ModuleSpecifier */, sourceFile)) : Debug.fail(); + ) : kind === "types" ? getCompletionEntriesFromTypings(host, program, scriptPath, getFragmentDirectory(toComplete), getExtensionOptions(compilerOptions, 1 /* ModuleSpecifier */, sourceFile)) : Debug.fail(); return addReplacementSpans(toComplete, range.pos + prefix.length, arrayFrom(names.values())); } -function getCompletionEntriesFromTypings(host, options, scriptPath, fragmentDirectory, extensionOptions, result = createNameAndKindSet()) { +function getCompletionEntriesFromTypings(host, program, scriptPath, fragmentDirectory, extensionOptions, result = createNameAndKindSet()) { + const options = program.getCompilerOptions(); const seen = /* @__PURE__ */ new Map(); const typeRoots = tryAndIgnoreErrors(() => getEffectiveTypeRoots(options, host)) || emptyArray; for (const root of typeRoots) { getCompletionEntriesFromDirectories(root); } - if (getPnpApi(scriptPath)) { - for (const root of getPnpTypeRoots(scriptPath)) { - getCompletionEntriesFromDirectories(root); - } - } else { - for (const packageJson of findPackageJsons(scriptPath, host)) { - const typesDir = combinePaths(getDirectoryPath(packageJson), "node_modules/@types"); - getCompletionEntriesFromDirectories(typesDir); - } + for (const packageJson of findPackageJsons(scriptPath, host)) { + const typesDir = combinePaths(getDirectoryPath(packageJson), "node_modules/@types"); + getCompletionEntriesFromDirectories(typesDir); } return result; function getCompletionEntriesFromDirectories(directory) { @@ -262112,6 +263032,7 @@ function getCompletionEntriesFromTypings(host, options, scriptPath, fragmentDire remainingFragment, baseDirectory, extensionOptions, + program, host, /*moduleSpecifierIsRelative*/ false, @@ -262182,11 +263103,9 @@ __export(ts_FindAllReferences_exports, { getImplementationsAtPosition: () => getImplementationsAtPosition, getImportOrExportSymbol: () => getImportOrExportSymbol, getReferenceEntriesForNode: () => getReferenceEntriesForNode, - getTextSpanOfEntry: () => getTextSpanOfEntry, isContextWithStartAndEndNode: () => isContextWithStartAndEndNode, isDeclarationOfSymbol: () => isDeclarationOfSymbol, isWriteAccessForReference: () => isWriteAccessForReference, - nodeEntry: () => nodeEntry, toContextSpan: () => toContextSpan, toHighlightSpan: () => toHighlightSpan, toReferenceEntry: () => toReferenceEntry, @@ -262450,12 +263369,12 @@ function getSearchesFromDirectImports(directImports, exportSymbol, exportKind, c } for (const element of namedBindings.elements) { const { name, propertyName } = element; - if (!isNameMatch((propertyName || name).escapedText)) { + if (!isNameMatch(moduleExportNameTextEscaped(propertyName || name))) { continue; } if (propertyName) { singleReferences.push(propertyName); - if (!isForRename || name.escapedText === exportSymbol.escapedName) { + if (!isForRename || moduleExportNameTextEscaped(name) === exportSymbol.escapedName) { addSearch(name, checker.getSymbolAtLocation(name)); } } else { @@ -263713,8 +264632,8 @@ var Core; function shouldAddSingleReference(singleRef, state) { if (!hasMatchingMeaning(singleRef, state)) return false; if (state.options.use !== 2 /* Rename */) return true; - if (!isIdentifier(singleRef)) return false; - return !(isImportOrExportSpecifier(singleRef.parent) && singleRef.escapedText === "default" /* Default */); + if (!isIdentifier(singleRef) && !isImportOrExportSpecifier(singleRef.parent)) return false; + return !(isImportOrExportSpecifier(singleRef.parent) && moduleExportNameIsDefault(singleRef)); } function searchForImportedSymbol(symbol, state) { if (!symbol.declarations) return; @@ -263876,7 +264795,7 @@ var Core; case 15 /* NoSubstitutionTemplateLiteral */: case 11 /* StringLiteral */: { const str = node; - return (isLiteralNameOfPropertyDeclarationOrIndexAccess(str) || isNameOfModuleDeclaration(node) || isExpressionOfExternalModuleImportEqualsDeclaration(node) || isCallExpression(node.parent) && isBindableObjectDefinePropertyCall(node.parent) && node.parent.arguments[1] === node) && str.text.length === searchSymbolName.length; + return str.text.length === searchSymbolName.length && (isLiteralNameOfPropertyDeclarationOrIndexAccess(str) || isNameOfModuleDeclaration(node) || isExpressionOfExternalModuleImportEqualsDeclaration(node) || isCallExpression(node.parent) && isBindableObjectDefinePropertyCall(node.parent) && node.parent.arguments[1] === node || isImportOrExportSpecifier(node.parent)); } case 9 /* NumericLiteral */: return isLiteralNameOfPropertyDeclarationOrIndexAccess(node) && node.text.length === searchSymbolName.length; @@ -263942,7 +264861,7 @@ var Core; return; } if (isExportSpecifier(parent2)) { - Debug.assert(referenceLocation.kind === 80 /* Identifier */); + Debug.assert(referenceLocation.kind === 80 /* Identifier */ || referenceLocation.kind === 11 /* StringLiteral */); getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, parent2, search, state, addReferencesHere); return; } @@ -263992,7 +264911,7 @@ var Core; return; } if (!propertyName) { - if (!(state.options.use === 2 /* Rename */ && name.escapedText === "default" /* Default */)) { + if (!(state.options.use === 2 /* Rename */ && moduleExportNameIsDefault(name))) { addRef(); } } else if (referenceLocation === propertyName) { @@ -264008,7 +264927,7 @@ var Core; } } if (!isForRenameWithPrefixAndSuffixText(state.options) || alwaysGetReferences) { - const isDefaultExport = referenceLocation.escapedText === "default" || exportSpecifier.name.escapedText === "default"; + const isDefaultExport = moduleExportNameIsDefault(referenceLocation) || moduleExportNameIsDefault(exportSpecifier.name); const exportKind = isDefaultExport ? 1 /* Default */ : 0 /* Named */; const exportSymbol = Debug.checkDefined(exportSpecifier.symbol); const exportInfo = getExportInfo(exportSymbol, exportKind, state.checker); @@ -264608,7 +265527,6 @@ var Core; var ts_GoToDefinition_exports = {}; __export(ts_GoToDefinition_exports, { createDefinitionInfo: () => createDefinitionInfo, - findReferenceInPosition: () => findReferenceInPosition, getDefinitionAndBoundSpan: () => getDefinitionAndBoundSpan, getDefinitionAtPosition: () => getDefinitionAtPosition, getReferenceAtPosition: () => getReferenceAtPosition, @@ -264723,12 +265641,13 @@ function getDefinitionAtPosition(program, sourceFile, position, searchOtherFiles const calledDeclaration = tryGetSignatureDeclaration(typeChecker, node); if (calledDeclaration && !(isJsxOpeningLikeElement(node.parent) && isJsxConstructorLike(calledDeclaration))) { const sigInfo = createDefinitionFromSignatureDeclaration(typeChecker, calledDeclaration, failedAliasResolution); + let declarationFilter = (d) => d !== calledDeclaration; if (typeChecker.getRootSymbols(symbol).some((s) => symbolMatchesSignature(s, calledDeclaration))) { - return [sigInfo]; - } else { - const defs = getDefinitionFromSymbol(typeChecker, symbol, node, failedAliasResolution, calledDeclaration) || emptyArray; - return node.kind === 108 /* SuperKeyword */ ? [sigInfo, ...defs] : [...defs, sigInfo]; + if (!isConstructorDeclaration(calledDeclaration)) return [sigInfo]; + declarationFilter = (d) => d !== calledDeclaration && (isClassDeclaration(d) || isClassExpression(d)); } + const defs = getDefinitionFromSymbol(typeChecker, symbol, node, failedAliasResolution, declarationFilter) || emptyArray; + return node.kind === 108 /* SuperKeyword */ ? [sigInfo, ...defs] : [...defs, sigInfo]; } if (node.parent.kind === 304 /* ShorthandPropertyAssignment */) { const shorthandSymbol = typeChecker.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); @@ -264965,7 +265884,7 @@ function getSymbol(node, checker, stopAtAlias) { return { symbol, failedAliasResolution }; } function shouldSkipAlias(node, declaration) { - if (node.kind !== 80 /* Identifier */) { + if (node.kind !== 80 /* Identifier */ && (node.kind !== 11 /* StringLiteral */ || !isImportOrExportSpecifier(node.parent))) { return false; } if (node.parent === declaration) { @@ -264985,9 +265904,9 @@ function isExpandoDeclaration(node) { }); return !!containingAssignment && getAssignmentDeclarationKind(containingAssignment) === 5 /* Property */; } -function getDefinitionFromSymbol(typeChecker, symbol, node, failedAliasResolution, excludeDeclaration) { - const filteredDeclarations = filter(symbol.declarations, (d) => d !== excludeDeclaration); - const signatureDefinition = getConstructSignatureDefinition() || getCallSignatureDefinition(); +function getDefinitionFromSymbol(typeChecker, symbol, node, failedAliasResolution, declarationFilter) { + const filteredDeclarations = declarationFilter !== void 0 ? filter(symbol.declarations, declarationFilter) : symbol.declarations; + const signatureDefinition = !declarationFilter && (getConstructSignatureDefinition() || getCallSignatureDefinition()); if (signatureDefinition) { return signatureDefinition; } @@ -265393,6 +266312,14 @@ function provideInlayHints(context) { if (!signature) { return; } + const typePredicate = checker.getTypePredicateOfSignature(signature); + if (typePredicate == null ? void 0 : typePredicate.type) { + const hintParts2 = typePredicateToInlayHintParts(typePredicate); + if (hintParts2) { + addTypeHints(hintParts2, getTypeAnnotationPosition(decl)); + return; + } + } const returnType = checker.getReturnTypeOfSignature(signature); if (isModuleReferenceType(returnType)) { return; @@ -265461,6 +266388,26 @@ function provideInlayHints(context) { ); }); } + function printTypePredicateInSingleLine(typePredicate) { + const flags = 70221824 /* IgnoreErrors */ | 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; + const printer = createPrinterWithRemoveComments(); + return usingSingleLineStringWriter((writer) => { + const typePredicateNode = checker.typePredicateToTypePredicateNode( + typePredicate, + /*enclosingDeclaration*/ + void 0, + flags + ); + Debug.assertIsDefined(typePredicateNode, "should always get typePredicateNode"); + printer.writeNode( + 4 /* Unspecified */, + typePredicateNode, + /*sourceFile*/ + file, + writer + ); + }); + } function typeToInlayHintParts(type) { if (!shouldUseInteractiveInlayHints(preferences)) { return printTypeInSingleLine(type); @@ -265472,29 +266419,46 @@ function provideInlayHints(context) { void 0, flags ); + Debug.assertIsDefined(typeNode, "should always get typeNode"); + return getInlayHintDisplayParts(typeNode); + } + function typePredicateToInlayHintParts(typePredicate) { + if (!shouldUseInteractiveInlayHints(preferences)) { + return printTypePredicateInSingleLine(typePredicate); + } + const flags = 70221824 /* IgnoreErrors */ | 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; + const typeNode = checker.typePredicateToTypePredicateNode( + typePredicate, + /*enclosingDeclaration*/ + void 0, + flags + ); Debug.assertIsDefined(typeNode, "should always get typenode"); + return getInlayHintDisplayParts(typeNode); + } + function getInlayHintDisplayParts(node) { const parts = []; - visitForDisplayParts(typeNode); + visitForDisplayParts(node); return parts; - function visitForDisplayParts(node) { + function visitForDisplayParts(node2) { var _a, _b; - if (!node) { + if (!node2) { return; } - const tokenString = tokenToString(node.kind); + const tokenString = tokenToString(node2.kind); if (tokenString) { parts.push({ text: tokenString }); return; } - if (isLiteralExpression(node)) { - parts.push({ text: getLiteralText2(node) }); + if (isLiteralExpression(node2)) { + parts.push({ text: getLiteralText2(node2) }); return; } - switch (node.kind) { + switch (node2.kind) { case 80 /* Identifier */: - Debug.assertNode(node, isIdentifier); - const identifierText = idText(node); - const name = node.symbol && node.symbol.declarations && node.symbol.declarations.length && getNameOfDeclaration(node.symbol.declarations[0]); + Debug.assertNode(node2, isIdentifier); + const identifierText = idText(node2); + const name = node2.symbol && node2.symbol.declarations && node2.symbol.declarations.length && getNameOfDeclaration(node2.symbol.declarations[0]); if (name) { parts.push(getNodeDisplayPart(identifierText, name)); } else { @@ -265502,331 +266466,331 @@ function provideInlayHints(context) { } break; case 166 /* QualifiedName */: - Debug.assertNode(node, isQualifiedName); - visitForDisplayParts(node.left); + Debug.assertNode(node2, isQualifiedName); + visitForDisplayParts(node2.left); parts.push({ text: "." }); - visitForDisplayParts(node.right); + visitForDisplayParts(node2.right); break; case 182 /* TypePredicate */: - Debug.assertNode(node, isTypePredicateNode); - if (node.assertsModifier) { + Debug.assertNode(node2, isTypePredicateNode); + if (node2.assertsModifier) { parts.push({ text: "asserts " }); } - visitForDisplayParts(node.parameterName); - if (node.type) { + visitForDisplayParts(node2.parameterName); + if (node2.type) { parts.push({ text: " is " }); - visitForDisplayParts(node.type); + visitForDisplayParts(node2.type); } break; case 183 /* TypeReference */: - Debug.assertNode(node, isTypeReferenceNode); - visitForDisplayParts(node.typeName); - if (node.typeArguments) { + Debug.assertNode(node2, isTypeReferenceNode); + visitForDisplayParts(node2.typeName); + if (node2.typeArguments) { parts.push({ text: "<" }); - visitDisplayPartList(node.typeArguments, ", "); + visitDisplayPartList(node2.typeArguments, ", "); parts.push({ text: ">" }); } break; case 168 /* TypeParameter */: - Debug.assertNode(node, isTypeParameterDeclaration); - if (node.modifiers) { - visitDisplayPartList(node.modifiers, " "); + Debug.assertNode(node2, isTypeParameterDeclaration); + if (node2.modifiers) { + visitDisplayPartList(node2.modifiers, " "); } - visitForDisplayParts(node.name); - if (node.constraint) { + visitForDisplayParts(node2.name); + if (node2.constraint) { parts.push({ text: " extends " }); - visitForDisplayParts(node.constraint); + visitForDisplayParts(node2.constraint); } - if (node.default) { + if (node2.default) { parts.push({ text: " = " }); - visitForDisplayParts(node.default); + visitForDisplayParts(node2.default); } break; case 169 /* Parameter */: - Debug.assertNode(node, isParameter); - if (node.modifiers) { - visitDisplayPartList(node.modifiers, " "); + Debug.assertNode(node2, isParameter); + if (node2.modifiers) { + visitDisplayPartList(node2.modifiers, " "); } - if (node.dotDotDotToken) { + if (node2.dotDotDotToken) { parts.push({ text: "..." }); } - visitForDisplayParts(node.name); - if (node.questionToken) { + visitForDisplayParts(node2.name); + if (node2.questionToken) { parts.push({ text: "?" }); } - if (node.type) { + if (node2.type) { parts.push({ text: ": " }); - visitForDisplayParts(node.type); + visitForDisplayParts(node2.type); } break; case 185 /* ConstructorType */: - Debug.assertNode(node, isConstructorTypeNode); + Debug.assertNode(node2, isConstructorTypeNode); parts.push({ text: "new " }); - visitParametersAndTypeParameters(node); + visitParametersAndTypeParameters(node2); parts.push({ text: " => " }); - visitForDisplayParts(node.type); + visitForDisplayParts(node2.type); break; case 186 /* TypeQuery */: - Debug.assertNode(node, isTypeQueryNode); + Debug.assertNode(node2, isTypeQueryNode); parts.push({ text: "typeof " }); - visitForDisplayParts(node.exprName); - if (node.typeArguments) { + visitForDisplayParts(node2.exprName); + if (node2.typeArguments) { parts.push({ text: "<" }); - visitDisplayPartList(node.typeArguments, ", "); + visitDisplayPartList(node2.typeArguments, ", "); parts.push({ text: ">" }); } break; case 187 /* TypeLiteral */: - Debug.assertNode(node, isTypeLiteralNode); + Debug.assertNode(node2, isTypeLiteralNode); parts.push({ text: "{" }); - if (node.members.length) { + if (node2.members.length) { parts.push({ text: " " }); - visitDisplayPartList(node.members, "; "); + visitDisplayPartList(node2.members, "; "); parts.push({ text: " " }); } parts.push({ text: "}" }); break; case 188 /* ArrayType */: - Debug.assertNode(node, isArrayTypeNode); - visitForDisplayParts(node.elementType); + Debug.assertNode(node2, isArrayTypeNode); + visitForDisplayParts(node2.elementType); parts.push({ text: "[]" }); break; case 189 /* TupleType */: - Debug.assertNode(node, isTupleTypeNode); + Debug.assertNode(node2, isTupleTypeNode); parts.push({ text: "[" }); - visitDisplayPartList(node.elements, ", "); + visitDisplayPartList(node2.elements, ", "); parts.push({ text: "]" }); break; case 202 /* NamedTupleMember */: - Debug.assertNode(node, isNamedTupleMember); - if (node.dotDotDotToken) { + Debug.assertNode(node2, isNamedTupleMember); + if (node2.dotDotDotToken) { parts.push({ text: "..." }); } - visitForDisplayParts(node.name); - if (node.questionToken) { + visitForDisplayParts(node2.name); + if (node2.questionToken) { parts.push({ text: "?" }); } parts.push({ text: ": " }); - visitForDisplayParts(node.type); + visitForDisplayParts(node2.type); break; case 190 /* OptionalType */: - Debug.assertNode(node, isOptionalTypeNode); - visitForDisplayParts(node.type); + Debug.assertNode(node2, isOptionalTypeNode); + visitForDisplayParts(node2.type); parts.push({ text: "?" }); break; case 191 /* RestType */: - Debug.assertNode(node, isRestTypeNode); + Debug.assertNode(node2, isRestTypeNode); parts.push({ text: "..." }); - visitForDisplayParts(node.type); + visitForDisplayParts(node2.type); break; case 192 /* UnionType */: - Debug.assertNode(node, isUnionTypeNode); - visitDisplayPartList(node.types, " | "); + Debug.assertNode(node2, isUnionTypeNode); + visitDisplayPartList(node2.types, " | "); break; case 193 /* IntersectionType */: - Debug.assertNode(node, isIntersectionTypeNode); - visitDisplayPartList(node.types, " & "); + Debug.assertNode(node2, isIntersectionTypeNode); + visitDisplayPartList(node2.types, " & "); break; case 194 /* ConditionalType */: - Debug.assertNode(node, isConditionalTypeNode); - visitForDisplayParts(node.checkType); + Debug.assertNode(node2, isConditionalTypeNode); + visitForDisplayParts(node2.checkType); parts.push({ text: " extends " }); - visitForDisplayParts(node.extendsType); + visitForDisplayParts(node2.extendsType); parts.push({ text: " ? " }); - visitForDisplayParts(node.trueType); + visitForDisplayParts(node2.trueType); parts.push({ text: " : " }); - visitForDisplayParts(node.falseType); + visitForDisplayParts(node2.falseType); break; case 195 /* InferType */: - Debug.assertNode(node, isInferTypeNode); + Debug.assertNode(node2, isInferTypeNode); parts.push({ text: "infer " }); - visitForDisplayParts(node.typeParameter); + visitForDisplayParts(node2.typeParameter); break; case 196 /* ParenthesizedType */: - Debug.assertNode(node, isParenthesizedTypeNode); + Debug.assertNode(node2, isParenthesizedTypeNode); parts.push({ text: "(" }); - visitForDisplayParts(node.type); + visitForDisplayParts(node2.type); parts.push({ text: ")" }); break; case 198 /* TypeOperator */: - Debug.assertNode(node, isTypeOperatorNode); - parts.push({ text: `${tokenToString(node.operator)} ` }); - visitForDisplayParts(node.type); + Debug.assertNode(node2, isTypeOperatorNode); + parts.push({ text: `${tokenToString(node2.operator)} ` }); + visitForDisplayParts(node2.type); break; case 199 /* IndexedAccessType */: - Debug.assertNode(node, isIndexedAccessTypeNode); - visitForDisplayParts(node.objectType); + Debug.assertNode(node2, isIndexedAccessTypeNode); + visitForDisplayParts(node2.objectType); parts.push({ text: "[" }); - visitForDisplayParts(node.indexType); + visitForDisplayParts(node2.indexType); parts.push({ text: "]" }); break; case 200 /* MappedType */: - Debug.assertNode(node, isMappedTypeNode); + Debug.assertNode(node2, isMappedTypeNode); parts.push({ text: "{ " }); - if (node.readonlyToken) { - if (node.readonlyToken.kind === 40 /* PlusToken */) { + if (node2.readonlyToken) { + if (node2.readonlyToken.kind === 40 /* PlusToken */) { parts.push({ text: "+" }); - } else if (node.readonlyToken.kind === 41 /* MinusToken */) { + } else if (node2.readonlyToken.kind === 41 /* MinusToken */) { parts.push({ text: "-" }); } parts.push({ text: "readonly " }); } parts.push({ text: "[" }); - visitForDisplayParts(node.typeParameter); - if (node.nameType) { + visitForDisplayParts(node2.typeParameter); + if (node2.nameType) { parts.push({ text: " as " }); - visitForDisplayParts(node.nameType); + visitForDisplayParts(node2.nameType); } parts.push({ text: "]" }); - if (node.questionToken) { - if (node.questionToken.kind === 40 /* PlusToken */) { + if (node2.questionToken) { + if (node2.questionToken.kind === 40 /* PlusToken */) { parts.push({ text: "+" }); - } else if (node.questionToken.kind === 41 /* MinusToken */) { + } else if (node2.questionToken.kind === 41 /* MinusToken */) { parts.push({ text: "-" }); } parts.push({ text: "?" }); } parts.push({ text: ": " }); - if (node.type) { - visitForDisplayParts(node.type); + if (node2.type) { + visitForDisplayParts(node2.type); } parts.push({ text: "; }" }); break; case 201 /* LiteralType */: - Debug.assertNode(node, isLiteralTypeNode); - visitForDisplayParts(node.literal); + Debug.assertNode(node2, isLiteralTypeNode); + visitForDisplayParts(node2.literal); break; case 184 /* FunctionType */: - Debug.assertNode(node, isFunctionTypeNode); - visitParametersAndTypeParameters(node); + Debug.assertNode(node2, isFunctionTypeNode); + visitParametersAndTypeParameters(node2); parts.push({ text: " => " }); - visitForDisplayParts(node.type); + visitForDisplayParts(node2.type); break; case 205 /* ImportType */: - Debug.assertNode(node, isImportTypeNode); - if (node.isTypeOf) { + Debug.assertNode(node2, isImportTypeNode); + if (node2.isTypeOf) { parts.push({ text: "typeof " }); } parts.push({ text: "import(" }); - visitForDisplayParts(node.argument); - if (node.assertions) { + visitForDisplayParts(node2.argument); + if (node2.assertions) { parts.push({ text: ", { assert: " }); - visitDisplayPartList(node.assertions.assertClause.elements, ", "); + visitDisplayPartList(node2.assertions.assertClause.elements, ", "); parts.push({ text: " }" }); } parts.push({ text: ")" }); - if (node.qualifier) { + if (node2.qualifier) { parts.push({ text: "." }); - visitForDisplayParts(node.qualifier); + visitForDisplayParts(node2.qualifier); } - if (node.typeArguments) { + if (node2.typeArguments) { parts.push({ text: "<" }); - visitDisplayPartList(node.typeArguments, ", "); + visitDisplayPartList(node2.typeArguments, ", "); parts.push({ text: ">" }); } break; case 171 /* PropertySignature */: - Debug.assertNode(node, isPropertySignature); - if ((_a = node.modifiers) == null ? void 0 : _a.length) { - visitDisplayPartList(node.modifiers, " "); + Debug.assertNode(node2, isPropertySignature); + if ((_a = node2.modifiers) == null ? void 0 : _a.length) { + visitDisplayPartList(node2.modifiers, " "); parts.push({ text: " " }); } - visitForDisplayParts(node.name); - if (node.questionToken) { + visitForDisplayParts(node2.name); + if (node2.questionToken) { parts.push({ text: "?" }); } - if (node.type) { + if (node2.type) { parts.push({ text: ": " }); - visitForDisplayParts(node.type); + visitForDisplayParts(node2.type); } break; case 181 /* IndexSignature */: - Debug.assertNode(node, isIndexSignatureDeclaration); + Debug.assertNode(node2, isIndexSignatureDeclaration); parts.push({ text: "[" }); - visitDisplayPartList(node.parameters, ", "); + visitDisplayPartList(node2.parameters, ", "); parts.push({ text: "]" }); - if (node.type) { + if (node2.type) { parts.push({ text: ": " }); - visitForDisplayParts(node.type); + visitForDisplayParts(node2.type); } break; case 173 /* MethodSignature */: - Debug.assertNode(node, isMethodSignature); - if ((_b = node.modifiers) == null ? void 0 : _b.length) { - visitDisplayPartList(node.modifiers, " "); + Debug.assertNode(node2, isMethodSignature); + if ((_b = node2.modifiers) == null ? void 0 : _b.length) { + visitDisplayPartList(node2.modifiers, " "); parts.push({ text: " " }); } - visitForDisplayParts(node.name); - if (node.questionToken) { + visitForDisplayParts(node2.name); + if (node2.questionToken) { parts.push({ text: "?" }); } - visitParametersAndTypeParameters(node); - if (node.type) { + visitParametersAndTypeParameters(node2); + if (node2.type) { parts.push({ text: ": " }); - visitForDisplayParts(node.type); + visitForDisplayParts(node2.type); } break; case 179 /* CallSignature */: - Debug.assertNode(node, isCallSignatureDeclaration); - visitParametersAndTypeParameters(node); - if (node.type) { + Debug.assertNode(node2, isCallSignatureDeclaration); + visitParametersAndTypeParameters(node2); + if (node2.type) { parts.push({ text: ": " }); - visitForDisplayParts(node.type); + visitForDisplayParts(node2.type); } break; case 207 /* ArrayBindingPattern */: - Debug.assertNode(node, isArrayBindingPattern); + Debug.assertNode(node2, isArrayBindingPattern); parts.push({ text: "[" }); - visitDisplayPartList(node.elements, ", "); + visitDisplayPartList(node2.elements, ", "); parts.push({ text: "]" }); break; case 206 /* ObjectBindingPattern */: - Debug.assertNode(node, isObjectBindingPattern); + Debug.assertNode(node2, isObjectBindingPattern); parts.push({ text: "{" }); - if (node.elements.length) { + if (node2.elements.length) { parts.push({ text: " " }); - visitDisplayPartList(node.elements, ", "); + visitDisplayPartList(node2.elements, ", "); parts.push({ text: " " }); } parts.push({ text: "}" }); break; case 208 /* BindingElement */: - Debug.assertNode(node, isBindingElement); - visitForDisplayParts(node.name); + Debug.assertNode(node2, isBindingElement); + visitForDisplayParts(node2.name); break; case 224 /* PrefixUnaryExpression */: - Debug.assertNode(node, isPrefixUnaryExpression); - parts.push({ text: tokenToString(node.operator) }); - visitForDisplayParts(node.operand); + Debug.assertNode(node2, isPrefixUnaryExpression); + parts.push({ text: tokenToString(node2.operator) }); + visitForDisplayParts(node2.operand); break; case 203 /* TemplateLiteralType */: - Debug.assertNode(node, isTemplateLiteralTypeNode); - visitForDisplayParts(node.head); - node.templateSpans.forEach(visitForDisplayParts); + Debug.assertNode(node2, isTemplateLiteralTypeNode); + visitForDisplayParts(node2.head); + node2.templateSpans.forEach(visitForDisplayParts); break; case 16 /* TemplateHead */: - Debug.assertNode(node, isTemplateHead); - parts.push({ text: getLiteralText2(node) }); + Debug.assertNode(node2, isTemplateHead); + parts.push({ text: getLiteralText2(node2) }); break; case 204 /* TemplateLiteralTypeSpan */: - Debug.assertNode(node, isTemplateLiteralTypeSpan); - visitForDisplayParts(node.type); - visitForDisplayParts(node.literal); + Debug.assertNode(node2, isTemplateLiteralTypeSpan); + visitForDisplayParts(node2.type); + visitForDisplayParts(node2.literal); break; case 17 /* TemplateMiddle */: - Debug.assertNode(node, isTemplateMiddle); - parts.push({ text: getLiteralText2(node) }); + Debug.assertNode(node2, isTemplateMiddle); + parts.push({ text: getLiteralText2(node2) }); break; case 18 /* TemplateTail */: - Debug.assertNode(node, isTemplateTail); - parts.push({ text: getLiteralText2(node) }); + Debug.assertNode(node2, isTemplateTail); + parts.push({ text: getLiteralText2(node2) }); break; case 197 /* ThisType */: - Debug.assertNode(node, isThisTypeNode); + Debug.assertNode(node2, isThisTypeNode); parts.push({ text: "this" }); break; default: - Debug.failBadSyntaxKind(node); + Debug.failBadSyntaxKind(node2); } } function visitParametersAndTypeParameters(signatureDeclaration) { @@ -265840,22 +266804,22 @@ function provideInlayHints(context) { parts.push({ text: ")" }); } function visitDisplayPartList(nodes, separator) { - nodes.forEach((node, index) => { + nodes.forEach((node2, index) => { if (index > 0) { parts.push({ text: separator }); } - visitForDisplayParts(node); + visitForDisplayParts(node2); }); } - function getLiteralText2(node) { - switch (node.kind) { + function getLiteralText2(node2) { + switch (node2.kind) { case 11 /* StringLiteral */: - return quotePreference === 0 /* Single */ ? `'${escapeString(node.text, 39 /* singleQuote */)}'` : `"${escapeString(node.text, 34 /* doubleQuote */)}"`; + return quotePreference === 0 /* Single */ ? `'${escapeString(node2.text, 39 /* singleQuote */)}'` : `"${escapeString(node2.text, 34 /* doubleQuote */)}"`; case 16 /* TemplateHead */: case 17 /* TemplateMiddle */: case 18 /* TemplateTail */: { - const rawText = node.rawText ?? escapeTemplateSubstitution(escapeString(node.text, 96 /* backtick */)); - switch (node.kind) { + const rawText = node2.rawText ?? escapeTemplateSubstitution(escapeString(node2.text, 96 /* backtick */)); + switch (node2.kind) { case 16 /* TemplateHead */: return "`" + rawText + "${"; case 17 /* TemplateMiddle */: @@ -265865,7 +266829,7 @@ function provideInlayHints(context) { } } } - return node.text; + return node2.text; } } function isUndefined(name) { @@ -266011,7 +266975,7 @@ function getJsDocCommentsFromDeclarations(declarations, checker) { return flatten(intersperse(parts, [lineBreakPart()])); } function isIdenticalListOfDisplayParts(parts1, parts2) { - return arraysEqual(parts1, parts2, (p1, p2) => p1.kind === p2.kind && p1.text === p2.text); + return arrayIsEqualTo(parts1, parts2, (p1, p2) => p1.kind === p2.kind && p1.text === p2.text); } function getCommentHavingNodes(declaration) { switch (declaration.kind) { @@ -266374,9 +267338,10 @@ ${content} parsedNodes.push({ sourceFile: sourceFile2, body: bod }); } } - const { body } = parsedNodes.sort( + parsedNodes.sort( (a, b) => a.sourceFile.parseDiagnostics.length - b.sourceFile.parseDiagnostics.length - )[0]; + ); + const { body } = parsedNodes[0]; return body; } function placeNodeGroup(originalFile, changeTracker, changes, focusLocations) { @@ -266525,7 +267490,6 @@ var ts_OrganizeImports_exports = {}; __export(ts_OrganizeImports_exports, { compareImportsOrRequireStatements: () => compareImportsOrRequireStatements, compareModuleSpecifiers: () => compareModuleSpecifiers2, - getDetectionLists: () => getDetectionLists, getImportDeclarationInsertionIndex: () => getImportDeclarationInsertionIndex, getImportSpecifierInsertionIndex: () => getImportSpecifierInsertionIndex, getNamedImportSpecifierComparerWithDetection: () => getNamedImportSpecifierComparerWithDetection, @@ -266581,7 +267545,7 @@ function organizeImports(sourceFile, formatContext, host, program, preferences, } setEmitFlags(oldImportDecls[0], 1024 /* NoLeadingComments */); const oldImportGroups = shouldCombine ? group(oldImportDecls, (importDecl) => getExternalModuleName2(importDecl.moduleSpecifier)) : [oldImportDecls]; - const sortedImportGroups = shouldSort ? stableSort(oldImportGroups, (group1, group2) => compareModuleSpecifiersWorker(group1[0].moduleSpecifier, group2[0].moduleSpecifier, comparer.moduleSpecifierComparer ?? defaultComparer)) : oldImportGroups; + const sortedImportGroups = shouldSort ? toSorted(oldImportGroups, (group1, group2) => compareModuleSpecifiersWorker(group1[0].moduleSpecifier, group2[0].moduleSpecifier, comparer.moduleSpecifierComparer ?? defaultComparer)) : oldImportGroups; const newImportDecls = flatMap(sortedImportGroups, (importGroup) => getExternalModuleName2(importGroup[0].moduleSpecifier) || importGroup[0].moduleSpecifier === void 0 ? coalesce(importGroup) : importGroup); if (newImportDecls.length === 0) { changeTracker.deleteNodes( @@ -266616,7 +267580,7 @@ function organizeImports(sourceFile, formatContext, host, program, preferences, const processImportsOfSameModuleSpecifier = (importGroup) => { if (shouldRemove) importGroup = removeUnusedImports(importGroup, sourceFile, program); if (shouldCombine) importGroup = coalesceImportsWorker(importGroup, detectedModuleCaseComparer, specifierComparer, sourceFile); - if (shouldSort) importGroup = stableSort(importGroup, (s1, s2) => compareImportsOrRequireStatements(s1, s2, detectedModuleCaseComparer)); + if (shouldSort) importGroup = toSorted(importGroup, (s1, s2) => compareImportsOrRequireStatements(s1, s2, detectedModuleCaseComparer)); return importGroup; }; organizeDeclsWorker(oldImportDecls, processImportsOfSameModuleSpecifier); @@ -266792,7 +267756,7 @@ function coalesceImportsWorker(importGroup, comparer, specifierComparer, sourceF const importGroupsByAttributes = groupBy(importGroup, (decl) => { if (decl.attributes) { let attrs = decl.attributes.token + " "; - for (const x of sort(decl.attributes.elements, (x2, y) => compareStringsCaseSensitive(x2.name.text, y.name.text))) { + for (const x of toSorted(decl.attributes.elements, (x2, y) => compareStringsCaseSensitive(x2.name.text, y.name.text))) { attrs += x.name.text + ":"; attrs += isStringLiteralLike(x.value) ? `"${x.value.text}"` : x.value.getText() + " "; } @@ -266817,7 +267781,7 @@ function coalesceImportsWorker(importGroup, comparer, specifierComparer, sourceF ); continue; } - const sortedNamespaceImports = stableSort(namespaceImports, (i1, i2) => comparer(i1.importClause.namedBindings.name.text, i2.importClause.namedBindings.name.text)); + const sortedNamespaceImports = toSorted(namespaceImports, (i1, i2) => comparer(i1.importClause.namedBindings.name.text, i2.importClause.namedBindings.name.text)); for (const namespaceImport of sortedNamespaceImports) { coalescedImports.push( updateImportDeclarationAndClause( @@ -266852,7 +267816,7 @@ function coalesceImportsWorker(importGroup, comparer, specifierComparer, sourceF } newImportSpecifiers.push(...getNewImportSpecifiers(namedImports)); const sortedImportSpecifiers = factory.createNodeArray( - stableSort(newImportSpecifiers, specifierComparer), + toSorted(newImportSpecifiers, specifierComparer), firstNamedImport == null ? void 0 : firstNamedImport.importClause.namedBindings.elements.hasTrailingComma ); const newNamedImports = sortedImportSpecifiers.length === 0 ? newDefaultImport ? void 0 : factory.createNamedImports(emptyArray) : firstNamedImport ? factory.updateNamedImports(firstNamedImport.importClause.namedBindings, sortedImportSpecifiers) : factory.createNamedImports(sortedImportSpecifiers); @@ -266900,7 +267864,7 @@ function coalesceExportsWorker(exportGroup, specifierComparer) { } const newExportSpecifiers = []; newExportSpecifiers.push(...flatMap(exportGroup2, (i) => i.exportClause && isNamedExports(i.exportClause) ? i.exportClause.elements : emptyArray)); - const sortedExportSpecifiers = stableSort(newExportSpecifiers, specifierComparer); + const sortedExportSpecifiers = toSorted(newExportSpecifiers, specifierComparer); const exportDecl = exportGroup2[0]; coalescedExports.push( factory.updateExportDeclaration( @@ -266978,7 +267942,7 @@ function hasModuleDeclarationMatchingSpecifier(sourceFile, moduleSpecifier) { return isString(moduleSpecifierText) && some(sourceFile.moduleAugmentations, (moduleName) => isStringLiteral(moduleName) && moduleName.text === moduleSpecifierText); } function getNewImportSpecifiers(namedImports) { - return flatMap(namedImports, (namedImport) => map(tryGetNamedBindingElements(namedImport), (importSpecifier) => importSpecifier.name && importSpecifier.propertyName && importSpecifier.name.escapedText === importSpecifier.propertyName.escapedText ? factory.updateImportSpecifier( + return flatMap(namedImports, (namedImport) => map(tryGetNamedBindingElements(namedImport), (importSpecifier) => importSpecifier.name && importSpecifier.propertyName && moduleExportNameTextEscaped(importSpecifier.name) === moduleExportNameTextEscaped(importSpecifier.propertyName) ? factory.updateImportSpecifier( importSpecifier, importSpecifier.isTypeOnly, /*propertyName*/ @@ -267188,7 +268152,8 @@ function collectElements(sourceFile, cancellationToken) { const res = []; addNodeOutliningSpans(sourceFile, cancellationToken, res); addRegionOutliningSpans(sourceFile, res); - return res.sort((span1, span2) => span1.textSpan.start - span2.textSpan.start); + res.sort((span1, span2) => span1.textSpan.start - span2.textSpan.start); + return res; } function addNodeOutliningSpans(sourceFile, cancellationToken, out) { let depthRemaining = 40; @@ -267254,11 +268219,11 @@ function addRegionOutliningSpans(sourceFile, out) { for (const currentLineStart of lineStarts) { const lineEnd = sourceFile.getLineEndOfPosition(currentLineStart); const lineText = sourceFile.text.substring(currentLineStart, lineEnd); - const result = isRegionDelimiter(lineText); + const result = parseRegionDelimiter(lineText); if (!result || isInComment(sourceFile, currentLineStart)) { continue; } - if (!result[1]) { + if (result.isStart) { const span = createTextSpanFromBounds(sourceFile.text.indexOf("//", currentLineStart), lineEnd); regions.push(createOutliningSpan( span, @@ -267266,7 +268231,7 @@ function addRegionOutliningSpans(sourceFile, out) { span, /*autoCollapse*/ false, - result[2] || "#region" + result.name || "#region" )); } else { const region = regions.pop(); @@ -267278,14 +268243,18 @@ function addRegionOutliningSpans(sourceFile, out) { } } } -var regionDelimiterRegExp = /^#(end)?region(?:\s+(.*))?(?:\r)?$/; -function isRegionDelimiter(lineText) { +var regionDelimiterRegExp = /^#(end)?region(.*)\r?$/; +function parseRegionDelimiter(lineText) { lineText = lineText.trimStart(); if (!startsWith(lineText, "//")) { return null; } lineText = lineText.slice(2).trim(); - return regionDelimiterRegExp.exec(lineText); + const result = regionDelimiterRegExp.exec(lineText); + if (result) { + return { isStart: !result[1], name: result[2].trim() }; + } + return void 0; } function addOutliningForLeadingCommentsForPos(pos, sourceFile, cancellationToken, out) { const comments = getLeadingCommentRanges(sourceFile.text, pos); @@ -267299,7 +268268,7 @@ function addOutliningForLeadingCommentsForPos(pos, sourceFile, cancellationToken switch (kind) { case 2 /* SingleLineCommentTrivia */: const commentText = sourceText.slice(pos2, end); - if (isRegionDelimiter(commentText)) { + if (parseRegionDelimiter(commentText)) { combineAndAddMultipleSingleLineComments(); singleLineCommentCount = 0; break; @@ -267831,9 +268800,6 @@ function getArgumentOrParameterListInfo(node, position, sourceFile, checker) { if (!info) return void 0; const { list, argumentIndex } = info; const argumentCount = getArgumentCount(checker, list); - if (argumentIndex !== 0) { - Debug.assertLessThan(argumentIndex, argumentCount); - } const argumentsSpan = getApplicableSpanForArguments(list, sourceFile); return { list, argumentIndex, argumentCount, argumentsSpan }; } @@ -268106,9 +269072,6 @@ function createSignatureHelpItems(candidates, resolvedSignature, { isTypeParamet void 0 ) : emptyArray; const items = map(candidates, (candidateSignature) => getSignatureHelpItem(candidateSignature, callTargetDisplayParts, isTypeParameterList, typeChecker, enclosingDeclaration, sourceFile)); - if (argumentIndex !== 0) { - Debug.assertLessThan(argumentIndex, argumentCount); - } let selectedItemIndex = 0; let itemsSeen = 0; for (let i = 0; i < items.length; i++) { @@ -269922,7 +270885,7 @@ var changesToText; function getTextChangesFromChanges(changes, newLineCharacter, formatContext, validate) { return mapDefined(group(changes, (c) => c.sourceFile.path), (changesInFile) => { const sourceFile = changesInFile[0].sourceFile; - const normalized = stableSort(changesInFile, (a, b) => a.range.pos - b.range.pos || a.range.end - b.range.end); + const normalized = toSorted(changesInFile, (a, b) => a.range.pos - b.range.pos || a.range.end - b.range.end); for (let i = 0; i < normalized.length - 1; i++) { Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", () => `${JSON.stringify(normalized[i].range)} and ${JSON.stringify(normalized[i + 1].range)}`); } @@ -273170,16 +274133,17 @@ function pasteEditsProvider(targetFile, pastedText, pasteLocations, copiedFrom, function pasteEdits(targetFile, pastedText, pasteLocations, copiedFrom, host, preferences, formatContext, cancellationToken, changes) { let actualPastedText; if (pastedText.length !== pasteLocations.length) { - actualPastedText = pastedText.length === 1 ? pastedText : [pastedText.join("\n")]; + actualPastedText = pastedText.length === 1 ? pastedText[0] : pastedText.join(getNewLineOrDefaultFromHost(formatContext.host, formatContext.options)); } const statements = []; let newText = targetFile.text; for (let i = pasteLocations.length - 1; i >= 0; i--) { const { pos, end } = pasteLocations[i]; - newText = actualPastedText ? newText.slice(0, pos) + actualPastedText[0] + newText.slice(end) : newText.slice(0, pos) + pastedText[i] + newText.slice(end); + newText = actualPastedText ? newText.slice(0, pos) + actualPastedText + newText.slice(end) : newText.slice(0, pos) + pastedText[i] + newText.slice(end); } + let importAdder; Debug.checkDefined(host.runWithTemporaryFileUpdate).call(host, targetFile.fileName, newText, (updatedProgram, originalProgram, updatedFile) => { - const importAdder = ts_codefix_exports.createImportAdder(updatedFile, updatedProgram, preferences, host); + importAdder = ts_codefix_exports.createImportAdder(updatedFile, updatedProgram, preferences, host); if (copiedFrom == null ? void 0 : copiedFrom.range) { Debug.assert(copiedFrom.range.length === pastedText.length); copiedFrom.range.forEach((copy) => { @@ -273192,7 +274156,7 @@ function pasteEdits(targetFile, pastedText, pasteLocations, copiedFrom, host, pr } statements.push(...statementsInSourceFile.slice(startNodeIndex, endNodeIndex === -1 ? statementsInSourceFile.length : endNodeIndex + 1)); }); - const usage = getUsageInfo(copiedFrom.file, statements, originalProgram.getTypeChecker(), getExistingLocals(updatedFile, statements, originalProgram.getTypeChecker())); + const usage = getUsageInfo(copiedFrom.file, statements, originalProgram.getTypeChecker(), getExistingLocals(updatedFile, statements, originalProgram.getTypeChecker()), { pos: copiedFrom.range[0].pos, end: copiedFrom.range[copiedFrom.range.length - 1].end }); Debug.assertIsDefined(originalProgram); const useEsModuleSyntax = !fileShouldUseJavaScriptRequire(targetFile.fileName, originalProgram, host, !!copiedFrom.file.commonJsModuleIndicator); addExportsInOldFile(copiedFrom.file, usage.targetFileImportsFromOldFile, changes, useEsModuleSyntax); @@ -273206,31 +274170,49 @@ function pasteEdits(targetFile, pastedText, pasteLocations, copiedFrom, host, pr preferences, formatContext }; - forEachChild(updatedFile, function cb(node) { - if (isIdentifier(node) && !(originalProgram == null ? void 0 : originalProgram.getTypeChecker().resolveName( - node.text, - node, - -1 /* All */, - /*excludeGlobals*/ - false - ))) { - importAdder.addImportForUnresolvedIdentifier( - context, + let offset = 0; + pasteLocations.forEach((location, i) => { + const oldTextLength = location.end - location.pos; + const textToBePasted = actualPastedText ?? pastedText[i]; + const startPos = location.pos + offset; + const endPos = startPos + textToBePasted.length; + const range = { pos: startPos, end: endPos }; + offset += textToBePasted.length - oldTextLength; + const enclosingNode = findAncestor( + getTokenAtPosition(context.sourceFile, range.pos), + (ancestorNode) => rangeContainsRange(ancestorNode, range) + ); + if (!enclosingNode) return; + forEachChild(enclosingNode, function importUnresolvedIdentifiers(node) { + const isImportCandidate = isIdentifier(node) && rangeContainsPosition(range, node.getStart(updatedFile)) && !(updatedProgram == null ? void 0 : updatedProgram.getTypeChecker().resolveName( + node.text, node, - /*useAutoImportProvider*/ - true - ); - } - node.forEachChild(cb); + -1 /* All */, + /*excludeGlobals*/ + false + )); + if (isImportCandidate) { + return importAdder.addImportForUnresolvedIdentifier( + context, + node, + /*useAutoImportProvider*/ + true + ); + } + node.forEachChild(importUnresolvedIdentifiers); + }); }); } importAdder.writeFixes(changes, getQuotePreference(copiedFrom ? copiedFrom.file : targetFile, preferences)); }); + if (!importAdder.hasFixes()) { + return; + } pasteLocations.forEach((paste, i) => { changes.replaceRangeWithText( targetFile, { pos: paste.pos, end: paste.end }, - actualPastedText ? actualPastedText[0] : pastedText[i] + actualPastedText ?? pastedText[i] ); }); } @@ -273288,7 +274270,6 @@ __export(ts_exports2, { GoToDefinition: () => ts_GoToDefinition_exports, HighlightSpanKind: () => HighlightSpanKind, IdentifierNameMap: () => IdentifierNameMap, - IdentifierNameMultiMap: () => IdentifierNameMultiMap, ImportKind: () => ImportKind, ImportsNotUsedAsValues: () => ImportsNotUsedAsValues, IndentStyle: () => IndentStyle, @@ -273299,6 +274280,7 @@ __export(ts_exports2, { InlayHintKind: () => InlayHintKind2, InlayHints: () => ts_InlayHints_exports, InternalEmitFlags: () => InternalEmitFlags, + InternalNodeBuilderFlags: () => InternalNodeBuilderFlags, InternalSymbolName: () => InternalSymbolName, IntersectionFlags: () => IntersectionFlags, InvalidatedProjectKind: () => InvalidatedProjectKind, @@ -273345,6 +274327,7 @@ __export(ts_exports2, { PollingInterval: () => PollingInterval, PollingWatchKind: () => PollingWatchKind, PragmaKindFlags: () => PragmaKindFlags, + PredicateSemantics: () => PredicateSemantics, PrivateIdentifierKind: () => PrivateIdentifierKind, ProcessLevel: () => ProcessLevel, ProgramUpdateLevel: () => ProgramUpdateLevel, @@ -273375,7 +274358,6 @@ __export(ts_exports2, { SymbolFlags: () => SymbolFlags, SymbolFormatFlags: () => SymbolFormatFlags, SyntaxKind: () => SyntaxKind, - SyntheticSymbolKind: () => SyntheticSymbolKind, Ternary: () => Ternary, ThrottledCancellationToken: () => ThrottledCancellationToken, TokenClass: () => TokenClass, @@ -273398,7 +274380,6 @@ __export(ts_exports2, { WatchLogLevel: () => WatchLogLevel, WatchType: () => WatchType, accessPrivateIdentifier: () => accessPrivateIdentifier, - addDisposableResourceHelper: () => addDisposableResourceHelper, addEmitFlags: () => addEmitFlags, addEmitHelper: () => addEmitHelper, addEmitHelpers: () => addEmitHelpers, @@ -273421,23 +274402,15 @@ __export(ts_exports2, { arrayFrom: () => arrayFrom, arrayIsEqualTo: () => arrayIsEqualTo, arrayIsHomogeneous: () => arrayIsHomogeneous, - arrayIsSorted: () => arrayIsSorted, arrayOf: () => arrayOf, arrayReverseIterator: () => arrayReverseIterator, arrayToMap: () => arrayToMap, arrayToMultiMap: () => arrayToMultiMap, arrayToNumericMap: () => arrayToNumericMap, - arraysEqual: () => arraysEqual, assertType: () => assertType, assign: () => assign, - assignHelper: () => assignHelper, - asyncDelegator: () => asyncDelegator, - asyncGeneratorHelper: () => asyncGeneratorHelper, asyncSuperHelper: () => asyncSuperHelper, - asyncValues: () => asyncValues, attachFileToDiagnostics: () => attachFileToDiagnostics, - awaitHelper: () => awaitHelper, - awaiterHelper: () => awaiterHelper, base64decode: () => base64decode, base64encode: () => base64encode, binarySearch: () => binarySearch, @@ -273450,6 +274423,7 @@ __export(ts_exports2, { buildOverload: () => buildOverload, bundlerModuleNameResolver: () => bundlerModuleNameResolver, canBeConvertedToAsync: () => canBeConvertedToAsync, + canEmitTsBuildInfo: () => canEmitTsBuildInfo, canHaveDecorators: () => canHaveDecorators, canHaveExportModifier: () => canHaveExportModifier, canHaveFlowNode: () => canHaveFlowNode, @@ -273460,8 +274434,9 @@ __export(ts_exports2, { canHaveJSDoc: () => canHaveJSDoc, canHaveLocals: () => canHaveLocals, canHaveModifiers: () => canHaveModifiers, + canHaveModuleSpecifier: () => canHaveModuleSpecifier, canHaveSymbol: () => canHaveSymbol, - canIncludeBindAndCheckDiagnsotics: () => canIncludeBindAndCheckDiagnsotics, + canIncludeBindAndCheckDiagnostics: () => canIncludeBindAndCheckDiagnostics, canJsonReportNoInputFiles: () => canJsonReportNoInputFiles, canProduceDiagnostics: () => canProduceDiagnostics, canUsePropertyAccess: () => canUsePropertyAccess, @@ -273478,16 +274453,13 @@ __export(ts_exports2, { changeFullExtension: () => changeFullExtension, changesAffectModuleResolution: () => changesAffectModuleResolution, changesAffectingProgramStructure: () => changesAffectingProgramStructure, - characterToRegularExpressionFlag: () => characterToRegularExpressionFlag, + characterCodeToRegularExpressionFlag: () => characterCodeToRegularExpressionFlag, childIsDecorated: () => childIsDecorated, classElementOrClassElementParameterIsDecorated: () => classElementOrClassElementParameterIsDecorated, classHasClassThisAssignment: () => classHasClassThisAssignment, classHasDeclaredOrExplicitlyAssignedName: () => classHasDeclaredOrExplicitlyAssignedName, classHasExplicitlyAssignedName: () => classHasExplicitlyAssignedName, classOrConstructorParameterIsDecorated: () => classOrConstructorParameterIsDecorated, - classPrivateFieldGetHelper: () => classPrivateFieldGetHelper, - classPrivateFieldInHelper: () => classPrivateFieldInHelper, - classPrivateFieldSetHelper: () => classPrivateFieldSetHelper, classicNameResolver: () => classicNameResolver, classifier: () => ts_classifier_exports, cleanExtendedConfigCache: () => cleanExtendedConfigCache, @@ -273495,7 +274467,6 @@ __export(ts_exports2, { clearMap: () => clearMap, clearSharedExtendedConfigFileWatcher: () => clearSharedExtendedConfigFileWatcher, climbPastPropertyAccess: () => climbPastPropertyAccess, - climbPastPropertyOrElementAccess: () => climbPastPropertyOrElementAccess, clone: () => clone, cloneCompilerOptions: () => cloneCompilerOptions, closeFileWatcher: () => closeFileWatcher, @@ -273508,12 +274479,10 @@ __export(ts_exports2, { commandLineOptionOfCustomType: () => commandLineOptionOfCustomType, commentPragmas: () => commentPragmas, commonOptionsWithBuild: () => commonOptionsWithBuild, - commonPackageFolders: () => commonPackageFolders, compact: () => compact, compareBooleans: () => compareBooleans, compareDataObjects: () => compareDataObjects, compareDiagnostics: () => compareDiagnostics, - compareDiagnosticsSkipRelatedInformation: () => compareDiagnosticsSkipRelatedInformation, compareEmitHelpers: () => compareEmitHelpers, compareNumberOfDirectorySeparators: () => compareNumberOfDirectorySeparators, comparePaths: () => comparePaths, @@ -273527,26 +274496,21 @@ __export(ts_exports2, { compareStringsCaseSensitiveUI: () => compareStringsCaseSensitiveUI, compareTextSpans: () => compareTextSpans, compareValues: () => compareValues, - compileOnSaveCommandLineOption: () => compileOnSaveCommandLineOption, compilerOptionsAffectDeclarationPath: () => compilerOptionsAffectDeclarationPath, compilerOptionsAffectEmit: () => compilerOptionsAffectEmit, compilerOptionsAffectSemanticDiagnostics: () => compilerOptionsAffectSemanticDiagnostics, compilerOptionsDidYouMeanDiagnostics: () => compilerOptionsDidYouMeanDiagnostics, compilerOptionsIndicateEsModules: () => compilerOptionsIndicateEsModules, - compose: () => compose, computeCommonSourceDirectoryOfFilenames: () => computeCommonSourceDirectoryOfFilenames, computeLineAndCharacterOfPosition: () => computeLineAndCharacterOfPosition, computeLineOfPosition: () => computeLineOfPosition, computeLineStarts: () => computeLineStarts, computePositionOfLineAndCharacter: () => computePositionOfLineAndCharacter, - computeSignature: () => computeSignature, computeSignatureWithDiagnostics: () => computeSignatureWithDiagnostics, computeSuggestionDiagnostics: () => computeSuggestionDiagnostics, computedOptions: () => computedOptions, concatenate: () => concatenate, concatenateDiagnosticMessageChains: () => concatenateDiagnosticMessageChains, - configDirTemplateSubstitutionOptions: () => configDirTemplateSubstitutionOptions, - configDirTemplateSubstitutionWatchOptions: () => configDirTemplateSubstitutionWatchOptions, consumesNodeCoreModules: () => consumesNodeCoreModules, contains: () => contains, containsIgnoredPath: () => containsIgnoredPath, @@ -273577,16 +274541,11 @@ __export(ts_exports2, { createAccessorPropertySetRedirector: () => createAccessorPropertySetRedirector, createBaseNodeFactory: () => createBaseNodeFactory, createBinaryExpressionTrampoline: () => createBinaryExpressionTrampoline, - createBindingHelper: () => createBindingHelper, - createBuildInfo: () => createBuildInfo, createBuilderProgram: () => createBuilderProgram, - createBuilderProgramUsingProgramBuildInfo: () => createBuilderProgramUsingProgramBuildInfo, + createBuilderProgramUsingIncrementalBuildInfo: () => createBuilderProgramUsingIncrementalBuildInfo, createBuilderStatusReporter: () => createBuilderStatusReporter, - createCacheWithRedirects: () => createCacheWithRedirects, createCacheableExportInfoMap: () => createCacheableExportInfoMap, createCachedDirectoryStructureHost: () => createCachedDirectoryStructureHost, - createClassNamedEvaluationHelperBlock: () => createClassNamedEvaluationHelperBlock, - createClassThisAssignmentBlock: () => createClassThisAssignmentBlock, createClassifier: () => createClassifier, createCommentDirectivesMap: () => createCommentDirectivesMap, createCompilerDiagnostic: () => createCompilerDiagnostic, @@ -273638,6 +274597,7 @@ __export(ts_exports2, { createMemberAccessForPropertyName: () => createMemberAccessForPropertyName, createModeAwareCache: () => createModeAwareCache, createModeAwareCacheKey: () => createModeAwareCacheKey, + createModeMismatchDetails: () => createModeMismatchDetails, createModuleNotFoundChain: () => createModuleNotFoundChain, createModuleResolutionCache: () => createModuleResolutionCache, createModuleResolutionLoader: () => createModuleResolutionLoader, @@ -273708,9 +274668,7 @@ __export(ts_exports2, { declarationNameToString: () => declarationNameToString, decodeMappings: () => decodeMappings, decodedTextSpanIntersectsWith: () => decodedTextSpanIntersectsWith, - decorateHelper: () => decorateHelper, deduplicate: () => deduplicate, - defaultIncludeSpec: () => defaultIncludeSpec, defaultInitCompilerOptions: () => defaultInitCompilerOptions, defaultMaximumTruncationLength: () => defaultMaximumTruncationLength, diagnosticCategoryName: () => diagnosticCategoryName, @@ -273721,27 +274679,22 @@ __export(ts_exports2, { displayPart: () => displayPart, displayPartsToString: () => displayPartsToString, disposeEmitNodes: () => disposeEmitNodes, - disposeResourcesHelper: () => disposeResourcesHelper, documentSpansEqual: () => documentSpansEqual, dumpTracingLegend: () => dumpTracingLegend, elementAt: () => elementAt, elideNodes: () => elideNodes, - emitComments: () => emitComments, emitDetachedComments: () => emitDetachedComments, emitFiles: () => emitFiles, emitFilesAndReportErrors: () => emitFilesAndReportErrors, emitFilesAndReportErrorsAndGetExitStatus: () => emitFilesAndReportErrorsAndGetExitStatus, emitModuleKindIsNonNodeESM: () => emitModuleKindIsNonNodeESM, emitNewLineBeforeLeadingCommentOfPosition: () => emitNewLineBeforeLeadingCommentOfPosition, - emitNewLineBeforeLeadingComments: () => emitNewLineBeforeLeadingComments, - emitNewLineBeforeLeadingCommentsOfPosition: () => emitNewLineBeforeLeadingCommentsOfPosition, emitResolverSkipsTypeChecking: () => emitResolverSkipsTypeChecking, emitSkippedWithNoDiagnostics: () => emitSkippedWithNoDiagnostics, emptyArray: () => emptyArray, emptyFileSystemEntries: () => emptyFileSystemEntries, emptyMap: () => emptyMap, emptyOptions: () => emptyOptions, - emptySet: () => emptySet, endsWith: () => endsWith, ensurePathIsNonModuleName: () => ensurePathIsNonModuleName, ensureScriptKind: () => ensureScriptKind, @@ -273752,7 +274705,6 @@ __export(ts_exports2, { equateStringsCaseInsensitive: () => equateStringsCaseInsensitive, equateStringsCaseSensitive: () => equateStringsCaseSensitive, equateValues: () => equateValues, - esDecorateHelper: () => esDecorateHelper, escapeJsxAttributeString: () => escapeJsxAttributeString, escapeLeadingUnderscores: () => escapeLeadingUnderscores, escapeNonAsciiString: () => escapeNonAsciiString, @@ -273766,15 +274718,14 @@ __export(ts_exports2, { explainFiles: () => explainFiles, explainIfFileIsRedirectAndImpliedFormat: () => explainIfFileIsRedirectAndImpliedFormat, exportAssignmentIsAlias: () => exportAssignmentIsAlias, - exportStarHelper: () => exportStarHelper, expressionResultIsUnused: () => expressionResultIsUnused, extend: () => extend, - extendsHelper: () => extendsHelper, extensionFromPath: () => extensionFromPath, extensionIsTS: () => extensionIsTS, extensionsNotSupportingExtensionlessResolution: () => extensionsNotSupportingExtensionlessResolution, externalHelpersModuleNameText: () => externalHelpersModuleNameText, factory: () => factory, + fileContainsPackageImport: () => fileContainsPackageImport, fileExtensionIs: () => fileExtensionIs, fileExtensionIsOneOf: () => fileExtensionIsOneOf, fileIncludeReasonToDiagnostics: () => fileIncludeReasonToDiagnostics, @@ -273796,7 +274747,6 @@ __export(ts_exports2, { findLast: () => findLast, findLastIndex: () => findLastIndex, findListItemInfo: () => findListItemInfo, - findMap: () => findMap, findModifier: () => findModifier, findNextToken: () => findNextToken, findPackageJson: () => findPackageJson, @@ -273844,7 +274794,6 @@ __export(ts_exports2, { forEachTsConfigPropArray: () => forEachTsConfigPropArray, forEachUnique: () => forEachUnique, forEachYieldExpression: () => forEachYieldExpression, - forSomeAncestorDirectory: () => forSomeAncestorDirectory, formatColorAndReset: () => formatColorAndReset, formatDiagnostic: () => formatDiagnostic, formatDiagnostics: () => formatDiagnostics, @@ -273855,11 +274804,8 @@ __export(ts_exports2, { formatMessage: () => formatMessage, formatStringFromArgs: () => formatStringFromArgs, formatting: () => ts_formatting_exports, - fullTripleSlashAMDReferencePathRegEx: () => fullTripleSlashAMDReferencePathRegEx, - fullTripleSlashReferencePathRegEx: () => fullTripleSlashReferencePathRegEx, generateDjb2Hash: () => generateDjb2Hash, generateTSConfig: () => generateTSConfig, - generatorHelper: () => generatorHelper, getAdjustedReferenceLocation: () => getAdjustedReferenceLocation, getAdjustedRenameLocation: () => getAdjustedRenameLocation, getAliasDeclarationFromName: () => getAliasDeclarationFromName, @@ -273878,7 +274824,6 @@ __export(ts_exports2, { getAreDeclarationMapsEnabled: () => getAreDeclarationMapsEnabled, getAssignedExpandoInitializer: () => getAssignedExpandoInitializer, getAssignedName: () => getAssignedName, - getAssignedNameOfIdentifier: () => getAssignedNameOfIdentifier, getAssignmentDeclarationKind: () => getAssignmentDeclarationKind, getAssignmentDeclarationPropertyAccessKind: () => getAssignmentDeclarationPropertyAccessKind, getAssignmentTargetKind: () => getAssignmentTargetKind, @@ -273919,7 +274864,6 @@ __export(ts_exports2, { getContainingObjectLiteralElement: () => getContainingObjectLiteralElement, getContextualTypeFromParent: () => getContextualTypeFromParent, getContextualTypeFromParentOrAncestorTypeNode: () => getContextualTypeFromParentOrAncestorTypeNode, - getCurrentTime: () => getCurrentTime, getDeclarationDiagnostics: () => getDeclarationDiagnostics, getDeclarationEmitExtensionForPath: () => getDeclarationEmitExtensionForPath, getDeclarationEmitOutputFilePath: () => getDeclarationEmitOutputFilePath, @@ -273937,6 +274881,7 @@ __export(ts_exports2, { getDefaultLibFilePath: () => getDefaultLibFilePath, getDefaultLikeExportInfo: () => getDefaultLikeExportInfo, getDefaultLikeExportNameFromDeclaration: () => getDefaultLikeExportNameFromDeclaration, + getDefaultResolutionModeForFileWorker: () => getDefaultResolutionModeForFileWorker, getDiagnosticText: () => getDiagnosticText, getDiagnosticsWithinSpan: () => getDiagnosticsWithinSpan, getDirectoryPath: () => getDirectoryPath, @@ -273967,6 +274912,7 @@ __export(ts_exports2, { getEmitFlags: () => getEmitFlags, getEmitHelpers: () => getEmitHelpers, getEmitModuleDetectionKind: () => getEmitModuleDetectionKind, + getEmitModuleFormatOfFileWorker: () => getEmitModuleFormatOfFileWorker, getEmitModuleKind: () => getEmitModuleKind, getEmitModuleResolutionKind: () => getEmitModuleResolutionKind, getEmitScriptTarget: () => getEmitScriptTarget, @@ -274017,11 +274963,11 @@ __export(ts_exports2, { getIdentifierGeneratedImportReference: () => getIdentifierGeneratedImportReference, getIdentifierTypeArguments: () => getIdentifierTypeArguments, getImmediatelyInvokedFunctionExpression: () => getImmediatelyInvokedFunctionExpression, + getImpliedNodeFormatForEmitWorker: () => getImpliedNodeFormatForEmitWorker, getImpliedNodeFormatForFile: () => getImpliedNodeFormatForFile, getImpliedNodeFormatForFileWorker: () => getImpliedNodeFormatForFileWorker, getImportNeedsImportDefaultHelper: () => getImportNeedsImportDefaultHelper, getImportNeedsImportStarHelper: () => getImportNeedsImportStarHelper, - getIndentSize: () => getIndentSize, getIndentString: () => getIndentString, getInferredLibraryNameResolveFrom: () => getInferredLibraryNameResolveFrom, getInitializedVariables: () => getInitializedVariables, @@ -274030,6 +274976,7 @@ __export(ts_exports2, { getInterfaceBaseTypeNodes: () => getInterfaceBaseTypeNodes, getInternalEmitFlags: () => getInternalEmitFlags, getInvokedExpression: () => getInvokedExpression, + getIsFileExcluded: () => getIsFileExcluded, getIsolatedModules: () => getIsolatedModules, getJSDocAugmentsTag: () => getJSDocAugmentsTag, getJSDocClassTag: () => getJSDocClassTag, @@ -274058,7 +275005,6 @@ __export(ts_exports2, { getJSDocSatisfiesExpressionType: () => getJSDocSatisfiesExpressionType, getJSDocSatisfiesTag: () => getJSDocSatisfiesTag, getJSDocTags: () => getJSDocTags, - getJSDocTagsNoCache: () => getJSDocTagsNoCache, getJSDocTemplateTag: () => getJSDocTemplateTag, getJSDocThisTag: () => getJSDocThisTag, getJSDocType: () => getJSDocType, @@ -274082,7 +275028,6 @@ __export(ts_exports2, { getLineAndCharacterOfPosition: () => getLineAndCharacterOfPosition, getLineInfo: () => getLineInfo, getLineOfLocalPosition: () => getLineOfLocalPosition, - getLineOfLocalPositionFromLineMap: () => getLineOfLocalPositionFromLineMap, getLineStartPositionForPosition: () => getLineStartPositionForPosition, getLineStarts: () => getLineStarts, getLinesBetweenPositionAndNextNonWhitespaceCharacter: () => getLinesBetweenPositionAndNextNonWhitespaceCharacter, @@ -274124,7 +275069,6 @@ __export(ts_exports2, { getNameOfScriptTarget: () => getNameOfScriptTarget, getNameOrArgument: () => getNameOrArgument, getNameTable: () => getNameTable, - getNamesForExportedSymbol: () => getNamesForExportedSymbol, getNamespaceDeclarationNode: () => getNamespaceDeclarationNode, getNewLineCharacter: () => getNewLineCharacter, getNewLineKind: () => getNewLineKind, @@ -274141,49 +275085,43 @@ __export(ts_exports2, { getNonAssignmentOperatorForCompoundAssignment: () => getNonAssignmentOperatorForCompoundAssignment, getNonAugmentationDeclaration: () => getNonAugmentationDeclaration, getNonDecoratorTokenPosOfNode: () => getNonDecoratorTokenPosOfNode, + getNonIncrementalBuildInfoRoots: () => getNonIncrementalBuildInfoRoots, + getNonModifierTokenPosOfNode: () => getNonModifierTokenPosOfNode, getNormalizedAbsolutePath: () => getNormalizedAbsolutePath, getNormalizedAbsolutePathWithoutRoot: () => getNormalizedAbsolutePathWithoutRoot, getNormalizedPathComponents: () => getNormalizedPathComponents, getObjectFlags: () => getObjectFlags, - getOperator: () => getOperator, getOperatorAssociativity: () => getOperatorAssociativity, getOperatorPrecedence: () => getOperatorPrecedence, getOptionFromName: () => getOptionFromName, getOptionsForLibraryResolution: () => getOptionsForLibraryResolution, getOptionsNameMap: () => getOptionsNameMap, getOrCreateEmitNode: () => getOrCreateEmitNode, - getOrCreateExternalHelpersModuleNameIfNeeded: () => getOrCreateExternalHelpersModuleNameIfNeeded, getOrUpdate: () => getOrUpdate, getOriginalNode: () => getOriginalNode, getOriginalNodeId: () => getOriginalNodeId, - getOriginalSourceFile: () => getOriginalSourceFile, getOutputDeclarationFileName: () => getOutputDeclarationFileName, getOutputDeclarationFileNameWorker: () => getOutputDeclarationFileNameWorker, getOutputExtension: () => getOutputExtension, getOutputFileNames: () => getOutputFileNames, getOutputJSFileNameWorker: () => getOutputJSFileNameWorker, getOutputPathsFor: () => getOutputPathsFor, - getOutputPathsForBundle: () => getOutputPathsForBundle, getOwnEmitOutputFilePath: () => getOwnEmitOutputFilePath, getOwnKeys: () => getOwnKeys, getOwnValues: () => getOwnValues, - getPackageJsonInfo: () => getPackageJsonInfo, getPackageJsonTypesVersionsPaths: () => getPackageJsonTypesVersionsPaths, - getPackageJsonsVisibleToFile: () => getPackageJsonsVisibleToFile, getPackageNameFromTypesPackageName: () => getPackageNameFromTypesPackageName, getPackageScopeForPath: () => getPackageScopeForPath, getParameterSymbolFromJSDoc: () => getParameterSymbolFromJSDoc, - getParameterTypeNode: () => getParameterTypeNode, getParentNodeInSpan: () => getParentNodeInSpan, getParseTreeNode: () => getParseTreeNode, getParsedCommandLineOfConfigFile: () => getParsedCommandLineOfConfigFile, getPathComponents: () => getPathComponents, - getPathComponentsRelativeTo: () => getPathComponentsRelativeTo, getPathFromPathComponents: () => getPathFromPathComponents, getPathUpdater: () => getPathUpdater, getPathsBasePath: () => getPathsBasePath, getPatternFromSpec: () => getPatternFromSpec, - getPendingEmitKind: () => getPendingEmitKind, + getPendingEmitKindWithSeen: () => getPendingEmitKindWithSeen, getPositionOfLineAndCharacter: () => getPositionOfLineAndCharacter, getPossibleGenericSignatures: () => getPossibleGenericSignatures, getPossibleOriginalInputExtensionForExtension: () => getPossibleOriginalInputExtensionForExtension, @@ -274196,7 +275134,6 @@ __export(ts_exports2, { getPropertyArrayElementValue: () => getPropertyArrayElementValue, getPropertyAssignmentAliasLikeExpression: () => getPropertyAssignmentAliasLikeExpression, getPropertyNameForPropertyNameNode: () => getPropertyNameForPropertyNameNode, - getPropertyNameForUniqueESSymbol: () => getPropertyNameForUniqueESSymbol, getPropertyNameFromType: () => getPropertyNameFromType, getPropertyNameOfBindingOrAssignmentElement: () => getPropertyNameOfBindingOrAssignmentElement, getPropertySymbolFromBindingElement: () => getPropertySymbolFromBindingElement, @@ -274220,13 +275157,14 @@ __export(ts_exports2, { getResolvePackageJsonExports: () => getResolvePackageJsonExports, getResolvePackageJsonImports: () => getResolvePackageJsonImports, getResolvedExternalModuleName: () => getResolvedExternalModuleName, + getResolvedModuleFromResolution: () => getResolvedModuleFromResolution, + getResolvedTypeReferenceDirectiveFromResolution: () => getResolvedTypeReferenceDirectiveFromResolution, getRestIndicatorOfBindingOrAssignmentElement: () => getRestIndicatorOfBindingOrAssignmentElement, getRestParameterElementType: () => getRestParameterElementType, getRightMostAssignedExpression: () => getRightMostAssignedExpression, getRootDeclaration: () => getRootDeclaration, getRootDirectoryOfResolutionCache: () => getRootDirectoryOfResolutionCache, getRootLength: () => getRootLength, - getRootPathSplitLength: () => getRootPathSplitLength, getScriptKind: () => getScriptKind, getScriptKindFromFileName: () => getScriptKindFromFileName, getScriptTargetFeatures: () => getScriptTargetFeatures, @@ -274238,14 +275176,12 @@ __export(ts_exports2, { getSetAccessorValueParameter: () => getSetAccessorValueParameter, getSetExternalModuleIndicator: () => getSetExternalModuleIndicator, getShebang: () => getShebang, - getSingleInitializerOfVariableStatementOrPropertyDeclaration: () => getSingleInitializerOfVariableStatementOrPropertyDeclaration, getSingleVariableOfVariableStatement: () => getSingleVariableOfVariableStatement, getSnapshotText: () => getSnapshotText, getSnippetElement: () => getSnippetElement, getSourceFileOfModule: () => getSourceFileOfModule, getSourceFileOfNode: () => getSourceFileOfNode, getSourceFilePathInNewDir: () => getSourceFilePathInNewDir, - getSourceFilePathInNewDirWorker: () => getSourceFilePathInNewDirWorker, getSourceFileVersionAsHashFromText: () => getSourceFileVersionAsHashFromText, getSourceFilesToEmit: () => getSourceFilesToEmit, getSourceMapRange: () => getSourceMapRange, @@ -274268,7 +275204,6 @@ __export(ts_exports2, { getSwitchedType: () => getSwitchedType, getSymbolId: () => getSymbolId, getSymbolNameForPrivateIdentifier: () => getSymbolNameForPrivateIdentifier, - getSymbolParentOrFail: () => getSymbolParentOrFail, getSymbolTarget: () => getSymbolTarget, getSyntacticClassifications: () => getSyntacticClassifications, getSyntacticModifierFlags: () => getSyntacticModifierFlags, @@ -274299,7 +275234,6 @@ __export(ts_exports2, { getTouchingToken: () => getTouchingToken, getTrailingCommentRanges: () => getTrailingCommentRanges, getTrailingSemicolonDeferringWriter: () => getTrailingSemicolonDeferringWriter, - getTransformFlagsSubtreeExclusions: () => getTransformFlagsSubtreeExclusions, getTransformers: () => getTransformers, getTsBuildInfoEmitOutputFilePath: () => getTsBuildInfoEmitOutputFilePath, getTsConfigObjectLiteralExpression: () => getTsConfigObjectLiteralExpression, @@ -274327,7 +275261,6 @@ __export(ts_exports2, { hasAccessorModifier: () => hasAccessorModifier, hasAmbientModifier: () => hasAmbientModifier, hasChangesInResolutions: () => hasChangesInResolutions, - hasChildOfKind: () => hasChildOfKind, hasContextSensitiveParameters: () => hasContextSensitiveParameters, hasDecorators: () => hasDecorators, hasDocComment: () => hasDocComment, @@ -274336,6 +275269,7 @@ __export(ts_exports2, { hasEffectiveModifiers: () => hasEffectiveModifiers, hasEffectiveReadonlyModifier: () => hasEffectiveReadonlyModifier, hasExtension: () => hasExtension, + hasImplementationTSFileExtension: () => hasImplementationTSFileExtension, hasIndexSignature: () => hasIndexSignature, hasInferredType: () => hasInferredType, hasInitializer: () => hasInitializer, @@ -274363,7 +275297,6 @@ __export(ts_exports2, { hasType: () => hasType, hasTypeArguments: () => hasTypeArguments, hasZeroOrOneAsteriskCharacter: () => hasZeroOrOneAsteriskCharacter, - helperString: () => helperString, hostGetCanonicalFileName: () => hostGetCanonicalFileName, hostUsesCaseSensitiveFileNames: () => hostUsesCaseSensitiveFileNames, idText: () => idText, @@ -274373,9 +275306,8 @@ __export(ts_exports2, { identitySourceMapConsumer: () => identitySourceMapConsumer, ignoreSourceNewlines: () => ignoreSourceNewlines, ignoredPaths: () => ignoredPaths, - importDefaultHelper: () => importDefaultHelper, importFromModuleSpecifier: () => importFromModuleSpecifier, - importStarHelper: () => importStarHelper, + importSyntaxAffectsModuleResolution: () => importSyntaxAffectsModuleResolution, indexOfAnyCharCode: () => indexOfAnyCharCode, indexOfNode: () => indexOfNode, indicesOf: () => indicesOf, @@ -274383,7 +275315,6 @@ __export(ts_exports2, { injectClassNamedEvaluationHelperBlockIfMissing: () => injectClassNamedEvaluationHelperBlockIfMissing, injectClassThisAssignmentIfMissing: () => injectClassThisAssignmentIfMissing, insertImports: () => insertImports, - insertLeadingStatement: () => insertLeadingStatement, insertSorted: () => insertSorted, insertStatementAfterCustomPrologue: () => insertStatementAfterCustomPrologue, insertStatementAfterStandardPrologue: () => insertStatementAfterStandardPrologue, @@ -274399,11 +275330,9 @@ __export(ts_exports2, { isAccessibilityModifier: () => isAccessibilityModifier, isAccessor: () => isAccessor, isAccessorModifier: () => isAccessorModifier, - isAliasSymbolDeclaration: () => isAliasSymbolDeclaration, isAliasableExpression: () => isAliasableExpression, isAmbientModule: () => isAmbientModule, isAmbientPropertyDeclaration: () => isAmbientPropertyDeclaration, - isAnonymousFunctionDefinition: () => isAnonymousFunctionDefinition, isAnyDirectorySeparator: () => isAnyDirectorySeparator, isAnyImportOrBareOrAccessedRequire: () => isAnyImportOrBareOrAccessedRequire, isAnyImportOrReExport: () => isAnyImportOrReExport, @@ -274439,6 +275368,7 @@ __export(ts_exports2, { isAwaitKeyword: () => isAwaitKeyword, isBigIntLiteral: () => isBigIntLiteral, isBinaryExpression: () => isBinaryExpression, + isBinaryLogicalOperator: () => isBinaryLogicalOperator, isBinaryOperatorToken: () => isBinaryOperatorToken, isBindableObjectDefinePropertyCall: () => isBindableObjectDefinePropertyCall, isBindableStaticAccessExpression: () => isBindableStaticAccessExpression, @@ -274460,7 +275390,7 @@ __export(ts_exports2, { isBreakStatement: () => isBreakStatement, isBuild: () => isBuild, isBuildInfoFile: () => isBuildInfoFile, - isBuilderProgram: () => isBuilderProgram2, + isBuilderProgram: () => isBuilderProgram, isBundle: () => isBundle, isCallChain: () => isCallChain, isCallExpression: () => isCallExpression, @@ -274479,7 +275409,6 @@ __export(ts_exports2, { isCatchClauseVariableDeclaration: () => isCatchClauseVariableDeclaration, isCatchClauseVariableDeclarationOrBindingElement: () => isCatchClauseVariableDeclarationOrBindingElement, isCheckJsEnabledForFile: () => isCheckJsEnabledForFile, - isChildOfNodeWithKind: () => isChildOfNodeWithKind, isCircularBuildOrder: () => isCircularBuildOrder, isClassDeclaration: () => isClassDeclaration, isClassElement: () => isClassElement, @@ -274491,7 +275420,6 @@ __export(ts_exports2, { isClassOrTypeElement: () => isClassOrTypeElement, isClassStaticBlockDeclaration: () => isClassStaticBlockDeclaration, isClassThisAssignmentBlock: () => isClassThisAssignmentBlock, - isCollapsedRange: () => isCollapsedRange, isColonToken: () => isColonToken, isCommaExpression: () => isCommaExpression, isCommaListExpression: () => isCommaListExpression, @@ -274534,16 +275462,13 @@ __export(ts_exports2, { isDeleteTarget: () => isDeleteTarget, isDeprecatedDeclaration: () => isDeprecatedDeclaration, isDestructuringAssignment: () => isDestructuringAssignment, - isDiagnosticWithLocation: () => isDiagnosticWithLocation, isDiskPathRoot: () => isDiskPathRoot, isDoStatement: () => isDoStatement, isDocumentRegistryEntry: () => isDocumentRegistryEntry, isDotDotDotToken: () => isDotDotDotToken, isDottedName: () => isDottedName, isDynamicName: () => isDynamicName, - isESSymbolIdentifier: () => isESSymbolIdentifier, isEffectiveExternalModule: () => isEffectiveExternalModule, - isEffectiveModuleDeclaration: () => isEffectiveModuleDeclaration, isEffectiveStrictModeSourceFile: () => isEffectiveStrictModeSourceFile, isElementAccessChain: () => isElementAccessChain, isElementAccessExpression: () => isElementAccessExpression, @@ -274613,13 +275538,11 @@ __export(ts_exports2, { isFunctionOrModuleBlock: () => isFunctionOrModuleBlock, isFunctionSymbol: () => isFunctionSymbol, isFunctionTypeNode: () => isFunctionTypeNode, - isFutureReservedKeyword: () => isFutureReservedKeyword, isGeneratedIdentifier: () => isGeneratedIdentifier, isGeneratedPrivateIdentifier: () => isGeneratedPrivateIdentifier, isGetAccessor: () => isGetAccessor, isGetAccessorDeclaration: () => isGetAccessorDeclaration, isGetOrSetAccessorDeclaration: () => isGetOrSetAccessorDeclaration, - isGlobalDeclaration: () => isGlobalDeclaration, isGlobalScopeAugmentation: () => isGlobalScopeAugmentation, isGlobalSourceFile: () => isGlobalSourceFile, isGrammarError: () => isGrammarError, @@ -274667,6 +275590,8 @@ __export(ts_exports2, { isInTemplateString: () => isInTemplateString, isInTopLevelContext: () => isInTopLevelContext, isInTypeQuery: () => isInTypeQuery, + isIncrementalBuildInfo: () => isIncrementalBuildInfo, + isIncrementalBundleEmitBuildInfo: () => isIncrementalBundleEmitBuildInfo, isIncrementalCompilation: () => isIncrementalCompilation, isIndexSignatureDeclaration: () => isIndexSignatureDeclaration, isIndexedAccessTypeNode: () => isIndexedAccessTypeNode, @@ -274773,7 +275698,6 @@ __export(ts_exports2, { isLabeledStatement: () => isLabeledStatement, isLateVisibilityPaintedStatement: () => isLateVisibilityPaintedStatement, isLeftHandSideExpression: () => isLeftHandSideExpression, - isLeftHandSideOfAssignment: () => isLeftHandSideOfAssignment, isLet: () => isLet, isLineBreak: () => isLineBreak, isLiteralComputedPropertyDeclarationName: () => isLiteralComputedPropertyDeclarationName, @@ -274781,10 +275705,7 @@ __export(ts_exports2, { isLiteralExpressionOfObject: () => isLiteralExpressionOfObject, isLiteralImportTypeNode: () => isLiteralImportTypeNode, isLiteralKind: () => isLiteralKind, - isLiteralLikeAccess: () => isLiteralLikeAccess, - isLiteralLikeElementAccess: () => isLiteralLikeElementAccess, isLiteralNameOfPropertyDeclarationOrIndexAccess: () => isLiteralNameOfPropertyDeclarationOrIndexAccess, - isLiteralTypeLikeExpression: () => isLiteralTypeLikeExpression, isLiteralTypeLiteral: () => isLiteralTypeLiteral, isLiteralTypeNode: () => isLiteralTypeNode, isLocalName: () => isLocalName, @@ -274809,6 +275730,7 @@ __export(ts_exports2, { isModuleBlock: () => isModuleBlock, isModuleBody: () => isModuleBody, isModuleDeclaration: () => isModuleDeclaration, + isModuleExportName: () => isModuleExportName, isModuleExportsAccessExpression: () => isModuleExportsAccessExpression, isModuleIdentifier: () => isModuleIdentifier, isModuleName: () => isModuleName, @@ -274818,7 +275740,6 @@ __export(ts_exports2, { isModuleWithStringLiteralName: () => isModuleWithStringLiteralName, isNameOfFunctionDeclaration: () => isNameOfFunctionDeclaration, isNameOfModuleDeclaration: () => isNameOfModuleDeclaration, - isNamedClassElement: () => isNamedClassElement, isNamedDeclaration: () => isNamedDeclaration, isNamedEvaluation: () => isNamedEvaluation, isNamedEvaluationSource: () => isNamedEvaluationSource, @@ -274836,7 +275757,6 @@ __export(ts_exports2, { isNewExpression: () => isNewExpression, isNewExpressionTarget: () => isNewExpressionTarget, isNoSubstitutionTemplateLiteral: () => isNoSubstitutionTemplateLiteral, - isNode: () => isNode, isNodeArray: () => isNodeArray, isNodeArrayMultiLine: () => isNodeArrayMultiLine, isNodeDescendantOf: () => isNodeDescendantOf, @@ -274845,14 +275765,11 @@ __export(ts_exports2, { isNodeModulesDirectory: () => isNodeModulesDirectory, isNodeWithPossibleHoistedDeclaration: () => isNodeWithPossibleHoistedDeclaration, isNonContextualKeyword: () => isNonContextualKeyword, - isNonExportDefaultModifier: () => isNonExportDefaultModifier, isNonGlobalAmbientModule: () => isNonGlobalAmbientModule, - isNonGlobalDeclaration: () => isNonGlobalDeclaration, isNonNullAccess: () => isNonNullAccess, isNonNullChain: () => isNonNullChain, isNonNullExpression: () => isNonNullExpression, isNonStaticMethodOrAccessorWithPrivateName: () => isNonStaticMethodOrAccessorWithPrivateName, - isNotEmittedOrPartiallyEmittedNode: () => isNotEmittedOrPartiallyEmittedNode, isNotEmittedStatement: () => isNotEmittedStatement, isNullishCoalesce: () => isNullishCoalesce, isNumber: () => isNumber, @@ -274868,7 +275785,6 @@ __export(ts_exports2, { isObjectLiteralMethod: () => isObjectLiteralMethod, isObjectLiteralOrClassExpressionMethodOrAccessor: () => isObjectLiteralOrClassExpressionMethodOrAccessor, isObjectTypeDeclaration: () => isObjectTypeDeclaration, - isOctalDigit: () => isOctalDigit, isOmittedExpression: () => isOmittedExpression, isOptionalChain: () => isOptionalChain, isOptionalChainRoot: () => isOptionalChainRoot, @@ -274902,7 +275818,6 @@ __export(ts_exports2, { isPrivateIdentifierClassElementDeclaration: () => isPrivateIdentifierClassElementDeclaration, isPrivateIdentifierPropertyAccessExpression: () => isPrivateIdentifierPropertyAccessExpression, isPrivateIdentifierSymbol: () => isPrivateIdentifierSymbol, - isProgramBundleEmitBuildInfo: () => isProgramBundleEmitBuildInfo, isProgramUptoDate: () => isProgramUptoDate, isPrologueDirective: () => isPrologueDirective, isPropertyAccessChain: () => isPropertyAccessChain, @@ -274915,7 +275830,6 @@ __export(ts_exports2, { isPropertyName: () => isPropertyName, isPropertyNameLiteral: () => isPropertyNameLiteral, isPropertySignature: () => isPropertySignature, - isProtoSetter: () => isProtoSetter, isPrototypeAccess: () => isPrototypeAccess, isPrototypePropertyAssignment: () => isPrototypePropertyAssignment, isPunctuation: () => isPunctuation, @@ -274925,7 +275839,6 @@ __export(ts_exports2, { isQuestionOrExclamationToken: () => isQuestionOrExclamationToken, isQuestionOrPlusOrMinusToken: () => isQuestionOrPlusOrMinusToken, isQuestionToken: () => isQuestionToken, - isRawSourceMap: () => isRawSourceMap, isReadonlyKeyword: () => isReadonlyKeyword, isReadonlyKeywordOrPlusOrMinusToken: () => isReadonlyKeywordOrPlusOrMinusToken, isRecognizedTripleSlashComment: () => isRecognizedTripleSlashComment, @@ -274947,24 +275860,22 @@ __export(ts_exports2, { isRootedDiskPath: () => isRootedDiskPath, isSameEntityName: () => isSameEntityName, isSatisfiesExpression: () => isSatisfiesExpression, - isScopeMarker: () => isScopeMarker, isSemicolonClassElement: () => isSemicolonClassElement, isSetAccessor: () => isSetAccessor, isSetAccessorDeclaration: () => isSetAccessorDeclaration, - isShebangTrivia: () => isShebangTrivia, isShiftOperatorOrHigher: () => isShiftOperatorOrHigher, isShorthandAmbientModuleSymbol: () => isShorthandAmbientModuleSymbol, isShorthandPropertyAssignment: () => isShorthandPropertyAssignment, + isSideEffectImport: () => isSideEffectImport, isSignedNumericLiteral: () => isSignedNumericLiteral, isSimpleCopiableExpression: () => isSimpleCopiableExpression, isSimpleInlineableExpression: () => isSimpleInlineableExpression, - isSimpleParameter: () => isSimpleParameter, isSimpleParameterList: () => isSimpleParameterList, isSingleOrDoubleQuote: () => isSingleOrDoubleQuote, + isSourceElement: () => isSourceElement, isSourceFile: () => isSourceFile, isSourceFileFromLibrary: () => isSourceFileFromLibrary, isSourceFileJS: () => isSourceFileJS, - isSourceFileNotJS: () => isSourceFileNotJS, isSourceFileNotJson: () => isSourceFileNotJson, isSourceMapping: () => isSourceMapping, isSpecialPropertyDeclaration: () => isSpecialPropertyDeclaration, @@ -274977,7 +275888,6 @@ __export(ts_exports2, { isStatic: () => isStatic, isStaticModifier: () => isStaticModifier, isString: () => isString, - isStringAKeyword: () => isStringAKeyword, isStringANonContextualKeyword: () => isStringANonContextualKeyword, isStringAndEmptyAnonymousObjectIntersection: () => isStringAndEmptyAnonymousObjectIntersection, isStringDoubleQuoted: () => isStringDoubleQuoted, @@ -274990,7 +275900,6 @@ __export(ts_exports2, { isStringTextContainingNode: () => isStringTextContainingNode, isSuperCall: () => isSuperCall, isSuperKeyword: () => isSuperKeyword, - isSuperOrSuperProperty: () => isSuperOrSuperProperty, isSuperProperty: () => isSuperProperty, isSupportedSourceFileName: () => isSupportedSourceFileName, isSwitchStatement: () => isSwitchStatement, @@ -275036,7 +275945,6 @@ __export(ts_exports2, { isTypeDeclaration: () => isTypeDeclaration, isTypeElement: () => isTypeElement, isTypeKeyword: () => isTypeKeyword, - isTypeKeywordToken: () => isTypeKeywordToken, isTypeKeywordTokenOrIdentifier: () => isTypeKeywordTokenOrIdentifier, isTypeLiteralNode: () => isTypeLiteralNode, isTypeNode: () => isTypeNode, @@ -275091,10 +275999,6 @@ __export(ts_exports2, { libMap: () => libMap, libs: () => libs, lineBreakPart: () => lineBreakPart, - linkNamePart: () => linkNamePart, - linkPart: () => linkPart, - linkTextPart: () => linkTextPart, - listFiles: () => listFiles, loadModuleFromGlobalCache: () => loadModuleFromGlobalCache, loadWithModeAwareCache: () => loadWithModeAwareCache, makeIdentifierFromModuleName: () => makeIdentifierFromModuleName, @@ -275104,7 +276008,6 @@ __export(ts_exports2, { map: () => map, mapAllOrFail: () => mapAllOrFail, mapDefined: () => mapDefined, - mapDefinedEntries: () => mapDefinedEntries, mapDefinedIterator: () => mapDefinedIterator, mapEntries: () => mapEntries, mapIterator: () => mapIterator, @@ -275114,18 +276017,19 @@ __export(ts_exports2, { matchPatternOrExact: () => matchPatternOrExact, matchedText: () => matchedText, matchesExclude: () => matchesExclude, + maxBy: () => maxBy, maybeBind: () => maybeBind, maybeSetLocalizedDiagnosticMessages: () => maybeSetLocalizedDiagnosticMessages, memoize: () => memoize, - memoizeCached: () => memoizeCached, memoizeOne: () => memoizeOne, - memoizeWeak: () => memoizeWeak, - metadataHelper: () => metadataHelper, min: () => min, minAndMax: () => minAndMax, missingFileModifiedTime: () => missingFileModifiedTime, modifierToFlag: () => modifierToFlag, modifiersToFlags: () => modifiersToFlags, + moduleExportNameIsDefault: () => moduleExportNameIsDefault, + moduleExportNameTextEscaped: () => moduleExportNameTextEscaped, + moduleExportNameTextUnescaped: () => moduleExportNameTextUnescaped, moduleOptionDeclaration: () => moduleOptionDeclaration, moduleResolutionIsEqualTo: () => moduleResolutionIsEqualTo, moduleResolutionNameAndModeGetter: () => moduleResolutionNameAndModeGetter, @@ -275165,11 +276069,11 @@ __export(ts_exports2, { nodePosToString: () => nodePosToString, nodeSeenTracker: () => nodeSeenTracker, nodeStartsNewLexicalEnvironment: () => nodeStartsNewLexicalEnvironment, - nodeToDisplayParts: () => nodeToDisplayParts, noop: () => noop, noopFileWatcher: () => noopFileWatcher, normalizePath: () => normalizePath, normalizeSlashes: () => normalizeSlashes, + normalizeSpans: () => normalizeSpans, not: () => not, notImplemented: () => notImplemented, notImplementedResolver: () => notImplementedResolver, @@ -275184,13 +276088,11 @@ __export(ts_exports2, { optionsForBuild: () => optionsForBuild, optionsForWatch: () => optionsForWatch, optionsHaveChanges: () => optionsHaveChanges, - optionsHaveModuleResolutionChanges: () => optionsHaveModuleResolutionChanges, or: () => or, orderedRemoveItem: () => orderedRemoveItem, orderedRemoveItemAt: () => orderedRemoveItemAt, packageIdToPackageName: () => packageIdToPackageName, packageIdToString: () => packageIdToString, - paramHelper: () => paramHelper, parameterIsThisKeyword: () => parameterIsThisKeyword, parameterNamePart: () => parameterNamePart, parseBaseNodeFactory: () => parseBaseNodeFactory, @@ -275221,10 +276123,8 @@ __export(ts_exports2, { pathIsBareSpecifier: () => pathIsBareSpecifier, pathIsRelative: () => pathIsRelative, patternText: () => patternText, - perfLogger: () => perfLogger, performIncrementalCompilation: () => performIncrementalCompilation, performance: () => ts_performance_exports, - plainJSErrors: () => plainJSErrors, positionBelongsToNode: () => positionBelongsToNode, positionIsASICandidate: () => positionIsASICandidate, positionIsSynthesized: () => positionIsSynthesized, @@ -275237,7 +276137,6 @@ __export(ts_exports2, { programContainsEsModules: () => programContainsEsModules, programContainsModules: () => programContainsModules, projectReferenceIsEqualTo: () => projectReferenceIsEqualTo, - propKeyHelper: () => propKeyHelper, propertyNamePart: () => propertyNamePart, pseudoBigIntToString: () => pseudoBigIntToString, punctuationPart: () => punctuationPart, @@ -275260,7 +276159,6 @@ __export(ts_exports2, { rangeStartPositionsAreOnSameLine: () => rangeStartPositionsAreOnSameLine, readBuilderProgram: () => readBuilderProgram, readConfigFile: () => readConfigFile, - readHelper: () => readHelper, readJson: () => readJson, readJsonConfigFile: () => readJsonConfigFile, readJsonOrUndefined: () => readJsonOrUndefined, @@ -275271,7 +276169,7 @@ __export(ts_exports2, { reducePathComponents: () => reducePathComponents, refactor: () => ts_refactor_exports, regExpEscape: () => regExpEscape, - regularExpressionFlagToCharacter: () => regularExpressionFlagToCharacter, + regularExpressionFlagToCharacterCode: () => regularExpressionFlagToCharacterCode, relativeComplement: () => relativeComplement, removeAllComments: () => removeAllComments, removeEmitHelper: () => removeEmitHelper, @@ -275279,7 +276177,6 @@ __export(ts_exports2, { removeFileExtension: () => removeFileExtension, removeIgnoredPath: () => removeIgnoredPath, removeMinAndVersionNumbers: () => removeMinAndVersionNumbers, - removeOptionality: () => removeOptionality, removePrefix: () => removePrefix, removeSuffix: () => removeSuffix, removeTrailingDirectorySeparator: () => removeTrailingDirectorySeparator, @@ -275298,20 +276195,16 @@ __export(ts_exports2, { resolveTripleslashReference: () => resolveTripleslashReference, resolveTypeReferenceDirective: () => resolveTypeReferenceDirective, resolvingEmptyArray: () => resolvingEmptyArray, - restHelper: () => restHelper, returnFalse: () => returnFalse, returnNoopFileWatcher: () => returnNoopFileWatcher, returnTrue: () => returnTrue, returnUndefined: () => returnUndefined, returnsPromise: () => returnsPromise, - runInitializersHelper: () => runInitializersHelper, sameFlatMap: () => sameFlatMap, sameMap: () => sameMap, sameMapping: () => sameMapping, - scanShebangTrivia: () => scanShebangTrivia, scanTokenAtPosition: () => scanTokenAtPosition, scanner: () => scanner, - screenStartingMessageCodes: () => screenStartingMessageCodes, semanticDiagnosticsOptionDeclarations: () => semanticDiagnosticsOptionDeclarations, serializeCompilerOptions: () => serializeCompilerOptions, server: () => ts_server_exports3, @@ -275319,16 +276212,13 @@ __export(ts_exports2, { setCommentRange: () => setCommentRange, setConfigFileInOptions: () => setConfigFileInOptions, setConstantValue: () => setConstantValue, - setEachParent: () => setEachParent, setEmitFlags: () => setEmitFlags, - setFunctionNameHelper: () => setFunctionNameHelper, setGetSourceFileAsHashVersioned: () => setGetSourceFileAsHashVersioned, setIdentifierAutoGenerate: () => setIdentifierAutoGenerate, setIdentifierGeneratedImportReference: () => setIdentifierGeneratedImportReference, setIdentifierTypeArguments: () => setIdentifierTypeArguments, setInternalEmitFlags: () => setInternalEmitFlags, setLocalizedDiagnosticMessages: () => setLocalizedDiagnosticMessages, - setModuleDefaultHelper: () => setModuleDefaultHelper, setNodeChildren: () => setNodeChildren, setNodeFlags: () => setNodeFlags, setObjectAllocator: () => setObjectAllocator, @@ -275357,7 +276247,6 @@ __export(ts_exports2, { shouldPreserveConstEnums: () => shouldPreserveConstEnums, shouldUseUriStyleNodeCoreModules: () => shouldUseUriStyleNodeCoreModules, showModuleSpecifier: () => showModuleSpecifier, - signatureHasLiteralTypes: () => signatureHasLiteralTypes, signatureHasRestParameter: () => signatureHasRestParameter, signatureToDisplayParts: () => signatureToDisplayParts, single: () => single, @@ -275366,18 +276255,17 @@ __export(ts_exports2, { singleOrMany: () => singleOrMany, singleOrUndefined: () => singleOrUndefined, skipAlias: () => skipAlias, - skipAssertions: () => skipAssertions, skipConstraint: () => skipConstraint, skipOuterExpressions: () => skipOuterExpressions, skipParentheses: () => skipParentheses, skipPartiallyEmittedExpressions: () => skipPartiallyEmittedExpressions, skipTrivia: () => skipTrivia, skipTypeChecking: () => skipTypeChecking, + skipTypeCheckingIgnoringNoCheck: () => skipTypeCheckingIgnoringNoCheck, skipTypeParentheses: () => skipTypeParentheses, skipWhile: () => skipWhile, sliceAfter: () => sliceAfter, some: () => some, - sort: () => sort, sortAndDeduplicate: () => sortAndDeduplicate, sortAndDeduplicateDiagnostics: () => sortAndDeduplicateDiagnostics, sourceFileAffectingCompilerOptions: () => sourceFileAffectingCompilerOptions, @@ -275386,8 +276274,6 @@ __export(ts_exports2, { sourceMapCommentRegExpDontCareLineStart: () => sourceMapCommentRegExpDontCareLineStart, spacePart: () => spacePart, spanMap: () => spanMap, - spreadArrayHelper: () => spreadArrayHelper, - stableSort: () => stableSort, startEndContainsRange: () => startEndContainsRange, startEndOverlapsWithStartEnd: () => startEndOverlapsWithStartEnd, startOnNewLine: () => startOnNewLine, @@ -275400,10 +276286,8 @@ __export(ts_exports2, { stringToToken: () => stringToToken, stripQuotes: () => stripQuotes, supportedDeclarationExtensions: () => supportedDeclarationExtensions, - supportedJSExtensions: () => supportedJSExtensions, supportedJSExtensionsFlat: () => supportedJSExtensionsFlat, supportedLocaleDirectories: () => supportedLocaleDirectories, - supportedTSExtensions: () => supportedTSExtensions, supportedTSExtensionsFlat: () => supportedTSExtensionsFlat, supportedTSImplementationExtensions: () => supportedTSImplementationExtensions, suppressLeadingAndTrailingTrivia: () => suppressLeadingAndTrailingTrivia, @@ -275412,16 +276296,12 @@ __export(ts_exports2, { symbolEscapedNameNoDefault: () => symbolEscapedNameNoDefault, symbolName: () => symbolName, symbolNameNoDefault: () => symbolNameNoDefault, - symbolPart: () => symbolPart, symbolToDisplayParts: () => symbolToDisplayParts, - syntaxMayBeASICandidate: () => syntaxMayBeASICandidate, - syntaxRequiresTrailingSemicolonOrASI: () => syntaxRequiresTrailingSemicolonOrASI, sys: () => sys, sysLog: () => sysLog, tagNamesAreEquivalent: () => tagNamesAreEquivalent, takeWhile: () => takeWhile, targetOptionDeclaration: () => targetOptionDeclaration, - templateObjectHelper: () => templateObjectHelper, testFormatSettings: () => testFormatSettings, textChangeRangeIsUnchanged: () => textChangeRangeIsUnchanged, textChangeRangeNewSpan: () => textChangeRangeNewSpan, @@ -275429,7 +276309,10 @@ __export(ts_exports2, { textOrKeywordPart: () => textOrKeywordPart, textPart: () => textPart, textRangeContainsPositionInclusive: () => textRangeContainsPositionInclusive, + textRangeContainsTextSpan: () => textRangeContainsTextSpan, + textRangeIntersectsWithTextSpan: () => textRangeIntersectsWithTextSpan, textSpanContainsPosition: () => textSpanContainsPosition, + textSpanContainsTextRange: () => textSpanContainsTextRange, textSpanContainsTextSpan: () => textSpanContainsTextSpan, textSpanEnd: () => textSpanEnd, textSpanIntersection: () => textSpanIntersection, @@ -275447,9 +276330,9 @@ __export(ts_exports2, { toBuilderStateFileInfoForMultiEmit: () => toBuilderStateFileInfoForMultiEmit, toEditorSettings: () => toEditorSettings, toFileNameLowerCase: () => toFileNameLowerCase, - toLowerCase: () => toLowerCase, toPath: () => toPath, toProgramEmitPending: () => toProgramEmitPending, + toSorted: () => toSorted, tokenIsIdentifierOrKeyword: () => tokenIsIdentifierOrKeyword, tokenIsIdentifierOrKeywordOrGreaterThan: () => tokenIsIdentifierOrKeywordOrGreaterThan, tokenToString: () => tokenToString, @@ -275471,11 +276354,11 @@ __export(ts_exports2, { transformESDecorators: () => transformESDecorators, transformESNext: () => transformESNext, transformGenerators: () => transformGenerators, + transformImpliedNodeFormatDependentModule: () => transformImpliedNodeFormatDependentModule, transformJsx: () => transformJsx, transformLegacyDecorators: () => transformLegacyDecorators, transformModule: () => transformModule, transformNamedEvaluation: () => transformNamedEvaluation, - transformNodeModule: () => transformNodeModule, transformNodes: () => transformNodes, transformSystemModule: () => transformSystemModule, transformTypeScript: () => transformTypeScript, @@ -275502,7 +276385,6 @@ __export(ts_exports2, { tryGetPropertyNameOfBindingOrAssignmentElement: () => tryGetPropertyNameOfBindingOrAssignmentElement, tryGetSourceMappingURL: () => tryGetSourceMappingURL, tryGetTextOfPropertyName: () => tryGetTextOfPropertyName, - tryIOAndConsumeErrors: () => tryIOAndConsumeErrors, tryParseJson: () => tryParseJson, tryParsePattern: () => tryParsePattern, tryParsePatterns: () => tryParsePatterns, @@ -275524,7 +276406,6 @@ __export(ts_exports2, { unescapeLeadingUnderscores: () => unescapeLeadingUnderscores, unmangleScopedPackageName: () => unmangleScopedPackageName, unorderedRemoveItem: () => unorderedRemoveItem, - unorderedRemoveItemAt: () => unorderedRemoveItemAt, unreachableCodeIsError: () => unreachableCodeIsError, unsetNodeChildren: () => unsetNodeChildren, unusedLabelIsError: () => unusedLabelIsError, @@ -275537,11 +276418,9 @@ __export(ts_exports2, { updateSharedExtendedConfigFileWatcher: () => updateSharedExtendedConfigFileWatcher, updateSourceFile: () => updateSourceFile, updateWatchingWildcardDirectories: () => updateWatchingWildcardDirectories, - usesExtensionsOnImports: () => usesExtensionsOnImports, usingSingleLineStringWriter: () => usingSingleLineStringWriter, utf16EncodeAsString: () => utf16EncodeAsString, validateLocaleAndSetLanguage: () => validateLocaleAndSetLanguage, - valuesHelper: () => valuesHelper, version: () => version, versionMajorMinor: () => versionMajorMinor, visitArray: () => visitArray, @@ -275554,7 +276433,6 @@ __export(ts_exports2, { visitNodes: () => visitNodes2, visitParameterList: () => visitParameterList, walkUpBindingElementsAndPatterns: () => walkUpBindingElementsAndPatterns, - walkUpLexicalEnvironments: () => walkUpLexicalEnvironments, walkUpOuterExpressions: () => walkUpOuterExpressions, walkUpParenthesizedExpressions: () => walkUpParenthesizedExpressions, walkUpParenthesizedTypes: () => walkUpParenthesizedTypes, @@ -275707,20 +276585,19 @@ __export(ts_server_exports3, { LogLevel: () => LogLevel2, Msg: () => Msg, OpenFileInfoTelemetryEvent: () => OpenFileInfoTelemetryEvent, - Project: () => Project3, + Project: () => Project2, ProjectInfoTelemetryEvent: () => ProjectInfoTelemetryEvent, ProjectKind: () => ProjectKind, ProjectLanguageServiceStateEvent: () => ProjectLanguageServiceStateEvent, ProjectLoadingFinishEvent: () => ProjectLoadingFinishEvent, ProjectLoadingStartEvent: () => ProjectLoadingStartEvent, - ProjectService: () => ProjectService3, + ProjectService: () => ProjectService2, ProjectsUpdatedInBackgroundEvent: () => ProjectsUpdatedInBackgroundEvent, ScriptInfo: () => ScriptInfo, ScriptVersionCache: () => ScriptVersionCache, Session: () => Session3, TextStorage: () => TextStorage, ThrottledOperations: () => ThrottledOperations, - TypingsCache: () => TypingsCache, TypingsInstallerAdapter: () => TypingsInstallerAdapter, allFilesAreJsOrDts: () => allFilesAreJsOrDts, allRootFilesAreJsOrDts: () => allRootFilesAreJsOrDts, @@ -275739,7 +276616,6 @@ __export(ts_server_exports3, { createSortedArray: () => createSortedArray2, emptyArray: () => emptyArray2, findArgument: () => findArgument, - forEachResolvedProjectReferenceProject: () => forEachResolvedProjectReferenceProject, formatDiagnosticToProtocol: () => formatDiagnosticToProtocol, formatMessage: () => formatMessage2, getBaseConfigFileName: () => getBaseConfigFileName, @@ -275765,7 +276641,6 @@ __export(ts_server_exports3, { nullCancellationToken: () => nullCancellationToken, nullTypingsInstaller: () => nullTypingsInstaller, protocol: () => ts_server_protocol_exports, - removeSorted: () => removeSorted, stringifyIndented: () => stringifyIndented, toEvent: () => toEvent, toNormalizedPath: () => toNormalizedPath, @@ -275832,7 +276707,6 @@ var TypingsInstaller = class { this.missingTypingsSet = /* @__PURE__ */ new Set(); this.knownCachesSet = /* @__PURE__ */ new Set(); this.projectWatchers = /* @__PURE__ */ new Map(); - /** @internal */ this.pendingRunRequests = []; this.installRunCount = 1; this.inFlightRequestCount = 0; @@ -276307,14 +277181,11 @@ var ThrottledOperations = class _ThrottledOperations { return this.pendingTimeouts.delete(operationId); } static run(operationId, self, cb) { - var _a, _b; - (_a = perfLogger) == null ? void 0 : _a.logStartScheduledOperation(operationId); self.pendingTimeouts.delete(operationId); if (self.logger) { self.logger.info(`Running: ${operationId}`); } cb(); - (_b = perfLogger) == null ? void 0 : _b.logStopScheduledOperation(); } }; var GcTimer = class _GcTimer { @@ -276330,9 +277201,7 @@ var GcTimer = class _GcTimer { this.timerId = this.host.setTimeout(_GcTimer.run, this.delay, this); } static run(self) { - var _a, _b; self.timerId = void 0; - (_a = perfLogger) == null ? void 0 : _a.logStartScheduledOperation("GC collect"); const log = self.logger.hasLevel(2 /* requestTime */); const before = log && self.host.getMemoryUsage(); self.host.gc(); @@ -276340,26 +277209,12 @@ var GcTimer = class _GcTimer { const after = self.host.getMemoryUsage(); self.logger.perftrc(`GC::before ${before}, after ${after}`); } - (_b = perfLogger) == null ? void 0 : _b.logStopScheduledOperation(); } }; function getBaseConfigFileName(configFilePath) { const base = getBaseFileName(configFilePath); return base === "tsconfig.json" || base === "jsconfig.json" ? base : void 0; } -function removeSorted(array, remove, compare) { - if (!array || array.length === 0) { - return; - } - if (array[0] === remove) { - array.splice(0, 1); - return; - } - const removeIndex = binarySearch(array, remove, identity, compare); - if (removeIndex >= 0) { - array.splice(removeIndex, 1); - } -} // src/server/_namespaces/ts.server.protocol.ts var ts_server_protocol_exports = {}; @@ -276374,7 +277229,7 @@ __export(ts_server_protocol_exports, { NewLineKind: () => NewLineKind2, OrganizeImportsMode: () => OrganizeImportsMode, PollingWatchKind: () => PollingWatchKind2, - ScriptTarget: () => ScriptTarget10, + ScriptTarget: () => ScriptTarget11, SemicolonPreference: () => SemicolonPreference, WatchDirectoryKind: () => WatchDirectoryKind2, WatchFileKind: () => WatchFileKind2 @@ -276565,24 +277420,24 @@ var NewLineKind2 = /* @__PURE__ */ ((NewLineKind3) => { NewLineKind3["Lf"] = "Lf"; return NewLineKind3; })(NewLineKind2 || {}); -var ScriptTarget10 = /* @__PURE__ */ ((ScriptTarget11) => { - ScriptTarget11["ES3"] = "es3"; - ScriptTarget11["ES5"] = "es5"; - ScriptTarget11["ES6"] = "es6"; - ScriptTarget11["ES2015"] = "es2015"; - ScriptTarget11["ES2016"] = "es2016"; - ScriptTarget11["ES2017"] = "es2017"; - ScriptTarget11["ES2018"] = "es2018"; - ScriptTarget11["ES2019"] = "es2019"; - ScriptTarget11["ES2020"] = "es2020"; - ScriptTarget11["ES2021"] = "es2021"; - ScriptTarget11["ES2022"] = "es2022"; - ScriptTarget11["ES2023"] = "es2023"; - ScriptTarget11["ESNext"] = "esnext"; - ScriptTarget11["JSON"] = "json"; - ScriptTarget11["Latest"] = "esnext" /* ESNext */; - return ScriptTarget11; -})(ScriptTarget10 || {}); +var ScriptTarget11 = /* @__PURE__ */ ((ScriptTarget12) => { + ScriptTarget12["ES3"] = "es3"; + ScriptTarget12["ES5"] = "es5"; + ScriptTarget12["ES6"] = "es6"; + ScriptTarget12["ES2015"] = "es2015"; + ScriptTarget12["ES2016"] = "es2016"; + ScriptTarget12["ES2017"] = "es2017"; + ScriptTarget12["ES2018"] = "es2018"; + ScriptTarget12["ES2019"] = "es2019"; + ScriptTarget12["ES2020"] = "es2020"; + ScriptTarget12["ES2021"] = "es2021"; + ScriptTarget12["ES2022"] = "es2022"; + ScriptTarget12["ES2023"] = "es2023"; + ScriptTarget12["ESNext"] = "esnext"; + ScriptTarget12["JSON"] = "json"; + ScriptTarget12["Latest"] = "esnext" /* ESNext */; + return ScriptTarget12; +})(ScriptTarget11 || {}); { } @@ -277067,17 +277922,80 @@ function failIfInvalidLocation(location) { Debug.assert(location.offset > 0, `Expected offset to be non-${location.offset === 0 ? "zero" : "negative"}`); } -// src/server/typingsCache.ts -var nullTypingsInstaller = { - isKnownTypesPackageName: returnFalse, - // Should never be called because we never provide a types registry. - installPackage: notImplemented, - enqueueInstallTypingsRequest: noop, - attach: noop, - onProjectClosed: noop, - globalTypingsCacheLocation: void 0 - // TODO: GH#18217 -}; +// src/server/project.ts +var ProjectKind = /* @__PURE__ */ ((ProjectKind2) => { + ProjectKind2[ProjectKind2["Inferred"] = 0] = "Inferred"; + ProjectKind2[ProjectKind2["Configured"] = 1] = "Configured"; + ProjectKind2[ProjectKind2["External"] = 2] = "External"; + ProjectKind2[ProjectKind2["AutoImportProvider"] = 3] = "AutoImportProvider"; + ProjectKind2[ProjectKind2["Auxiliary"] = 4] = "Auxiliary"; + return ProjectKind2; +})(ProjectKind || {}); +function countEachFileTypes(infos, includeSizes = false) { + const result = { + js: 0, + jsSize: 0, + jsx: 0, + jsxSize: 0, + ts: 0, + tsSize: 0, + tsx: 0, + tsxSize: 0, + dts: 0, + dtsSize: 0, + deferred: 0, + deferredSize: 0 + }; + for (const info of infos) { + const fileSize = includeSizes ? info.textStorage.getTelemetryFileSize() : 0; + switch (info.scriptKind) { + case 1 /* JS */: + result.js += 1; + result.jsSize += fileSize; + break; + case 2 /* JSX */: + result.jsx += 1; + result.jsxSize += fileSize; + break; + case 3 /* TS */: + if (isDeclarationFileName(info.fileName)) { + result.dts += 1; + result.dtsSize += fileSize; + } else { + result.ts += 1; + result.tsSize += fileSize; + } + break; + case 4 /* TSX */: + result.tsx += 1; + result.tsxSize += fileSize; + break; + case 7 /* Deferred */: + result.deferred += 1; + result.deferredSize += fileSize; + break; + } + } + return result; +} +function hasOneOrMoreJsAndNoTsFiles(project) { + const counts2 = countEachFileTypes(project.getScriptInfos()); + return counts2.js > 0 && counts2.ts === 0 && counts2.tsx === 0; +} +function allRootFilesAreJsOrDts(project) { + const counts2 = countEachFileTypes(project.getRootScriptInfos()); + return counts2.ts === 0 && counts2.tsx === 0; +} +function allFilesAreJsOrDts(project) { + const counts2 = countEachFileTypes(project.getScriptInfos()); + return counts2.ts === 0 && counts2.tsx === 0; +} +function hasNoTypeScriptSource(fileNames) { + return !fileNames.some((fileName) => fileExtensionIs(fileName, ".ts" /* Ts */) && !isDeclarationFileName(fileName) || fileExtensionIs(fileName, ".tsx" /* Tsx */)); +} +function isGeneratedFileWatcher(watch) { + return watch.generatedFilePath !== void 0; +} function setIsEqualTo(arr1, arr2) { if (arr1 === arr2) { return true; @@ -277117,127 +278035,7 @@ function unresolvedImportsChanged(imports1, imports2) { } return !arrayIsEqualTo(imports1, imports2); } -var TypingsCache = class { - constructor(installer) { - this.installer = installer; - this.perProjectCache = /* @__PURE__ */ new Map(); - } - isKnownTypesPackageName(name) { - return this.installer.isKnownTypesPackageName(name); - } - installPackage(options) { - return this.installer.installPackage(options); - } - enqueueInstallTypingsForProject(project, unresolvedImports, forceRefresh) { - const typeAcquisition = project.getTypeAcquisition(); - if (!typeAcquisition || !typeAcquisition.enable) { - return; - } - const entry = this.perProjectCache.get(project.getProjectName()); - if (forceRefresh || !entry || typeAcquisitionChanged(typeAcquisition, entry.typeAcquisition) || compilerOptionsChanged(project.getCompilationSettings(), entry.compilerOptions) || unresolvedImportsChanged(unresolvedImports, entry.unresolvedImports)) { - this.perProjectCache.set(project.getProjectName(), { - compilerOptions: project.getCompilationSettings(), - typeAcquisition, - typings: entry ? entry.typings : emptyArray2, - unresolvedImports, - poisoned: true - }); - this.installer.enqueueInstallTypingsRequest(project, typeAcquisition, unresolvedImports); - } - } - updateTypingsForProject(projectName, compilerOptions, typeAcquisition, unresolvedImports, newTypings) { - const typings = sort(newTypings); - this.perProjectCache.set(projectName, { - compilerOptions, - typeAcquisition, - typings, - unresolvedImports, - poisoned: false - }); - return !typeAcquisition || !typeAcquisition.enable ? emptyArray2 : typings; - } - onProjectClosed(project) { - if (this.perProjectCache.delete(project.getProjectName())) { - this.installer.onProjectClosed(project); - } - } -}; - -// src/server/project.ts -var ProjectKind = /* @__PURE__ */ ((ProjectKind2) => { - ProjectKind2[ProjectKind2["Inferred"] = 0] = "Inferred"; - ProjectKind2[ProjectKind2["Configured"] = 1] = "Configured"; - ProjectKind2[ProjectKind2["External"] = 2] = "External"; - ProjectKind2[ProjectKind2["AutoImportProvider"] = 3] = "AutoImportProvider"; - ProjectKind2[ProjectKind2["Auxiliary"] = 4] = "Auxiliary"; - return ProjectKind2; -})(ProjectKind || {}); -function countEachFileTypes(infos, includeSizes = false) { - const result = { - js: 0, - jsSize: 0, - jsx: 0, - jsxSize: 0, - ts: 0, - tsSize: 0, - tsx: 0, - tsxSize: 0, - dts: 0, - dtsSize: 0, - deferred: 0, - deferredSize: 0 - }; - for (const info of infos) { - const fileSize = includeSizes ? info.textStorage.getTelemetryFileSize() : 0; - switch (info.scriptKind) { - case 1 /* JS */: - result.js += 1; - result.jsSize += fileSize; - break; - case 2 /* JSX */: - result.jsx += 1; - result.jsxSize += fileSize; - break; - case 3 /* TS */: - if (isDeclarationFileName(info.fileName)) { - result.dts += 1; - result.dtsSize += fileSize; - } else { - result.ts += 1; - result.tsSize += fileSize; - } - break; - case 4 /* TSX */: - result.tsx += 1; - result.tsxSize += fileSize; - break; - case 7 /* Deferred */: - result.deferred += 1; - result.deferredSize += fileSize; - break; - } - } - return result; -} -function hasOneOrMoreJsAndNoTsFiles(project) { - const counts2 = countEachFileTypes(project.getScriptInfos()); - return counts2.js > 0 && counts2.ts === 0 && counts2.tsx === 0; -} -function allRootFilesAreJsOrDts(project) { - const counts2 = countEachFileTypes(project.getRootScriptInfos()); - return counts2.ts === 0 && counts2.tsx === 0; -} -function allFilesAreJsOrDts(project) { - const counts2 = countEachFileTypes(project.getScriptInfos()); - return counts2.ts === 0 && counts2.tsx === 0; -} -function hasNoTypeScriptSource(fileNames) { - return !fileNames.some((fileName) => fileExtensionIs(fileName, ".ts" /* Ts */) && !isDeclarationFileName(fileName) || fileExtensionIs(fileName, ".tsx" /* Tsx */)); -} -function isGeneratedFileWatcher(watch) { - return watch.generatedFilePath !== void 0; -} -var Project3 = class _Project { +var Project2 = class _Project { /** @internal */ constructor(projectName, projectKind, projectService, documentRegistry, hasExplicitListOfFiles, lastFileExceededProgramSize, compilerOptions, compileOnSaveEnabled, watchOptions, directoryStructureHost, currentDirectory) { this.projectKind = projectKind; @@ -277257,9 +278055,7 @@ var Project3 = class _Project { * @internal */ this.cachedUnresolvedImportsPerFile = /* @__PURE__ */ new Map(); - /** @internal */ this.hasAddedorRemovedFiles = false; - /** @internal */ this.hasAddedOrRemovedSymlinks = false; /** * Last version that was reported. @@ -277284,7 +278080,6 @@ var Project3 = class _Project { this.dirty = false; /** @internal */ this.typingFiles = emptyArray2; - /** @internal */ this.moduleSpecifierCache = createModuleSpecifierCache(this); /** @internal */ this.createHash = maybeBind(this.projectService.host, this.projectService.host.createHash); @@ -277330,6 +278125,7 @@ var Project3 = class _Project { this.trace = (s) => host.trace(s); } this.realpath = maybeBind(host, host.realpath); + this.preferNonRecursiveWatch = this.projectService.canUseWatchEvents || host.preferNonRecursiveWatch; this.resolutionCache = createResolutionCache( this, this.currentDirectory, @@ -277403,18 +278199,15 @@ var Project3 = class _Project { return { pluginConfigEntry, resolvedModule, errorLogs }; } isKnownTypesPackageName(name) { - return this.typingsCache.isKnownTypesPackageName(name); + return this.projectService.typingsInstaller.isKnownTypesPackageName(name); } installPackage(options) { - return this.typingsCache.installPackage({ ...options, projectName: this.projectName, projectRootPath: this.toPath(this.currentDirectory) }); + return this.projectService.typingsInstaller.installPackage({ ...options, projectName: this.projectName, projectRootPath: this.toPath(this.currentDirectory) }); } /** @internal */ getGlobalTypingsCacheLocation() { return this.getGlobalCache(); } - get typingsCache() { - return this.projectService.typingsCache; - } /** @internal */ getSymlinkCache() { if (!this.symlinks) { @@ -277519,7 +278312,7 @@ var Project3 = class _Project { } fileExists(file) { const path = this.toPath(file); - return !this.isWatchedMissingFile(path) && this.directoryStructureHost.fileExists(file); + return !!this.projectService.getScriptInfoForPath(path) || !this.isWatchedMissingFile(path) && this.directoryStructureHost.fileExists(file); } /** @internal */ resolveModuleNameLiterals(moduleLiterals, containingFile, redirectedReference, options, containingSourceFile, reusedNames) { @@ -277786,13 +278579,13 @@ var Project3 = class _Project { return this.projectName; } removeLocalTypingsFromTypeAcquisition(newTypeAcquisition) { - if (!newTypeAcquisition || !newTypeAcquisition.include) { + if (!newTypeAcquisition.enable || !newTypeAcquisition.include) { return newTypeAcquisition; } return { ...newTypeAcquisition, include: this.removeExistingTypings(newTypeAcquisition.include) }; } getExternalFiles(updateLevel) { - return sort(flatMap(this.plugins, (plugin) => { + return toSorted(flatMap(this.plugins, (plugin) => { if (typeof plugin.module.getExternalFiles !== "function") return; try { return plugin.module.getExternalFiles(this, updateLevel || 0 /* Update */); @@ -277817,7 +278610,8 @@ var Project3 = class _Project { } close() { var _a; - this.projectService.typingsCache.onProjectClosed(this); + if (this.typingsCache) this.projectService.typingsInstaller.onProjectClosed(this); + this.typingsCache = void 0; this.closeWatchingTypingLocations(); this.cleanupProgram(); forEach(this.externalFiles, (externalFile) => this.detachScriptInfoIfNotRoot(externalFile)); @@ -278059,6 +278853,12 @@ var Project3 = class _Project { this.hasAddedOrRemovedSymlinks = true; } /** @internal */ + onReleaseOldSourceFile(oldSourceFile, _oldOptions, hasSourceFileByPath, newSourceFileByResolvedPath) { + if (!newSourceFileByResolvedPath || oldSourceFile.resolvedPath === oldSourceFile.path && newSourceFileByResolvedPath.resolvedPath !== oldSourceFile.path) { + this.detachScriptInfoFromProject(oldSourceFile.fileName, hasSourceFileByPath); + } + } + /** @internal */ updateFromProject() { updateProjectIfDirty(this); } @@ -278067,9 +278867,8 @@ var Project3 = class _Project { * @returns: true if set of files in the project stays the same and false - otherwise. */ updateGraph() { - var _a, _b, _c, _d; + var _a, _b; (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Session, "updateGraph", { name: this.projectName, kind: ProjectKind[this.projectKind] }); - (_b = perfLogger) == null ? void 0 : _b.logStartUpdateGraph(); this.resolutionCache.startRecordingFilesWithChangedResolutions(); const hasNewProgram = this.updateGraphWorker(); const hasAddedorRemovedFiles = this.hasAddedorRemovedFiles; @@ -278083,7 +278882,7 @@ var Project3 = class _Project { if (hasNewProgram || changedFiles.length) { this.lastCachedUnresolvedImportsList = getUnresolvedImports(this.program, this.cachedUnresolvedImportsPerFile); } - this.projectService.typingsCache.enqueueInstallTypingsForProject(this, this.lastCachedUnresolvedImportsList, hasAddedorRemovedFiles); + this.enqueueInstallTypingsForProject(hasAddedorRemovedFiles); } else { this.lastCachedUnresolvedImportsList = void 0; } @@ -278097,12 +278896,33 @@ var Project3 = class _Project { if (isFirstProgramLoad) { this.getPackageJsonAutoImportProvider(); } - (_c = perfLogger) == null ? void 0 : _c.logStopUpdateGraph(); - (_d = tracing) == null ? void 0 : _d.pop(); + (_b = tracing) == null ? void 0 : _b.pop(); return !hasNewProgram; } /** @internal */ - updateTypingFiles(typingFiles) { + enqueueInstallTypingsForProject(forceRefresh) { + const typeAcquisition = this.getTypeAcquisition(); + if (!typeAcquisition || !typeAcquisition.enable || this.projectService.typingsInstaller === nullTypingsInstaller) { + return; + } + const entry = this.typingsCache; + if (forceRefresh || !entry || typeAcquisitionChanged(typeAcquisition, entry.typeAcquisition) || compilerOptionsChanged(this.getCompilationSettings(), entry.compilerOptions) || unresolvedImportsChanged(this.lastCachedUnresolvedImportsList, entry.unresolvedImports)) { + this.typingsCache = { + compilerOptions: this.getCompilationSettings(), + typeAcquisition, + unresolvedImports: this.lastCachedUnresolvedImportsList + }; + this.projectService.typingsInstaller.enqueueInstallTypingsRequest(this, typeAcquisition, this.lastCachedUnresolvedImportsList); + } + } + /** @internal */ + updateTypingFiles(compilerOptions, typeAcquisition, unresolvedImports, newTypings) { + this.typingsCache = { + compilerOptions, + typeAcquisition, + unresolvedImports + }; + const typingFiles = !typeAcquisition || !typeAcquisition.enable ? emptyArray2 : toSorted(newTypings); if (enumerateInsertsAndDeletes( typingFiles, this.typingFiles, @@ -278116,12 +278936,10 @@ var Project3 = class _Project { this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(this); } } - /** @internal */ closeWatchingTypingLocations() { if (this.typingWatchers) clearMap(this.typingWatchers, closeFileWatcher); this.typingWatchers = void 0; } - /** @internal */ onTypingInstallerWatchInvoke() { this.typingWatchers.isInvoked = true; this.projectService.updateTypingsForProject({ projectName: this.getProjectName(), kind: ActionInvalidate }); @@ -278199,8 +279017,9 @@ var Project3 = class _Project { return this.program; } removeExistingTypings(include) { + if (!include.length) return include; const existing = getAutomaticTypeDirectiveNames(this.getCompilerOptions(), this.directoryStructureHost); - return include.filter((i) => !existing.includes(i)); + return filter(include, (i) => !existing.includes(i)); } updateGraphWorker() { var _a, _b; @@ -278224,30 +279043,6 @@ var Project3 = class _Project { let hasNewProgram = false; if (this.program && (!oldProgram || this.program !== oldProgram && this.program.structureIsReused !== 2 /* Completely */)) { hasNewProgram = true; - if (oldProgram) { - for (const f of oldProgram.getSourceFiles()) { - const newFile = this.program.getSourceFileByPath(f.resolvedPath); - if (!newFile || f.resolvedPath === f.path && newFile.resolvedPath !== f.path) { - this.detachScriptInfoFromProject( - f.fileName, - !!this.program.getSourceFileByPath(f.path), - /*syncDirWatcherRemove*/ - true - ); - } - } - oldProgram.forEachResolvedProjectReference((resolvedProjectReference) => { - if (!this.program.getResolvedProjectReferenceByPath(resolvedProjectReference.sourceFile.path)) { - this.detachScriptInfoFromProject( - resolvedProjectReference.sourceFile.fileName, - /*noRemoveResolution*/ - void 0, - /*syncDirWatcherRemove*/ - true - ); - } - }); - } this.rootFilesMap.forEach((value, path) => { var _a2; const file = this.program.getSourceFileByPath(path); @@ -278372,12 +279167,12 @@ var Project3 = class _Project { sendPerformanceEvent(kind, durationMs) { this.projectService.sendPerformanceEvent(kind, durationMs); } - detachScriptInfoFromProject(uncheckedFileName, noRemoveResolution, syncDirWatcherRemove) { + detachScriptInfoFromProject(uncheckedFileName, noRemoveResolution) { const scriptInfoToDetach = this.projectService.getScriptInfo(uncheckedFileName); if (scriptInfoToDetach) { scriptInfoToDetach.detachFromProject(this); if (!noRemoveResolution) { - this.resolutionCache.removeResolutionsOfFile(scriptInfoToDetach.path, syncDirWatcherRemove); + this.resolutionCache.removeResolutionsOfFile(scriptInfoToDetach.path); } } } @@ -278477,7 +279272,6 @@ var Project3 = class _Project { false ); } - /** @internal */ filesToStringWorker(writeProjectFileNames, writeFileExplaination, writeFileVersionAndText) { if (this.isInitialLoadPending()) return " Files (0) InitialLoadPending\n"; if (!this.program) return " Files (0) NoProgram\n"; @@ -278811,7 +279605,6 @@ var Project3 = class _Project { (_c = tracing) == null ? void 0 : _c.pop(); } } - /** @internal */ isDefaultProjectForOpenFiles() { return !!forEachEntry( this.projectService.openFiles, @@ -278843,16 +279636,15 @@ var Project3 = class _Project { var _a, _b, _c, _d; const originalProgram = this.program; const rootSourceFile = Debug.checkDefined((_a = this.program) == null ? void 0 : _a.getSourceFile(rootFile), "Expected file to be part of program"); - const originalText = Debug.checkDefined(rootSourceFile.getText()); + const originalText = Debug.checkDefined(rootSourceFile.getFullText()); (_b = this.getScriptInfo(rootFile)) == null ? void 0 : _b.editContent(0, originalText.length, updatedText); this.updateGraph(); try { cb(this.program, originalProgram, (_c = this.program) == null ? void 0 : _c.getSourceFile(rootFile)); } finally { - (_d = this.getScriptInfo(rootFile)) == null ? void 0 : _d.editContent(0, this.program.getSourceFile(rootFile).getText().length, originalText); + (_d = this.getScriptInfo(rootFile)) == null ? void 0 : _d.editContent(0, updatedText.length, originalText); } } - /** @internal */ getCompilerOptionsForNoDtsResolutionProject() { return { ...this.getCompilerOptions(), @@ -278893,7 +279685,7 @@ function extractUnresolvedImportsFromSourceFile(program, file, ambientModules, c return unresolvedImports || emptyArray2; }); } -var InferredProject2 = class extends Project3 { +var InferredProject2 = class extends Project2 { /** @internal */ constructor(projectService, documentRegistry, compilerOptions, watchOptions, projectRootPath, currentDirectory, typeAcquisition) { super( @@ -278987,7 +279779,7 @@ var InferredProject2 = class extends Project3 { }; } }; -var AuxiliaryProject = class extends Project3 { +var AuxiliaryProject = class extends Project2 { constructor(projectService, documentRegistry, compilerOptions, currentDirectory) { super( projectService.newAuxiliaryProjectName(), @@ -279014,7 +279806,7 @@ var AuxiliaryProject = class extends Project3 { return; } }; -var _AutoImportProviderProject = class _AutoImportProviderProject extends Project3 { +var _AutoImportProviderProject = class _AutoImportProviderProject extends Project2 { /** @internal */ constructor(hostProject, initialRootNames, documentRegistry, compilerOptions) { super( @@ -279270,7 +280062,6 @@ var _AutoImportProviderProject = class _AutoImportProviderProject extends Projec return (_a = this.hostProject.getCurrentProgram()) == null ? void 0 : _a.getModuleResolutionCache(); } }; -/** @internal */ _AutoImportProviderProject.maxDependencies = 10; /** @internal */ _AutoImportProviderProject.compilerOptionsOverrides = { @@ -279282,7 +280073,7 @@ _AutoImportProviderProject.compilerOptionsOverrides = { noLib: true }; var AutoImportProviderProject = _AutoImportProviderProject; -var ConfiguredProject2 = class extends Project3 { +var ConfiguredProject2 = class extends Project2 { /** @internal */ constructor(configFileName, canonicalConfigFilePath, projectService, documentRegistry, cachedDirectoryStructureHost, pendingUpdateReason) { super( @@ -279345,7 +280136,6 @@ var ConfiguredProject2 = class extends Project3 { onReleaseParsedCommandLine(fileName) { this.releaseParsedConfig(asNormalizedPath(this.projectService.toCanonicalFileName(asNormalizedPath(normalizePath(fileName))))); } - /** @internal */ releaseParsedConfig(canonicalConfigFilePath) { this.projectService.stopWatchingWildCards(canonicalConfigFilePath, this); this.projectService.releaseParsedConfig(canonicalConfigFilePath, this); @@ -279404,29 +280194,6 @@ var ConfiguredProject2 = class extends Project3 { return this.projectReferences; } updateReferences(refs) { - if (typeof process.versions.pnp !== `undefined`) { - const basePath = this.getCurrentDirectory(); - const getPnpPath = (path) => { - try { - const pnpApi = getPnpApi(`${path}/`); - if (!pnpApi) { - return path; - } - const targetLocator = pnpApi.findPackageLocator(`${path}/`); - const { packageLocation } = pnpApi.getPackageInformation(targetLocator); - const request = combinePaths(targetLocator.name, getRelativePathFromDirectory( - packageLocation, - path, - /*ignoreCase*/ - false - )); - return pnpApi.resolveToUnqualified(request, `${basePath}/`); - } catch { - return path; - } - }; - refs = refs == null ? void 0 : refs.map((r) => ({ ...r, path: getPnpPath(r.path) })); - } this.projectReferences = refs; this.potentialProjectReferences = void 0; } @@ -279511,7 +280278,7 @@ var ConfiguredProject2 = class extends Project3 { updateErrorForNoInputFiles(fileNames, this.getConfigFilePath(), this.getCompilerOptions().configFile.configFileSpecs, this.projectErrors, this.canConfigFileJsonReportNoInputFiles); } }; -var ExternalProject = class extends Project3 { +var ExternalProject = class extends Project2 { /** @internal */ constructor(externalProjectName, projectService, documentRegistry, compilerOptions, lastFileExceededProgramSize, compileOnSaveEnabled, projectFilePath, watchOptions) { super( @@ -279718,6 +280485,16 @@ function findProjectByName(projectName, projects) { } } } +var nullTypingsInstaller = { + isKnownTypesPackageName: returnFalse, + // Should never be called because we never provide a types registry. + installPackage: notImplemented, + enqueueInstallTypingsRequest: noop, + attach: noop, + onProjectClosed: noop, + globalTypingsCacheLocation: void 0 + // TODO: GH#18217 +}; var noopConfigFileWatcher = { close: noop }; function getConfigFileNameFromCache(info, cache) { if (!cache || isAncestorConfigFileInfo(info)) return void 0; @@ -279916,8 +280693,11 @@ function createProjectNameFactoryWithCounter(nameFactory) { function getHostWatcherMap() { return { idToCallbacks: /* @__PURE__ */ new Map(), pathToId: /* @__PURE__ */ new Map() }; } +function getCanUseWatchEvents(service, canUseWatchEvents) { + return !!canUseWatchEvents && !!service.eventHandler && !!service.session; +} function createWatchFactoryHostUsingWatchEvents(service, canUseWatchEvents) { - if (!canUseWatchEvents || !service.eventHandler || !service.session) return void 0; + if (!getCanUseWatchEvents(service, canUseWatchEvents)) return void 0; const watchedFiles = getHostWatcherMap(); const watchedDirectories = getHostWatcherMap(); const watchedDirectoriesRecursive = getHostWatcherMap(); @@ -280075,9 +280855,7 @@ var _ProjectService = class _ProjectService { this.pendingEnsureProjectForOpenFiles = false; /** Tracks projects that we have already sent telemetry for. */ this.seenProjects = /* @__PURE__ */ new Map(); - /** @internal */ this.sharedExtendedConfigFileWatchers = /* @__PURE__ */ new Map(); - /** @internal */ this.extendedConfigCache = /* @__PURE__ */ new Map(); /** @internal */ this.baseline = noop; @@ -280121,7 +280899,6 @@ var _ProjectService = class _ProjectService { this.logger.info("No types map provided; using the default"); } this.typingsInstaller.attach(this); - this.typingsCache = new TypingsCache(this.typingsInstaller); this.hostConfiguration = { formatCodeOptions: getDefaultFormatCodeSettings(this.host.newLine), preferences: emptyOptions, @@ -280141,7 +280918,7 @@ var _ProjectService = class _ProjectService { log, getDetailWatchInfo ); - this.pnpWatcher = this.watchPnpFile(); + this.canUseWatchEvents = getCanUseWatchEvents(this, opts.canUseWatchEvents); (_a = opts.incrementalVerifier) == null ? void 0 : _a.call(opts, this); } toPath(fileName) { @@ -280215,12 +280992,15 @@ var _ProjectService = class _ProjectService { } switch (response.kind) { case ActionSet: - project.updateTypingFiles(this.typingsCache.updateTypingsForProject(response.projectName, response.compilerOptions, response.typeAcquisition, response.unresolvedImports, response.typings)); + project.updateTypingFiles( + response.compilerOptions, + response.typeAcquisition, + response.unresolvedImports, + response.typings + ); return; case ActionInvalidate: - this.typingsCache.enqueueInstallTypingsForProject( - project, - project.lastCachedUnresolvedImportsList, + project.enqueueInstallTypingsForProject( /*forceRefresh*/ true ); @@ -280533,65 +281313,17 @@ var _ProjectService = class _ProjectService { } /** * This is to watch whenever files are added or removed to the wildcard directories - * - * @internal */ watchWildcardDirectory(directory, flags, configFileName, config) { let watcher = this.watchFactory.watchDirectory( directory, - (fileOrDirectory) => { - const fileOrDirectoryPath = this.toPath(fileOrDirectory); - const fsResult = config.cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); - if (getBaseFileName(fileOrDirectoryPath) === "package.json" && !isInsideNodeModules(fileOrDirectoryPath) && (fsResult && fsResult.fileExists || !fsResult && this.host.fileExists(fileOrDirectory))) { - const file = this.getNormalizedAbsolutePath(fileOrDirectory); - this.logger.info(`Config: ${configFileName} Detected new package.json: ${file}`); - this.packageJsonCache.addOrUpdate(file, fileOrDirectoryPath); - this.watchPackageJsonFile(file, fileOrDirectoryPath, result); - } - const configuredProjectForConfig = this.findConfiguredProjectByProjectName(configFileName); - if (isIgnoredFileFromWildCardWatching({ - watchedDirPath: this.toPath(directory), - fileOrDirectory, - fileOrDirectoryPath, - configFileName, - extraFileExtensions: this.hostConfiguration.extraFileExtensions, - currentDirectory: this.currentDirectory, - options: config.parsedCommandLine.options, - program: (configuredProjectForConfig == null ? void 0 : configuredProjectForConfig.getCurrentProgram()) || config.parsedCommandLine.fileNames, - useCaseSensitiveFileNames: this.host.useCaseSensitiveFileNames, - writeLog: (s) => this.logger.info(s), - toPath: (s) => this.toPath(s), - getScriptKind: configuredProjectForConfig ? (fileName) => configuredProjectForConfig.getScriptKind(fileName) : void 0 - })) return; - if (config.updateLevel !== 2 /* Full */) config.updateLevel = 1 /* RootNamesAndUpdate */; - config.projects.forEach((watchWildcardDirectories, projectCanonicalPath) => { - var _a; - if (!watchWildcardDirectories) return; - const project = this.getConfiguredProjectByCanonicalConfigFilePath(projectCanonicalPath); - if (!project) return; - if (configuredProjectForConfig !== project && this.getHostPreferences().includeCompletionsForModuleExports) { - const path = this.toPath(configFileName); - if (find((_a = project.getCurrentProgram()) == null ? void 0 : _a.getResolvedProjectReferences(), (ref) => (ref == null ? void 0 : ref.sourceFile.path) === path)) { - project.markAutoImportProviderAsDirty(); - } - } - const updateLevel = configuredProjectForConfig === project ? 1 /* RootNamesAndUpdate */ : 0 /* Update */; - if (project.pendingUpdateLevel > updateLevel) return; - if (this.openFiles.has(fileOrDirectoryPath)) { - const info = Debug.checkDefined(this.getScriptInfoForPath(fileOrDirectoryPath)); - if (info.isAttached(project)) { - const loadLevelToSet = Math.max(updateLevel, project.openFileWatchTriggered.get(fileOrDirectoryPath) || 0 /* Update */); - project.openFileWatchTriggered.set(fileOrDirectoryPath, loadLevelToSet); - } else { - project.pendingUpdateLevel = updateLevel; - this.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(project); - } - } else { - project.pendingUpdateLevel = updateLevel; - this.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(project); - } - }); - }, + (fileOrDirectory) => this.onWildCardDirectoryWatcherInvoke( + directory, + configFileName, + config, + result, + fileOrDirectory + ), flags, this.getWatchOptionsFromProjectWatchOptions(config.parsedCommandLine.watchOptions, getDirectoryPath(configFileName)), WatchType.WildcardDirectory, @@ -280614,7 +281346,62 @@ var _ProjectService = class _ProjectService { }; return result; } - /** @internal */ + onWildCardDirectoryWatcherInvoke(directory, configFileName, config, wildCardWatcher, fileOrDirectory) { + const fileOrDirectoryPath = this.toPath(fileOrDirectory); + const fsResult = config.cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + if (getBaseFileName(fileOrDirectoryPath) === "package.json" && !isInsideNodeModules(fileOrDirectoryPath) && (fsResult && fsResult.fileExists || !fsResult && this.host.fileExists(fileOrDirectory))) { + const file = this.getNormalizedAbsolutePath(fileOrDirectory); + this.logger.info(`Config: ${configFileName} Detected new package.json: ${file}`); + this.packageJsonCache.addOrUpdate(file, fileOrDirectoryPath); + this.watchPackageJsonFile(file, fileOrDirectoryPath, wildCardWatcher); + } + if (!(fsResult == null ? void 0 : fsResult.fileExists)) { + this.sendSourceFileChange(fileOrDirectoryPath); + } + const configuredProjectForConfig = this.findConfiguredProjectByProjectName(configFileName); + if (isIgnoredFileFromWildCardWatching({ + watchedDirPath: this.toPath(directory), + fileOrDirectory, + fileOrDirectoryPath, + configFileName, + extraFileExtensions: this.hostConfiguration.extraFileExtensions, + currentDirectory: this.currentDirectory, + options: config.parsedCommandLine.options, + program: (configuredProjectForConfig == null ? void 0 : configuredProjectForConfig.getCurrentProgram()) || config.parsedCommandLine.fileNames, + useCaseSensitiveFileNames: this.host.useCaseSensitiveFileNames, + writeLog: (s) => this.logger.info(s), + toPath: (s) => this.toPath(s), + getScriptKind: configuredProjectForConfig ? (fileName) => configuredProjectForConfig.getScriptKind(fileName) : void 0 + })) return; + if (config.updateLevel !== 2 /* Full */) config.updateLevel = 1 /* RootNamesAndUpdate */; + config.projects.forEach((watchWildcardDirectories, projectCanonicalPath) => { + var _a; + if (!watchWildcardDirectories) return; + const project = this.getConfiguredProjectByCanonicalConfigFilePath(projectCanonicalPath); + if (!project) return; + if (configuredProjectForConfig !== project && this.getHostPreferences().includeCompletionsForModuleExports) { + const path = this.toPath(configFileName); + if (find((_a = project.getCurrentProgram()) == null ? void 0 : _a.getResolvedProjectReferences(), (ref) => (ref == null ? void 0 : ref.sourceFile.path) === path)) { + project.markAutoImportProviderAsDirty(); + } + } + const updateLevel = configuredProjectForConfig === project ? 1 /* RootNamesAndUpdate */ : 0 /* Update */; + if (project.pendingUpdateLevel > updateLevel) return; + if (this.openFiles.has(fileOrDirectoryPath)) { + const info = Debug.checkDefined(this.getScriptInfoForPath(fileOrDirectoryPath)); + if (info.isAttached(project)) { + const loadLevelToSet = Math.max(updateLevel, project.openFileWatchTriggered.get(fileOrDirectoryPath) || 0 /* Update */); + project.openFileWatchTriggered.set(fileOrDirectoryPath, loadLevelToSet); + } else { + project.pendingUpdateLevel = updateLevel; + this.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(project); + } + } else { + project.pendingUpdateLevel = updateLevel; + this.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(project); + } + }); + } delayUpdateProjectsFromParsedConfigOnConfigFileChange(canonicalConfigFilePath, loadReason) { const configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); if (!(configFileExistenceInfo == null ? void 0 : configFileExistenceInfo.config)) return false; @@ -280642,7 +281429,6 @@ var _ProjectService = class _ProjectService { }); return scheduledAnyProjectUpdate; } - /** @internal */ onConfigFileChanged(configFileName, canonicalConfigFilePath, eventKind) { const configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); const project = this.getConfiguredProjectByCanonicalConfigFilePath(canonicalConfigFilePath); @@ -280864,7 +281650,6 @@ var _ProjectService = class _ProjectService { this.configFileExistenceInfoCache.set(canonicalConfigFilePath, { exists, openFilesImpactedByConfigFile }); return exists; } - /** @internal */ createConfigFileWatcherForParsedConfig(configFileName, canonicalConfigFilePath, forProject) { var _a, _b; const configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); @@ -281205,8 +281990,6 @@ var _ProjectService = class _ProjectService { } /** * Read the config file of the project, and update the project root file names. - * - * @internal */ loadConfiguredProject(project, reason) { var _a, _b; @@ -281458,7 +282241,6 @@ var _ProjectService = class _ProjectService { project.markAsDirty(); return project.updateGraph(); } - /** @internal */ reloadFileNamesOfParsedConfig(configFileName, config) { if (config.updateLevel === void 0) return config.parsedCommandLine.fileNames; Debug.assert(config.updateLevel === 1 /* RootNamesAndUpdate */); @@ -281503,7 +282285,6 @@ var _ProjectService = class _ProjectService { true ); } - /** @internal */ clearSemanticCache(project) { project.originalConfiguredProjects = void 0; project.resolutionCache.clear(); @@ -282024,7 +282805,7 @@ Dynamic files must always be opened with service's current directory or service this.performanceEventHandler = performanceEventHandler; } setHostConfiguration(args) { - var _a, _b; + var _a; if (args.file) { const info = this.getScriptInfoForNormalizedPath(toNormalizedPath(args.file)); if (info) { @@ -282073,8 +282854,6 @@ Dynamic files must always be opened with service's current directory or service this.hostConfiguration.watchOptions = substitution; this.hostConfiguration.beforeSubstitution = substitution === watchOptions ? void 0 : watchOptions; this.logger.info(`Host watch options changed to ${JSON.stringify(this.hostConfiguration.watchOptions)}, it will be take effect for next watches.`); - (_b = this.pnpWatcher) == null ? void 0 : _b.close(); - this.watchPnpFile(); } } } @@ -282082,7 +282861,6 @@ Dynamic files must always be opened with service's current directory or service getWatchOptions(project) { return this.getWatchOptionsFromProjectWatchOptions(project.getWatchOptions(), project.getCurrentDirectory()); } - /** @internal */ getWatchOptionsFromProjectWatchOptions(projectOptions, basePath) { const hostWatchOptions = !this.hostConfiguration.beforeSubstitution ? this.hostConfiguration.watchOptions : handleWatchOptionsConfigDirTemplateSubstitution( this.hostConfiguration.beforeSubstitution, @@ -282093,20 +282871,34 @@ Dynamic files must always be opened with service's current directory or service closeLog() { this.logger.close(); } - /** - * This function rebuilds the project for every file opened by the client - * This does not reload contents of open files from disk. But we could do that if needed - */ - reloadProjects() { - this.logger.info("reload projects."); + sendSourceFileChange(inPath) { this.filenameToScriptInfo.forEach((info) => { if (this.openFiles.has(info.path)) return; if (!info.fileWatcher) return; + const eventKind = memoize( + () => this.host.fileExists(info.fileName) ? info.deferredDelete ? 0 /* Created */ : 1 /* Changed */ : 2 /* Deleted */ + ); + if (inPath) { + if (isScriptInfoWatchedFromNodeModules(info) || !info.path.startsWith(inPath)) return; + if (eventKind() === 2 /* Deleted */ && info.deferredDelete) return; + this.logger.info(`Invoking sourceFileChange on ${info.fileName}:: ${eventKind()}`); + } this.onSourceFileChanged( info, - this.host.fileExists(info.fileName) ? info.deferredDelete ? 0 /* Created */ : 1 /* Changed */ : 2 /* Deleted */ + eventKind() ); }); + } + /** + * This function rebuilds the project for every file opened by the client + * This does not reload contents of open files from disk. But we could do that if needed + */ + reloadProjects() { + this.logger.info("reload projects."); + this.sendSourceFileChange( + /*inPath*/ + void 0 + ); this.pendingProjectUpdates.forEach((_project, projectName) => { this.throttledOperations.cancel(projectName); this.pendingProjectUpdates.delete(projectName); @@ -282455,12 +283247,12 @@ Dynamic files must always be opened with service's current directory or service } /** @internal */ loadAncestorProjectTree(forProjects) { - forProjects = forProjects || mapDefinedEntries( - this.configuredProjects, - (key, project) => !project.isInitialLoadPending() ? [key, true] : void 0 - ); + forProjects ?? (forProjects = new Set( + mapDefinedIterator(this.configuredProjects.entries(), ([key, project]) => !project.isInitialLoadPending() ? key : void 0) + )); const seenProjects = /* @__PURE__ */ new Set(); - for (const project of arrayFrom(this.configuredProjects.values())) { + const currentConfiguredProjects = arrayFrom(this.configuredProjects.values()); + for (const project of currentConfiguredProjects) { if (forEachPotentialProjectReference(project, (potentialRefPath) => forProjects.has(potentialRefPath))) { updateProjectIfDirty(project); } @@ -282506,8 +283298,38 @@ Dynamic files must always be opened with service's current directory or service } this.removeOrphanScriptInfos(); } + tryInvokeWildCardDirectories(info) { + this.configFileExistenceInfoCache.forEach((configFileExistenceInfo, config) => { + var _a, _b; + if (!((_a = configFileExistenceInfo.config) == null ? void 0 : _a.parsedCommandLine) || contains( + configFileExistenceInfo.config.parsedCommandLine.fileNames, + info.fileName, + !this.host.useCaseSensitiveFileNames ? equateStringsCaseInsensitive : equateStringsCaseSensitive + )) { + return; + } + (_b = configFileExistenceInfo.config.watchedDirectories) == null ? void 0 : _b.forEach((watcher, directory) => { + if (containsPath(directory, info.fileName, !this.host.useCaseSensitiveFileNames)) { + this.logger.info(`Invoking ${config}:: wildcard for open scriptInfo:: ${info.fileName}`); + this.onWildCardDirectoryWatcherInvoke( + directory, + config, + configFileExistenceInfo.config, + watcher.watcher, + info.fileName + ); + } + }); + }); + } openClientFileWithNormalizedPath(fileName, fileContent, scriptKind, hasMixedContent, projectRootPath) { + const existing = this.getScriptInfoForPath(normalizedPathToPath( + fileName, + projectRootPath ? this.getNormalizedAbsolutePath(projectRootPath) : this.currentDirectory, + this.toCanonicalFileName + )); const info = this.getOrCreateOpenScriptInfo(fileName, fileContent, scriptKind, hasMixedContent, projectRootPath); + if (!existing && info && !info.isDynamic) this.tryInvokeWildCardDirectories(info); const { retainProjects, ...result } = this.assignProjectToOpenedScriptInfo(info); this.cleanupProjectsAndScriptInfos( retainProjects, @@ -282654,10 +283476,16 @@ Dynamic files must always be opened with service's current directory or service } /** @internal */ applyChangesInOpenFiles(openFiles, changedFiles, closedFiles) { + let existingOpenScriptInfos; let openScriptInfos; let assignOrphanScriptInfosToInferredProject = false; if (openFiles) { for (const file of openFiles) { + (existingOpenScriptInfos ?? (existingOpenScriptInfos = [])).push(this.getScriptInfoForPath(normalizedPathToPath( + toNormalizedPath(file.fileName), + file.projectRootPath ? this.getNormalizedAbsolutePath(file.projectRootPath) : this.currentDirectory, + this.toCanonicalFileName + ))); const info = this.getOrCreateOpenScriptInfo( toNormalizedPath(file.fileName), file.content, @@ -282685,6 +283513,10 @@ Dynamic files must always be opened with service's current directory or service } } let retainProjects; + forEach( + existingOpenScriptInfos, + (existing, index) => !existing && openScriptInfos[index] && !openScriptInfos[index].isDynamic ? this.tryInvokeWildCardDirectories(openScriptInfos[index]) : void 0 + ); openScriptInfos == null ? void 0 : openScriptInfos.forEach((info) => { var _a; return (_a = this.assignProjectToOpenedScriptInfo(info).retainProjects) == null ? void 0 : _a.forEach((p) => (retainProjects ?? (retainProjects = /* @__PURE__ */ new Set())).add(p)); @@ -282927,12 +283759,12 @@ Dynamic files must always be opened with service's current directory or service return; } this.logger.info(`Enabling plugin ${pluginConfigEntry.name} from candidate paths: ${searchPaths.join(",")}`); - if (!pluginConfigEntry.name || isExternalModuleNameRelative(pluginConfigEntry.name) || /[\\/]\.\.?($|[\\/])/.test(pluginConfigEntry.name)) { + if (!pluginConfigEntry.name || isExternalModuleNameRelative(pluginConfigEntry.name) || /[\\/]\.\.?(?:$|[\\/])/.test(pluginConfigEntry.name)) { this.logger.info(`Skipped loading plugin ${pluginConfigEntry.name || JSON.stringify(pluginConfigEntry)} because only package name is allowed plugin name`); return; } if (this.host.importPlugin) { - const importPromise = Project3.importServicePluginAsync( + const importPromise = Project2.importServicePluginAsync( pluginConfigEntry, searchPaths, this.host, @@ -282946,7 +283778,7 @@ Dynamic files must always be opened with service's current directory or service } this.endEnablePlugin( project, - Project3.importServicePluginSync( + Project2.importServicePluginSync( pluginConfigEntry, searchPaths, this.host, @@ -282956,7 +283788,6 @@ Dynamic files must always be opened with service's current directory or service } /** * Performs the remaining steps of enabling a plugin after its module has been instantiated. - * @internal */ endEnablePlugin(project, { pluginConfigEntry, resolvedModule, errorLogs }) { var _a; @@ -283072,30 +283903,6 @@ Dynamic files must always be opened with service's current directory or service } }); } - /** @internal */ - watchPnpFile() { - const pnpApiPath = getPnpApiPath(__filename); - if (!pnpApiPath) { - return; - } - return this.watchFactory.watchFile( - pnpApiPath, - () => { - this.forEachProject((project) => { - for (const info of project.getScriptInfos()) { - project.resolutionCache.invalidateResolutionOfFile(info.path); - } - project.markAsDirty(); - updateProjectIfDirty(project); - }); - this.delayEnsureProjectForOpenFiles(); - }, - 250 /* Low */, - this.hostConfiguration.watchOptions, - WatchType.ConfigFile - ); - } - /** @internal */ watchPackageJsonFile(file, path, project) { Debug.assert(project !== void 0); let result = (this.packageJsonFilesMap ?? (this.packageJsonFilesMap = /* @__PURE__ */ new Map())).get(path); @@ -283136,7 +283943,6 @@ Dynamic files must always be opened with service's current directory or service result.projects.add(project); (project.packageJsonWatches ?? (project.packageJsonWatches = /* @__PURE__ */ new Set())).add(result); } - /** @internal */ onPackageJsonChange(result) { result.projects.forEach((project) => { var _a; @@ -283161,7 +283967,7 @@ Dynamic files must always be opened with service's current directory or service }; /** Makes a filename safe to insert in a RegExp */ _ProjectService.filenameEscapeRegexp = /[-/\\^$*+?.()|[\]{}]/g; -var ProjectService3 = _ProjectService; +var ProjectService2 = _ProjectService; function createIncompleteCompletionsCache() { let info; return { @@ -283205,6 +284011,8 @@ function createModuleSpecifierCache(host) { kind, modulePaths, moduleSpecifiers, + /*packageName*/ + void 0, /*isBlockedByPackageJsonDependencies*/ false )); @@ -283235,16 +284043,19 @@ function createModuleSpecifierCache(host) { modulePaths, /*moduleSpecifiers*/ void 0, + /*packageName*/ + void 0, /*isBlockedByPackageJsonDependencies*/ void 0 )); } }, - setBlockedByPackageJsonDependencies(fromFileName, toFileName2, preferences, options, isBlockedByPackageJsonDependencies) { + setBlockedByPackageJsonDependencies(fromFileName, toFileName2, preferences, options, packageName, isBlockedByPackageJsonDependencies) { const cache2 = ensureCache(fromFileName, preferences, options); const info = cache2.get(toFileName2); if (info) { info.isBlockedByPackageJsonDependencies = isBlockedByPackageJsonDependencies; + info.packageName = packageName; } else { cache2.set(toFileName2, createInfo( /*kind*/ @@ -283253,6 +284064,7 @@ function createModuleSpecifierCache(host) { void 0, /*moduleSpecifiers*/ void 0, + packageName, isBlockedByPackageJsonDependencies )); } @@ -283282,8 +284094,8 @@ function createModuleSpecifierCache(host) { function key(fromFileName, preferences, options) { return `${fromFileName},${preferences.importModuleSpecifierEnding},${preferences.importModuleSpecifierPreference},${options.overrideImportMode}`; } - function createInfo(kind, modulePaths, moduleSpecifiers, isBlockedByPackageJsonDependencies) { - return { kind, modulePaths, moduleSpecifiers, isBlockedByPackageJsonDependencies }; + function createInfo(kind, modulePaths, moduleSpecifiers, packageName, isBlockedByPackageJsonDependencies) { + return { kind, modulePaths, moduleSpecifiers, packageName, isBlockedByPackageJsonDependencies }; } } @@ -283435,11 +284247,12 @@ var MultistepOperation = class { } complete() { if (this.requestId !== void 0) { - this.operationHost.sendRequestCompletedEvent(this.requestId); + this.operationHost.sendRequestCompletedEvent(this.requestId, this.performanceData); this.requestId = void 0; } this.setTimerHandle(void 0); this.setImmediateId(void 0); + this.performanceData = void 0; } immediate(actionType, action) { const requestId = this.requestId; @@ -283447,7 +284260,7 @@ var MultistepOperation = class { this.setImmediateId( this.operationHost.getServerHost().setImmediate(() => { this.immediateId = void 0; - this.operationHost.executeWithRequestId(requestId, () => this.executeAction(action)); + this.operationHost.executeWithRequestId(requestId, () => this.executeAction(action), this.performanceData); }, actionType) ); } @@ -283458,7 +284271,7 @@ var MultistepOperation = class { this.operationHost.getServerHost().setTimeout( () => { this.timerHandle = void 0; - this.operationHost.executeWithRequestId(requestId, () => this.executeAction(action)); + this.operationHost.executeWithRequestId(requestId, () => this.executeAction(action), this.performanceData); }, ms, actionType @@ -283487,6 +284300,7 @@ var MultistepOperation = class { this.operationHost.logError(e, `delayed processing of request ${this.requestId}`); } } + this.performanceData = this.operationHost.getPerformanceData(); if (stop || !this.hasPendingWork()) { this.complete(); } @@ -283840,6 +284654,9 @@ var invalidSyntacticModeCommands = [ var Session3 = class _Session { constructor(opts) { this.changeSeq = 0; + // Minimum number of lines for attempting to use region diagnostics for a file. + /** @internal */ + this.regionDiagLineCountThreshold = 500; this.handlers = new Map(Object.entries({ // TODO(jakebailey): correctly type the handlers ["status" /* Status */]: () => { @@ -283940,7 +284757,10 @@ var Session3 = class _Session { }, ["exit" /* Exit */]: () => { this.exit(); - return this.notRequired(); + return this.notRequired( + /*request*/ + void 0 + ); }, ["definition" /* Definition */]: (request) => { return this.requiredResponse(this.getDefinition( @@ -284032,7 +284852,7 @@ var Session3 = class _Session { // TODO: GH#18217 request.arguments.projectRootPath ? toNormalizedPath(request.arguments.projectRootPath) : void 0 ); - return this.notRequired(); + return this.notRequired(request); }, ["quickinfo" /* Quickinfo */]: (request) => { return this.requiredResponse(this.getQuickInfoWorker( @@ -284182,41 +285002,39 @@ var Session3 = class _Session { }, ["geterr" /* Geterr */]: (request) => { this.errorCheck.startNew((next) => this.getDiagnostics(next, request.arguments.delay, request.arguments.files)); - return this.notRequired(); + return this.notRequired( + /*request*/ + void 0 + ); }, ["geterrForProject" /* GeterrForProject */]: (request) => { this.errorCheck.startNew((next) => this.getDiagnosticsForProject(next, request.arguments.delay, request.arguments.file)); - return this.notRequired(); + return this.notRequired( + /*request*/ + void 0 + ); }, ["change" /* Change */]: (request) => { this.change(request.arguments); - return this.notRequired(); + return this.notRequired(request); }, ["configure" /* Configure */]: (request) => { this.projectService.setHostConfiguration(request.arguments); - this.doOutput( - /*info*/ - void 0, - "configure" /* Configure */, - request.seq, - /*success*/ - true - ); - return this.notRequired(); + return this.notRequired(request); }, ["reload" /* Reload */]: (request) => { - this.reload(request.arguments, request.seq); + this.reload(request.arguments); return this.requiredResponse({ reloadFinished: true }); }, ["saveto" /* Saveto */]: (request) => { const savetoArgs = request.arguments; this.saveToTmp(savetoArgs.file, savetoArgs.tmpfile); - return this.notRequired(); + return this.notRequired(request); }, ["close" /* Close */]: (request) => { const closeArgs = request.arguments; this.closeClientFile(closeArgs.file); - return this.notRequired(); + return this.notRequired(request); }, ["navto" /* Navto */]: (request) => { return this.requiredResponse(this.getNavigateToItems( @@ -284298,9 +285116,9 @@ var Session3 = class _Session { ["projectInfo" /* ProjectInfo */]: (request) => { return this.requiredResponse(this.getProjectInfo(request.arguments)); }, - ["reloadProjects" /* ReloadProjects */]: () => { + ["reloadProjects" /* ReloadProjects */]: (request) => { this.projectService.reloadProjects(); - return this.notRequired(); + return this.notRequired(request); }, ["jsxClosingTag" /* JsxClosingTag */]: (request) => { return this.requiredResponse(this.getJsxClosingTag(request.arguments)); @@ -284395,15 +285213,7 @@ var Session3 = class _Session { }, ["configurePlugin" /* ConfigurePlugin */]: (request) => { this.configurePlugin(request.arguments); - this.doOutput( - /*info*/ - void 0, - "configurePlugin" /* ConfigurePlugin */, - request.seq, - /*success*/ - true - ); - return this.notRequired(); + return this.notRequired(request); }, ["selectionRange" /* SelectionRange */]: (request) => { return this.requiredResponse(this.getSmartSelectionRange( @@ -284503,11 +285313,12 @@ var Session3 = class _Session { const { throttleWaitMilliseconds } = opts; this.eventHandler = this.canUseEvents ? opts.eventHandler || ((event) => this.defaultEventHandler(event)) : void 0; const multistepOperationHost = { - executeWithRequestId: (requestId, action) => this.executeWithRequestId(requestId, action), + executeWithRequestId: (requestId, action, performanceData) => this.executeWithRequestId(requestId, action, performanceData), getCurrentRequestId: () => this.currentRequestId, + getPerformanceData: () => this.performanceData, getServerHost: () => this.host, logError: (err, cmd) => this.logError(err, cmd), - sendRequestCompletedEvent: (requestId) => this.sendRequestCompletedEvent(requestId), + sendRequestCompletedEvent: (requestId, performanceData) => this.sendRequestCompletedEvent(requestId, performanceData), isCancellationRequested: () => this.cancellationToken.isCancellationRequested() }; this.errorCheck = new MultistepOperation(multistepOperationHost); @@ -284530,7 +285341,7 @@ var Session3 = class _Session { canUseWatchEvents: opts.canUseWatchEvents, incrementalVerifier: opts.incrementalVerifier }; - this.projectService = new ProjectService3(settings); + this.projectService = new ProjectService2(settings); this.projectService.setPerformanceEventHandler(this.performanceEventHandler.bind(this)); this.gcTimer = new GcTimer( this.host, @@ -284559,8 +285370,14 @@ var Session3 = class _Session { Debug.assertNever(this.projectService.serverMode); } } - sendRequestCompletedEvent(requestId) { - this.event({ request_seq: requestId }, "requestCompleted"); + sendRequestCompletedEvent(requestId, performanceData) { + this.event( + { + request_seq: requestId, + performanceData: performanceData && toProtocolPerformanceData(performanceData) + }, + "requestCompleted" + ); } addPerformanceData(key, value) { if (!this.performanceData) { @@ -284568,6 +285385,15 @@ var Session3 = class _Session { } this.performanceData[key] = (this.performanceData[key] ?? 0) + value; } + addDiagnosticsPerformanceData(file, kind, duration) { + var _a, _b; + if (!this.performanceData) { + this.performanceData = {}; + } + let fileDiagnosticDuration = (_a = this.performanceData.diagnosticsDuration) == null ? void 0 : _a.get(file); + if (!fileDiagnosticDuration) ((_b = this.performanceData).diagnosticsDuration ?? (_b.diagnosticsDuration = /* @__PURE__ */ new Map())).set(file, fileDiagnosticDuration = {}); + fileDiagnosticDuration[kind] = duration; + } performanceEventHandler(event) { switch (event.kind) { case "UpdateGraph": @@ -284710,23 +285536,21 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter this.writeMessage(msg); } writeMessage(msg) { - var _a; const msgText = formatMessage2(msg, this.logger, this.byteLength, this.host.newLine); - (_a = perfLogger) == null ? void 0 : _a.logEvent(`Response message size: ${msgText.length}`); this.host.write(msgText); } event(body, eventName) { this.send(toEvent(eventName, body)); } /** @internal */ - doOutput(info, cmdName, reqSeq, success, message) { + doOutput(info, cmdName, reqSeq, success, performanceData, message) { const res = { seq: 0, type: "response", command: cmdName, request_seq: reqSeq, success, - performanceData: this.performanceData + performanceData: performanceData && toProtocolPerformanceData(performanceData) }; if (success) { let metadata; @@ -284756,32 +285580,70 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter } semanticCheck(file, project) { var _a, _b; + const diagnosticsStartTime = timestamp(); (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Session, "semanticCheck", { file, configFilePath: project.canonicalConfigFilePath }); const diags = isDeclarationFileInJSOnlyNonConfiguredProject(project, file) ? emptyArray2 : project.getLanguageService().getSemanticDiagnostics(file).filter((d) => !!d.file); - this.sendDiagnosticsEvent(file, project, diags, "semanticDiag"); + this.sendDiagnosticsEvent(file, project, diags, "semanticDiag", diagnosticsStartTime); (_b = tracing) == null ? void 0 : _b.pop(); } syntacticCheck(file, project) { var _a, _b; + const diagnosticsStartTime = timestamp(); (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Session, "syntacticCheck", { file, configFilePath: project.canonicalConfigFilePath }); - this.sendDiagnosticsEvent(file, project, project.getLanguageService().getSyntacticDiagnostics(file), "syntaxDiag"); + this.sendDiagnosticsEvent(file, project, project.getLanguageService().getSyntacticDiagnostics(file), "syntaxDiag", diagnosticsStartTime); (_b = tracing) == null ? void 0 : _b.pop(); } suggestionCheck(file, project) { var _a, _b; + const diagnosticsStartTime = timestamp(); (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Session, "suggestionCheck", { file, configFilePath: project.canonicalConfigFilePath }); - this.sendDiagnosticsEvent(file, project, project.getLanguageService().getSuggestionDiagnostics(file), "suggestionDiag"); + this.sendDiagnosticsEvent(file, project, project.getLanguageService().getSuggestionDiagnostics(file), "suggestionDiag", diagnosticsStartTime); (_b = tracing) == null ? void 0 : _b.pop(); } - sendDiagnosticsEvent(file, project, diagnostics, kind) { + regionSemanticCheck(file, project, ranges) { + var _a, _b, _c; + const diagnosticsStartTime = timestamp(); + (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Session, "regionSemanticCheck", { file, configFilePath: project.canonicalConfigFilePath }); + let diagnosticsResult; + if (!this.shouldDoRegionCheck(file) || !(diagnosticsResult = project.getLanguageService().getRegionSemanticDiagnostics(file, ranges))) { + (_b = tracing) == null ? void 0 : _b.pop(); + return; + } + this.sendDiagnosticsEvent(file, project, diagnosticsResult.diagnostics, "regionSemanticDiag", diagnosticsStartTime, diagnosticsResult.spans); + (_c = tracing) == null ? void 0 : _c.pop(); + return; + } + // We should only do the region-based semantic check if we think it would be + // considerably faster than a whole-file semantic check. + /** @internal */ + shouldDoRegionCheck(file) { + var _a; + const lineCount = (_a = this.projectService.getScriptInfoForNormalizedPath(file)) == null ? void 0 : _a.textStorage.getLineInfo().getLineCount(); + return !!(lineCount && lineCount >= this.regionDiagLineCountThreshold); + } + sendDiagnosticsEvent(file, project, diagnostics, kind, diagnosticsStartTime, spans) { try { - this.event({ file, diagnostics: diagnostics.map((diag2) => formatDiag(file, project, diag2)) }, kind); + const scriptInfo = Debug.checkDefined(project.getScriptInfo(file)); + const duration = timestamp() - diagnosticsStartTime; + const body = { + file, + diagnostics: diagnostics.map((diag2) => formatDiag(file, project, diag2)), + spans: spans == null ? void 0 : spans.map((span) => toProtocolTextSpan(span, scriptInfo)) + }; + this.event( + body, + kind + ); + this.addDiagnosticsPerformanceData(file, kind, duration); } catch (err) { this.logError(err, kind); } } /** It is the caller's responsibility to verify that `!this.suppressDiagnosticEvents`. */ updateErrorCheck(next, checkList, ms, requireOpen = true) { + if (checkList.length === 0) { + return; + } Debug.assert(!this.suppressDiagnosticEvents); const seq = this.changeSeq; const followMs = Math.min(ms, 200); @@ -284789,20 +285651,36 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter const goNext = () => { index++; if (checkList.length > index) { - next.delay("checkOne", followMs, checkOne); + return next.delay("checkOne", followMs, checkOne); } }; + const doSemanticCheck = (fileName, project) => { + this.semanticCheck(fileName, project); + if (this.changeSeq !== seq) { + return; + } + if (this.getPreferences(fileName).disableSuggestions) { + return goNext(); + } + next.immediate("suggestionCheck", () => { + this.suggestionCheck(fileName, project); + goNext(); + }); + }; const checkOne = () => { if (this.changeSeq !== seq) { return; } + let ranges; let item = checkList[index]; if (isString(item)) { item = this.toPendingErrorCheck(item); - if (!item) { - goNext(); - return; - } + } else if ("ranges" in item) { + ranges = item.ranges; + item = this.toPendingErrorCheck(item.file); + } + if (!item) { + return goNext(); } const { fileName, project } = item; updateProjectIfDirty(project); @@ -284814,23 +285692,21 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter return; } if (project.projectService.serverMode !== 0 /* Semantic */) { - goNext(); - return; + return goNext(); } - next.immediate("semanticCheck", () => { - this.semanticCheck(fileName, project); - if (this.changeSeq !== seq) { - return; - } - if (this.getPreferences(fileName).disableSuggestions) { - goNext(); - return; - } - next.immediate("suggestionCheck", () => { - this.suggestionCheck(fileName, project); - goNext(); + if (ranges) { + return next.immediate("regionSemanticCheck", () => { + const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(fileName); + if (scriptInfo) { + this.regionSemanticCheck(fileName, project, ranges.map((range) => this.getRange({ file: fileName, ...range }, scriptInfo))); + } + if (this.changeSeq !== seq) { + return; + } + next.immediate("semanticCheck", () => doSemanticCheck(fileName, project)); }); - }); + } + next.immediate("semanticCheck", () => doSemanticCheck(fileName, project)); }; if (checkList.length > index && this.changeSeq === seq) { next.delay("checkOne", ms, checkOne); @@ -285067,7 +285943,7 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter const packageDirectory = fileName.substring(0, nodeModulesPathParts.packageRootIndex); const packageJsonCache = (_a2 = project.getModuleResolutionCache()) == null ? void 0 : _a2.getPackageJsonInfoCache(); const compilerOptions = project.getCompilationSettings(); - const packageJson = getPackageScopeForPath(getNormalizedAbsolutePath(packageDirectory + "/package.json", project.getCurrentDirectory()), getTemporaryModuleResolutionState(packageJsonCache, project, compilerOptions)); + const packageJson = getPackageScopeForPath(getNormalizedAbsolutePath(packageDirectory, project.getCurrentDirectory()), getTemporaryModuleResolutionState(packageJsonCache, project, compilerOptions)); if (!packageJson) return void 0; const entrypoints = getEntrypointsFromPackageJsonInfo( packageJson, @@ -285751,42 +286627,12 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter const prefix = args.prefix || ""; const entries = mapDefined(completions.entries, (entry) => { if (completions.isMemberCompletion || startsWith(entry.name.toLowerCase(), prefix.toLowerCase())) { - const { - name, - kind: kind2, - kindModifiers, - sortText, - insertText, - filterText, - replacementSpan, - hasAction, - source, - sourceDisplay, - labelDetails, - isSnippet, - isRecommended, - isPackageJsonImport, - isImportStatementCompletion, - data - } = entry; - const convertedSpan = replacementSpan ? toProtocolTextSpan(replacementSpan, scriptInfo) : void 0; + const convertedSpan = entry.replacementSpan ? toProtocolTextSpan(entry.replacementSpan, scriptInfo) : void 0; return { - name, - kind: kind2, - kindModifiers, - sortText, - insertText, - filterText, + ...entry, replacementSpan: convertedSpan, - isSnippet, - hasAction: hasAction || void 0, - source, - sourceDisplay, - labelDetails, - isRecommended, - isPackageJsonImport, - isImportStatementCompletion, - data + hasAction: entry.hasAction || void 0, + symbol: void 0 }; } }); @@ -285909,12 +286755,12 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter const project = this.projectService.tryGetDefaultProjectForFile(fileName); return project && { fileName, project }; } - getDiagnostics(next, delay, fileNames) { + getDiagnostics(next, delay, fileArgs) { if (this.suppressDiagnosticEvents) { return; } - if (fileNames.length > 0) { - this.updateErrorCheck(next, fileNames, delay); + if (fileArgs.length > 0) { + this.updateErrorCheck(next, fileArgs, delay); } } change(args) { @@ -285935,22 +286781,13 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter ); } } - reload(args, reqSeq) { + reload(args) { const file = toNormalizedPath(args.file); const tempFileName = args.tmpfile === void 0 ? void 0 : toNormalizedPath(args.tmpfile); const info = this.projectService.getScriptInfoForNormalizedPath(file); if (info) { this.changeSeq++; - if (info.reloadFromFile(tempFileName)) { - this.doOutput( - /*info*/ - void 0, - "reload" /* Reload */, - reqSeq, - /*success*/ - true - ); - } + info.reloadFromFile(tempFileName); } } saveToTmp(fileName, tempFileName) { @@ -286499,11 +287336,20 @@ ${e.message}`; } exit() { } - notRequired() { - return { responseRequired: false }; + notRequired(request) { + if (request) this.doOutput( + /*info*/ + void 0, + request.command, + request.seq, + /*success*/ + true, + this.performanceData + ); + return { responseRequired: false, performanceData: this.performanceData }; } requiredResponse(response) { - return { response, responseRequired: true }; + return { response, responseRequired: true, performanceData: this.performanceData }; } addProtocolHandler(command, handler) { if (this.handlers.has(command)) { @@ -286521,18 +287367,27 @@ ${e.message}`; this.currentRequestId = void 0; this.cancellationToken.resetRequest(requestId); } - executeWithRequestId(requestId, f) { + // eslint-disable-line @typescript-eslint/unified-signatures + executeWithRequestId(requestId, f, perfomanceData) { + const currentPerformanceData = this.performanceData; try { + this.performanceData = perfomanceData; this.setCurrentRequest(requestId); return f(); } finally { this.resetCurrentRequest(requestId); + this.performanceData = currentPerformanceData; } } executeCommand(request) { const handler = this.handlers.get(request.command); if (handler) { - const response = this.executeWithRequestId(request.seq, () => handler(request)); + const response = this.executeWithRequestId( + request.seq, + () => handler(request), + /*perfomanceData*/ + void 0 + ); this.projectService.enableRequestedPlugins(); return response; } else { @@ -286544,16 +287399,18 @@ ${e.message}`; request.seq, /*success*/ false, + /*performanceData*/ + void 0, `Unrecognized JSON command: ${request.command}` ); return { responseRequired: false }; } } onMessage(message) { - var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k; + var _a, _b, _c, _d, _e, _f, _g; this.gcTimer.scheduleCollect(); - this.performanceData = void 0; let start; + const currentPerformanceData = this.performanceData; if (this.logger.hasLevel(2 /* requestTime */)) { start = this.hrtime(); if (this.logger.hasLevel(3 /* verbose */)) { @@ -286566,16 +287423,15 @@ ${e.message}`; request = this.parseMessage(message); relevantFile = request.arguments && request.arguments.file ? request.arguments : void 0; (_a = tracing) == null ? void 0 : _a.instant(tracing.Phase.Session, "request", { seq: request.seq, command: request.command }); - (_b = perfLogger) == null ? void 0 : _b.logStartCommand("" + request.command, this.toStringMessage(message).substring(0, 100)); - (_c = tracing) == null ? void 0 : _c.push( + (_b = tracing) == null ? void 0 : _b.push( tracing.Phase.Session, "executeCommand", { seq: request.seq, command: request.command }, /*separateBeginAndEnd*/ true ); - const { response, responseRequired } = this.executeCommand(request); - (_d = tracing) == null ? void 0 : _d.pop(); + const { response, responseRequired, performanceData } = this.executeCommand(request); + (_c = tracing) == null ? void 0 : _c.pop(); if (this.logger.hasLevel(2 /* requestTime */)) { const elapsedTime = hrTimeToMilliseconds(this.hrtime(start)).toFixed(4); if (responseRequired) { @@ -286584,15 +287440,15 @@ ${e.message}`; this.logger.perftrc(`${request.seq}::${request.command}: async elapsed time (in milliseconds) ${elapsedTime}`); } } - (_e = perfLogger) == null ? void 0 : _e.logStopCommand("" + request.command, "Success"); - (_f = tracing) == null ? void 0 : _f.instant(tracing.Phase.Session, "response", { seq: request.seq, command: request.command, success: !!response }); + (_d = tracing) == null ? void 0 : _d.instant(tracing.Phase.Session, "response", { seq: request.seq, command: request.command, success: !!response }); if (response) { this.doOutput( response, request.command, request.seq, /*success*/ - true + true, + performanceData ); } else if (responseRequired) { this.doOutput( @@ -286602,26 +287458,26 @@ ${e.message}`; request.seq, /*success*/ false, + performanceData, "No content available." ); } } catch (err) { - (_g = tracing) == null ? void 0 : _g.popAll(); + (_e = tracing) == null ? void 0 : _e.popAll(); if (err instanceof OperationCanceledException) { - (_h = perfLogger) == null ? void 0 : _h.logStopCommand("" + (request && request.command), "Canceled: " + err); - (_i = tracing) == null ? void 0 : _i.instant(tracing.Phase.Session, "commandCanceled", { seq: request == null ? void 0 : request.seq, command: request == null ? void 0 : request.command }); + (_f = tracing) == null ? void 0 : _f.instant(tracing.Phase.Session, "commandCanceled", { seq: request == null ? void 0 : request.seq, command: request == null ? void 0 : request.command }); this.doOutput( { canceled: true }, request.command, request.seq, /*success*/ - true + true, + this.performanceData ); return; } this.logErrorWorker(err, this.toStringMessage(message), relevantFile); - (_j = perfLogger) == null ? void 0 : _j.logStopCommand("" + (request && request.command), "Error: " + err); - (_k = tracing) == null ? void 0 : _k.instant(tracing.Phase.Session, "commandError", { seq: request == null ? void 0 : request.seq, command: request == null ? void 0 : request.command, message: err.message }); + (_g = tracing) == null ? void 0 : _g.instant(tracing.Phase.Session, "commandError", { seq: request == null ? void 0 : request.seq, command: request == null ? void 0 : request.command, message: err.message }); this.doOutput( /*info*/ void 0, @@ -286629,8 +287485,11 @@ ${e.message}`; request ? request.seq : 0, /*success*/ false, + this.performanceData, "Error processing request. " + err.message + "\n" + err.stack ); + } finally { + this.performanceData = currentPerformanceData; } } parseMessage(message) { @@ -286652,6 +287511,10 @@ ${e.message}`; return this.projectService.getHostPreferences(); } }; +function toProtocolPerformanceData(performanceData) { + const diagnosticsDuration = performanceData.diagnosticsDuration && arrayFrom(performanceData.diagnosticsDuration, ([file, data]) => ({ ...data, file })); + return { ...performanceData, diagnosticsDuration }; +} function toProtocolTextSpan(textSpan, scriptInfo) { return { start: scriptInfo.positionToLineOffset(textSpan.start), @@ -287632,20 +288495,19 @@ __export(ts_server_exports4, { LogLevel: () => LogLevel2, Msg: () => Msg, OpenFileInfoTelemetryEvent: () => OpenFileInfoTelemetryEvent, - Project: () => Project3, + Project: () => Project2, ProjectInfoTelemetryEvent: () => ProjectInfoTelemetryEvent, ProjectKind: () => ProjectKind, ProjectLanguageServiceStateEvent: () => ProjectLanguageServiceStateEvent, ProjectLoadingFinishEvent: () => ProjectLoadingFinishEvent, ProjectLoadingStartEvent: () => ProjectLoadingStartEvent, - ProjectService: () => ProjectService3, + ProjectService: () => ProjectService2, ProjectsUpdatedInBackgroundEvent: () => ProjectsUpdatedInBackgroundEvent, ScriptInfo: () => ScriptInfo, ScriptVersionCache: () => ScriptVersionCache, Session: () => Session3, TextStorage: () => TextStorage, ThrottledOperations: () => ThrottledOperations, - TypingsCache: () => TypingsCache, TypingsInstallerAdapter: () => TypingsInstallerAdapter, allFilesAreJsOrDts: () => allFilesAreJsOrDts, allRootFilesAreJsOrDts: () => allRootFilesAreJsOrDts, @@ -287664,7 +288526,6 @@ __export(ts_server_exports4, { createSortedArray: () => createSortedArray2, emptyArray: () => emptyArray2, findArgument: () => findArgument, - forEachResolvedProjectReferenceProject: () => forEachResolvedProjectReferenceProject, formatDiagnosticToProtocol: () => formatDiagnosticToProtocol, formatMessage: () => formatMessage2, getBaseConfigFileName: () => getBaseConfigFileName, @@ -287690,7 +288551,6 @@ __export(ts_server_exports4, { nullCancellationToken: () => nullCancellationToken, nullTypingsInstaller: () => nullTypingsInstaller, protocol: () => ts_server_protocol_exports, - removeSorted: () => removeSorted, stringifyIndented: () => stringifyIndented, toEvent: () => toEvent, toNormalizedPath: () => toNormalizedPath, @@ -295005,6 +295865,7 @@ const get_nx_workspace_files_1 = __nccwpck_require__(27333); const get_context_file_data_1 = __nccwpck_require__(50356); const get_files_in_directory_1 = __nccwpck_require__(52095); const hash_glob_1 = __nccwpck_require__(26613); +const task_history_1 = __nccwpck_require__(39901); const force_shutdown_1 = __nccwpck_require__(36438); const get_sync_generator_changes_1 = __nccwpck_require__(72396); const get_registered_sync_generators_1 = __nccwpck_require__(41015); @@ -295051,9 +295912,11 @@ class DaemonClient { // CI=true,env=undefined => no daemon // CI=true,env=false => no daemon // CI=true,env=true => daemon + // docker=true,env=undefined => no daemon + // docker=true,env=false => no daemon + // docker=true,env=true => daemon // WASM => no daemon because file watching does not work - if (((0, is_ci_1.isCI)() && env !== 'true') || - isDocker() || + if ((((0, is_ci_1.isCI)() || isDocker()) && env !== 'true') || (0, tmp_dir_1.isDaemonDisabled)() || nxJsonIsNotPresent() || (useDaemonProcessOption === undefined && env === 'false') || @@ -295215,16 +296078,16 @@ class DaemonClient { }; return this.sendToDaemonViaQueue(message); } - getTaskHistoryForHashes(hashes) { + getFlakyTasks(hashes) { const message = { - type: 'GET_TASK_HISTORY_FOR_HASHES', + type: task_history_1.GET_FLAKY_TASKS, hashes, }; return this.sendToDaemonViaQueue(message); } - writeTaskRunsToHistory(taskRuns) { + recordTaskRuns(taskRuns) { const message = { - type: 'WRITE_TASK_RUNS_TO_HISTORY', + type: task_history_1.RECORD_TASK_RUNS, taskRuns, }; return this.sendMessageToDaemon(message); @@ -295701,22 +296564,22 @@ function isHandleHashGlobMessage(message) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.WRITE_TASK_RUNS_TO_HISTORY = exports.GET_TASK_HISTORY_FOR_HASHES = void 0; -exports.isHandleGetTaskHistoryForHashesMessage = isHandleGetTaskHistoryForHashesMessage; +exports.RECORD_TASK_RUNS = exports.GET_FLAKY_TASKS = void 0; +exports.isHandleGetFlakyTasksMessage = isHandleGetFlakyTasksMessage; exports.isHandleWriteTaskRunsToHistoryMessage = isHandleWriteTaskRunsToHistoryMessage; -exports.GET_TASK_HISTORY_FOR_HASHES = 'GET_TASK_HISTORY_FOR_HASHES'; -function isHandleGetTaskHistoryForHashesMessage(message) { +exports.GET_FLAKY_TASKS = 'GET_FLAKY_TASKS'; +function isHandleGetFlakyTasksMessage(message) { return (typeof message === 'object' && message !== null && 'type' in message && - message['type'] === exports.GET_TASK_HISTORY_FOR_HASHES); + message['type'] === exports.GET_FLAKY_TASKS); } -exports.WRITE_TASK_RUNS_TO_HISTORY = 'WRITE_TASK_RUNS_TO_HISTORY'; +exports.RECORD_TASK_RUNS = 'RECORD_TASK_RUNS'; function isHandleWriteTaskRunsToHistoryMessage(message) { return (typeof message === 'object' && message !== null && 'type' in message && - message['type'] === exports.WRITE_TASK_RUNS_TO_HISTORY); + message['type'] === exports.RECORD_TASK_RUNS); } @@ -295994,25 +296857,6 @@ async function handleGetSyncGeneratorChanges(generators) { } -/***/ }), - -/***/ 61494: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.handleGetTaskHistoryForHashes = handleGetTaskHistoryForHashes; -const task_history_1 = __nccwpck_require__(83523); -async function handleGetTaskHistoryForHashes(hashes) { - const history = await (0, task_history_1.getHistoryForHashes)(hashes); - return { - response: JSON.stringify(history), - description: 'handleGetTaskHistoryForHashes', - }; -} - - /***/ }), /***/ 22069: @@ -296280,38 +297124,55 @@ async function handleRequestShutdown(server, numberOfConnections) { /***/ }), -/***/ 76914: +/***/ 10563: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.handleUpdateWorkspaceContext = handleUpdateWorkspaceContext; -const project_graph_incremental_recomputation_1 = __nccwpck_require__(96952); -async function handleUpdateWorkspaceContext(createdFiles, updatedFiles, deletedFiles) { - (0, project_graph_incremental_recomputation_1.addUpdatedAndDeletedFiles)(createdFiles, updatedFiles, deletedFiles); +exports.handleRecordTaskRuns = handleRecordTaskRuns; +exports.handleGetFlakyTasks = handleGetFlakyTasks; +const task_history_1 = __nccwpck_require__(83523); +let taskHistory; +function getTaskHistory() { + if (!taskHistory) { + taskHistory = new task_history_1.TaskHistory(); + } + return taskHistory; +} +async function handleRecordTaskRuns(taskRuns) { + const taskHistory = getTaskHistory(); + await taskHistory.recordTaskRuns(taskRuns); return { - response: '{}', - description: 'handleUpdateContextFiles', + response: 'true', + description: 'handleRecordTaskRuns', + }; +} +async function handleGetFlakyTasks(hashes) { + const taskHistory = getTaskHistory(); + const history = await taskHistory.getFlakyTasks(hashes); + return { + response: JSON.stringify(history), + description: 'handleGetFlakyTasks', }; } /***/ }), -/***/ 8340: +/***/ 76914: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.handleWriteTaskRunsToHistory = handleWriteTaskRunsToHistory; -const task_history_1 = __nccwpck_require__(83523); -async function handleWriteTaskRunsToHistory(taskRuns) { - await (0, task_history_1.writeTaskRunsToHistory)(taskRuns); +exports.handleUpdateWorkspaceContext = handleUpdateWorkspaceContext; +const project_graph_incremental_recomputation_1 = __nccwpck_require__(96952); +async function handleUpdateWorkspaceContext(createdFiles, updatedFiles, deletedFiles) { + (0, project_graph_incremental_recomputation_1.addUpdatedAndDeletedFiles)(createdFiles, updatedFiles, deletedFiles); return { - response: 'true', - description: 'handleWriteTaskRunsToHistory', + response: '{}', + description: 'handleUpdateContextFiles', }; } @@ -296856,8 +297717,7 @@ const handle_get_files_in_directory_1 = __nccwpck_require__(63873); const hash_glob_1 = __nccwpck_require__(26613); const handle_hash_glob_1 = __nccwpck_require__(75631); const task_history_1 = __nccwpck_require__(39901); -const handle_get_task_history_1 = __nccwpck_require__(61494); -const handle_write_task_runs_to_history_1 = __nccwpck_require__(8340); +const handle_task_history_1 = __nccwpck_require__(10563); const force_shutdown_1 = __nccwpck_require__(36438); const handle_force_shutdown_1 = __nccwpck_require__(71375); const get_sync_generator_changes_1 = __nccwpck_require__(72396); @@ -296958,11 +297818,11 @@ async function handleMessage(socket, data) { else if ((0, hash_glob_1.isHandleHashGlobMessage)(payload)) { await handleResult(socket, hash_glob_1.HASH_GLOB, () => (0, handle_hash_glob_1.handleHashGlob)(payload.globs, payload.exclude)); } - else if ((0, task_history_1.isHandleGetTaskHistoryForHashesMessage)(payload)) { - await handleResult(socket, 'GET_TASK_HISTORY_FOR_HASHES', () => (0, handle_get_task_history_1.handleGetTaskHistoryForHashes)(payload.hashes)); + else if ((0, task_history_1.isHandleGetFlakyTasksMessage)(payload)) { + await handleResult(socket, 'GET_TASK_HISTORY_FOR_HASHES', () => (0, handle_task_history_1.handleGetFlakyTasks)(payload.hashes)); } else if ((0, task_history_1.isHandleWriteTaskRunsToHistoryMessage)(payload)) { - await handleResult(socket, 'WRITE_TASK_RUNS_TO_HISTORY', () => (0, handle_write_task_runs_to_history_1.handleWriteTaskRunsToHistory)(payload.taskRuns)); + await handleResult(socket, 'WRITE_TASK_RUNS_TO_HISTORY', () => (0, handle_task_history_1.handleRecordTaskRuns)(payload.taskRuns)); } else if ((0, force_shutdown_1.isHandleForceShutdownMessage)(payload)) { await handleResult(socket, 'FORCE_SHUTDOWN', () => (0, handle_force_shutdown_1.handleForceShutdown)(server)); @@ -297176,7 +298036,7 @@ async function startServer() { logger_1.serverLogger.watcherLog(`Subscribed to changes within: ${workspace_root_1.workspaceRoot} (native)`); } if (!(0, shutdown_utils_1.getOutputWatcherInstance)()) { - (0, shutdown_utils_1.storeOutputWatcherInstance)(await (0, watcher_1.watchOutputFiles)(handleOutputsChanges)); + (0, shutdown_utils_1.storeOutputWatcherInstance)(await (0, watcher_1.watchOutputFiles)(server, handleOutputsChanges)); } // listen for project graph recomputation events to collect and schedule sync generators (0, project_graph_incremental_recomputation_1.registerProjectGraphRecomputationListener)(sync_generators_1.collectAndScheduleSyncGenerators); @@ -297305,6 +298165,7 @@ exports.getCachedSyncGeneratorChanges = getCachedSyncGeneratorChanges; exports.flushSyncGeneratorChangesToDisk = flushSyncGeneratorChangesToDisk; exports.collectAndScheduleSyncGenerators = collectAndScheduleSyncGenerators; exports.getCachedRegisteredSyncGenerators = getCachedRegisteredSyncGenerators; +exports._getConflictingGeneratorGroups = _getConflictingGeneratorGroups; const nx_json_1 = __nccwpck_require__(21173); const tree_1 = __nccwpck_require__(10818); const file_hasher_1 = __nccwpck_require__(19482); @@ -297322,10 +298183,10 @@ let registeredSyncGenerators; let scheduledTimeoutId; let storedProjectGraphHash; let storedNxJsonHash; +let storedDisabledTaskSyncGeneratorsHash; const log = (...messageParts) => { logger_1.serverLogger.log('[SYNC]:', ...messageParts); }; -// TODO(leo): check conflicts and reuse the Tree where possible async function getCachedSyncGeneratorChanges(generators) { try { log('get sync generators changes on demand', generators); @@ -297337,51 +298198,15 @@ async function getCachedSyncGeneratorChanges(generators) { } // reset the wait time waitPeriod = 100; - let projects; - let errored = false; - const getProjectsConfigurations = async () => { - if (projects || errored) { - return projects; - } - const { projectGraph, error } = await (0, project_graph_incremental_recomputation_1.getCachedSerializedProjectGraphPromise)(); - projects = projectGraph - ? (0, project_graph_1.readProjectsConfigurationFromProjectGraph)(projectGraph).projects - : null; - errored = error !== undefined; - return projects; - }; - return (await Promise.all(generators.map(async (generator) => { - if (scheduledGenerators.has(generator) || - !syncGeneratorsCacheResultPromises.has(generator)) { - // it's scheduled to run (there are pending changes to process) or - // it's not scheduled and there's no cached result, so run it - const projects = await getProjectsConfigurations(); - if (projects) { - log(generator, 'already scheduled or not cached, running it now'); - runGenerator(generator, projects); - } - else { - log(generator, 'already scheduled or not cached, project graph errored'); - /** - * This should never happen. This is invoked imperatively, and by - * the time it is invoked, the project graph would have already - * been requested. If it errored, it would have been reported and - * this wouldn't have been invoked. We handle it just in case. - * - * Since the project graph would be reported by the relevant - * handlers separately, we just ignore the error, don't cache - * any result and return an empty result, the next time this is - * invoked the process will repeat until it eventually recovers - * when the project graph is fixed. - */ - return Promise.resolve({ changes: [], generatorName: generator }); - } - } - else { - log(generator, 'not scheduled and has cached result, returning cached result'); - } - return syncGeneratorsCacheResultPromises.get(generator); - }))).flat(); + const results = await getFromCacheOrRunGenerators(generators); + const conflicts = _getConflictingGeneratorGroups(results); + if (!conflicts.length) { + // there are no conflicts + return results; + } + // there are conflicts, so we need to re-run the conflicting generators + // using the same tree + return await processConflictingGenerators(conflicts, results); } catch (e) { console.error(e); @@ -297408,6 +298233,10 @@ function collectAndScheduleSyncGenerators(projectGraph) { // a change imply we need to re-run all the generators // make sure to schedule all the collected generators scheduledGenerators.clear(); + if (!registeredSyncGenerators.size) { + // there are no generators to run + return; + } for (const generator of registeredSyncGenerators) { scheduledGenerators.add(generator); } @@ -297427,7 +298256,7 @@ function collectAndScheduleSyncGenerators(projectGraph) { } const { projects } = (0, project_graph_1.readProjectsConfigurationFromProjectGraph)(projectGraph); for (const generator of scheduledGenerators) { - runGenerator(generator, projects); + syncGeneratorsCacheResultPromises.set(generator, runGenerator(generator, projects)); } await Promise.all(syncGeneratorsCacheResultPromises.values()); }, waitPeriod); @@ -297444,17 +298273,177 @@ async function getCachedRegisteredSyncGenerators() { } return [...registeredSyncGenerators]; } +async function getFromCacheOrRunGenerators(generators) { + let projects; + let errored = false; + const getProjectsConfigurations = async () => { + if (projects || errored) { + return projects; + } + const { projectGraph, error } = await (0, project_graph_incremental_recomputation_1.getCachedSerializedProjectGraphPromise)(); + projects = projectGraph + ? (0, project_graph_1.readProjectsConfigurationFromProjectGraph)(projectGraph).projects + : null; + errored = error !== undefined; + return projects; + }; + return (await Promise.all(generators.map(async (generator) => { + if (scheduledGenerators.has(generator) || + !syncGeneratorsCacheResultPromises.has(generator)) { + // it's scheduled to run (there are pending changes to process) or + // it's not scheduled and there's no cached result, so run it + const projects = await getProjectsConfigurations(); + if (projects) { + log(generator, 'already scheduled or not cached, running it now'); + syncGeneratorsCacheResultPromises.set(generator, runGenerator(generator, projects)); + } + else { + log(generator, 'already scheduled or not cached, project graph errored'); + /** + * This should never happen. This is invoked imperatively, and by + * the time it is invoked, the project graph would have already + * been requested. If it errored, it would have been reported and + * this wouldn't have been invoked. We handle it just in case. + * + * Since the project graph would be reported by the relevant + * handlers separately, we just ignore the error, don't cache + * any result and return an empty result, the next time this is + * invoked the process will repeat until it eventually recovers + * when the project graph is fixed. + */ + return Promise.resolve({ changes: [], generatorName: generator }); + } + } + else { + log(generator, 'not scheduled and has cached result, returning cached result'); + } + return syncGeneratorsCacheResultPromises.get(generator); + }))).flat(); +} +async function runConflictingGenerators(tree, generators) { + const { projectGraph } = await (0, project_graph_incremental_recomputation_1.getCachedSerializedProjectGraphPromise)(); + const projects = projectGraph + ? (0, project_graph_1.readProjectsConfigurationFromProjectGraph)(projectGraph).projects + : null; + if (!projects) { + /** + * This should never happen. This is invoked imperatively, and by + * the time it is invoked, the project graph would have already + * been requested. If it errored, it would have been reported and + * this wouldn't have been invoked. We handle it just in case. + * + * Since the project graph would be reported by the relevant + * handlers separately, we just ignore the error. + */ + return generators.map((generator) => ({ + changes: [], + generatorName: generator, + })); + } + // we need to run conflicting generators sequentially because they use the same tree + const results = []; + for (const generator of generators) { + log(generator, 'running it now'); + results.push(await runGenerator(generator, projects, tree)); + } + return results; +} +async function processConflictingGenerators(conflicts, initialResults) { + const conflictRunResults = (await Promise.all(conflicts.map((generators) => { + const [firstGenerator, ...generatorsToRun] = generators; + // it must exists because the conflicts were identified from the initial results + const firstGeneratorResult = initialResults.find((r) => r.generatorName === firstGenerator); + const tree = new tree_1.FsTree(workspace_root_1.workspaceRoot, false, `running sync generators ${generators.join(',')}`); + // pre-apply the changes from the first generator to avoid running it + for (const change of firstGeneratorResult.changes) { + if (change.type === 'CREATE' || change.type === 'UPDATE') { + tree.write(change.path, change.content, change.options); + } + else if (change.type === 'DELETE') { + tree.delete(change.path); + } + } + /** + * We don't cache the results of conflicting generators because they + * use the same tree, so some files might contain results from multiple + * generators and we don't have guarantees that the same combination of + * generators will run together. + */ + return runConflictingGenerators(tree, generatorsToRun); + }))).flat(); + /** + * The order of the results from the re-run generators is important because + * the last result from a group of conflicting generators will contain the + * changes from the previous conflicting generators. So, instead of replacing + * in-place the initial results, we first add the results from the re-run + * generators, and then add the initial results that were not from a + * conflicting generator. + */ + const results = [...conflictRunResults]; + for (const result of initialResults) { + if (conflictRunResults.every((r) => r.generatorName !== result.generatorName)) { + // this result is not from a conflicting generator, so we add it to the + // results + results.push(result); + } + } + return results; +} +/** + * @internal + */ +function _getConflictingGeneratorGroups(results) { + const changedFileToGeneratorMap = new Map(); + for (const result of results) { + for (const change of result.changes) { + if (!changedFileToGeneratorMap.has(change.path)) { + changedFileToGeneratorMap.set(change.path, new Set()); + } + changedFileToGeneratorMap.get(change.path).add(result.generatorName); + } + } + const conflicts = []; + for (const generatorSet of changedFileToGeneratorMap.values()) { + if (generatorSet.size === 1) { + // no conflicts + continue; + } + if (conflicts.length === 0) { + // there are no conflicts yet, so we just add the first group + conflicts.push(new Set(generatorSet)); + continue; + } + // identify if any of the current generator sets intersect with any of the + // existing conflict groups + const generatorsArray = Array.from(generatorSet); + const existingConflictGroup = conflicts.find((group) => generatorsArray.some((generator) => group.has(generator))); + if (existingConflictGroup) { + // there's an intersecting group, so we merge the two + for (const generator of generatorsArray) { + existingConflictGroup.add(generator); + } + } + else { + // there's no intersecting group, so we create a new one + conflicts.push(new Set(generatorsArray)); + } + } + return conflicts.map((group) => Array.from(group)); +} function collectAllRegisteredSyncGenerators(projectGraph) { + const nxJson = (0, nx_json_1.readNxJson)(); const projectGraphHash = hashProjectGraph(projectGraph); - if (storedProjectGraphHash !== projectGraphHash) { + const disabledTaskSyncGeneratorsHash = (0, file_hasher_1.hashArray)(nxJson.sync?.disabledTaskSyncGenerators?.sort() ?? []); + if (projectGraphHash !== storedProjectGraphHash || + disabledTaskSyncGeneratorsHash !== storedDisabledTaskSyncGeneratorsHash) { storedProjectGraphHash = projectGraphHash; + storedDisabledTaskSyncGeneratorsHash = disabledTaskSyncGeneratorsHash; registeredTaskSyncGenerators = - (0, sync_generators_1.collectRegisteredTaskSyncGenerators)(projectGraph); + (0, sync_generators_1.collectEnabledTaskSyncGeneratorsFromProjectGraph)(projectGraph, nxJson); } else { log('project graph hash is the same, not collecting task sync generators'); } - const nxJson = (0, nx_json_1.readNxJson)(); const nxJsonHash = (0, file_hasher_1.hashArray)(nxJson.sync?.globalGenerators?.sort() ?? []); if (storedNxJsonHash !== nxJsonHash) { storedNxJsonHash = nxJsonHash; @@ -297484,16 +298473,15 @@ function collectAllRegisteredSyncGenerators(projectGraph) { } } } -function runGenerator(generator, projects) { +function runGenerator(generator, projects, tree) { log('running scheduled generator', generator); // remove it from the scheduled set scheduledGenerators.delete(generator); - const tree = new tree_1.FsTree(workspace_root_1.workspaceRoot, false, `running sync generator ${generator}`); - // run the generator and cache the result - syncGeneratorsCacheResultPromises.set(generator, (0, sync_generators_1.runSyncGenerator)(tree, generator, projects).then((result) => { + tree ??= new tree_1.FsTree(workspace_root_1.workspaceRoot, false, `running sync generator ${generator}`); + return (0, sync_generators_1.runSyncGenerator)(tree, generator, projects).then((result) => { log(generator, 'changes:', result.changes.map((c) => c.path).join(', ')); return result; - })); + }); } function hashProjectGraph(projectGraph) { const stringifiedProjects = Object.entries(projectGraph.nodes) @@ -297528,21 +298516,12 @@ const ALWAYS_IGNORE = [ ]; async function watchWorkspace(server, cb) { const { Watcher } = await Promise.resolve().then(() => __nccwpck_require__(71926)); - let relativeServerProcess = (0, path_2.normalizePath)((0, path_1.relative)(workspace_root_1.workspaceRoot, cache_1.serverProcessJsonPath)); - let watcher = new Watcher(workspace_root_1.workspaceRoot, [`!${relativeServerProcess}`]); + const watcher = new Watcher(workspace_root_1.workspaceRoot); watcher.watch((err, events) => { if (err) { return cb(err, null); } for (const event of events) { - if (event.path == relativeServerProcess && - (0, cache_1.getDaemonProcessIdSync)() !== process.pid) { - (0, shutdown_utils_1.handleServerProcessTermination)({ - server, - reason: 'this process is no longer the current daemon (native)', - sockets: server_1.openSockets, - }); - } if (event.path.endsWith('.gitignore') || event.path === '.nxignore') { // If the ignore files themselves have changed we need to dynamically update our cached ignoreGlobs (0, shutdown_utils_1.handleServerProcessTermination)({ @@ -297556,13 +298535,24 @@ async function watchWorkspace(server, cb) { }); return watcher; } -async function watchOutputFiles(cb) { +async function watchOutputFiles(server, cb) { const { Watcher } = await Promise.resolve().then(() => __nccwpck_require__(71926)); - let watcher = new Watcher(workspace_root_1.workspaceRoot, null, false); + const relativeServerProcess = (0, path_2.normalizePath)((0, path_1.relative)(workspace_root_1.workspaceRoot, cache_1.serverProcessJsonPath)); + const watcher = new Watcher(workspace_root_1.workspaceRoot, [`!${relativeServerProcess}`], false); watcher.watch((err, events) => { if (err) { return cb(err, null); } + for (const event of events) { + if (event.path == relativeServerProcess && + (0, cache_1.getDaemonProcessIdSync)() !== process.pid) { + return (0, shutdown_utils_1.handleServerProcessTermination)({ + server, + reason: 'this process is no longer the current daemon (native)', + sockets: server_1.openSockets, + }); + } + } if (events.length !== 0) { cb(null, events); } @@ -298917,10 +299907,10 @@ class NodeTaskHasherImpl { this.hashProjectFileset(projectName, projectFilesets), this.hashProjectConfig(projectName), this.hashTsConfig(projectName), - ...[ - ...workspaceFilesets, - ...this.legacyFilesetInputs.map((r) => r.fileset), - ].map((fileset) => this.hashRootFileset(fileset)), + ...(workspaceFilesets.length + ? [this.hashRootFilesets(workspaceFilesets)] + : []), + this.hashRootFilesets(this.legacyFilesetInputs.map((r) => r.fileset)), ...[...notFilesets, ...this.legacyRuntimeInputs].map((r) => r['runtime'] ? this.hashRuntime(env, r['runtime']) : this.hashEnv(env, r['env'])), @@ -298938,22 +299928,40 @@ class NodeTaskHasherImpl { } return Promise.all(partialHashes).then((hashes) => hashes.flat()); } - async hashRootFileset(fileset) { - const mapKey = fileset; - const withoutWorkspaceRoot = fileset.substring(16); + async hashRootFilesets(filesets) { + const mapKey = `workspace:[${filesets.join(',')}]`; if (!this.filesetHashes[mapKey]) { this.filesetHashes[mapKey] = new Promise(async (res) => { const parts = []; - const matchingFile = this.allWorkspaceFiles.find((t) => t.file === withoutWorkspaceRoot); - if (matchingFile) { - parts.push(matchingFile.hash); + const negativePatterns = []; + const positivePatterns = []; + for (const fileset of filesets) { + if (fileset.startsWith('!')) { + negativePatterns.push(fileset.substring(17)); + } + else { + positivePatterns.push(fileset.substring(16)); + } } - else { - this.allWorkspaceFiles - .filter((f) => (0, minimatch_1.minimatch)(f.file, withoutWorkspaceRoot)) - .forEach((f) => { - parts.push(f.hash); - }); + for (const fileset of positivePatterns) { + const withoutWorkspaceRoot = fileset; + // Used to shortcut minimatch if not necessary + const matchingFile = this.allWorkspaceFiles.find((t) => t.file === withoutWorkspaceRoot); + // shortcut because there is a direct match + if (matchingFile) { + if (!negativePatterns.some((p) => (0, minimatch_1.minimatch)(matchingFile.file, p))) { + parts.push(matchingFile.hash); + } + // No direct match, check if pattern matched + } + else { + this.allWorkspaceFiles + .filter((f) => (0, minimatch_1.minimatch)(f.file, withoutWorkspaceRoot) && + !negativePatterns.some((p) => (0, minimatch_1.minimatch)(f.file, p))) + .forEach((f) => { + parts.push(f.hash); + }); + } } const value = (0, file_hasher_1.hashArray)(parts); res({ @@ -299795,22 +300803,28 @@ if (!nativeBinding) { module.exports.ChildProcess = nativeBinding.ChildProcess module.exports.HashPlanner = nativeBinding.HashPlanner module.exports.ImportResult = nativeBinding.ImportResult +module.exports.NxCache = nativeBinding.NxCache +module.exports.NxTaskHistory = nativeBinding.NxTaskHistory module.exports.RustPseudoTerminal = nativeBinding.RustPseudoTerminal +module.exports.TaskDetails = nativeBinding.TaskDetails module.exports.TaskHasher = nativeBinding.TaskHasher module.exports.Watcher = nativeBinding.Watcher module.exports.WorkspaceContext = nativeBinding.WorkspaceContext +module.exports.connectToNxDb = nativeBinding.connectToNxDb module.exports.copy = nativeBinding.copy module.exports.EventType = nativeBinding.EventType module.exports.expandOutputs = nativeBinding.expandOutputs module.exports.findImports = nativeBinding.findImports module.exports.getBinaryTarget = nativeBinding.getBinaryTarget module.exports.getFilesForOutputs = nativeBinding.getFilesForOutputs +module.exports.getTransformableOutputs = nativeBinding.getTransformableOutputs module.exports.hashArray = nativeBinding.hashArray module.exports.hashFile = nativeBinding.hashFile module.exports.IS_WASM = nativeBinding.IS_WASM module.exports.remove = nativeBinding.remove module.exports.testOnlyTransferFileMap = nativeBinding.testOnlyTransferFileMap module.exports.transferProjectGraph = nativeBinding.transferProjectGraph +module.exports.validateOutputs = nativeBinding.validateOutputs module.exports.WorkspaceErrors = nativeBinding.WorkspaceErrors @@ -300528,7 +301542,7 @@ function buildProjectConfigurationFromPackageJson(packageJson, workspaceRoot, pa sourceRoot: projectRoot, name, ...packageJson.nx, - targets: (0, package_json_1.readTargetsFromPackageJson)(packageJson), + targets: (0, package_json_1.readTargetsFromPackageJson)(packageJson, nxJson), tags: (0, package_json_1.getTagsFromPackageJson)(packageJson), metadata: (0, package_json_1.getMetadataFromPackageJson)(packageJson), }; @@ -302273,7 +303287,7 @@ async function startPluginWorker() { socket, }); } - else if (attempts > 1000) { + else if (attempts > 10000) { // daemon fails to start, the process probably exited // we print the logs and exit the client reject('Failed to start plugin worker.'); @@ -304405,6 +305419,7 @@ const project_graph_1 = __nccwpck_require__(54913); const find_matching_projects_1 = __nccwpck_require__(50630); const minimatch_1 = __nccwpck_require__(62362); const globs_1 = __nccwpck_require__(30699); +const native_1 = __nccwpck_require__(71926); function getDependencyConfigs({ project, target }, extraTargetDependencies, projectGraph, allTargetNames) { const dependencyConfigs = (projectGraph.nodes[project].data?.targets[target]?.dependsOn ?? // This is passed into `run-command` from programmatic invocations @@ -304545,19 +305560,15 @@ function assertOutputsAreValidType(outputs) { } function validateOutputs(outputs) { assertOutputsAreValidType(outputs); - const invalidOutputs = new Set(); - for (const output of outputs) { - if (!/^!?{[\s\S]+}/.test(output)) { - invalidOutputs.add(output); - } - } - if (invalidOutputs.size > 0) { - throw new InvalidOutputsError(outputs, invalidOutputs); - } + (0, native_1.validateOutputs)(outputs); } -function transformLegacyOutputs(projectRoot, error) { - return error.outputs.map((output) => { - if (!error.invalidOutputs.has(output)) { +function transformLegacyOutputs(projectRoot, outputs) { + const transformableOutputs = new Set((0, native_1.getTransformableOutputs)(outputs)); + if (transformableOutputs.size === 0) { + return outputs; + } + return outputs.map((output) => { + if (!transformableOutputs.has(output)) { return output; } let [isNegated, outputPath] = output.startsWith('!') @@ -304865,6 +305876,7 @@ function detectAndSetInvalidProjectGlobValues(map, sourceName, desiredImplicitDe Object.defineProperty(exports, "__esModule", ({ value: true })); exports.workspaceDataDirectory = exports.cacheDir = void 0; exports.cacheDirectoryForWorkspace = cacheDirectoryForWorkspace; +exports.workspaceDataDirectoryForWorkspace = workspaceDataDirectoryForWorkspace; const fs_1 = __nccwpck_require__(57147); const path_1 = __nccwpck_require__(71017); const fileutils_1 = __nccwpck_require__(40910); @@ -304925,9 +305937,12 @@ exports.cacheDir = cacheDirectory(workspace_root_1.workspaceRoot, readCacheDirec function cacheDirectoryForWorkspace(workspaceRoot) { return cacheDirectory(workspaceRoot, readCacheDirectoryProperty(workspaceRoot)); } -exports.workspaceDataDirectory = absolutePath(workspace_root_1.workspaceRoot, process.env.NX_WORKSPACE_DATA_DIRECTORY ?? - process.env.NX_PROJECT_GRAPH_CACHE_DIRECTORY ?? - defaultWorkspaceDataDirectory(workspace_root_1.workspaceRoot)); +exports.workspaceDataDirectory = workspaceDataDirectoryForWorkspace(workspace_root_1.workspaceRoot); +function workspaceDataDirectoryForWorkspace(workspaceRoot) { + return absolutePath(workspaceRoot, process.env.NX_WORKSPACE_DATA_DIRECTORY ?? + process.env.NX_PROJECT_GRAPH_CACHE_DIRECTORY ?? + defaultWorkspaceDataDirectory(workspaceRoot)); +} /***/ }), @@ -305133,6 +306148,25 @@ function consumeMessagesFromSocket(callback) { } +/***/ }), + +/***/ 25789: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getDbConnection = getDbConnection; +const native_1 = __nccwpck_require__(71926); +const cache_directory_1 = __nccwpck_require__(11622); +const package_json_1 = __nccwpck_require__(89617); +let dbConnection; +function getDbConnection(directory = cache_directory_1.workspaceDataDirectory) { + dbConnection ??= (0, native_1.connectToNxDb)(directory, package_json_1.version); + return dbConnection; +} + + /***/ }), /***/ 69510: @@ -306277,7 +307311,7 @@ function getTagsFromPackageJson(packageJson) { } return tags; } -function readTargetsFromPackageJson(packageJson) { +function readTargetsFromPackageJson(packageJson, nxJson) { const { scripts, nx, private: isPrivate } = packageJson ?? {}; const res = {}; const includedScripts = nx?.includedScripts || Object.keys(scripts ?? {}); @@ -306292,12 +307326,23 @@ function readTargetsFromPackageJson(packageJson) { * Add implicit nx-release-publish target for all package.json files that are * not marked as `"private": true` to allow for lightweight configuration for * package based repos. + * + * Any targetDefaults for the nx-release-publish target set by the user should + * be merged with the implicit target. */ if (!isPrivate && !res['nx-release-publish']) { + const nxReleasePublishTargetDefaults = nxJson?.targetDefaults?.['nx-release-publish'] ?? {}; res['nx-release-publish'] = { - dependsOn: ['^nx-release-publish'], executor: '@nx/js:release-publish', - options: {}, + ...nxReleasePublishTargetDefaults, + dependsOn: [ + // For maximum correctness, projects should only ever be published once their dependencies are successfully published + '^nx-release-publish', + ...(nxReleasePublishTargetDefaults.dependsOn ?? []), + ], + options: { + ...(nxReleasePublishTargetDefaults.options ?? {}), + }, }; } return res; @@ -308339,7 +309384,8 @@ exports.getSyncGeneratorChanges = getSyncGeneratorChanges; exports.flushSyncGeneratorChanges = flushSyncGeneratorChanges; exports.collectAllRegisteredSyncGenerators = collectAllRegisteredSyncGenerators; exports.runSyncGenerator = runSyncGenerator; -exports.collectRegisteredTaskSyncGenerators = collectRegisteredTaskSyncGenerators; +exports.collectEnabledTaskSyncGeneratorsFromProjectGraph = collectEnabledTaskSyncGeneratorsFromProjectGraph; +exports.collectEnabledTaskSyncGeneratorsFromTaskGraph = collectEnabledTaskSyncGeneratorsFromTaskGraph; exports.collectRegisteredGlobalSyncGenerators = collectRegisteredGlobalSyncGenerators; exports.syncGeneratorResultsToMessageLines = syncGeneratorResultsToMessageLines; const perf_hooks_1 = __nccwpck_require__(4074); @@ -308374,10 +309420,10 @@ async function flushSyncGeneratorChanges(results) { await client_1.daemonClient.flushSyncGeneratorChangesToDisk(results.map((r) => r.generatorName)); } } -async function collectAllRegisteredSyncGenerators(projectGraph) { +async function collectAllRegisteredSyncGenerators(projectGraph, nxJson) { if (!client_1.daemonClient.enabled()) { return [ - ...collectRegisteredTaskSyncGenerators(projectGraph), + ...collectEnabledTaskSyncGeneratorsFromProjectGraph(projectGraph, nxJson), ...collectRegisteredGlobalSyncGenerators(), ]; } @@ -308404,17 +309450,38 @@ async function runSyncGenerator(tree, generatorSpecifier, projects) { outOfSyncMessage, }; } -function collectRegisteredTaskSyncGenerators(projectGraph) { +function collectEnabledTaskSyncGeneratorsFromProjectGraph(projectGraph, nxJson) { const taskSyncGenerators = new Set(); + const disabledTaskSyncGenerators = new Set(nxJson.sync?.disabledTaskSyncGenerators ?? []); for (const { data: { targets }, } of Object.values(projectGraph.nodes)) { if (!targets) { continue; } for (const target of Object.values(targets)) { - if (!target.syncGenerators) { + if (!target.syncGenerators?.length) { continue; } for (const generator of target.syncGenerators) { + if (!disabledTaskSyncGenerators.has(generator) && + !taskSyncGenerators.has(generator)) { + taskSyncGenerators.add(generator); + } + } + } + } + return taskSyncGenerators; +} +function collectEnabledTaskSyncGeneratorsFromTaskGraph(taskGraph, projectGraph, nxJson) { + const taskSyncGenerators = new Set(); + const disabledTaskSyncGenerators = new Set(nxJson.sync?.disabledTaskSyncGenerators ?? []); + for (const { target } of Object.values(taskGraph.tasks)) { + const { syncGenerators } = projectGraph.nodes[target.project].data.targets[target.target]; + if (!syncGenerators?.length) { + continue; + } + for (const generator of syncGenerators) { + if (!disabledTaskSyncGenerators.has(generator) && + !taskSyncGenerators.has(generator)) { taskSyncGenerators.add(generator); } } @@ -308503,101 +309570,29 @@ function processSyncGeneratorResults(results) { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.taskHistoryFile = void 0; -exports.getHistoryForHashes = getHistoryForHashes; -exports.writeTaskRunsToHistory = writeTaskRunsToHistory; -const fs_1 = __nccwpck_require__(57147); -const path_1 = __nccwpck_require__(71017); +exports.TaskHistory = void 0; const client_1 = __nccwpck_require__(76940); const is_on_daemon_1 = __nccwpck_require__(45153); -const cache_directory_1 = __nccwpck_require__(11622); -const taskRunKeys = [ - 'project', - 'target', - 'configuration', - 'hash', - 'code', - 'status', - 'start', - 'end', -]; -let taskHistory = undefined; -let taskHashToIndicesMap = new Map(); -async function getHistoryForHashes(hashes) { - if ((0, is_on_daemon_1.isOnDaemon)() || !client_1.daemonClient.enabled()) { - if (taskHistory === undefined) { - loadTaskHistoryFromDisk(); - } - const result = {}; - for (let hash of hashes) { - const indices = taskHashToIndicesMap.get(hash); - if (!indices) { - result[hash] = []; - } - else { - result[hash] = indices.map((index) => taskHistory[index]); - } - } - return result; +const native_1 = __nccwpck_require__(71926); +const db_connection_1 = __nccwpck_require__(25789); +class TaskHistory { + constructor() { + this.taskHistory = new native_1.NxTaskHistory((0, db_connection_1.getDbConnection)()); } - return await client_1.daemonClient.getTaskHistoryForHashes(hashes); -} -async function writeTaskRunsToHistory(taskRuns) { - if ((0, is_on_daemon_1.isOnDaemon)() || !client_1.daemonClient.enabled()) { - if (taskHistory === undefined) { - loadTaskHistoryFromDisk(); + async getFlakyTasks(hashes) { + if ((0, is_on_daemon_1.isOnDaemon)() || !client_1.daemonClient.enabled()) { + return this.taskHistory.getFlakyTasks(hashes); } - const serializedLines = []; - for (let taskRun of taskRuns) { - const serializedLine = taskRunKeys.map((key) => taskRun[key]).join(','); - serializedLines.push(serializedLine); - recordTaskRunInMemory(taskRun); - } - if (!(0, fs_1.existsSync)(exports.taskHistoryFile)) { - (0, fs_1.writeFileSync)(exports.taskHistoryFile, `${taskRunKeys.join(',')}\n`); - } - (0, fs_1.appendFileSync)(exports.taskHistoryFile, serializedLines.join('\n') + '\n'); - } - else { - await client_1.daemonClient.writeTaskRunsToHistory(taskRuns); - } -} -exports.taskHistoryFile = (0, path_1.join)(cache_directory_1.workspaceDataDirectory, 'task-history.csv'); -function loadTaskHistoryFromDisk() { - taskHashToIndicesMap.clear(); - taskHistory = []; - if (!(0, fs_1.existsSync)(exports.taskHistoryFile)) { - return; - } - const fileContent = (0, fs_1.readFileSync)(exports.taskHistoryFile, 'utf8'); - if (!fileContent) { - return; + return await client_1.daemonClient.getFlakyTasks(hashes); } - const lines = fileContent.split('\n'); - // if there are no lines or just the header, return - if (lines.length <= 1) { - return; - } - const contentLines = lines.slice(1).filter((l) => l.trim() !== ''); - // read the values from csv format where each header is a key and the value is the value - for (let line of contentLines) { - const values = line.trim().split(','); - const run = {}; - taskRunKeys.forEach((header, index) => { - run[header] = values[index]; - }); - recordTaskRunInMemory(run); - } -} -function recordTaskRunInMemory(taskRun) { - const index = taskHistory.push(taskRun) - 1; - if (taskHashToIndicesMap.has(taskRun.hash)) { - taskHashToIndicesMap.get(taskRun.hash).push(index); - } - else { - taskHashToIndicesMap.set(taskRun.hash, [index]); + async recordTaskRuns(taskRuns) { + if ((0, is_on_daemon_1.isOnDaemon)() || !client_1.daemonClient.enabled()) { + return this.taskHistory.recordTaskRuns(taskRuns); + } + return client_1.daemonClient.recordTaskRuns(taskRuns); } } +exports.TaskHistory = TaskHistory; /***/ }), @@ -308639,7 +309634,7 @@ let workspaceContext; function setupWorkspaceContext(workspaceRoot) { const { WorkspaceContext } = __nccwpck_require__(71926); perf_hooks_1.performance.mark('workspace-context'); - workspaceContext = new WorkspaceContext(workspaceRoot, (0, cache_directory_1.cacheDirectoryForWorkspace)(workspaceRoot)); + workspaceContext = new WorkspaceContext(workspaceRoot, (0, cache_directory_1.workspaceDataDirectoryForWorkspace)(workspaceRoot)); perf_hooks_1.performance.mark('workspace-context:end'); perf_hooks_1.performance.measure('workspace context init', 'workspace-context', 'workspace-context:end'); } @@ -309706,49 +310701,63 @@ const { instance: __napiInstance, module: __wasiModule, napiModule: __napiModule }) function __napi_rs_initialize_modules(__napiInstance) { - __napiInstance.exports['__napi_register__expand_outputs_0']?.() - __napiInstance.exports['__napi_register__get_files_for_outputs_1']?.() - __napiInstance.exports['__napi_register__remove_2']?.() - __napiInstance.exports['__napi_register__copy_3']?.() - __napiInstance.exports['__napi_register__hash_array_4']?.() - __napiInstance.exports['__napi_register__hash_file_5']?.() - __napiInstance.exports['__napi_register__IS_WASM_6']?.() - __napiInstance.exports['__napi_register__get_binary_target_7']?.() - __napiInstance.exports['__napi_register__ImportResult_struct_8']?.() - __napiInstance.exports['__napi_register__find_imports_9']?.() - __napiInstance.exports['__napi_register__transfer_project_graph_10']?.() - __napiInstance.exports['__napi_register__ExternalNode_struct_11']?.() - __napiInstance.exports['__napi_register__Target_struct_12']?.() - __napiInstance.exports['__napi_register__Project_struct_13']?.() - __napiInstance.exports['__napi_register__ProjectGraph_struct_14']?.() - __napiInstance.exports['__napi_register__HashPlanner_struct_15']?.() - __napiInstance.exports['__napi_register__HashPlanner_impl_19']?.() - __napiInstance.exports['__napi_register__HashDetails_struct_20']?.() - __napiInstance.exports['__napi_register__HasherOptions_struct_21']?.() - __napiInstance.exports['__napi_register__TaskHasher_struct_22']?.() - __napiInstance.exports['__napi_register__TaskHasher_impl_25']?.() - __napiInstance.exports['__napi_register__Task_struct_26']?.() - __napiInstance.exports['__napi_register__TaskTarget_struct_27']?.() - __napiInstance.exports['__napi_register__TaskGraph_struct_28']?.() - __napiInstance.exports['__napi_register__FileData_struct_29']?.() - __napiInstance.exports['__napi_register__InputsInput_struct_30']?.() - __napiInstance.exports['__napi_register__FileSetInput_struct_31']?.() - __napiInstance.exports['__napi_register__RuntimeInput_struct_32']?.() - __napiInstance.exports['__napi_register__EnvironmentInput_struct_33']?.() - __napiInstance.exports['__napi_register__ExternalDependenciesInput_struct_34']?.() - __napiInstance.exports['__napi_register__DepsOutputsInput_struct_35']?.() - __napiInstance.exports['__napi_register__NxJson_struct_36']?.() - __napiInstance.exports['__napi_register__WorkspaceContext_struct_37']?.() - __napiInstance.exports['__napi_register__WorkspaceContext_impl_46']?.() - __napiInstance.exports['__napi_register__WorkspaceErrors_47']?.() - __napiInstance.exports['__napi_register__NxWorkspaceFiles_struct_48']?.() - __napiInstance.exports['__napi_register__NxWorkspaceFilesExternals_struct_49']?.() - __napiInstance.exports['__napi_register__UpdatedWorkspaceFiles_struct_50']?.() - __napiInstance.exports['__napi_register__FileMap_struct_51']?.() - __napiInstance.exports['__napi_register____test_only_transfer_file_map_52']?.() + __napiInstance.exports['__napi_register__CachedResult_struct_0']?.() + __napiInstance.exports['__napi_register__NxCache_struct_1']?.() + __napiInstance.exports['__napi_register__NxCache_impl_9']?.() + __napiInstance.exports['__napi_register__expand_outputs_10']?.() + __napiInstance.exports['__napi_register__get_files_for_outputs_11']?.() + __napiInstance.exports['__napi_register__remove_12']?.() + __napiInstance.exports['__napi_register__copy_13']?.() + __napiInstance.exports['__napi_register__validate_outputs_14']?.() + __napiInstance.exports['__napi_register__get_transformable_outputs_15']?.() + __napiInstance.exports['__napi_register__hash_array_16']?.() + __napiInstance.exports['__napi_register__hash_file_17']?.() + __napiInstance.exports['__napi_register__IS_WASM_18']?.() + __napiInstance.exports['__napi_register__get_binary_target_19']?.() + __napiInstance.exports['__napi_register__ImportResult_struct_20']?.() + __napiInstance.exports['__napi_register__find_imports_21']?.() + __napiInstance.exports['__napi_register__transfer_project_graph_22']?.() + __napiInstance.exports['__napi_register__ExternalNode_struct_23']?.() + __napiInstance.exports['__napi_register__Target_struct_24']?.() + __napiInstance.exports['__napi_register__Project_struct_25']?.() + __napiInstance.exports['__napi_register__ProjectGraph_struct_26']?.() + __napiInstance.exports['__napi_register__HashedTask_struct_27']?.() + __napiInstance.exports['__napi_register__TaskDetails_struct_28']?.() + __napiInstance.exports['__napi_register__TaskDetails_impl_31']?.() + __napiInstance.exports['__napi_register__HashPlanner_struct_32']?.() + __napiInstance.exports['__napi_register__HashPlanner_impl_36']?.() + __napiInstance.exports['__napi_register__HashDetails_struct_37']?.() + __napiInstance.exports['__napi_register__HasherOptions_struct_38']?.() + __napiInstance.exports['__napi_register__TaskHasher_struct_39']?.() + __napiInstance.exports['__napi_register__TaskHasher_impl_42']?.() + __napiInstance.exports['__napi_register__TaskRun_struct_43']?.() + __napiInstance.exports['__napi_register__NxTaskHistory_struct_44']?.() + __napiInstance.exports['__napi_register__NxTaskHistory_impl_48']?.() + __napiInstance.exports['__napi_register__Task_struct_49']?.() + __napiInstance.exports['__napi_register__TaskTarget_struct_50']?.() + __napiInstance.exports['__napi_register__TaskGraph_struct_51']?.() + __napiInstance.exports['__napi_register__FileData_struct_52']?.() + __napiInstance.exports['__napi_register__InputsInput_struct_53']?.() + __napiInstance.exports['__napi_register__FileSetInput_struct_54']?.() + __napiInstance.exports['__napi_register__RuntimeInput_struct_55']?.() + __napiInstance.exports['__napi_register__EnvironmentInput_struct_56']?.() + __napiInstance.exports['__napi_register__ExternalDependenciesInput_struct_57']?.() + __napiInstance.exports['__napi_register__DepsOutputsInput_struct_58']?.() + __napiInstance.exports['__napi_register__NxJson_struct_59']?.() + __napiInstance.exports['__napi_register__WorkspaceContext_struct_60']?.() + __napiInstance.exports['__napi_register__WorkspaceContext_impl_69']?.() + __napiInstance.exports['__napi_register__WorkspaceErrors_70']?.() + __napiInstance.exports['__napi_register__NxWorkspaceFiles_struct_71']?.() + __napiInstance.exports['__napi_register__NxWorkspaceFilesExternals_struct_72']?.() + __napiInstance.exports['__napi_register__UpdatedWorkspaceFiles_struct_73']?.() + __napiInstance.exports['__napi_register__FileMap_struct_74']?.() + __napiInstance.exports['__napi_register____test_only_transfer_file_map_75']?.() } module.exports.HashPlanner = __napiModule.exports.HashPlanner module.exports.ImportResult = __napiModule.exports.ImportResult +module.exports.NxCache = __napiModule.exports.NxCache +module.exports.NxTaskHistory = __napiModule.exports.NxTaskHistory +module.exports.TaskDetails = __napiModule.exports.TaskDetails module.exports.TaskHasher = __napiModule.exports.TaskHasher module.exports.WorkspaceContext = __napiModule.exports.WorkspaceContext module.exports.copy = __napiModule.exports.copy @@ -309756,12 +310765,14 @@ module.exports.expandOutputs = __napiModule.exports.expandOutputs module.exports.findImports = __napiModule.exports.findImports module.exports.getBinaryTarget = __napiModule.exports.getBinaryTarget module.exports.getFilesForOutputs = __napiModule.exports.getFilesForOutputs +module.exports.getTransformableOutputs = __napiModule.exports.getTransformableOutputs module.exports.hashArray = __napiModule.exports.hashArray module.exports.hashFile = __napiModule.exports.hashFile module.exports.IS_WASM = __napiModule.exports.IS_WASM module.exports.remove = __napiModule.exports.remove module.exports.testOnlyTransferFileMap = __napiModule.exports.testOnlyTransferFileMap module.exports.transferProjectGraph = __napiModule.exports.transferProjectGraph +module.exports.validateOutputs = __napiModule.exports.validateOutputs module.exports.WorkspaceErrors = __napiModule.exports.WorkspaceErrors @@ -311044,7 +312055,7 @@ var t=__nccwpck_require__(39491);class e extends Error{constructor(t){super(t||" /***/ ((module) => { "use strict"; -module.exports = {"version":"1.7.14"}; +module.exports = {"version":"1.7.26"}; /***/ }), @@ -311084,7 +312095,7 @@ module.exports = JSON.parse('{"$schema":"https://json.schemastore.org/tsconfig", /***/ ((module) => { "use strict"; -module.exports = {"version":"19.6.2"}; +module.exports = JSON.parse('{"name":"nx","version":"19.7.2","private":false,"description":"The core Nx plugin contains the core functionality of Nx like the project graph, nx commands and task orchestration.","repository":{"type":"git","url":"https://github.com/nrwl/nx.git","directory":"packages/nx"},"scripts":{"postinstall":"node ./bin/post-install"},"keywords":["Monorepo","Angular","React","Web","Node","Nest","Jest","Cypress","CLI","Testing","Front-end","Backend","Mobile"],"bin":{"nx":"./bin/nx.js","nx-cloud":"./bin/nx-cloud.js"},"author":"Victor Savkin","license":"MIT","bugs":{"url":"https://github.com/nrwl/nx/issues"},"homepage":"https://nx.dev","dependencies":{"@napi-rs/wasm-runtime":"0.2.4","@yarnpkg/lockfile":"^1.1.0","@yarnpkg/parsers":"3.0.0-rc.46","@zkochan/js-yaml":"0.0.7","axios":"^1.7.4","chalk":"^4.1.0","cli-cursor":"3.1.0","cli-spinners":"2.6.1","cliui":"^8.0.1","dotenv":"~16.4.5","dotenv-expand":"~11.0.6","enquirer":"~2.3.6","figures":"3.2.0","flat":"^5.0.2","front-matter":"^4.0.2","fs-extra":"^11.1.0","ignore":"^5.0.4","jest-diff":"^29.4.1","jsonc-parser":"3.2.0","lines-and-columns":"2.0.3","minimatch":"9.0.3","npm-run-path":"^4.0.1","open":"^8.4.0","semver":"^7.5.3","string-width":"^4.2.3","strong-log-transformer":"^2.1.0","tar-stream":"~2.2.0","tmp":"~0.2.1","tsconfig-paths":"^4.1.2","tslib":"^2.3.0","yargs":"^17.6.2","yargs-parser":"21.1.1","node-machine-id":"1.1.12","ora":"5.3.0","@nrwl/tao":"19.7.2"},"peerDependencies":{"@swc-node/register":"^1.8.0","@swc/core":"^1.3.85"},"peerDependenciesMeta":{"@swc-node/register":{"optional":true},"@swc/core":{"optional":true}},"optionalDependencies":{"@nx/nx-darwin-x64":"19.7.2","@nx/nx-darwin-arm64":"19.7.2","@nx/nx-linux-x64-gnu":"19.7.2","@nx/nx-linux-x64-musl":"19.7.2","@nx/nx-win32-x64-msvc":"19.7.2","@nx/nx-linux-arm64-gnu":"19.7.2","@nx/nx-linux-arm64-musl":"19.7.2","@nx/nx-linux-arm-gnueabihf":"19.7.2","@nx/nx-win32-arm64-msvc":"19.7.2","@nx/nx-freebsd-x64":"19.7.2"},"nx-migrations":{"migrations":"./migrations.json","packageGroup":["@nx/js","@nrwl/js","@nx/jest","@nrwl/jest","@nx/linter","@nx/eslint","@nrwl/linter","@nx/workspace","@nrwl/workspace","@nx/angular","@nrwl/angular","@nx/cypress","@nrwl/cypress","@nx/detox","@nrwl/detox","@nx/devkit","@nrwl/devkit","@nx/esbuild","@nrwl/esbuild","@nx/eslint-plugin","@nrwl/eslint-plugin-nx","@nx/expo","@nrwl/expo","@nx/express","@nrwl/express","@nx/gradle","@nx/nest","@nrwl/nest","@nx/next","@nrwl/next","@nx/node","@nrwl/node","@nx/nuxt","@nx/playwright","@nx/plugin","@nrwl/nx-plugin","@nx/react","@nrwl/react","@nx/react-native","@nrwl/react-native","@nx/rollup","@nrwl/rollup","@nx/remix","@nrwl/remix","@nx/storybook","@nrwl/storybook","@nrwl/tao","@nx/vite","@nrwl/vite","@nx/vue","@nx/web","@nrwl/web","@nx/webpack","@nrwl/webpack",{"package":"nx-cloud","version":"latest"},{"package":"@nrwl/nx-cloud","version":"latest"}]},"generators":"./generators.json","executors":"./executors.json","builders":"./executors.json","publishConfig":{"access":"public"},"napi":{"binaryName":"nx","packageName":"@nx/nx","wasm":{"initialMemory":1024,"maximumMemory":32768},"targets":["x86_64-unknown-linux-gnu","x86_64-pc-windows-msvc","x86_64-apple-darwin","aarch64-apple-darwin","aarch64-unknown-linux-gnu","aarch64-unknown-linux-musl","aarch64-pc-windows-msvc","armv7-unknown-linux-gnueabihf","x86_64-unknown-linux-musl","x86_64-unknown-freebsd"]},"main":"./bin/nx.js","type":"commonjs","types":"./bin/nx.d.ts"}'); /***/ }), diff --git a/actions/run-many/dist/native-bindings.js b/actions/run-many/dist/native-bindings.js index 9c34dc6e..cd921e8e 100644 --- a/actions/run-many/dist/native-bindings.js +++ b/actions/run-many/dist/native-bindings.js @@ -364,20 +364,26 @@ if (!nativeBinding) { module.exports.ChildProcess = nativeBinding.ChildProcess module.exports.HashPlanner = nativeBinding.HashPlanner module.exports.ImportResult = nativeBinding.ImportResult +module.exports.NxCache = nativeBinding.NxCache +module.exports.NxTaskHistory = nativeBinding.NxTaskHistory module.exports.RustPseudoTerminal = nativeBinding.RustPseudoTerminal +module.exports.TaskDetails = nativeBinding.TaskDetails module.exports.TaskHasher = nativeBinding.TaskHasher module.exports.Watcher = nativeBinding.Watcher module.exports.WorkspaceContext = nativeBinding.WorkspaceContext +module.exports.connectToNxDb = nativeBinding.connectToNxDb module.exports.copy = nativeBinding.copy module.exports.EventType = nativeBinding.EventType module.exports.expandOutputs = nativeBinding.expandOutputs module.exports.findImports = nativeBinding.findImports module.exports.getBinaryTarget = nativeBinding.getBinaryTarget module.exports.getFilesForOutputs = nativeBinding.getFilesForOutputs +module.exports.getTransformableOutputs = nativeBinding.getTransformableOutputs module.exports.hashArray = nativeBinding.hashArray module.exports.hashFile = nativeBinding.hashFile module.exports.IS_WASM = nativeBinding.IS_WASM module.exports.remove = nativeBinding.remove module.exports.testOnlyTransferFileMap = nativeBinding.testOnlyTransferFileMap module.exports.transferProjectGraph = nativeBinding.transferProjectGraph +module.exports.validateOutputs = nativeBinding.validateOutputs module.exports.WorkspaceErrors = nativeBinding.WorkspaceErrors diff --git a/actions/run-many/dist/nx.linux-x64-gnu.node b/actions/run-many/dist/nx.linux-x64-gnu.node index 6ab26426..b8b17e7e 100644 Binary files a/actions/run-many/dist/nx.linux-x64-gnu.node and b/actions/run-many/dist/nx.linux-x64-gnu.node differ diff --git a/actions/run-many/dist/package.json b/actions/run-many/dist/package.json index ab606894..a3bbbbdb 100644 --- a/actions/run-many/dist/package.json +++ b/actions/run-many/dist/package.json @@ -1,6 +1,6 @@ { "name": "nx", - "version": "19.6.2", + "version": "19.7.2", "private": false, "description": "The core Nx plugin contains the core functionality of Nx like the project graph, nx commands and task orchestration.", "repository": { @@ -56,7 +56,7 @@ "ignore": "^5.0.4", "jest-diff": "^29.4.1", "jsonc-parser": "3.2.0", - "lines-and-columns": "~2.0.3", + "lines-and-columns": "2.0.3", "minimatch": "9.0.3", "npm-run-path": "^4.0.1", "open": "^8.4.0", @@ -71,7 +71,7 @@ "yargs-parser": "21.1.1", "node-machine-id": "1.1.12", "ora": "5.3.0", - "@nrwl/tao": "19.6.2" + "@nrwl/tao": "19.7.2" }, "peerDependencies": { "@swc-node/register": "^1.8.0", @@ -86,16 +86,16 @@ } }, "optionalDependencies": { - "@nx/nx-darwin-x64": "19.6.2", - "@nx/nx-darwin-arm64": "19.6.2", - "@nx/nx-linux-x64-gnu": "19.6.2", - "@nx/nx-linux-x64-musl": "19.6.2", - "@nx/nx-win32-x64-msvc": "19.6.2", - "@nx/nx-linux-arm64-gnu": "19.6.2", - "@nx/nx-linux-arm64-musl": "19.6.2", - "@nx/nx-linux-arm-gnueabihf": "19.6.2", - "@nx/nx-win32-arm64-msvc": "19.6.2", - "@nx/nx-freebsd-x64": "19.6.2" + "@nx/nx-darwin-x64": "19.7.2", + "@nx/nx-darwin-arm64": "19.7.2", + "@nx/nx-linux-x64-gnu": "19.7.2", + "@nx/nx-linux-x64-musl": "19.7.2", + "@nx/nx-win32-x64-msvc": "19.7.2", + "@nx/nx-linux-arm64-gnu": "19.7.2", + "@nx/nx-linux-arm64-musl": "19.7.2", + "@nx/nx-linux-arm-gnueabihf": "19.7.2", + "@nx/nx-win32-arm64-msvc": "19.7.2", + "@nx/nx-freebsd-x64": "19.7.2" }, "nx-migrations": { "migrations": "./migrations.json", diff --git a/actions/run-many/dist/swc.linux-x64-gnu.node b/actions/run-many/dist/swc.linux-x64-gnu.node index 8c48e76c..141b4202 100644 Binary files a/actions/run-many/dist/swc.linux-x64-gnu.node and b/actions/run-many/dist/swc.linux-x64-gnu.node differ