vite 5.0.0-beta.0 → 5.0.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,15 +1,15 @@
1
- import fs$l from 'node:fs';
1
+ import fs$l, { promises as promises$1 } from 'node:fs';
2
2
  import fsp from 'node:fs/promises';
3
- import path$o, { dirname as dirname$2, join as join$2, posix as posix$1, isAbsolute as isAbsolute$2, relative as relative$2, basename as basename$2, extname as extname$1 } from 'node:path';
3
+ import path$o, { posix as posix$1, isAbsolute as isAbsolute$2, join as join$2, relative as relative$2, dirname as dirname$2, basename as basename$2, extname as extname$1 } from 'node:path';
4
4
  import { fileURLToPath, URL as URL$3, URLSearchParams, parse as parse$i, pathToFileURL } from 'node:url';
5
5
  import { promisify as promisify$4, format as format$2, inspect } from 'node:util';
6
6
  import { performance } from 'node:perf_hooks';
7
7
  import { createRequire as createRequire$1, builtinModules } from 'node:module';
8
8
  import require$$0$3 from 'tty';
9
9
  import esbuild, { transform as transform$1, formatMessages, build as build$3 } from 'esbuild';
10
- import require$$0$4, { win32, posix, isAbsolute as isAbsolute$1, resolve as resolve$3, relative as relative$1, basename as basename$1, extname, dirname as dirname$1, join as join$1, sep as sep$1, normalize } from 'path';
10
+ import require$$0$4, { win32, posix, isAbsolute as isAbsolute$1, resolve as resolve$3, relative as relative$1, basename as basename$1, extname, dirname as dirname$1, join as join$1, sep, normalize } from 'path';
11
11
  import * as require$$0$2 from 'fs';
12
- import require$$0__default, { existsSync, readFileSync, statSync as statSync$1, promises as promises$1, readdir as readdir$4, readdirSync } from 'fs';
12
+ import require$$0__default, { existsSync, readFileSync, statSync as statSync$1, readdirSync } from 'fs';
13
13
  import require$$0$5 from 'events';
14
14
  import require$$5 from 'assert';
15
15
  import require$$0$6 from 'util';
@@ -31,13 +31,13 @@ import assert$1 from 'node:assert';
31
31
  import process$1 from 'node:process';
32
32
  import v8 from 'node:v8';
33
33
  import { VERSION } from 'rollup';
34
- import require$$1 from 'worker_threads';
35
34
  import { createServer as createServer$3, STATUS_CODES } from 'node:http';
36
35
  import { createServer as createServer$2 } from 'node:https';
37
36
  import require$$0$a from 'zlib';
38
37
  import require$$0$b from 'buffer';
39
38
  import require$$1$2 from 'https';
40
39
  import require$$4$1 from 'tls';
40
+ import require$$1 from 'worker_threads';
41
41
  import * as qs from 'querystring';
42
42
  import readline from 'node:readline';
43
43
  import zlib$1, { gzip } from 'node:zlib';
@@ -420,7 +420,7 @@ let SyncWalker$1 = class SyncWalker extends WalkerBase$1 {
420
420
  * }} walker
421
421
  * @returns {BaseNode}
422
422
  */
423
- function walk$4(ast, { enter, leave }) {
423
+ function walk$3(ast, { enter, leave }) {
424
424
  const instance = new SyncWalker$1(enter, leave);
425
425
  return instance.visit(ast, null);
426
426
  }
@@ -2559,7 +2559,7 @@ let Scope$1 = class Scope {
2559
2559
  };
2560
2560
  const attachScopes = function attachScopes(ast, propertyName = 'scope') {
2561
2561
  let scope = new Scope$1();
2562
- walk$4(ast, {
2562
+ walk$3(ast, {
2563
2563
  enter(n, parent) {
2564
2564
  const node = n;
2565
2565
  // function foo () {...}
@@ -7796,7 +7796,7 @@ function getEsImportProxy(id, defaultIsModuleExports) {
7796
7796
  /* eslint-disable no-param-reassign, no-undefined */
7797
7797
 
7798
7798
  function getCandidatesForExtension(resolved, extension) {
7799
- return [resolved + extension, `${resolved}${sep$1}index${extension}`];
7799
+ return [resolved + extension, `${resolved}${sep}index${extension}`];
7800
7800
  }
7801
7801
 
7802
7802
  function getCandidates(resolved, extensions) {
@@ -8849,7 +8849,7 @@ async function transformCommonjs(
8849
8849
  const importedVariables = new Set();
8850
8850
  const indentExclusionRanges = [];
8851
8851
 
8852
- walk$4(ast, {
8852
+ walk$3(ast, {
8853
8853
  enter(node, parent) {
8854
8854
  if (skippedNodes.has(node)) {
8855
8855
  this.skip();
@@ -11549,7 +11549,7 @@ if (typeof process === 'undefined' || process.type === 'renderer' || process.bro
11549
11549
  }
11550
11550
 
11551
11551
  var srcExports$1 = src$2.exports;
11552
- var debug$g = /*@__PURE__*/getDefaultExportFromCjs(srcExports$1);
11552
+ var debug$h = /*@__PURE__*/getDefaultExportFromCjs(srcExports$1);
11553
11553
 
11554
11554
  let pnp;
11555
11555
  if (process.versions.pnp) {
@@ -11707,7 +11707,7 @@ function watchPackageDataPlugin(packageCache) {
11707
11707
  let watchFile = watchFileStub;
11708
11708
  const setPackageData = packageCache.set.bind(packageCache);
11709
11709
  packageCache.set = (id, pkg) => {
11710
- if (!isInNodeModules(pkg.dir) && !watchedDirs.has(pkg.dir)) {
11710
+ if (!isInNodeModules$1(pkg.dir) && !watchedDirs.has(pkg.dir)) {
11711
11711
  watchedDirs.add(pkg.dir);
11712
11712
  watchFile(path$o.join(pkg.dir, 'package.json'));
11713
11713
  }
@@ -11857,11 +11857,11 @@ function isBuiltin(id) {
11857
11857
  ? id.slice(NODE_BUILTIN_NAMESPACE.length)
11858
11858
  : id);
11859
11859
  }
11860
- function isInNodeModules(id) {
11860
+ function isInNodeModules$1(id) {
11861
11861
  return id.includes('node_modules');
11862
11862
  }
11863
11863
  function moduleListContains(moduleList, id) {
11864
- return moduleList?.some((m) => m === id || id.startsWith(m + '/'));
11864
+ return moduleList?.some((m) => m === id || id.startsWith(withTrailingSlash(m)));
11865
11865
  }
11866
11866
  function isOptimizable(id, optimizeDeps) {
11867
11867
  const { extensions } = optimizeDeps;
@@ -11876,7 +11876,7 @@ const _require$3 = createRequire$1(import.meta.url);
11876
11876
  const filter = process.env.VITE_DEBUG_FILTER;
11877
11877
  const DEBUG = process.env.DEBUG;
11878
11878
  function createDebugger(namespace, options = {}) {
11879
- const log = debug$g(namespace);
11879
+ const log = debug$h(namespace);
11880
11880
  const { onlyWhenFocused } = options;
11881
11881
  let enabled = log.enabled;
11882
11882
  if (enabled && onlyWhenFocused) {
@@ -11925,6 +11925,12 @@ function fsPathFromId(id) {
11925
11925
  function fsPathFromUrl(url) {
11926
11926
  return fsPathFromId(cleanUrl(url));
11927
11927
  }
11928
+ function withTrailingSlash(path) {
11929
+ if (path[path.length - 1] !== '/') {
11930
+ return `${path}/`;
11931
+ }
11932
+ return path;
11933
+ }
11928
11934
  /**
11929
11935
  * Check if dir is a parent of file
11930
11936
  *
@@ -11935,9 +11941,7 @@ function fsPathFromUrl(url) {
11935
11941
  * @returns true if dir is a parent of file
11936
11942
  */
11937
11943
  function isParentDirectory(dir, file) {
11938
- if (dir[dir.length - 1] !== '/') {
11939
- dir = `${dir}/`;
11940
- }
11944
+ dir = withTrailingSlash(dir);
11941
11945
  return (file.startsWith(dir) ||
11942
11946
  (isCaseInsensitiveFS && file.toLowerCase().startsWith(dir.toLowerCase())));
11943
11947
  }
@@ -12289,7 +12293,7 @@ function optimizeSafeRealPathSync() {
12289
12293
  function ensureWatchedFile(watcher, file, root) {
12290
12294
  if (file &&
12291
12295
  // only need to watch if out of root
12292
- !file.startsWith(root + '/') &&
12296
+ !file.startsWith(withTrailingSlash(root)) &&
12293
12297
  // some rollup plugins use null bytes for private resolved Ids
12294
12298
  !file.includes('\0') &&
12295
12299
  fs$l.existsSync(file)) {
@@ -12689,7 +12693,7 @@ const isNonDriveRelativeAbsolutePath = (p) => {
12689
12693
  };
12690
12694
  /**
12691
12695
  * Determine if a file is being requested with the correct case, to ensure
12692
- * consistent behaviour between dev and prod and across operating systems.
12696
+ * consistent behavior between dev and prod and across operating systems.
12693
12697
  */
12694
12698
  function shouldServeFile(filePath, root) {
12695
12699
  // can skip case check on Linux
@@ -12729,7 +12733,7 @@ function stripBase(path, base) {
12729
12733
  if (path === base) {
12730
12734
  return '/';
12731
12735
  }
12732
- const devBase = base[base.length - 1] === '/' ? base : base + '/';
12736
+ const devBase = withTrailingSlash(base);
12733
12737
  return path.startsWith(devBase) ? path.slice(devBase.length - 1) : path;
12734
12738
  }
12735
12739
  function arrayEqual(a, b) {
@@ -12999,7 +13003,7 @@ function buildReporterPlugin(config) {
12999
13003
  // the same chunk. The intersecting dynamic importers' dynamic import is not
13000
13004
  // expected to work. Note we're only detecting the direct ineffective
13001
13005
  // dynamic import here.
13002
- const detectedIneffectiveDynamicImport = module.dynamicImporters.some((id) => !isInNodeModules(id) && chunk.moduleIds.includes(id));
13006
+ const detectedIneffectiveDynamicImport = module.dynamicImporters.some((id) => !isInNodeModules$1(id) && chunk.moduleIds.includes(id));
13003
13007
  if (detectedIneffectiveDynamicImport) {
13004
13008
  this.warn(`\n(!) ${module.id} is dynamically imported by ${module.dynamicImporters.join(', ')} but also statically imported by ${module.importers.join(', ')}, dynamic import will not move module into another chunk.\n`);
13005
13009
  }
@@ -13086,9 +13090,10 @@ function buildReporterPlugin(config) {
13086
13090
  if (isLarge)
13087
13091
  hasLargeChunks = true;
13088
13092
  const sizeColor = isLarge ? colors$1.yellow : colors$1.dim;
13089
- let log = colors$1.dim(relativeOutDir + '/');
13093
+ let log = colors$1.dim(withTrailingSlash(relativeOutDir));
13090
13094
  log +=
13091
- !config.build.lib && entry.name.startsWith(assetsDir)
13095
+ !config.build.lib &&
13096
+ entry.name.startsWith(withTrailingSlash(assetsDir))
13092
13097
  ? colors$1.dim(assetsDir) +
13093
13098
  group.color(entry.name
13094
13099
  .slice(assetsDir.length)
@@ -13167,637 +13172,990 @@ function displayTime(time) {
13167
13172
  return `${mins}m${seconds < 1 ? '' : ` ${seconds.toFixed(0)}s`}`;
13168
13173
  }
13169
13174
 
13170
- // src/find.ts
13171
- async function find(filename, options) {
13172
- let dir = require$$0$4.dirname(require$$0$4.resolve(filename));
13173
- const root = (options == null ? void 0 : options.root) ? require$$0$4.resolve(options.root) : null;
13174
- while (dir) {
13175
- const tsconfig = await tsconfigInDir(dir, options);
13176
- if (tsconfig) {
13177
- return tsconfig;
13178
- } else {
13179
- if (root === dir) {
13180
- break;
13181
- }
13182
- const parent = require$$0$4.dirname(dir);
13183
- if (parent === dir) {
13184
- break;
13185
- } else {
13186
- dir = parent;
13187
- }
13188
- }
13189
- }
13190
- throw new Error(`no tsconfig file found for ${filename}`);
13175
+ const POSIX_SEP_RE = new RegExp('\\' + path$o.posix.sep, 'g');
13176
+ const NATIVE_SEP_RE = new RegExp('\\' + path$o.sep, 'g');
13177
+ /** @type {Map<string,RegExp>}*/
13178
+ const PATTERN_REGEX_CACHE = new Map();
13179
+ const GLOB_ALL_PATTERN = `**/*`;
13180
+ const DEFAULT_EXTENSIONS = ['.ts', '.tsx', '.mts', '.cts'];
13181
+ const DEFAULT_EXTENSIONS_RE_GROUP = `\\.(?:${DEFAULT_EXTENSIONS.map((ext) => ext.substring(1)).join(
13182
+ '|'
13183
+ )})`;
13184
+
13185
+ const IS_POSIX = path$o.posix.sep === path$o.sep;
13186
+
13187
+ /**
13188
+ * @template T
13189
+ * @returns {{resolve:(result:T)=>void, reject:(error:any)=>void, promise: Promise<T>}}
13190
+ */
13191
+ function makePromise() {
13192
+ let resolve, reject;
13193
+ const promise = new Promise((res, rej) => {
13194
+ resolve = res;
13195
+ reject = rej;
13196
+ });
13197
+ return { promise, resolve, reject };
13191
13198
  }
13192
- async function tsconfigInDir(dir, options) {
13193
- const tsconfig = require$$0$4.join(dir, "tsconfig.json");
13194
- if (options == null ? void 0 : options.tsConfigPaths) {
13195
- return options.tsConfigPaths.has(tsconfig) ? tsconfig : void 0;
13196
- }
13197
- try {
13198
- const stat = await promises$1.stat(tsconfig);
13199
- if (stat.isFile() || stat.isFIFO()) {
13200
- return tsconfig;
13201
- }
13202
- } catch (e) {
13203
- if (e.code !== "ENOENT") {
13204
- throw e;
13205
- }
13206
- }
13199
+
13200
+ /**
13201
+ * @param {string} filename
13202
+ * @param {import('./cache.js').TSConfckCache} [cache]
13203
+ * @returns {Promise<string|void>}
13204
+ */
13205
+ async function resolveTSConfigJson(filename, cache) {
13206
+ if (path$o.extname(filename) !== '.json') {
13207
+ return; // ignore files that are not json
13208
+ }
13209
+ const tsconfig = path$o.resolve(filename);
13210
+ if (cache) {
13211
+ if (cache.hasParseResult(tsconfig) || cache.hasParseResult(filename)) {
13212
+ return tsconfig;
13213
+ }
13214
+ }
13215
+ return promises$1.stat(tsconfig).then((stat) => {
13216
+ if (stat.isFile() || stat.isFIFO()) {
13217
+ return tsconfig;
13218
+ } else {
13219
+ throw new Error(`${filename} exists but is not a regular file.`);
13220
+ }
13221
+ });
13207
13222
  }
13208
- var sep = require$$0$4.sep;
13209
- async function findAll(dir, options) {
13210
- const state = {
13211
- files: [],
13212
- calls: 0,
13213
- skip: options == null ? void 0 : options.skip,
13214
- err: false
13215
- };
13216
- return new Promise((resolve, reject) => {
13217
- walk$3(require$$0$4.resolve(dir), state, (err, files) => err ? reject(err) : resolve(files));
13218
- });
13223
+
13224
+ /**
13225
+ *
13226
+ * @param {string} dir an absolute directory path
13227
+ * @returns {boolean} if dir path includes a node_modules segment
13228
+ */
13229
+ const isInNodeModules = IS_POSIX
13230
+ ? (dir) => dir.includes('/node_modules/')
13231
+ : (dir) => dir.match(/[/\\]node_modules[/\\]/);
13232
+
13233
+ /**
13234
+ * convert posix separator to native separator
13235
+ *
13236
+ * eg.
13237
+ * windows: C:/foo/bar -> c:\foo\bar
13238
+ * linux: /foo/bar -> /foo/bar
13239
+ *
13240
+ * @param {string} filename with posix separators
13241
+ * @returns {string} filename with native separators
13242
+ */
13243
+ const posix2native = IS_POSIX
13244
+ ? (filename) => filename
13245
+ : (filename) => filename.replace(POSIX_SEP_RE, path$o.sep);
13246
+
13247
+ /**
13248
+ * convert native separator to posix separator
13249
+ *
13250
+ * eg.
13251
+ * windows: C:\foo\bar -> c:/foo/bar
13252
+ * linux: /foo/bar -> /foo/bar
13253
+ *
13254
+ * @param {string} filename - filename with native separators
13255
+ * @returns {string} filename with posix separators
13256
+ */
13257
+ const native2posix = IS_POSIX
13258
+ ? (filename) => filename
13259
+ : (filename) => filename.replace(NATIVE_SEP_RE, path$o.posix.sep);
13260
+
13261
+ /**
13262
+ * converts params to native separator, resolves path and converts native back to posix
13263
+ *
13264
+ * needed on windows to handle posix paths in tsconfig
13265
+ *
13266
+ * @param dir {string|null} directory to resolve from
13267
+ * @param filename {string} filename or pattern to resolve
13268
+ * @returns string
13269
+ */
13270
+ const resolve2posix = IS_POSIX
13271
+ ? (dir, filename) => (dir ? path$o.resolve(dir, filename) : path$o.resolve(filename))
13272
+ : (dir, filename) =>
13273
+ native2posix(
13274
+ dir
13275
+ ? path$o.resolve(posix2native(dir), posix2native(filename))
13276
+ : path$o.resolve(posix2native(filename))
13277
+ );
13278
+
13279
+ /**
13280
+ *
13281
+ * @param {import('./public.d.ts').TSConfckParseResult} result
13282
+ * @returns {string[]}
13283
+ */
13284
+ function resolveReferencedTSConfigFiles(result) {
13285
+ const dir = path$o.dirname(result.tsconfigFile);
13286
+ return result.tsconfig.references.map((ref) => {
13287
+ const refPath = ref.path.endsWith('.json') ? ref.path : path$o.join(ref.path, 'tsconfig.json');
13288
+ return resolve2posix(dir, refPath);
13289
+ });
13219
13290
  }
13220
- function walk$3(dir, state, done) {
13221
- if (state.err) {
13222
- return;
13223
- }
13224
- state.calls++;
13225
- readdir$4(dir, { withFileTypes: true }, (err, entries = []) => {
13226
- var _a;
13227
- if (state.err) {
13228
- return;
13229
- }
13230
- if (err && !(err.code === "ENOENT" || err.code === "EACCES" || err.code === "EPERM")) {
13231
- state.err = true;
13232
- done(err);
13233
- } else {
13234
- for (const ent of entries) {
13235
- if (ent.isDirectory() && !((_a = state.skip) == null ? void 0 : _a.call(state, ent.name))) {
13236
- walk$3(`${dir}${sep}${ent.name}`, state, done);
13237
- } else if (ent.isFile() && ent.name === "tsconfig.json") {
13238
- state.files.push(`${dir}${sep}tsconfig.json`);
13239
- }
13240
- }
13241
- if (--state.calls === 0) {
13242
- if (!state.err) {
13243
- done(null, state.files);
13244
- }
13245
- }
13246
- }
13247
- });
13291
+
13292
+ /**
13293
+ * @param {string} filename
13294
+ * @param {import('./public.d.ts').TSConfckParseResult} result
13295
+ * @returns {import('./public.d.ts').TSConfckParseResult}
13296
+ */
13297
+ function resolveSolutionTSConfig(filename, result) {
13298
+ if (
13299
+ result.referenced &&
13300
+ DEFAULT_EXTENSIONS.some((ext) => filename.endsWith(ext)) &&
13301
+ !isIncluded(filename, result)
13302
+ ) {
13303
+ const solutionTSConfig = result.referenced.find((referenced) =>
13304
+ isIncluded(filename, referenced)
13305
+ );
13306
+ if (solutionTSConfig) {
13307
+ return solutionTSConfig;
13308
+ }
13309
+ }
13310
+ return result;
13311
+ }
13312
+
13313
+ /**
13314
+ *
13315
+ * @param {string} filename
13316
+ * @param {import('./public.d.ts').TSConfckParseResult} result
13317
+ * @returns {boolean}
13318
+ */
13319
+ function isIncluded(filename, result) {
13320
+ const dir = native2posix(path$o.dirname(result.tsconfigFile));
13321
+ const files = (result.tsconfig.files || []).map((file) => resolve2posix(dir, file));
13322
+ const absoluteFilename = resolve2posix(null, filename);
13323
+ if (files.includes(filename)) {
13324
+ return true;
13325
+ }
13326
+ const isIncluded = isGlobMatch(
13327
+ absoluteFilename,
13328
+ dir,
13329
+ result.tsconfig.include || (result.tsconfig.files ? [] : [GLOB_ALL_PATTERN])
13330
+ );
13331
+ if (isIncluded) {
13332
+ const isExcluded = isGlobMatch(absoluteFilename, dir, result.tsconfig.exclude || []);
13333
+ return !isExcluded;
13334
+ }
13335
+ return false;
13336
+ }
13337
+
13338
+ /**
13339
+ * test filenames agains glob patterns in tsconfig
13340
+ *
13341
+ * @param filename {string} posix style abolute path to filename to test
13342
+ * @param dir {string} posix style absolute path to directory of tsconfig containing patterns
13343
+ * @param patterns {string[]} glob patterns to match against
13344
+ * @returns {boolean} true when at least one pattern matches filename
13345
+ */
13346
+ function isGlobMatch(filename, dir, patterns) {
13347
+ return patterns.some((pattern) => {
13348
+ // filename must end with part of pattern that comes after last wildcard
13349
+ let lastWildcardIndex = pattern.length;
13350
+ let hasWildcard = false;
13351
+ for (let i = pattern.length - 1; i > -1; i--) {
13352
+ if (pattern[i] === '*' || pattern[i] === '?') {
13353
+ lastWildcardIndex = i;
13354
+ hasWildcard = true;
13355
+ break;
13356
+ }
13357
+ }
13358
+
13359
+ // if pattern does not end with wildcard, filename must end with pattern after last wildcard
13360
+ if (
13361
+ lastWildcardIndex < pattern.length - 1 &&
13362
+ !filename.endsWith(pattern.slice(lastWildcardIndex + 1))
13363
+ ) {
13364
+ return false;
13365
+ }
13366
+
13367
+ // if pattern ends with *, filename must end with a default extension
13368
+ if (pattern.endsWith('*') && !DEFAULT_EXTENSIONS.some((ext) => filename.endsWith(ext))) {
13369
+ return false;
13370
+ }
13371
+
13372
+ // for **/* , filename must start with the dir
13373
+ if (pattern === GLOB_ALL_PATTERN) {
13374
+ return filename.startsWith(`${dir}/`);
13375
+ }
13376
+
13377
+ const resolvedPattern = resolve2posix(dir, pattern);
13378
+
13379
+ // filename must start with part of pattern that comes before first wildcard
13380
+ let firstWildcardIndex = -1;
13381
+ for (let i = 0; i < resolvedPattern.length; i++) {
13382
+ if (resolvedPattern[i] === '*' || resolvedPattern[i] === '?') {
13383
+ firstWildcardIndex = i;
13384
+ hasWildcard = true;
13385
+ break;
13386
+ }
13387
+ }
13388
+ if (
13389
+ firstWildcardIndex > 1 &&
13390
+ !filename.startsWith(resolvedPattern.slice(0, firstWildcardIndex - 1))
13391
+ ) {
13392
+ return false;
13393
+ }
13394
+
13395
+ // if no wildcard in pattern, filename must be equal to resolved pattern
13396
+ if (!hasWildcard) {
13397
+ return filename === resolvedPattern;
13398
+ }
13399
+
13400
+ // complex pattern, use regex to check it
13401
+ if (PATTERN_REGEX_CACHE.has(resolvedPattern)) {
13402
+ return PATTERN_REGEX_CACHE.get(resolvedPattern).test(filename);
13403
+ }
13404
+ const regex = pattern2regex(resolvedPattern);
13405
+ PATTERN_REGEX_CACHE.set(resolvedPattern, regex);
13406
+ return regex.test(filename);
13407
+ });
13408
+ }
13409
+
13410
+ /**
13411
+ * @param {string} resolvedPattern
13412
+ * @returns {RegExp}
13413
+ */
13414
+ function pattern2regex(resolvedPattern) {
13415
+ let regexStr = '^';
13416
+ for (let i = 0; i < resolvedPattern.length; i++) {
13417
+ const char = resolvedPattern[i];
13418
+ if (char === '?') {
13419
+ regexStr += '[^\\/]';
13420
+ continue;
13421
+ }
13422
+ if (char === '*') {
13423
+ if (resolvedPattern[i + 1] === '*' && resolvedPattern[i + 2] === '/') {
13424
+ i += 2;
13425
+ regexStr += '(?:[^\\/]*\\/)*'; // zero or more path segments
13426
+ continue;
13427
+ }
13428
+ regexStr += '[^\\/]*';
13429
+ continue;
13430
+ }
13431
+ if ('/.+^${}()|[]\\'.includes(char)) {
13432
+ regexStr += `\\`;
13433
+ }
13434
+ regexStr += char;
13435
+ }
13436
+
13437
+ // add known file endings if pattern ends on *
13438
+ if (resolvedPattern.endsWith('*')) {
13439
+ regexStr += DEFAULT_EXTENSIONS_RE_GROUP;
13440
+ }
13441
+ regexStr += '$';
13442
+
13443
+ return new RegExp(regexStr);
13444
+ }
13445
+
13446
+ /**
13447
+ * find the closest tsconfig.json file
13448
+ *
13449
+ * @param {string} filename - path to file to find tsconfig for (absolute or relative to cwd)
13450
+ * @param {import('./public.d.ts').TSConfckFindOptions} [options] - options
13451
+ * @returns {Promise<string|null>} absolute path to closest tsconfig.json or null if not found
13452
+ */
13453
+ async function find(filename, options) {
13454
+ let dir = path$o.dirname(path$o.resolve(filename));
13455
+ if (options?.ignoreNodeModules && isInNodeModules(dir)) {
13456
+ return null;
13457
+ }
13458
+ const cache = options?.cache;
13459
+ if (cache?.hasTSConfigPath(dir)) {
13460
+ return cache.getTSConfigPath(dir);
13461
+ }
13462
+ const { /** @type {Promise<string|null>} */ promise, resolve, reject } = makePromise();
13463
+ const root = options?.root ? path$o.resolve(options.root) : null;
13464
+ findUp(dir, { promise, resolve, reject }, options?.cache, root);
13465
+ return promise;
13248
13466
  }
13249
13467
 
13250
- // src/to-json.ts
13468
+ /**
13469
+ *
13470
+ * @param {string} dir
13471
+ * @param {{promise:Promise<string|null>,resolve:(result:string|null)=>void,reject:(err:any)=>void}} madePromise
13472
+ * @param {import('./cache.js').TSConfckCache} [cache]
13473
+ * @param {string} [root]
13474
+ */
13475
+ function findUp(dir, { resolve, reject, promise }, cache, root) {
13476
+ const tsconfig = path$o.join(dir, 'tsconfig.json');
13477
+ if (cache) {
13478
+ if (cache.hasTSConfigPath(dir)) {
13479
+ let cached;
13480
+ try {
13481
+ cached = cache.getTSConfigPath(dir);
13482
+ } catch (e) {
13483
+ reject(e);
13484
+ return;
13485
+ }
13486
+ if (cached?.then) {
13487
+ cached.then(resolve).catch(reject);
13488
+ } else {
13489
+ resolve(cached);
13490
+ }
13491
+ } else {
13492
+ cache.setTSConfigPath(dir, promise);
13493
+ }
13494
+ }
13495
+ fs$l.stat(tsconfig, (err, stats) => {
13496
+ if (stats && (stats.isFile() || stats.isFIFO())) {
13497
+ resolve(tsconfig);
13498
+ } else if (err?.code !== 'ENOENT') {
13499
+ reject(err);
13500
+ } else {
13501
+ let parent;
13502
+ if (root === dir || (parent = path$o.dirname(dir)) === dir) {
13503
+ resolve(null);
13504
+ } else {
13505
+ findUp(parent, { promise, resolve, reject }, cache, root);
13506
+ }
13507
+ }
13508
+ });
13509
+ }
13510
+
13511
+ /*
13512
+ this file contains code from strip-bom and strip-json-comments by Sindre Sorhus
13513
+ https://github.com/sindresorhus/strip-json-comments/blob/v4.0.0/index.js
13514
+ https://github.com/sindresorhus/strip-bom/blob/v5.0.0/index.js
13515
+ licensed under MIT, see ../LICENSE
13516
+ */
13517
+
13518
+ /**
13519
+ * convert content of tsconfig.json to regular json
13520
+ *
13521
+ * @param {string} tsconfigJson - content of tsconfig.json
13522
+ * @returns {string} content as regular json, comments and dangling commas have been replaced with whitespace
13523
+ */
13251
13524
  function toJson(tsconfigJson) {
13252
- const stripped = stripDanglingComma(stripJsonComments(stripBom(tsconfigJson)));
13253
- if (stripped.trim() === "") {
13254
- return "{}";
13255
- } else {
13256
- return stripped;
13257
- }
13525
+ const stripped = stripDanglingComma(stripJsonComments(stripBom(tsconfigJson)));
13526
+ if (stripped.trim() === '') {
13527
+ // only whitespace left after stripping, return empty object so that JSON.parse still works
13528
+ return '{}';
13529
+ } else {
13530
+ return stripped;
13531
+ }
13258
13532
  }
13533
+
13534
+ /**
13535
+ * replace dangling commas from pseudo-json string with single space
13536
+ * implementation heavily inspired by strip-json-comments
13537
+ *
13538
+ * @param {string} pseudoJson
13539
+ * @returns {string}
13540
+ */
13259
13541
  function stripDanglingComma(pseudoJson) {
13260
- let insideString = false;
13261
- let offset = 0;
13262
- let result = "";
13263
- let danglingCommaPos = null;
13264
- for (let i = 0; i < pseudoJson.length; i++) {
13265
- const currentCharacter = pseudoJson[i];
13266
- if (currentCharacter === '"') {
13267
- const escaped = isEscaped(pseudoJson, i);
13268
- if (!escaped) {
13269
- insideString = !insideString;
13270
- }
13271
- }
13272
- if (insideString) {
13273
- danglingCommaPos = null;
13274
- continue;
13275
- }
13276
- if (currentCharacter === ",") {
13277
- danglingCommaPos = i;
13278
- continue;
13279
- }
13280
- if (danglingCommaPos) {
13281
- if (currentCharacter === "}" || currentCharacter === "]") {
13282
- result += pseudoJson.slice(offset, danglingCommaPos) + " ";
13283
- offset = danglingCommaPos + 1;
13284
- danglingCommaPos = null;
13285
- } else if (!currentCharacter.match(/\s/)) {
13286
- danglingCommaPos = null;
13287
- }
13288
- }
13289
- }
13290
- return result + pseudoJson.substring(offset);
13542
+ let insideString = false;
13543
+ let offset = 0;
13544
+ let result = '';
13545
+ let danglingCommaPos = null;
13546
+ for (let i = 0; i < pseudoJson.length; i++) {
13547
+ const currentCharacter = pseudoJson[i];
13548
+ if (currentCharacter === '"') {
13549
+ const escaped = isEscaped(pseudoJson, i);
13550
+ if (!escaped) {
13551
+ insideString = !insideString;
13552
+ }
13553
+ }
13554
+ if (insideString) {
13555
+ danglingCommaPos = null;
13556
+ continue;
13557
+ }
13558
+ if (currentCharacter === ',') {
13559
+ danglingCommaPos = i;
13560
+ continue;
13561
+ }
13562
+ if (danglingCommaPos) {
13563
+ if (currentCharacter === '}' || currentCharacter === ']') {
13564
+ result += pseudoJson.slice(offset, danglingCommaPos) + ' ';
13565
+ offset = danglingCommaPos + 1;
13566
+ danglingCommaPos = null;
13567
+ } else if (!currentCharacter.match(/\s/)) {
13568
+ danglingCommaPos = null;
13569
+ }
13570
+ }
13571
+ }
13572
+ return result + pseudoJson.substring(offset);
13291
13573
  }
13574
+
13575
+ // start strip-json-comments
13576
+ /**
13577
+ *
13578
+ * @param {string} jsonString
13579
+ * @param {number} quotePosition
13580
+ * @returns {boolean}
13581
+ */
13292
13582
  function isEscaped(jsonString, quotePosition) {
13293
- let index = quotePosition - 1;
13294
- let backslashCount = 0;
13295
- while (jsonString[index] === "\\") {
13296
- index -= 1;
13297
- backslashCount += 1;
13298
- }
13299
- return Boolean(backslashCount % 2);
13583
+ let index = quotePosition - 1;
13584
+ let backslashCount = 0;
13585
+
13586
+ while (jsonString[index] === '\\') {
13587
+ index -= 1;
13588
+ backslashCount += 1;
13589
+ }
13590
+
13591
+ return Boolean(backslashCount % 2);
13300
13592
  }
13593
+
13594
+ /**
13595
+ *
13596
+ * @param {string} string
13597
+ * @param {number?} start
13598
+ * @param {number?} end
13599
+ */
13301
13600
  function strip(string, start, end) {
13302
- return string.slice(start, end).replace(/\S/g, " ");
13601
+ return string.slice(start, end).replace(/\S/g, ' ');
13303
13602
  }
13304
- var singleComment = Symbol("singleComment");
13305
- var multiComment = Symbol("multiComment");
13603
+
13604
+ const singleComment = Symbol('singleComment');
13605
+ const multiComment = Symbol('multiComment');
13606
+
13607
+ /**
13608
+ * @param {string} jsonString
13609
+ * @returns {string}
13610
+ */
13306
13611
  function stripJsonComments(jsonString) {
13307
- let isInsideString = false;
13308
- let isInsideComment = false;
13309
- let offset = 0;
13310
- let result = "";
13311
- for (let index = 0; index < jsonString.length; index++) {
13312
- const currentCharacter = jsonString[index];
13313
- const nextCharacter = jsonString[index + 1];
13314
- if (!isInsideComment && currentCharacter === '"') {
13315
- const escaped = isEscaped(jsonString, index);
13316
- if (!escaped) {
13317
- isInsideString = !isInsideString;
13318
- }
13319
- }
13320
- if (isInsideString) {
13321
- continue;
13322
- }
13323
- if (!isInsideComment && currentCharacter + nextCharacter === "//") {
13324
- result += jsonString.slice(offset, index);
13325
- offset = index;
13326
- isInsideComment = singleComment;
13327
- index++;
13328
- } else if (isInsideComment === singleComment && currentCharacter + nextCharacter === "\r\n") {
13329
- index++;
13330
- isInsideComment = false;
13331
- result += strip(jsonString, offset, index);
13332
- offset = index;
13333
- } else if (isInsideComment === singleComment && currentCharacter === "\n") {
13334
- isInsideComment = false;
13335
- result += strip(jsonString, offset, index);
13336
- offset = index;
13337
- } else if (!isInsideComment && currentCharacter + nextCharacter === "/*") {
13338
- result += jsonString.slice(offset, index);
13339
- offset = index;
13340
- isInsideComment = multiComment;
13341
- index++;
13342
- } else if (isInsideComment === multiComment && currentCharacter + nextCharacter === "*/") {
13343
- index++;
13344
- isInsideComment = false;
13345
- result += strip(jsonString, offset, index + 1);
13346
- offset = index + 1;
13347
- }
13348
- }
13349
- return result + (isInsideComment ? strip(jsonString.slice(offset)) : jsonString.slice(offset));
13612
+ let isInsideString = false;
13613
+ /** @type {false | symbol} */
13614
+ let isInsideComment = false;
13615
+ let offset = 0;
13616
+ let result = '';
13617
+
13618
+ for (let index = 0; index < jsonString.length; index++) {
13619
+ const currentCharacter = jsonString[index];
13620
+ const nextCharacter = jsonString[index + 1];
13621
+
13622
+ if (!isInsideComment && currentCharacter === '"') {
13623
+ const escaped = isEscaped(jsonString, index);
13624
+ if (!escaped) {
13625
+ isInsideString = !isInsideString;
13626
+ }
13627
+ }
13628
+
13629
+ if (isInsideString) {
13630
+ continue;
13631
+ }
13632
+
13633
+ if (!isInsideComment && currentCharacter + nextCharacter === '//') {
13634
+ result += jsonString.slice(offset, index);
13635
+ offset = index;
13636
+ isInsideComment = singleComment;
13637
+ index++;
13638
+ } else if (isInsideComment === singleComment && currentCharacter + nextCharacter === '\r\n') {
13639
+ index++;
13640
+ isInsideComment = false;
13641
+ result += strip(jsonString, offset, index);
13642
+ offset = index;
13643
+ } else if (isInsideComment === singleComment && currentCharacter === '\n') {
13644
+ isInsideComment = false;
13645
+ result += strip(jsonString, offset, index);
13646
+ offset = index;
13647
+ } else if (!isInsideComment && currentCharacter + nextCharacter === '/*') {
13648
+ result += jsonString.slice(offset, index);
13649
+ offset = index;
13650
+ isInsideComment = multiComment;
13651
+ index++;
13652
+ } else if (isInsideComment === multiComment && currentCharacter + nextCharacter === '*/') {
13653
+ index++;
13654
+ isInsideComment = false;
13655
+ result += strip(jsonString, offset, index + 1);
13656
+ offset = index + 1;
13657
+ }
13658
+ }
13659
+
13660
+ return result + (isInsideComment ? strip(jsonString.slice(offset)) : jsonString.slice(offset));
13350
13661
  }
13662
+ // end strip-json-comments
13663
+
13664
+ // start strip-bom
13665
+ /**
13666
+ * @param {string} string
13667
+ * @returns {string}
13668
+ */
13351
13669
  function stripBom(string) {
13352
- if (string.charCodeAt(0) === 65279) {
13353
- return string.slice(1);
13354
- }
13355
- return string;
13356
- }
13357
- var POSIX_SEP_RE = new RegExp("\\" + require$$0$4.posix.sep, "g");
13358
- var NATIVE_SEP_RE = new RegExp("\\" + require$$0$4.sep, "g");
13359
- var PATTERN_REGEX_CACHE = /* @__PURE__ */ new Map();
13360
- var GLOB_ALL_PATTERN = `**/*`;
13361
- var DEFAULT_EXTENSIONS = [".ts", ".tsx", ".mts", ".cts"];
13362
- var DEFAULT_EXTENSIONS_RE_GROUP = `\\.(?:${DEFAULT_EXTENSIONS.map((ext) => ext.substring(1)).join(
13363
- "|"
13364
- )})`;
13365
- new Function("path", "return import(path).then(m => m.default)");
13366
- async function resolveTSConfig(filename) {
13367
- if (require$$0$4.extname(filename) !== ".json") {
13368
- return;
13369
- }
13370
- const tsconfig = require$$0$4.resolve(filename);
13371
- try {
13372
- const stat = await promises$1.stat(tsconfig);
13373
- if (stat.isFile() || stat.isFIFO()) {
13374
- return tsconfig;
13375
- }
13376
- } catch (e) {
13377
- if (e.code !== "ENOENT") {
13378
- throw e;
13379
- }
13380
- }
13381
- throw new Error(`no tsconfig file found for ${filename}`);
13382
- }
13383
- function posix2native(filename) {
13384
- return require$$0$4.posix.sep !== require$$0$4.sep && filename.includes(require$$0$4.posix.sep) ? filename.replace(POSIX_SEP_RE, require$$0$4.sep) : filename;
13385
- }
13386
- function native2posix(filename) {
13387
- return require$$0$4.posix.sep !== require$$0$4.sep && filename.includes(require$$0$4.sep) ? filename.replace(NATIVE_SEP_RE, require$$0$4.posix.sep) : filename;
13388
- }
13389
- function resolve2posix(dir, filename) {
13390
- if (require$$0$4.sep === require$$0$4.posix.sep) {
13391
- return dir ? require$$0$4.resolve(dir, filename) : require$$0$4.resolve(filename);
13392
- }
13393
- return native2posix(
13394
- dir ? require$$0$4.resolve(posix2native(dir), posix2native(filename)) : require$$0$4.resolve(posix2native(filename))
13395
- );
13396
- }
13397
- function resolveReferencedTSConfigFiles(result) {
13398
- const dir = require$$0$4.dirname(result.tsconfigFile);
13399
- return result.tsconfig.references.map((ref) => {
13400
- const refPath = ref.path.endsWith(".json") ? ref.path : require$$0$4.join(ref.path, "tsconfig.json");
13401
- return resolve2posix(dir, refPath);
13402
- });
13403
- }
13404
- function resolveSolutionTSConfig(filename, result) {
13405
- if (result.referenced && DEFAULT_EXTENSIONS.some((ext) => filename.endsWith(ext)) && !isIncluded(filename, result)) {
13406
- const solutionTSConfig = result.referenced.find(
13407
- (referenced) => isIncluded(filename, referenced)
13408
- );
13409
- if (solutionTSConfig) {
13410
- return {
13411
- ...solutionTSConfig,
13412
- solution: result
13413
- };
13414
- }
13415
- }
13416
- return result;
13417
- }
13418
- function isIncluded(filename, result) {
13419
- const dir = native2posix(require$$0$4.dirname(result.tsconfigFile));
13420
- const files = (result.tsconfig.files || []).map((file) => resolve2posix(dir, file));
13421
- const absoluteFilename = resolve2posix(null, filename);
13422
- if (files.includes(filename)) {
13423
- return true;
13424
- }
13425
- const isIncluded2 = isGlobMatch(
13426
- absoluteFilename,
13427
- dir,
13428
- result.tsconfig.include || (result.tsconfig.files ? [] : [GLOB_ALL_PATTERN])
13429
- );
13430
- if (isIncluded2) {
13431
- const isExcluded = isGlobMatch(absoluteFilename, dir, result.tsconfig.exclude || []);
13432
- return !isExcluded;
13433
- }
13434
- return false;
13435
- }
13436
- function isGlobMatch(filename, dir, patterns) {
13437
- return patterns.some((pattern) => {
13438
- let lastWildcardIndex = pattern.length;
13439
- let hasWildcard = false;
13440
- for (let i = pattern.length - 1; i > -1; i--) {
13441
- if (pattern[i] === "*" || pattern[i] === "?") {
13442
- lastWildcardIndex = i;
13443
- hasWildcard = true;
13444
- break;
13445
- }
13446
- }
13447
- if (lastWildcardIndex < pattern.length - 1 && !filename.endsWith(pattern.slice(lastWildcardIndex + 1))) {
13448
- return false;
13449
- }
13450
- if (pattern.endsWith("*") && !DEFAULT_EXTENSIONS.some((ext) => filename.endsWith(ext))) {
13451
- return false;
13452
- }
13453
- if (pattern === GLOB_ALL_PATTERN) {
13454
- return filename.startsWith(`${dir}/`);
13455
- }
13456
- const resolvedPattern = resolve2posix(dir, pattern);
13457
- let firstWildcardIndex = -1;
13458
- for (let i = 0; i < resolvedPattern.length; i++) {
13459
- if (resolvedPattern[i] === "*" || resolvedPattern[i] === "?") {
13460
- firstWildcardIndex = i;
13461
- hasWildcard = true;
13462
- break;
13463
- }
13464
- }
13465
- if (firstWildcardIndex > 1 && !filename.startsWith(resolvedPattern.slice(0, firstWildcardIndex - 1))) {
13466
- return false;
13467
- }
13468
- if (!hasWildcard) {
13469
- return filename === resolvedPattern;
13470
- }
13471
- if (PATTERN_REGEX_CACHE.has(resolvedPattern)) {
13472
- return PATTERN_REGEX_CACHE.get(resolvedPattern).test(filename);
13473
- }
13474
- const regex = pattern2regex(resolvedPattern);
13475
- PATTERN_REGEX_CACHE.set(resolvedPattern, regex);
13476
- return regex.test(filename);
13477
- });
13478
- }
13479
- function pattern2regex(resolvedPattern) {
13480
- let regexStr = "^";
13481
- for (let i = 0; i < resolvedPattern.length; i++) {
13482
- const char = resolvedPattern[i];
13483
- if (char === "?") {
13484
- regexStr += "[^\\/]";
13485
- continue;
13486
- }
13487
- if (char === "*") {
13488
- if (resolvedPattern[i + 1] === "*" && resolvedPattern[i + 2] === "/") {
13489
- i += 2;
13490
- regexStr += "(?:[^\\/]*\\/)*";
13491
- continue;
13492
- }
13493
- regexStr += "[^\\/]*";
13494
- continue;
13495
- }
13496
- if ("/.+^${}()|[]\\".includes(char)) {
13497
- regexStr += `\\`;
13498
- }
13499
- regexStr += char;
13500
- }
13501
- if (resolvedPattern.endsWith("*")) {
13502
- regexStr += DEFAULT_EXTENSIONS_RE_GROUP;
13503
- }
13504
- regexStr += "$";
13505
- return new RegExp(regexStr);
13670
+ // Catches EFBBBF (UTF-8 BOM) because the buffer-to-string
13671
+ // conversion translates it to FEFF (UTF-16 BOM).
13672
+ if (string.charCodeAt(0) === 0xfeff) {
13673
+ return string.slice(1);
13674
+ }
13675
+ return string;
13506
13676
  }
13677
+ // end strip-bom
13678
+
13679
+ const not_found_result = {
13680
+ tsconfigFile: null,
13681
+ tsconfig: {}
13682
+ };
13507
13683
 
13508
- // src/parse.ts
13684
+ /**
13685
+ * parse the closest tsconfig.json file
13686
+ *
13687
+ * @param {string} filename - path to a tsconfig .json or a source file or directory (absolute or relative to cwd)
13688
+ * @param {import('./public.d.ts').TSConfckParseOptions} [options] - options
13689
+ * @returns {Promise<import('./public.d.ts').TSConfckParseResult>}
13690
+ * @throws {TSConfckParseError}
13691
+ */
13509
13692
  async function parse$f(filename, options) {
13510
- const cache = options == null ? void 0 : options.cache;
13511
- if (cache == null ? void 0 : cache.has(filename)) {
13512
- return cache.get(filename);
13513
- }
13514
- let tsconfigFile;
13515
- if (options == null ? void 0 : options.resolveWithEmptyIfConfigNotFound) {
13516
- try {
13517
- tsconfigFile = await resolveTSConfig(filename) || await find(filename, options);
13518
- } catch (e) {
13519
- const notFoundResult = {
13520
- tsconfigFile: "no_tsconfig_file_found",
13521
- tsconfig: {}
13522
- };
13523
- cache == null ? void 0 : cache.set(filename, notFoundResult);
13524
- return notFoundResult;
13525
- }
13526
- } else {
13527
- tsconfigFile = await resolveTSConfig(filename) || await find(filename, options);
13528
- }
13529
- let result;
13530
- if (cache == null ? void 0 : cache.has(tsconfigFile)) {
13531
- result = cache.get(tsconfigFile);
13532
- } else {
13533
- result = await parseFile$1(tsconfigFile, cache);
13534
- await Promise.all([parseExtends(result, cache), parseReferences(result, cache)]);
13535
- cache == null ? void 0 : cache.set(tsconfigFile, result);
13536
- }
13537
- result = resolveSolutionTSConfig(filename, result);
13538
- cache == null ? void 0 : cache.set(filename, result);
13539
- return result;
13693
+ /** @type {import('./cache.js').TSConfckCache} */
13694
+ const cache = options?.cache;
13695
+ if (cache?.hasParseResult(filename)) {
13696
+ return cache.getParseResult(filename);
13697
+ }
13698
+ const {
13699
+ resolve,
13700
+ reject,
13701
+ /** @type {Promise<import('./public.d.ts').TSConfckParseResult>}*/
13702
+ promise
13703
+ } = makePromise();
13704
+ cache?.setParseResult(filename, promise);
13705
+ try {
13706
+ let tsconfigFile =
13707
+ (await resolveTSConfigJson(filename, cache)) || (await find(filename, options));
13708
+ if (!tsconfigFile) {
13709
+ resolve(not_found_result);
13710
+ return promise;
13711
+ }
13712
+ let result;
13713
+ if (filename !== tsconfigFile && cache?.hasParseResult(tsconfigFile)) {
13714
+ result = await cache.getParseResult(tsconfigFile);
13715
+ } else {
13716
+ result = await parseFile$1(tsconfigFile, cache, filename === tsconfigFile);
13717
+ await Promise.all([parseExtends(result, cache), parseReferences(result, cache)]);
13718
+ }
13719
+ resolve(resolveSolutionTSConfig(filename, result));
13720
+ return promise;
13721
+ } catch (e) {
13722
+ reject(e);
13723
+ return promise;
13724
+ }
13540
13725
  }
13541
- async function parseFile$1(tsconfigFile, cache) {
13542
- if (cache == null ? void 0 : cache.has(tsconfigFile)) {
13543
- return cache.get(tsconfigFile);
13544
- }
13545
- try {
13546
- const tsconfigJson = await promises$1.readFile(tsconfigFile, "utf-8");
13547
- const json = toJson(tsconfigJson);
13548
- const result = {
13549
- tsconfigFile,
13550
- tsconfig: normalizeTSConfig(JSON.parse(json), require$$0$4.dirname(tsconfigFile))
13551
- };
13552
- cache == null ? void 0 : cache.set(tsconfigFile, result);
13553
- return result;
13554
- } catch (e) {
13555
- throw new TSConfckParseError(
13556
- `parsing ${tsconfigFile} failed: ${e}`,
13557
- "PARSE_FILE",
13558
- tsconfigFile,
13559
- e
13560
- );
13561
- }
13726
+
13727
+ /**
13728
+ *
13729
+ * @param {string} tsconfigFile - path to tsconfig file
13730
+ * @param {import('./cache.js').TSConfckCache} [cache] - cache
13731
+ * @param {boolean} [skipCache] - skip cache
13732
+ * @returns {Promise<import('./public.d.ts').TSConfckParseResult>}
13733
+ */
13734
+ async function parseFile$1(tsconfigFile, cache, skipCache) {
13735
+ if (!skipCache && cache?.hasParseResult(tsconfigFile)) {
13736
+ return cache.getParseResult(tsconfigFile);
13737
+ }
13738
+ const promise = promises$1
13739
+ .readFile(tsconfigFile, 'utf-8')
13740
+ .then(toJson)
13741
+ .then((json) => {
13742
+ return {
13743
+ tsconfigFile,
13744
+ tsconfig: normalizeTSConfig(JSON.parse(json), path$o.dirname(tsconfigFile))
13745
+ };
13746
+ })
13747
+ .catch((e) => {
13748
+ throw new TSConfckParseError(
13749
+ `parsing ${tsconfigFile} failed: ${e}`,
13750
+ 'PARSE_FILE',
13751
+ tsconfigFile,
13752
+ e
13753
+ );
13754
+ });
13755
+ if (!skipCache) {
13756
+ cache?.setParseResult(tsconfigFile, promise);
13757
+ }
13758
+ return promise;
13562
13759
  }
13760
+
13761
+ /**
13762
+ * normalize to match the output of ts.parseJsonConfigFileContent
13763
+ *
13764
+ * @param {any} tsconfig - typescript tsconfig output
13765
+ * @param {string} dir - directory
13766
+ */
13563
13767
  function normalizeTSConfig(tsconfig, dir) {
13564
- var _a;
13565
- if (((_a = tsconfig.compilerOptions) == null ? void 0 : _a.baseUrl) && !require$$0$4.isAbsolute(tsconfig.compilerOptions.baseUrl)) {
13566
- tsconfig.compilerOptions.baseUrl = resolve2posix(dir, tsconfig.compilerOptions.baseUrl);
13567
- }
13568
- return tsconfig;
13768
+ // set baseUrl to absolute path
13769
+ if (tsconfig.compilerOptions?.baseUrl && !path$o.isAbsolute(tsconfig.compilerOptions.baseUrl)) {
13770
+ tsconfig.compilerOptions.baseUrl = resolve2posix(dir, tsconfig.compilerOptions.baseUrl);
13771
+ }
13772
+ return tsconfig;
13569
13773
  }
13774
+
13775
+ /**
13776
+ *
13777
+ * @param {import('./public.d.ts').TSConfckParseResult} result
13778
+ * @param {import('./cache.js').TSConfckCache} [cache]
13779
+ * @returns {Promise<void>}
13780
+ */
13570
13781
  async function parseReferences(result, cache) {
13571
- if (!result.tsconfig.references) {
13572
- return;
13573
- }
13574
- const referencedFiles = resolveReferencedTSConfigFiles(result);
13575
- const referenced = await Promise.all(referencedFiles.map((file) => parseFile$1(file, cache)));
13576
- await Promise.all(referenced.map((ref) => parseExtends(ref, cache)));
13577
- result.referenced = referenced;
13782
+ if (!result.tsconfig.references) {
13783
+ return;
13784
+ }
13785
+ const referencedFiles = resolveReferencedTSConfigFiles(result);
13786
+ const referenced = await Promise.all(referencedFiles.map((file) => parseFile$1(file, cache)));
13787
+ await Promise.all(referenced.map((ref) => parseExtends(ref, cache)));
13788
+ referenced.forEach((ref) => {
13789
+ ref.solution = result;
13790
+ });
13791
+ result.referenced = referenced;
13578
13792
  }
13793
+
13794
+ /**
13795
+ * @param {import('./public.d.ts').TSConfckParseResult} result
13796
+ * @param {import('./cache.js').TSConfckCache}[cache]
13797
+ * @returns {Promise<void>}
13798
+ */
13579
13799
  async function parseExtends(result, cache) {
13580
- if (!result.tsconfig.extends) {
13581
- return;
13582
- }
13583
- const extended = [
13584
- { tsconfigFile: result.tsconfigFile, tsconfig: JSON.parse(JSON.stringify(result.tsconfig)) }
13585
- ];
13586
- let pos = 0;
13587
- const extendsPath = [];
13588
- let currentBranchDepth = 0;
13589
- while (pos < extended.length) {
13590
- const extending = extended[pos];
13591
- extendsPath.push(extending.tsconfigFile);
13592
- if (extending.tsconfig.extends) {
13593
- currentBranchDepth += 1;
13594
- let resolvedExtends;
13595
- if (!Array.isArray(extending.tsconfig.extends)) {
13596
- resolvedExtends = [resolveExtends(extending.tsconfig.extends, extending.tsconfigFile)];
13597
- } else {
13598
- resolvedExtends = extending.tsconfig.extends.reverse().map((ex) => resolveExtends(ex, extending.tsconfigFile));
13599
- }
13600
- const circularExtends = resolvedExtends.find(
13601
- (tsconfigFile) => extendsPath.includes(tsconfigFile)
13602
- );
13603
- if (circularExtends) {
13604
- const circle = extendsPath.concat([circularExtends]).join(" -> ");
13605
- throw new TSConfckParseError(
13606
- `Circular dependency in "extends": ${circle}`,
13607
- "EXTENDS_CIRCULAR",
13608
- result.tsconfigFile
13609
- );
13610
- }
13611
- extended.splice(
13612
- pos + 1,
13613
- 0,
13614
- ...await Promise.all(resolvedExtends.map((file) => parseFile$1(file, cache)))
13615
- );
13616
- } else {
13617
- extendsPath.splice(-currentBranchDepth);
13618
- currentBranchDepth = 0;
13619
- }
13620
- pos = pos + 1;
13621
- }
13622
- result.extended = extended;
13623
- for (const ext of result.extended.slice(1)) {
13624
- extendTSConfig(result, ext);
13625
- }
13800
+ if (!result.tsconfig.extends) {
13801
+ return;
13802
+ }
13803
+ // use result as first element in extended
13804
+ // but dereference tsconfig so that mergeExtended can modify the original without affecting extended[0]
13805
+ /** @type {import('./public.d.ts').TSConfckParseResult[]} */
13806
+ const extended = [
13807
+ { tsconfigFile: result.tsconfigFile, tsconfig: JSON.parse(JSON.stringify(result.tsconfig)) }
13808
+ ];
13809
+
13810
+ // flatten extends graph into extended
13811
+ let pos = 0;
13812
+ /** @type {string[]} */
13813
+ const extendsPath = [];
13814
+ let currentBranchDepth = 0;
13815
+ while (pos < extended.length) {
13816
+ const extending = extended[pos];
13817
+ extendsPath.push(extending.tsconfigFile);
13818
+ if (extending.tsconfig.extends) {
13819
+ // keep following this branch
13820
+ currentBranchDepth += 1;
13821
+ /** @type {string[]} */
13822
+ let resolvedExtends;
13823
+ if (!Array.isArray(extending.tsconfig.extends)) {
13824
+ resolvedExtends = [resolveExtends(extending.tsconfig.extends, extending.tsconfigFile)];
13825
+ } else {
13826
+ // reverse because typescript 5.0 treats ['a','b','c'] as c extends b extends a
13827
+ resolvedExtends = extending.tsconfig.extends
13828
+ .reverse()
13829
+ .map((ex) => resolveExtends(ex, extending.tsconfigFile));
13830
+ }
13831
+
13832
+ const circularExtends = resolvedExtends.find((tsconfigFile) =>
13833
+ extendsPath.includes(tsconfigFile)
13834
+ );
13835
+ if (circularExtends) {
13836
+ const circle = extendsPath.concat([circularExtends]).join(' -> ');
13837
+ throw new TSConfckParseError(
13838
+ `Circular dependency in "extends": ${circle}`,
13839
+ 'EXTENDS_CIRCULAR',
13840
+ result.tsconfigFile
13841
+ );
13842
+ }
13843
+ // add new extends to the list directly after current
13844
+ extended.splice(
13845
+ pos + 1,
13846
+ 0,
13847
+ ...(await Promise.all(resolvedExtends.map((file) => parseFile$1(file, cache))))
13848
+ );
13849
+ } else {
13850
+ // reached a leaf, backtrack to the last branching point and continue
13851
+ extendsPath.splice(-currentBranchDepth);
13852
+ currentBranchDepth = 0;
13853
+ }
13854
+ pos = pos + 1;
13855
+ }
13856
+ result.extended = extended;
13857
+ // skip first as it is the original config
13858
+ for (const ext of result.extended.slice(1)) {
13859
+ extendTSConfig(result, ext);
13860
+ }
13626
13861
  }
13862
+
13863
+ /**
13864
+ *
13865
+ * @param {string} extended
13866
+ * @param {string} from
13867
+ * @returns {string}
13868
+ */
13627
13869
  function resolveExtends(extended, from) {
13628
- let error;
13629
- try {
13630
- return createRequire$2(from).resolve(extended);
13631
- } catch (e) {
13632
- error = e;
13633
- }
13634
- if (!require$$0$4.isAbsolute(extended) && !extended.startsWith("./") && !extended.startsWith("../")) {
13635
- try {
13636
- const fallbackExtended = require$$0$4.join(extended, "tsconfig.json");
13637
- return createRequire$2(from).resolve(fallbackExtended);
13638
- } catch (e) {
13639
- error = e;
13640
- }
13641
- }
13642
- throw new TSConfckParseError(
13643
- `failed to resolve "extends":"${extended}" in ${from}`,
13644
- "EXTENDS_RESOLVE",
13645
- from,
13646
- error
13647
- );
13870
+ let error;
13871
+
13872
+ try {
13873
+ return createRequire$2(from).resolve(extended);
13874
+ } catch (e) {
13875
+ error = e;
13876
+ }
13877
+
13878
+ if (!path$o.isAbsolute(extended) && !extended.startsWith('./') && !extended.startsWith('../')) {
13879
+ try {
13880
+ const fallbackExtended = path$o.join(extended, 'tsconfig.json');
13881
+ return createRequire$2(from).resolve(fallbackExtended);
13882
+ } catch (e) {
13883
+ error = e;
13884
+ }
13885
+ }
13886
+
13887
+ throw new TSConfckParseError(
13888
+ `failed to resolve "extends":"${extended}" in ${from}`,
13889
+ 'EXTENDS_RESOLVE',
13890
+ from,
13891
+ error
13892
+ );
13648
13893
  }
13649
- var EXTENDABLE_KEYS = [
13650
- "compilerOptions",
13651
- "files",
13652
- "include",
13653
- "exclude",
13654
- "watchOptions",
13655
- "compileOnSave",
13656
- "typeAcquisition",
13657
- "buildOptions"
13894
+
13895
+ // references, extends and custom keys are not carried over
13896
+ const EXTENDABLE_KEYS = [
13897
+ 'compilerOptions',
13898
+ 'files',
13899
+ 'include',
13900
+ 'exclude',
13901
+ 'watchOptions',
13902
+ 'compileOnSave',
13903
+ 'typeAcquisition',
13904
+ 'buildOptions'
13658
13905
  ];
13906
+
13907
+ /**
13908
+ *
13909
+ * @param {import('./public.d.ts').TSConfckParseResult} extending
13910
+ * @param {import('./public.d.ts').TSConfckParseResult} extended
13911
+ * @returns void
13912
+ */
13659
13913
  function extendTSConfig(extending, extended) {
13660
- const extendingConfig = extending.tsconfig;
13661
- const extendedConfig = extended.tsconfig;
13662
- const relativePath = native2posix(
13663
- require$$0$4.relative(require$$0$4.dirname(extending.tsconfigFile), require$$0$4.dirname(extended.tsconfigFile))
13664
- );
13665
- for (const key of Object.keys(extendedConfig).filter((key2) => EXTENDABLE_KEYS.includes(key2))) {
13666
- if (key === "compilerOptions") {
13667
- if (!extendingConfig.compilerOptions) {
13668
- extendingConfig.compilerOptions = {};
13669
- }
13670
- for (const option of Object.keys(extendedConfig.compilerOptions)) {
13671
- if (Object.prototype.hasOwnProperty.call(extendingConfig.compilerOptions, option)) {
13672
- continue;
13673
- }
13674
- extendingConfig.compilerOptions[option] = rebaseRelative(
13675
- option,
13676
- extendedConfig.compilerOptions[option],
13677
- relativePath
13678
- );
13679
- }
13680
- } else if (extendingConfig[key] === void 0) {
13681
- if (key === "watchOptions") {
13682
- extendingConfig.watchOptions = {};
13683
- for (const option of Object.keys(extendedConfig.watchOptions)) {
13684
- extendingConfig.watchOptions[option] = rebaseRelative(
13685
- option,
13686
- extendedConfig.watchOptions[option],
13687
- relativePath
13688
- );
13689
- }
13690
- } else {
13691
- extendingConfig[key] = rebaseRelative(key, extendedConfig[key], relativePath);
13692
- }
13693
- }
13694
- }
13695
- }
13696
- var REBASE_KEYS = [
13697
- // root
13698
- "files",
13699
- "include",
13700
- "exclude",
13701
- // compilerOptions
13702
- "baseUrl",
13703
- "rootDir",
13704
- "rootDirs",
13705
- "typeRoots",
13706
- "outDir",
13707
- "outFile",
13708
- "declarationDir",
13709
- // watchOptions
13710
- "excludeDirectories",
13711
- "excludeFiles"
13712
- ];
13713
- function rebaseRelative(key, value, prependPath) {
13714
- if (!REBASE_KEYS.includes(key)) {
13715
- return value;
13716
- }
13717
- if (Array.isArray(value)) {
13718
- return value.map((x) => rebasePath(x, prependPath));
13719
- } else {
13720
- return rebasePath(value, prependPath);
13721
- }
13722
- }
13723
- function rebasePath(value, prependPath) {
13724
- if (require$$0$4.isAbsolute(value)) {
13725
- return value;
13726
- } else {
13727
- return require$$0$4.posix.normalize(require$$0$4.posix.join(prependPath, value));
13728
- }
13914
+ const extendingConfig = extending.tsconfig;
13915
+ const extendedConfig = extended.tsconfig;
13916
+ const relativePath = native2posix(
13917
+ path$o.relative(path$o.dirname(extending.tsconfigFile), path$o.dirname(extended.tsconfigFile))
13918
+ );
13919
+ for (const key of Object.keys(extendedConfig).filter((key) => EXTENDABLE_KEYS.includes(key))) {
13920
+ if (key === 'compilerOptions') {
13921
+ if (!extendingConfig.compilerOptions) {
13922
+ extendingConfig.compilerOptions = {};
13923
+ }
13924
+ for (const option of Object.keys(extendedConfig.compilerOptions)) {
13925
+ if (Object.prototype.hasOwnProperty.call(extendingConfig.compilerOptions, option)) {
13926
+ continue; // already set
13927
+ }
13928
+ extendingConfig.compilerOptions[option] = rebaseRelative(
13929
+ option,
13930
+ extendedConfig.compilerOptions[option],
13931
+ relativePath
13932
+ );
13933
+ }
13934
+ } else if (extendingConfig[key] === undefined) {
13935
+ if (key === 'watchOptions') {
13936
+ extendingConfig.watchOptions = {};
13937
+ for (const option of Object.keys(extendedConfig.watchOptions)) {
13938
+ extendingConfig.watchOptions[option] = rebaseRelative(
13939
+ option,
13940
+ extendedConfig.watchOptions[option],
13941
+ relativePath
13942
+ );
13943
+ }
13944
+ } else {
13945
+ extendingConfig[key] = rebaseRelative(key, extendedConfig[key], relativePath);
13946
+ }
13947
+ }
13948
+ }
13729
13949
  }
13730
- var TSConfckParseError = class _TSConfckParseError extends Error {
13731
- constructor(message, code, tsconfigFile, cause) {
13732
- super(message);
13733
- Object.setPrototypeOf(this, _TSConfckParseError.prototype);
13734
- this.name = _TSConfckParseError.name;
13735
- this.code = code;
13736
- this.cause = cause;
13737
- this.tsconfigFile = tsconfigFile;
13738
- }
13739
- };
13740
13950
 
13741
- // https://github.com/vitejs/vite/issues/2820#issuecomment-812495079
13742
- const ROOT_FILES = [
13743
- // '.git',
13744
- // https://pnpm.io/workspaces/
13745
- 'pnpm-workspace.yaml',
13746
- // https://rushjs.io/pages/advanced/config_files/
13747
- // 'rush.json',
13748
- // https://nx.dev/latest/react/getting-started/nx-setup
13749
- // 'workspace.json',
13750
- // 'nx.json',
13751
- // https://github.com/lerna/lerna#lernajson
13752
- 'lerna.json',
13951
+ const REBASE_KEYS = [
13952
+ // root
13953
+ 'files',
13954
+ 'include',
13955
+ 'exclude',
13956
+ // compilerOptions
13957
+ 'baseUrl',
13958
+ 'rootDir',
13959
+ 'rootDirs',
13960
+ 'typeRoots',
13961
+ 'outDir',
13962
+ 'outFile',
13963
+ 'declarationDir',
13964
+ // watchOptions
13965
+ 'excludeDirectories',
13966
+ 'excludeFiles'
13753
13967
  ];
13754
- // npm: https://docs.npmjs.com/cli/v7/using-npm/workspaces#installing-workspaces
13755
- // yarn: https://classic.yarnpkg.com/en/docs/workspaces/#toc-how-to-use-it
13756
- function hasWorkspacePackageJSON(root) {
13757
- const path = join$2(root, 'package.json');
13758
- if (!isFileReadable(path)) {
13759
- return false;
13760
- }
13761
- const content = JSON.parse(fs$l.readFileSync(path, 'utf-8')) || {};
13762
- return !!content.workspaces;
13763
- }
13764
- function hasRootFile(root) {
13765
- return ROOT_FILES.some((file) => fs$l.existsSync(join$2(root, file)));
13766
- }
13767
- function hasPackageJSON(root) {
13768
- const path = join$2(root, 'package.json');
13769
- return fs$l.existsSync(path);
13770
- }
13968
+
13969
+ /** @typedef {string | string[]} PathValue */
13970
+
13771
13971
  /**
13772
- * Search up for the nearest `package.json`
13972
+ *
13973
+ * @param {string} key
13974
+ * @param {PathValue} value
13975
+ * @param {string} prependPath
13976
+ * @returns {PathValue}
13773
13977
  */
13774
- function searchForPackageRoot(current, root = current) {
13775
- if (hasPackageJSON(current))
13776
- return current;
13777
- const dir = dirname$2(current);
13778
- // reach the fs root
13779
- if (!dir || dir === current)
13780
- return root;
13781
- return searchForPackageRoot(dir, root);
13978
+ function rebaseRelative(key, value, prependPath) {
13979
+ if (!REBASE_KEYS.includes(key)) {
13980
+ return value;
13981
+ }
13982
+ if (Array.isArray(value)) {
13983
+ return value.map((x) => rebasePath(x, prependPath));
13984
+ } else {
13985
+ return rebasePath(value, prependPath);
13986
+ }
13782
13987
  }
13988
+
13783
13989
  /**
13784
- * Search up for the nearest workspace root
13990
+ *
13991
+ * @param {string} value
13992
+ * @param {string} prependPath
13993
+ * @returns {string}
13785
13994
  */
13786
- function searchForWorkspaceRoot(current, root = searchForPackageRoot(current)) {
13787
- if (hasRootFile(current))
13788
- return current;
13789
- if (hasWorkspacePackageJSON(current))
13790
- return current;
13791
- const dir = dirname$2(current);
13792
- // reach the fs root
13793
- if (!dir || dir === current)
13794
- return root;
13795
- return searchForWorkspaceRoot(dir, root);
13995
+ function rebasePath(value, prependPath) {
13996
+ if (path$o.isAbsolute(value)) {
13997
+ return value;
13998
+ } else {
13999
+ // relative paths use posix syntax in tsconfig
14000
+ return path$o.posix.normalize(path$o.posix.join(prependPath, value));
14001
+ }
14002
+ }
14003
+
14004
+ class TSConfckParseError extends Error {
14005
+ /**
14006
+ * error code
14007
+ * @type {string}
14008
+ */
14009
+ code;
14010
+ /**
14011
+ * error cause
14012
+ * @type { Error | undefined}
14013
+ */
14014
+ cause;
14015
+
14016
+ /**
14017
+ * absolute path of tsconfig file where the error happened
14018
+ * @type {string}
14019
+ */
14020
+ tsconfigFile;
14021
+ /**
14022
+ *
14023
+ * @param {string} message - error message
14024
+ * @param {string} code - error code
14025
+ * @param {string} tsconfigFile - path to tsconfig file
14026
+ * @param {Error?} cause - cause of this error
14027
+ */
14028
+ constructor(message, code, tsconfigFile, cause) {
14029
+ super(message);
14030
+ // Set the prototype explicitly.
14031
+ Object.setPrototypeOf(this, TSConfckParseError.prototype);
14032
+ this.name = TSConfckParseError.name;
14033
+ this.code = code;
14034
+ this.cause = cause;
14035
+ this.tsconfigFile = tsconfigFile;
14036
+ }
13796
14037
  }
13797
14038
 
13798
- const debug$f = createDebugger('vite:esbuild');
13799
- const INJECT_HELPERS_IIFE_RE = /^(.*?)((?:const|var)\s+\S+\s*=\s*function\s*\([^)]*\)\s*\{\s*"use strict";)/s;
13800
- const INJECT_HELPERS_UMD_RE = /^(.*?)(\(function\([^)]*\)\s*\{.+?amd.+?function\([^)]*\)\s*\{\s*"use strict";)/s;
14039
+ /** @template T */
14040
+ class TSConfckCache {
14041
+ /**
14042
+ * clear cache, use this if you have a long running process and tsconfig files have been added,changed or deleted
14043
+ */
14044
+ clear() {
14045
+ this.#tsconfigPaths.clear();
14046
+ this.#parsed.clear();
14047
+ }
14048
+
14049
+ /**
14050
+ * has cached closest tsconfig for files in dir
14051
+ * @param {string} dir
14052
+ * @returns {boolean}
14053
+ */
14054
+ hasTSConfigPath(dir) {
14055
+ return this.#tsconfigPaths.has(dir);
14056
+ }
14057
+
14058
+ /**
14059
+ * get cached closest tsconfig for files in dir
14060
+ * @param {string} dir
14061
+ * @returns {Promise<string|null>|string|null}
14062
+ * @throws {unknown} if cached value is an error
14063
+ */
14064
+ getTSConfigPath(dir) {
14065
+ const value = this.#tsconfigPaths.get(dir);
14066
+ if (value === null || value.length || value.then) {
14067
+ return value;
14068
+ } else {
14069
+ throw value;
14070
+ }
14071
+ }
14072
+
14073
+ /**
14074
+ * has parsed tsconfig for file
14075
+ * @param {string} file
14076
+ * @returns {boolean}
14077
+ */
14078
+ hasParseResult(file) {
14079
+ return this.#parsed.has(file);
14080
+ }
14081
+
14082
+ /**
14083
+ * get parsed tsconfig for file
14084
+ * @param {string} file
14085
+ * @returns {Promise<T>|T}
14086
+ * @throws {unknown} if cached value is an error
14087
+ */
14088
+ getParseResult(file) {
14089
+ const value = this.#parsed.get(file);
14090
+ if (value.then || value.tsconfig) {
14091
+ return value;
14092
+ } else {
14093
+ throw value; // cached error, rethrow
14094
+ }
14095
+ }
14096
+
14097
+ /**
14098
+ * @internal
14099
+ * @private
14100
+ * @param file
14101
+ * @param {Promise<T>} result
14102
+ */
14103
+ setParseResult(file, result) {
14104
+ this.#parsed.set(file, result);
14105
+ result
14106
+ .then((parsed) => {
14107
+ if (this.#parsed.get(file) === result) {
14108
+ this.#parsed.set(file, parsed);
14109
+ }
14110
+ })
14111
+ .catch((e) => {
14112
+ if (this.#parsed.get(file) === result) {
14113
+ this.#parsed.set(file, e);
14114
+ }
14115
+ });
14116
+ }
14117
+
14118
+ /**
14119
+ * @internal
14120
+ * @private
14121
+ * @param {string} dir
14122
+ * @param {Promise<string|null>} tsconfigPath
14123
+ */
14124
+ setTSConfigPath(dir, tsconfigPath) {
14125
+ this.#tsconfigPaths.set(dir, tsconfigPath);
14126
+ tsconfigPath
14127
+ .then((path) => {
14128
+ if (this.#tsconfigPaths.get(dir) === tsconfigPath) {
14129
+ this.#tsconfigPaths.set(dir, path);
14130
+ }
14131
+ })
14132
+ .catch((e) => {
14133
+ if (this.#tsconfigPaths.get(dir) === tsconfigPath) {
14134
+ this.#tsconfigPaths.set(dir, e);
14135
+ }
14136
+ });
14137
+ }
14138
+
14139
+ /**
14140
+ * map directories to their closest tsconfig.json
14141
+ * @internal
14142
+ * @private
14143
+ * @type{Map<string,(Promise<string|null>|string|null)>}
14144
+ */
14145
+ #tsconfigPaths = new Map();
14146
+
14147
+ /**
14148
+ * map files to their parsed tsconfig result
14149
+ * @internal
14150
+ * @private
14151
+ * @type {Map<string,(Promise<T>|T)> }
14152
+ */
14153
+ #parsed = new Map();
14154
+ }
14155
+
14156
+ const debug$g = createDebugger('vite:esbuild');
14157
+ // IIFE content looks like `var MyLib = function() {`. Spaces are removed when minified
14158
+ const IIFE_BEGIN_RE = /(const|var)\s+\S+\s*=\s*function\(\)\s*\{.*"use strict";/s;
13801
14159
  const validExtensionRE = /\.\w+$/;
13802
14160
  const jsxExtensionsRE = /\.(?:j|t)sx\b/;
13803
14161
  let server;
@@ -13931,7 +14289,7 @@ async function transformWithEsbuild(code, filename, options, inMap) {
13931
14289
  };
13932
14290
  }
13933
14291
  catch (e) {
13934
- debug$f?.(`esbuild error with options used: `, resolvedOptions);
14292
+ debug$g?.(`esbuild error with options used: `, resolvedOptions);
13935
14293
  // patch error information
13936
14294
  if (e.errors) {
13937
14295
  e.frame = '';
@@ -13967,7 +14325,6 @@ function esbuildPlugin(config) {
13967
14325
  // tree-shaking. (#9164)
13968
14326
  keepNames: false,
13969
14327
  };
13970
- initTSConfck(config.root);
13971
14328
  return {
13972
14329
  name: 'vite:esbuild',
13973
14330
  configureServer(_server) {
@@ -14014,7 +14371,6 @@ const rollupToEsbuildFormatMap = {
14014
14371
  iife: undefined,
14015
14372
  };
14016
14373
  const buildEsbuildPlugin = (config) => {
14017
- initTSConfck(config.root);
14018
14374
  return {
14019
14375
  name: 'vite:esbuild-transpile',
14020
14376
  async renderChunk(code, chunk, opts) {
@@ -14030,16 +14386,26 @@ const buildEsbuildPlugin = (config) => {
14030
14386
  if (config.build.lib) {
14031
14387
  // #7188, esbuild adds helpers out of the UMD and IIFE wrappers, and the
14032
14388
  // names are minified potentially causing collision with other globals.
14033
- // We use a regex to inject the helpers inside the wrappers.
14389
+ // We inject the helpers inside the wrappers.
14390
+ // e.g. turn:
14391
+ // <esbuild helpers> (function(){ /*actual content/* })()
14392
+ // into:
14393
+ // (function(){ <esbuild helpers> /*actual content/* })()
14394
+ // Not using regex because it's too hard to rule out performance issues like #8738 #8099 #10900 #14065
14395
+ // Instead, using plain string index manipulation (indexOf, slice) which is simple and performant
14034
14396
  // We don't need to create a MagicString here because both the helpers and
14035
14397
  // the headers don't modify the sourcemap
14036
- const injectHelpers = opts.format === 'umd'
14037
- ? INJECT_HELPERS_UMD_RE
14038
- : opts.format === 'iife'
14039
- ? INJECT_HELPERS_IIFE_RE
14040
- : undefined;
14041
- if (injectHelpers) {
14042
- res.code = res.code.replace(injectHelpers, (_, helpers, header) => header + helpers);
14398
+ const esbuildCode = res.code;
14399
+ const contentIndex = opts.format === 'iife'
14400
+ ? esbuildCode.match(IIFE_BEGIN_RE)?.index || 0
14401
+ : opts.format === 'umd'
14402
+ ? esbuildCode.indexOf(`(function(`) // same for minified or not
14403
+ : 0;
14404
+ if (contentIndex > 0) {
14405
+ const esbuildHelpers = esbuildCode.slice(0, contentIndex);
14406
+ res.code = esbuildCode
14407
+ .slice(contentIndex)
14408
+ .replace(`"use strict";`, `"use strict";` + esbuildHelpers);
14043
14409
  }
14044
14410
  }
14045
14411
  return res;
@@ -14142,40 +14508,26 @@ function prettifyMessage(m, code) {
14142
14508
  }
14143
14509
  return res + `\n`;
14144
14510
  }
14145
- let tsconfckRoot;
14146
- let tsconfckParseOptions = { resolveWithEmptyIfConfigNotFound: true };
14147
- function initTSConfck(root, force = false) {
14148
- // bail if already cached
14149
- if (!force && root === tsconfckRoot)
14150
- return;
14151
- const workspaceRoot = searchForWorkspaceRoot(root);
14152
- tsconfckRoot = root;
14153
- tsconfckParseOptions = initTSConfckParseOptions(workspaceRoot);
14154
- // cached as the options value itself when promise is resolved
14155
- tsconfckParseOptions.then((options) => {
14156
- if (root === tsconfckRoot) {
14157
- tsconfckParseOptions = options;
14158
- }
14159
- });
14160
- }
14161
- async function initTSConfckParseOptions(workspaceRoot) {
14162
- const start = debug$f ? performance.now() : 0;
14163
- const options = {
14164
- cache: new Map(),
14165
- root: workspaceRoot,
14166
- tsConfigPaths: new Set(await findAll(workspaceRoot, {
14167
- skip: (dir) => dir === 'node_modules' || dir === '.git',
14168
- })),
14169
- resolveWithEmptyIfConfigNotFound: true,
14170
- };
14171
- debug$f?.(timeFrom(start), 'tsconfck init', colors$1.dim(workspaceRoot));
14172
- return options;
14173
- }
14511
+ let tsconfckCache;
14174
14512
  async function loadTsconfigJsonForFile(filename) {
14175
14513
  try {
14176
- const result = await parse$f(filename, await tsconfckParseOptions);
14514
+ if (tsconfckCache) {
14515
+ // shortcut, the cache stores resolved TSConfckParseResult
14516
+ // so getting it from the cache directly we bypass aysnc fn call wrapping it in a promise again
14517
+ if (tsconfckCache.hasParseResult(filename)) {
14518
+ const result = await tsconfckCache.getParseResult(filename);
14519
+ return result.tsconfig;
14520
+ }
14521
+ }
14522
+ else {
14523
+ tsconfckCache = new TSConfckCache();
14524
+ }
14525
+ const result = await parse$f(filename, {
14526
+ cache: tsconfckCache,
14527
+ ignoreNodeModules: true,
14528
+ });
14177
14529
  // tsconfig could be out of root, make sure it is watched on dev
14178
- if (server && result.tsconfigFile !== 'no_tsconfig_file_found') {
14530
+ if (server && result.tsconfigFile) {
14179
14531
  ensureWatchedFile(server.watcher, result.tsconfigFile, server.config.root);
14180
14532
  }
14181
14533
  return result.tsconfig;
@@ -14198,12 +14550,12 @@ async function reloadOnTsconfigChange(changedFile) {
14198
14550
  // any json file in the tsconfig cache could have been used to compile ts
14199
14551
  if (path$o.basename(changedFile) === 'tsconfig.json' ||
14200
14552
  (changedFile.endsWith('.json') &&
14201
- (await tsconfckParseOptions)?.cache?.has(changedFile))) {
14553
+ tsconfckCache?.hasParseResult(changedFile))) {
14202
14554
  server.config.logger.info(`changed tsconfig file detected: ${changedFile} - Clearing cache and forcing full-reload to ensure TypeScript is compiled with updated config values.`, { clear: server.config.clearScreen, timestamp: true });
14203
14555
  // clear module graph to remove code compiled with outdated config
14204
14556
  server.moduleGraph.invalidateAll();
14205
14557
  // reset tsconfck so that recompile works with up2date configs
14206
- initTSConfck(server.config.root, true);
14558
+ tsconfckCache.clear();
14207
14559
  // server may not be available if vite config is updated at the same time
14208
14560
  if (server) {
14209
14561
  // force full reload
@@ -16186,7 +16538,7 @@ function checkPublicFile(url, { publicDir }) {
16186
16538
  return;
16187
16539
  }
16188
16540
  const publicFile = path$o.join(publicDir, cleanUrl(url));
16189
- if (!publicFile.startsWith(publicDir)) {
16541
+ if (!normalizePath$3(publicFile).startsWith(withTrailingSlash(normalizePath$3(publicDir)))) {
16190
16542
  // can happen if URL starts with '../'
16191
16543
  return;
16192
16544
  }
@@ -16211,7 +16563,7 @@ function fileToDevUrl(id, config) {
16211
16563
  // in public dir during dev, keep the url as-is
16212
16564
  rtn = id;
16213
16565
  }
16214
- else if (id.startsWith(config.root)) {
16566
+ else if (id.startsWith(withTrailingSlash(config.root))) {
16215
16567
  // in project root, infer short public path
16216
16568
  rtn = '/' + path$o.posix.relative(config.root, id);
16217
16569
  }
@@ -16720,7 +17072,7 @@ var convertSourceMap$1 = {};
16720
17072
 
16721
17073
  var convertSourceMap = /*@__PURE__*/getDefaultExportFromCjs(convertSourceMap$1);
16722
17074
 
16723
- const debug$e = createDebugger('vite:sourcemap', {
17075
+ const debug$f = createDebugger('vite:sourcemap', {
16724
17076
  onlyWhenFocused: true,
16725
17077
  });
16726
17078
  // Virtual modules should be prefixed with a null byte to avoid a
@@ -16759,7 +17111,7 @@ async function injectSourcesContent(map, file, logger) {
16759
17111
  // …to log the missing sources.
16760
17112
  if (missingSources.length) {
16761
17113
  logger.warnOnce(`Sourcemap for "${file}" points to missing source files`);
16762
- debug$e?.(`Missing sources:\n ` + missingSources.join(`\n `));
17114
+ debug$f?.(`Missing sources:\n ` + missingSources.join(`\n `));
16763
17115
  }
16764
17116
  }
16765
17117
  function genSourceMapUrl(map) {
@@ -16769,7 +17121,7 @@ function genSourceMapUrl(map) {
16769
17121
  return `data:application/json;base64,${Buffer.from(map).toString('base64')}`;
16770
17122
  }
16771
17123
  function getCodeWithSourcemap(type, code, map) {
16772
- if (debug$e) {
17124
+ if (debug$f) {
16773
17125
  code += `\n/*${JSON.stringify(map, null, 2).replace(/\*\//g, '*\\/')}*/\n`;
16774
17126
  }
16775
17127
  if (type === 'js') {
@@ -22488,7 +22840,7 @@ pp$8.parseForStatement = function(node) {
22488
22840
 
22489
22841
  pp$8.parseFunctionStatement = function(node, isAsync, declarationPosition) {
22490
22842
  this.next();
22491
- return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync)
22843
+ return this.parseFunction(node, FUNC_STATEMENT$1 | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync)
22492
22844
  };
22493
22845
 
22494
22846
  pp$8.parseIfStatement = function(node) {
@@ -22758,7 +23110,7 @@ pp$8.parseVarId = function(decl, kind) {
22758
23110
  this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false);
22759
23111
  };
22760
23112
 
22761
- var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4;
23113
+ var FUNC_STATEMENT$1 = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID$1 = 4;
22762
23114
 
22763
23115
  // Parse a function declaration or literal (depending on the
22764
23116
  // `statement & FUNC_STATEMENT`).
@@ -22774,8 +23126,8 @@ pp$8.parseFunction = function(node, statement, allowExpressionBody, isAsync, for
22774
23126
  if (this.options.ecmaVersion >= 8)
22775
23127
  { node.async = !!isAsync; }
22776
23128
 
22777
- if (statement & FUNC_STATEMENT) {
22778
- node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types$1.name ? null : this.parseIdent();
23129
+ if (statement & FUNC_STATEMENT$1) {
23130
+ node.id = (statement & FUNC_NULLABLE_ID$1) && this.type !== types$1.name ? null : this.parseIdent();
22779
23131
  if (node.id && !(statement & FUNC_HANGING_STATEMENT))
22780
23132
  // If it is a regular function declaration in sloppy mode, then it is
22781
23133
  // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding
@@ -22790,7 +23142,7 @@ pp$8.parseFunction = function(node, statement, allowExpressionBody, isAsync, for
22790
23142
  this.awaitIdentPos = 0;
22791
23143
  this.enterScope(functionFlags(node.async, node.generator));
22792
23144
 
22793
- if (!(statement & FUNC_STATEMENT))
23145
+ if (!(statement & FUNC_STATEMENT$1))
22794
23146
  { node.id = this.type === types$1.name ? this.parseIdent() : null; }
22795
23147
 
22796
23148
  this.parseFunctionParams(node);
@@ -22799,7 +23151,7 @@ pp$8.parseFunction = function(node, statement, allowExpressionBody, isAsync, for
22799
23151
  this.yieldPos = oldYieldPos;
22800
23152
  this.awaitPos = oldAwaitPos;
22801
23153
  this.awaitIdentPos = oldAwaitIdentPos;
22802
- return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression")
23154
+ return this.finishNode(node, (statement & FUNC_STATEMENT$1) ? "FunctionDeclaration" : "FunctionExpression")
22803
23155
  };
22804
23156
 
22805
23157
  pp$8.parseFunctionParams = function(node) {
@@ -23154,7 +23506,7 @@ pp$8.parseExportDefaultDeclaration = function() {
23154
23506
  var fNode = this.startNode();
23155
23507
  this.next();
23156
23508
  if (isAsync) { this.next(); }
23157
- return this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync)
23509
+ return this.parseFunction(fNode, FUNC_STATEMENT$1 | FUNC_NULLABLE_ID$1, false, isAsync)
23158
23510
  } else if (this.type === types$1._class) {
23159
23511
  var cNode = this.startNode();
23160
23512
  return this.parseClass(cNode, "nullableID")
@@ -28022,7 +28374,7 @@ const browserExternalId = '__vite-browser-external';
28022
28374
  const optionalPeerDepId = '__vite-optional-peer-dep';
28023
28375
  const subpathImportsPrefix = '#';
28024
28376
  const startsWithWordCharRE = /^\w/;
28025
- const debug$d = createDebugger('vite:resolve-details', {
28377
+ const debug$e = createDebugger('vite:resolve-details', {
28026
28378
  onlyWhenFocused: true,
28027
28379
  });
28028
28380
  function resolvePlugin(resolveOptions) {
@@ -28091,15 +28443,17 @@ function resolvePlugin(resolveOptions) {
28091
28443
  // We don't need to resolve these paths since they are already resolved
28092
28444
  // always return here even if res doesn't exist since /@fs/ is explicit
28093
28445
  // if the file doesn't exist it should be a 404.
28094
- debug$d?.(`[@fs] ${colors$1.cyan(id)} -> ${colors$1.dim(res)}`);
28446
+ debug$e?.(`[@fs] ${colors$1.cyan(id)} -> ${colors$1.dim(res)}`);
28095
28447
  return ensureVersionQuery(res, id, options, depsOptimizer);
28096
28448
  }
28097
28449
  // URL
28098
28450
  // /foo -> /fs-root/foo
28099
- if (asSrc && id[0] === '/' && (rootInRoot || !id.startsWith(root))) {
28451
+ if (asSrc &&
28452
+ id[0] === '/' &&
28453
+ (rootInRoot || !id.startsWith(withTrailingSlash(root)))) {
28100
28454
  const fsPath = path$o.resolve(root, id.slice(1));
28101
28455
  if ((res = tryFsResolve(fsPath, options))) {
28102
- debug$d?.(`[url] ${colors$1.cyan(id)} -> ${colors$1.dim(res)}`);
28456
+ debug$e?.(`[url] ${colors$1.cyan(id)} -> ${colors$1.dim(res)}`);
28103
28457
  return ensureVersionQuery(res, id, options, depsOptimizer);
28104
28458
  }
28105
28459
  }
@@ -28130,7 +28484,7 @@ function resolvePlugin(resolveOptions) {
28130
28484
  }
28131
28485
  if ((res = tryFsResolve(fsPath, options))) {
28132
28486
  res = ensureVersionQuery(res, id, options, depsOptimizer);
28133
- debug$d?.(`[relative] ${colors$1.cyan(id)} -> ${colors$1.dim(res)}`);
28487
+ debug$e?.(`[relative] ${colors$1.cyan(id)} -> ${colors$1.dim(res)}`);
28134
28488
  // If this isn't a script imported from a .html file, include side effects
28135
28489
  // hints so the non-used code is properly tree-shaken during build time.
28136
28490
  if (!options.idOnly &&
@@ -28153,14 +28507,14 @@ function resolvePlugin(resolveOptions) {
28153
28507
  const basedir = importer ? path$o.dirname(importer) : process.cwd();
28154
28508
  const fsPath = path$o.resolve(basedir, id);
28155
28509
  if ((res = tryFsResolve(fsPath, options))) {
28156
- debug$d?.(`[drive-relative] ${colors$1.cyan(id)} -> ${colors$1.dim(res)}`);
28510
+ debug$e?.(`[drive-relative] ${colors$1.cyan(id)} -> ${colors$1.dim(res)}`);
28157
28511
  return ensureVersionQuery(res, id, options, depsOptimizer);
28158
28512
  }
28159
28513
  }
28160
28514
  // absolute fs paths
28161
28515
  if (isNonDriveRelativeAbsolutePath(id) &&
28162
28516
  (res = tryFsResolve(id, options))) {
28163
- debug$d?.(`[fs] ${colors$1.cyan(id)} -> ${colors$1.dim(res)}`);
28517
+ debug$e?.(`[fs] ${colors$1.cyan(id)} -> ${colors$1.dim(res)}`);
28164
28518
  return ensureVersionQuery(res, id, options, depsOptimizer);
28165
28519
  }
28166
28520
  // external
@@ -28206,7 +28560,7 @@ function resolvePlugin(resolveOptions) {
28206
28560
  }
28207
28561
  else {
28208
28562
  if (!asSrc) {
28209
- debug$d?.(`externalized node built-in "${id}" to empty module. ` +
28563
+ debug$e?.(`externalized node built-in "${id}" to empty module. ` +
28210
28564
  `(imported by: ${colors$1.white(colors$1.dim(importer))})`);
28211
28565
  }
28212
28566
  else if (isProduction) {
@@ -28219,7 +28573,7 @@ function resolvePlugin(resolveOptions) {
28219
28573
  }
28220
28574
  }
28221
28575
  }
28222
- debug$d?.(`[fallthrough] ${colors$1.dim(id)}`);
28576
+ debug$e?.(`[fallthrough] ${colors$1.dim(id)}`);
28223
28577
  },
28224
28578
  load(id) {
28225
28579
  if (id.startsWith(browserExternalId)) {
@@ -28273,7 +28627,7 @@ function ensureVersionQuery(resolved, id, options, depsOptimizer) {
28273
28627
  // as if they would have been imported through a bare import
28274
28628
  // Use the original id to do the check as the resolved id may be the real
28275
28629
  // file path after symlinks resolution
28276
- const isNodeModule = isInNodeModules(id) || isInNodeModules(resolved);
28630
+ const isNodeModule = isInNodeModules$1(id) || isInNodeModules$1(resolved);
28277
28631
  if (isNodeModule && !resolved.match(DEP_VERSION_RE)) {
28278
28632
  const versionHash = depsOptimizer.metadata.browserHash;
28279
28633
  if (versionHash && isOptimizable(resolved, depsOptimizer.options)) {
@@ -28292,7 +28646,7 @@ function tryFsResolve(fsPath, options, tryIndex = true, targetWeb = true, skipPa
28292
28646
  // source code so we only need to perform the check for dependencies.
28293
28647
  // We don't support `?` in node_modules paths, so we only need to check in this branch.
28294
28648
  const hashIndex = fsPath.indexOf('#');
28295
- if (hashIndex >= 0 && isInNodeModules(fsPath)) {
28649
+ if (hashIndex >= 0 && isInNodeModules$1(fsPath)) {
28296
28650
  const queryIndex = fsPath.indexOf('?');
28297
28651
  // We only need to check foo#bar?baz and foo#bar, ignore foo?bar#baz
28298
28652
  if (queryIndex < 0 || queryIndex > hashIndex) {
@@ -28388,7 +28742,9 @@ function tryNodeResolve(id, importer, options, targetWeb, depsOptimizer, ssr = f
28388
28742
  const { root, dedupe, isBuild, preserveSymlinks, packageCache } = options;
28389
28743
  // check for deep import, e.g. "my-lib/foo"
28390
28744
  const deepMatch = id.match(deepImportRE);
28391
- const pkgId = deepMatch ? deepMatch[1] || deepMatch[2] : id;
28745
+ // package name doesn't include postfixes
28746
+ // trim them to support importing package with queries (e.g. `import css from 'normalize.css?inline'`)
28747
+ const pkgId = deepMatch ? deepMatch[1] || deepMatch[2] : cleanUrl(id);
28392
28748
  let basedir;
28393
28749
  if (dedupe?.includes(pkgId)) {
28394
28750
  basedir = root;
@@ -28423,7 +28779,7 @@ function tryNodeResolve(id, importer, options, targetWeb, depsOptimizer, ssr = f
28423
28779
  return;
28424
28780
  }
28425
28781
  const resolveId = deepMatch ? resolveDeepImport : resolvePackageEntry;
28426
- const unresolvedId = deepMatch ? '.' + id.slice(pkgId.length) : pkgId;
28782
+ const unresolvedId = deepMatch ? '.' + id.slice(pkgId.length) : id;
28427
28783
  let resolved;
28428
28784
  try {
28429
28785
  resolved = resolveId(unresolvedId, pkg, targetWeb, options);
@@ -28449,7 +28805,7 @@ function tryNodeResolve(id, importer, options, targetWeb, depsOptimizer, ssr = f
28449
28805
  return resolved;
28450
28806
  }
28451
28807
  // don't external symlink packages
28452
- if (!allowLinkedExternal && !isInNodeModules(resolved.id)) {
28808
+ if (!allowLinkedExternal && !isInNodeModules$1(resolved.id)) {
28453
28809
  return resolved;
28454
28810
  }
28455
28811
  const resolvedExt = path$o.extname(resolved.id);
@@ -28467,7 +28823,7 @@ function tryNodeResolve(id, importer, options, targetWeb, depsOptimizer, ssr = f
28467
28823
  const index = resolved.id.indexOf(id);
28468
28824
  if (index > -1) {
28469
28825
  resolvedId = resolved.id.slice(index);
28470
- debug$d?.(`[processResult] ${colors$1.cyan(id)} -> ${colors$1.dim(resolvedId)}`);
28826
+ debug$e?.(`[processResult] ${colors$1.cyan(id)} -> ${colors$1.dim(resolvedId)}`);
28471
28827
  }
28472
28828
  }
28473
28829
  return { ...resolved, id: resolvedId, external: true };
@@ -28483,7 +28839,7 @@ function tryNodeResolve(id, importer, options, targetWeb, depsOptimizer, ssr = f
28483
28839
  }
28484
28840
  const ext = path$o.extname(resolved);
28485
28841
  if (!options.ssrOptimizeCheck &&
28486
- (!isInNodeModules(resolved) || // linked
28842
+ (!isInNodeModules$1(resolved) || // linked
28487
28843
  !depsOptimizer || // resolving before listening to the server
28488
28844
  options.scan) // initial esbuild scan phase
28489
28845
  ) {
@@ -28502,7 +28858,7 @@ function tryNodeResolve(id, importer, options, targetWeb, depsOptimizer, ssr = f
28502
28858
  }
28503
28859
  const skipOptimization = depsOptimizer?.options.noDiscovery ||
28504
28860
  !isJsType ||
28505
- (importer && isInNodeModules(importer)) ||
28861
+ (importer && isInNodeModules$1(importer)) ||
28506
28862
  exclude?.includes(pkgId) ||
28507
28863
  exclude?.includes(id) ||
28508
28864
  SPECIAL_QUERY_RE.test(resolved) ||
@@ -28590,15 +28946,16 @@ async function tryOptimizedResolve(depsOptimizer, id, importer, preserveSymlinks
28590
28946
  idPkgDir = normalizePath$3(idPkgDir);
28591
28947
  }
28592
28948
  // match by src to correctly identify if id belongs to nested dependency
28593
- if (optimizedData.src.startsWith(idPkgDir)) {
28949
+ if (optimizedData.src.startsWith(withTrailingSlash(idPkgDir))) {
28594
28950
  return depsOptimizer.getOptimizedDepId(optimizedData);
28595
28951
  }
28596
28952
  }
28597
28953
  }
28598
28954
  function resolvePackageEntry(id, { dir, data, setResolvedCache, getResolvedCache }, targetWeb, options) {
28955
+ const { file: idWithoutPostfix, postfix } = splitFileAndPostfix(id);
28599
28956
  const cached = getResolvedCache('.', targetWeb);
28600
28957
  if (cached) {
28601
- return cached;
28958
+ return cached + postfix;
28602
28959
  }
28603
28960
  try {
28604
28961
  let entryPoint;
@@ -28686,9 +29043,9 @@ function resolvePackageEntry(id, { dir, data, setResolvedCache, getResolvedCache
28686
29043
  const entryPointPath = path$o.join(dir, entry);
28687
29044
  const resolvedEntryPoint = tryFsResolve(entryPointPath, options, true, true, skipPackageJson);
28688
29045
  if (resolvedEntryPoint) {
28689
- debug$d?.(`[package entry] ${colors$1.cyan(id)} -> ${colors$1.dim(resolvedEntryPoint)}`);
29046
+ debug$e?.(`[package entry] ${colors$1.cyan(idWithoutPostfix)} -> ${colors$1.dim(resolvedEntryPoint)}${postfix !== '' ? ` (postfix: ${postfix})` : ''}`);
28690
29047
  setResolvedCache('.', resolvedEntryPoint, targetWeb);
28691
- return resolvedEntryPoint;
29048
+ return resolvedEntryPoint + postfix;
28692
29049
  }
28693
29050
  }
28694
29051
  }
@@ -28770,7 +29127,7 @@ function resolveDeepImport(id, { webResolvedImports, setResolvedCache, getResolv
28770
29127
  const resolved = tryFsResolve(path$o.join(dir, relativeId), options, !exportsField, // try index only if no exports field
28771
29128
  targetWeb);
28772
29129
  if (resolved) {
28773
- debug$d?.(`[node/deep-import] ${colors$1.cyan(id)} -> ${colors$1.dim(resolved)}`);
29130
+ debug$e?.(`[node/deep-import] ${colors$1.cyan(id)} -> ${colors$1.dim(resolved)}`);
28774
29131
  setResolvedCache(id, resolved, targetWeb);
28775
29132
  return resolved;
28776
29133
  }
@@ -28787,7 +29144,7 @@ function tryResolveBrowserMapping(id, importer, options, isFilePath, externalize
28787
29144
  if ((res = bareImportRE.test(browserMappedPath)
28788
29145
  ? tryNodeResolve(browserMappedPath, importer, options, true)?.id
28789
29146
  : tryFsResolve(path$o.join(pkg.dir, browserMappedPath), options))) {
28790
- debug$d?.(`[browser mapped] ${colors$1.cyan(id)} -> ${colors$1.dim(res)}`);
29147
+ debug$e?.(`[browser mapped] ${colors$1.cyan(id)} -> ${colors$1.dim(res)}`);
28791
29148
  let result = { id: res };
28792
29149
  if (options.idOnly) {
28793
29150
  return result;
@@ -37267,7 +37624,7 @@ function resolveEnvPrefix({ envPrefix = 'VITE_', }) {
37267
37624
  }
37268
37625
 
37269
37626
  const modulePreloadPolyfillId = 'vite/modulepreload-polyfill';
37270
- const resolvedModulePreloadPolyfillId = '\0' + modulePreloadPolyfillId;
37627
+ const resolvedModulePreloadPolyfillId = '\0' + modulePreloadPolyfillId + '.js';
37271
37628
  function modulePreloadPolyfillPlugin(config) {
37272
37629
  // `isModernFlag` is only available during build since it is resolved by `vite:build-import-analysis`
37273
37630
  const skip = config.command !== 'build' || config.build.ssr;
@@ -38202,7 +38559,6 @@ const commonjsProxyRE = /\?commonjs-proxy/;
38202
38559
  const inlineRE = /[?&]inline\b/;
38203
38560
  const inlineCSSRE = /[?&]inline-css\b/;
38204
38561
  const styleAttrRE = /[?&]style-attr\b/;
38205
- const usedRE = /[?&]used\b/;
38206
38562
  const varRE = /^var\(/i;
38207
38563
  const cssBundleName = 'style.css';
38208
38564
  const isCSSRequest = (request) => CSS_LANGS_RE.test(request);
@@ -38355,7 +38711,7 @@ function cssPostPlugin(config) {
38355
38711
  };
38356
38712
  return {
38357
38713
  name: 'vite:css-post',
38358
- buildStart() {
38714
+ renderStart() {
38359
38715
  // Ensure new caches for every build (i.e. rebuilding in watch mode)
38360
38716
  pureCssChunks = new Set();
38361
38717
  outputToExtractedCSSMap = new Map();
@@ -38405,8 +38761,7 @@ function cssPostPlugin(config) {
38405
38761
  `const __vite__css = ${JSON.stringify(cssContent)}`,
38406
38762
  `__vite__updateStyle(__vite__id, __vite__css)`,
38407
38763
  // css modules exports change on edit so it can't self accept
38408
- `${modulesCode ||
38409
- `import.meta.hot.accept()\nexport default __vite__css`}`,
38764
+ `${modulesCode || 'import.meta.hot.accept()'}`,
38410
38765
  `import.meta.hot.prune(() => __vite__removeStyle(__vite__id))`,
38411
38766
  ].join('\n');
38412
38767
  return { code, map: { mappings: '' } };
@@ -38429,24 +38784,19 @@ function cssPostPlugin(config) {
38429
38784
  styles.set(id, css);
38430
38785
  }
38431
38786
  let code;
38432
- if (usedRE.test(id)) {
38433
- if (modulesCode) {
38434
- code = modulesCode;
38435
- }
38436
- else {
38437
- let content = css;
38438
- if (config.build.cssMinify) {
38439
- content = await minifyCSS(content, config, true);
38440
- }
38441
- code = `export default ${JSON.stringify(content)}`;
38787
+ if (modulesCode) {
38788
+ code = modulesCode;
38789
+ }
38790
+ else if (inlined) {
38791
+ let content = css;
38792
+ if (config.build.cssMinify) {
38793
+ content = await minifyCSS(content, config, true);
38442
38794
  }
38795
+ code = `export default ${JSON.stringify(content)}`;
38443
38796
  }
38444
38797
  else {
38445
- // if moduleCode exists return it **even if** it does not have `?used`
38446
- // this will disable tree-shake to work with `import './foo.module.css'` but this usually does not happen
38447
- // this is a limitation of the current approach by `?used` to make tree-shake work
38448
- // See #8936 for more details
38449
- code = modulesCode || `export default ''`;
38798
+ // empty module when it's not a CSS module nor `?inline`
38799
+ code = '';
38450
38800
  }
38451
38801
  return {
38452
38802
  code,
@@ -38636,9 +38986,9 @@ function cssPostPlugin(config) {
38636
38986
  // chunks instead.
38637
38987
  chunk.imports = chunk.imports.filter((file) => {
38638
38988
  if (pureCssChunkNames.includes(file)) {
38639
- const { importedCss } = bundle[file]
38640
- .viteMetadata;
38989
+ const { importedCss, importedAssets } = bundle[file].viteMetadata;
38641
38990
  importedCss.forEach((file) => chunk.viteMetadata.importedCss.add(file));
38991
+ importedAssets.forEach((file) => chunk.viteMetadata.importedAssets.add(file));
38642
38992
  return false;
38643
38993
  }
38644
38994
  return true;
@@ -38652,6 +39002,7 @@ function cssPostPlugin(config) {
38652
39002
  pureCssChunkNames.forEach((fileName) => {
38653
39003
  removedPureCssFiles.set(fileName, bundle[fileName]);
38654
39004
  delete bundle[fileName];
39005
+ delete bundle[`${fileName}.map`];
38655
39006
  });
38656
39007
  }
38657
39008
  let extractedCss = outputToExtractedCSSMap.get(opts);
@@ -38962,8 +39313,8 @@ function createCachedImport(imp) {
38962
39313
  return cached;
38963
39314
  };
38964
39315
  }
38965
- const importPostcssImport = createCachedImport(() => import('./dep-1d1f72b4.js').then(function (n) { return n.i; }));
38966
- const importPostcssModules = createCachedImport(() => import('./dep-3d0847ee.js').then(function (n) { return n.i; }));
39316
+ const importPostcssImport = createCachedImport(() => import('./dep-13ae786e.js').then(function (n) { return n.i; }));
39317
+ const importPostcssModules = createCachedImport(() => import('./dep-5c5f3875.js').then(function (n) { return n.i; }));
38967
39318
  const importPostcss = createCachedImport(() => import('postcss'));
38968
39319
  /**
38969
39320
  * @experimental
@@ -39629,10 +39980,9 @@ async function compileLightningCSS(id, src, config, urlReplacer) {
39629
39980
  ? (await importLightningCSS()).transformStyleAttribute({
39630
39981
  filename,
39631
39982
  code: Buffer.from(src),
39632
- minify: config.isProduction && !!config.build.cssMinify,
39633
39983
  targets: config.css?.lightningcss?.targets,
39984
+ minify: config.isProduction && !!config.build.cssMinify,
39634
39985
  analyzeDependencies: true,
39635
- visitor: config.css?.lightningcss?.visitor,
39636
39986
  })
39637
39987
  : await (await importLightningCSS()).bundleAsync({
39638
39988
  ...config.css?.lightningcss,
@@ -40044,7 +40394,248 @@ function esbuildCjsExternalPlugin(externals, platform) {
40044
40394
  };
40045
40395
  }
40046
40396
 
40047
- const debug$c = createDebugger('vite:ssr-external');
40397
+ const leftCurlyBrace = "{".charCodeAt(0);
40398
+ const space = " ".charCodeAt(0);
40399
+
40400
+ const keyword = "assert";
40401
+ const FUNC_STATEMENT = 1, FUNC_NULLABLE_ID = 4;
40402
+
40403
+ function importAssertions(Parser) {
40404
+ // Use supplied version acorn version if present, to avoid
40405
+ // reference mismatches due to different acorn versions. This
40406
+ // allows this plugin to be used with Rollup which supplies
40407
+ // its own internal version of acorn and thereby sidesteps
40408
+ // the package manager.
40409
+ const acorn$1 = Parser.acorn || acorn;
40410
+ const { tokTypes: tt, TokenType } = acorn$1;
40411
+
40412
+ return class extends Parser {
40413
+ constructor(...args) {
40414
+ super(...args);
40415
+ this.assertToken = new TokenType(keyword);
40416
+ }
40417
+
40418
+ _codeAt(i) {
40419
+ return this.input.charCodeAt(i);
40420
+ }
40421
+
40422
+ _eat(t) {
40423
+ if (this.type !== t) {
40424
+ this.unexpected();
40425
+ }
40426
+ this.next();
40427
+ }
40428
+
40429
+ readToken(code) {
40430
+ let i = 0;
40431
+ for (; i < keyword.length; i++) {
40432
+ if (this._codeAt(this.pos + i) !== keyword.charCodeAt(i)) {
40433
+ return super.readToken(code);
40434
+ }
40435
+ }
40436
+
40437
+ // ensure that the keyword is at the correct location
40438
+ // ie `assert{...` or `assert {...`
40439
+ for (;; i++) {
40440
+ if (this._codeAt(this.pos + i) === leftCurlyBrace) {
40441
+ // Found '{'
40442
+ break;
40443
+ } else if (this._codeAt(this.pos + i) === space) {
40444
+ // white space is allowed between `assert` and `{`, so continue.
40445
+ continue;
40446
+ } else {
40447
+ return super.readToken(code);
40448
+ }
40449
+ }
40450
+
40451
+ // If we're inside a dynamic import expression we'll parse
40452
+ // the `assert` keyword as a standard object property name
40453
+ // ie `import(""./foo.json", { assert: { type: "json" } })`
40454
+ if (this.type.label === "{") {
40455
+ return super.readToken(code);
40456
+ }
40457
+
40458
+ this.pos += keyword.length;
40459
+ return this.finishToken(this.assertToken);
40460
+ }
40461
+
40462
+ parseDynamicImport(node) {
40463
+ this.next(); // skip `(`
40464
+
40465
+ // Parse node.source.
40466
+ node.source = this.parseMaybeAssign();
40467
+
40468
+ if (this.eat(tt.comma)) {
40469
+ const obj = this.parseObj(false);
40470
+ node.arguments = [obj];
40471
+ }
40472
+ this._eat(tt.parenR);
40473
+ return this.finishNode(node, "ImportExpression");
40474
+ }
40475
+
40476
+ // ported from acorn/src/statement.js pp.parseExport
40477
+ parseExport(node, exports) {
40478
+ this.next();
40479
+ // export * from '...'
40480
+ if (this.eat(tt.star)) {
40481
+ if (this.options.ecmaVersion >= 11) {
40482
+ if (this.eatContextual("as")) {
40483
+ node.exported = this.parseIdent(true);
40484
+ this.checkExport(exports, node.exported.name, this.lastTokStart);
40485
+ } else {
40486
+ node.exported = null;
40487
+ }
40488
+ }
40489
+ this.expectContextual("from");
40490
+ if (this.type !== tt.string) { this.unexpected(); }
40491
+ node.source = this.parseExprAtom();
40492
+
40493
+ if (this.type === this.assertToken || this.type === tt._with) {
40494
+ this.next();
40495
+ const assertions = this.parseImportAssertions();
40496
+ if (assertions) {
40497
+ node.assertions = assertions;
40498
+ }
40499
+ }
40500
+
40501
+ this.semicolon();
40502
+ return this.finishNode(node, "ExportAllDeclaration")
40503
+ }
40504
+ if (this.eat(tt._default)) { // export default ...
40505
+ this.checkExport(exports, "default", this.lastTokStart);
40506
+ var isAsync;
40507
+ if (this.type === tt._function || (isAsync = this.isAsyncFunction())) {
40508
+ var fNode = this.startNode();
40509
+ this.next();
40510
+ if (isAsync) { this.next(); }
40511
+ node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync);
40512
+ } else if (this.type === tt._class) {
40513
+ var cNode = this.startNode();
40514
+ node.declaration = this.parseClass(cNode, "nullableID");
40515
+ } else {
40516
+ node.declaration = this.parseMaybeAssign();
40517
+ this.semicolon();
40518
+ }
40519
+ return this.finishNode(node, "ExportDefaultDeclaration")
40520
+ }
40521
+ // export var|const|let|function|class ...
40522
+ if (this.shouldParseExportStatement()) {
40523
+ node.declaration = this.parseStatement(null);
40524
+ if (node.declaration.type === "VariableDeclaration")
40525
+ { this.checkVariableExport(exports, node.declaration.declarations); }
40526
+ else
40527
+ { this.checkExport(exports, node.declaration.id.name, node.declaration.id.start); }
40528
+ node.specifiers = [];
40529
+ node.source = null;
40530
+ } else { // export { x, y as z } [from '...']
40531
+ node.declaration = null;
40532
+ node.specifiers = this.parseExportSpecifiers(exports);
40533
+ if (this.eatContextual("from")) {
40534
+ if (this.type !== tt.string) { this.unexpected(); }
40535
+ node.source = this.parseExprAtom();
40536
+
40537
+ if (this.type === this.assertToken || this.type === tt._with) {
40538
+ this.next();
40539
+ const assertions = this.parseImportAssertions();
40540
+ if (assertions) {
40541
+ node.assertions = assertions;
40542
+ }
40543
+ }
40544
+ } else {
40545
+ for (var i = 0, list = node.specifiers; i < list.length; i += 1) {
40546
+ // check for keywords used as local names
40547
+ var spec = list[i];
40548
+
40549
+ this.checkUnreserved(spec.local);
40550
+ // check if export is defined
40551
+ this.checkLocalExport(spec.local);
40552
+ }
40553
+
40554
+ node.source = null;
40555
+ }
40556
+ this.semicolon();
40557
+ }
40558
+ return this.finishNode(node, "ExportNamedDeclaration")
40559
+ }
40560
+
40561
+ parseImport(node) {
40562
+ this.next();
40563
+ // import '...'
40564
+ if (this.type === tt.string) {
40565
+ node.specifiers = [];
40566
+ node.source = this.parseExprAtom();
40567
+ } else {
40568
+ node.specifiers = this.parseImportSpecifiers();
40569
+ this.expectContextual("from");
40570
+ node.source =
40571
+ this.type === tt.string ? this.parseExprAtom() : this.unexpected();
40572
+ }
40573
+
40574
+ if (this.type === this.assertToken || this.type == tt._with) {
40575
+ this.next();
40576
+ const assertions = this.parseImportAssertions();
40577
+ if (assertions) {
40578
+ node.assertions = assertions;
40579
+ }
40580
+ }
40581
+ this.semicolon();
40582
+ return this.finishNode(node, "ImportDeclaration");
40583
+ }
40584
+
40585
+ parseImportAssertions() {
40586
+ this._eat(tt.braceL);
40587
+ const attrs = this.parseAssertEntries();
40588
+ this._eat(tt.braceR);
40589
+ return attrs;
40590
+ }
40591
+
40592
+ parseAssertEntries() {
40593
+ const attrs = [];
40594
+ const attrNames = new Set();
40595
+
40596
+ do {
40597
+ if (this.type === tt.braceR) {
40598
+ break;
40599
+ }
40600
+
40601
+ const node = this.startNode();
40602
+
40603
+ // parse AssertionKey : IdentifierName, StringLiteral
40604
+ let assertionKeyNode;
40605
+ if (this.type === tt.string) {
40606
+ assertionKeyNode = this.parseLiteral(this.value);
40607
+ } else {
40608
+ assertionKeyNode = this.parseIdent(true);
40609
+ }
40610
+ this.next();
40611
+ node.key = assertionKeyNode;
40612
+
40613
+ // check if we already have an entry for an attribute
40614
+ // if a duplicate entry is found, throw an error
40615
+ // for now this logic will come into play only when someone declares `type` twice
40616
+ if (attrNames.has(node.key.name)) {
40617
+ this.raise(this.pos, "Duplicated key in assertions");
40618
+ }
40619
+ attrNames.add(node.key.name);
40620
+
40621
+ if (this.type !== tt.string) {
40622
+ this.raise(
40623
+ this.pos,
40624
+ "Only string is supported as an assertion value"
40625
+ );
40626
+ }
40627
+
40628
+ node.value = this.parseLiteral(this.value);
40629
+
40630
+ attrs.push(this.finishNode(node, "ImportAttribute"));
40631
+ } while (this.eat(tt.comma));
40632
+
40633
+ return attrs;
40634
+ }
40635
+ };
40636
+ }
40637
+
40638
+ const debug$d = createDebugger('vite:ssr-external');
40048
40639
  /**
40049
40640
  * Converts "parent > child" syntax to just "child"
40050
40641
  */
@@ -40122,7 +40713,7 @@ function createIsConfiguredAsSsrExternal(config) {
40122
40713
  try {
40123
40714
  return !!tryNodeResolve(id,
40124
40715
  // Skip passing importer in build to avoid externalizing non-hoisted dependencies
40125
- // unresolveable from root (which would be unresolvable from output bundles also)
40716
+ // unresolvable from root (which would be unresolvable from output bundles also)
40126
40717
  config.command === 'build' ? undefined : importer, resolveOptions, ssr?.target === 'webworker', undefined, true,
40127
40718
  // try to externalize, will return undefined or an object without
40128
40719
  // a external flag if it isn't externalizable
@@ -40132,7 +40723,7 @@ function createIsConfiguredAsSsrExternal(config) {
40132
40723
  !!configuredAsExternal)?.external;
40133
40724
  }
40134
40725
  catch (e) {
40135
- debug$c?.(`Failed to node resolve "${id}". Skipping externalizing it by default.`);
40726
+ debug$d?.(`Failed to node resolve "${id}". Skipping externalizing it by default.`);
40136
40727
  // may be an invalid import that's resolved by a plugin
40137
40728
  return false;
40138
40729
  }
@@ -40223,7 +40814,7 @@ function cjsSsrCollectExternals(root, resolveOptions, ssrExternals, seen, logger
40223
40814
  // no main entry, but deep imports may be allowed
40224
40815
  const pkgDir = resolvePackageData(id, root)?.dir;
40225
40816
  if (pkgDir) {
40226
- if (isInNodeModules(pkgDir)) {
40817
+ if (isInNodeModules$1(pkgDir)) {
40227
40818
  ssrExternals.add(id);
40228
40819
  }
40229
40820
  else {
@@ -40232,7 +40823,7 @@ function cjsSsrCollectExternals(root, resolveOptions, ssrExternals, seen, logger
40232
40823
  continue;
40233
40824
  }
40234
40825
  // resolve failed, assume include
40235
- debug$c?.(`Failed to resolve entries for package "${id}"\n`, e);
40826
+ debug$d?.(`Failed to resolve entries for package "${id}"\n`, e);
40236
40827
  continue;
40237
40828
  }
40238
40829
  // no esm entry but has require entry
@@ -40240,7 +40831,7 @@ function cjsSsrCollectExternals(root, resolveOptions, ssrExternals, seen, logger
40240
40831
  ssrExternals.add(id);
40241
40832
  }
40242
40833
  // trace the dependencies of linked packages
40243
- else if (!isInNodeModules(esmEntry)) {
40834
+ else if (!isInNodeModules$1(esmEntry)) {
40244
40835
  const pkgDir = resolvePackageData(id, root)?.dir;
40245
40836
  if (pkgDir) {
40246
40837
  depsToTrace.add(pkgDir);
@@ -40285,7 +40876,8 @@ function cjsShouldExternalizeForSSR(id, externals) {
40285
40876
  }
40286
40877
  // deep imports, check ext before externalizing - only externalize
40287
40878
  // extension-less imports and explicit .js imports
40288
- if (id.startsWith(e + '/') && (!path$o.extname(id) || id.endsWith('.js'))) {
40879
+ if (id.startsWith(withTrailingSlash(e)) &&
40880
+ (!path$o.extname(id) || id.endsWith('.js'))) {
40289
40881
  return true;
40290
40882
  }
40291
40883
  });
@@ -40350,7 +40942,7 @@ function jsonPlugin(options = {}, isBuild) {
40350
40942
 
40351
40943
  const ERR_OPTIMIZE_DEPS_PROCESSING_ERROR = 'ERR_OPTIMIZE_DEPS_PROCESSING_ERROR';
40352
40944
  const ERR_OUTDATED_OPTIMIZED_DEP = 'ERR_OUTDATED_OPTIMIZED_DEP';
40353
- const debug$b = createDebugger('vite:optimize-deps');
40945
+ const debug$c = createDebugger('vite:optimize-deps');
40354
40946
  function optimizedDepsPlugin(config) {
40355
40947
  return {
40356
40948
  name: 'vite:optimized-deps',
@@ -40397,7 +40989,7 @@ function optimizedDepsPlugin(config) {
40397
40989
  }
40398
40990
  }
40399
40991
  }
40400
- debug$b?.(`load ${colors$1.cyan(file)}`);
40992
+ debug$c?.(`load ${colors$1.cyan(file)}`);
40401
40993
  // Load the file from the cache instead of waiting for other plugin
40402
40994
  // load hooks to avoid race conditions, once processing is resolved,
40403
40995
  // we are sure that the file has been properly save to disk
@@ -40460,7 +41052,7 @@ function optimizedDepsBuildPlugin(config) {
40460
41052
  const info = optimizedDepInfoFromFile(depsOptimizer.metadata, file);
40461
41053
  if (info) {
40462
41054
  await info.processing;
40463
- debug$b?.(`load ${colors$1.cyan(file)}`);
41055
+ debug$c?.(`load ${colors$1.cyan(file)}`);
40464
41056
  }
40465
41057
  else {
40466
41058
  throw new Error(`Something unexpected happened while optimizing "${id}".`);
@@ -40818,7 +41410,7 @@ function importGlobPlugin(config) {
40818
41410
  async transform(code, id) {
40819
41411
  if (!code.includes('import.meta.glob'))
40820
41412
  return;
40821
- const result = await transformGlobImport(code, id, config.root, (im, _, options) => this.resolve(im, id, options).then((i) => i?.id || im), config.isProduction, config.experimental.importGlobRestoreExtension);
41413
+ const result = await transformGlobImport(code, id, config.root, (im, _, options) => this.resolve(im, id, options).then((i) => i?.id || im), config.experimental.importGlobRestoreExtension);
40822
41414
  if (result) {
40823
41415
  if (server) {
40824
41416
  const allGlobs = result.matches.map((i) => i.globsResolved);
@@ -40999,18 +41591,10 @@ async function parseImportGlob(code, importer, root, resolveId) {
40999
41591
  }
41000
41592
  const importPrefix = '__vite_glob_';
41001
41593
  const { basename, dirname, relative, join } = posix$1;
41002
- const warnedCSSDefaultImportVarName = '__vite_warned_css_default_import';
41003
- const jsonStringifyInOneline = (input) => JSON.stringify(input).replace(/[{,:]/g, '$& ').replace(/\}/g, ' }');
41004
- const createCssDefaultImportWarning = (globs, options) => `if (!${warnedCSSDefaultImportVarName}) {` +
41005
- `${warnedCSSDefaultImportVarName} = true;` +
41006
- `console.warn(${JSON.stringify('Default import of CSS without `?inline` is deprecated. ' +
41007
- "Add the `{ query: '?inline' }` glob option to fix this.\n" +
41008
- `For example: \`import.meta.glob(${jsonStringifyInOneline(globs.length === 1 ? globs[0] : globs)}, ${jsonStringifyInOneline({ ...options, query: '?inline' })})\``)});` +
41009
- `}`;
41010
41594
  /**
41011
41595
  * @param optimizeExport for dynamicImportVar plugin don't need to optimize export.
41012
41596
  */
41013
- async function transformGlobImport(code, id, root, resolveId, isProduction, restoreQueryExtension = false) {
41597
+ async function transformGlobImport(code, id, root, resolveId, restoreQueryExtension = false) {
41014
41598
  id = slash$1(id);
41015
41599
  root = slash$1(root);
41016
41600
  const isVirtual = isVirtualModule(id);
@@ -41020,7 +41604,7 @@ async function transformGlobImport(code, id, root, resolveId, isProduction, rest
41020
41604
  if (!matches.length)
41021
41605
  return null;
41022
41606
  const s = new MagicString(code);
41023
- const staticImports = (await Promise.all(matches.map(async ({ globs, globsResolved, isRelative, options, index, start, end, }) => {
41607
+ const staticImports = (await Promise.all(matches.map(async ({ globsResolved, isRelative, options, index, start, end }) => {
41024
41608
  const cwd = getCommonBase(globsResolved) ?? root;
41025
41609
  const files = (await glob(globsResolved, {
41026
41610
  cwd,
@@ -41062,7 +41646,6 @@ async function transformGlobImport(code, id, root, resolveId, isProduction, rest
41062
41646
  }
41063
41647
  return { filePath, importPath };
41064
41648
  };
41065
- let includesCSS = false;
41066
41649
  files.forEach((file, i) => {
41067
41650
  const paths = resolvePaths(file);
41068
41651
  const filePath = paths.filePath;
@@ -41074,8 +41657,6 @@ async function transformGlobImport(code, id, root, resolveId, isProduction, rest
41074
41657
  importQuery = `${importQuery}&lang.${fileExtension}`;
41075
41658
  }
41076
41659
  importPath = `${importPath}${importQuery}`;
41077
- const isCSS = !query && isCSSRequest(file) && !isModuleCSSRequest(file);
41078
- includesCSS ||= isCSS;
41079
41660
  const importKey = options.import && options.import !== '*'
41080
41661
  ? options.import
41081
41662
  : undefined;
@@ -41085,23 +41666,13 @@ async function transformGlobImport(code, id, root, resolveId, isProduction, rest
41085
41666
  ? `{ ${importKey} as ${variableName} }`
41086
41667
  : `* as ${variableName}`;
41087
41668
  staticImports.push(`import ${expression} from ${JSON.stringify(importPath)}`);
41088
- if (!isProduction && isCSS) {
41089
- objectProps.push(`get ${JSON.stringify(filePath)}() { ${createCssDefaultImportWarning(globs, options)} return ${variableName} }`);
41090
- }
41091
- else {
41092
- objectProps.push(`${JSON.stringify(filePath)}: ${variableName}`);
41093
- }
41669
+ objectProps.push(`${JSON.stringify(filePath)}: ${variableName}`);
41094
41670
  }
41095
41671
  else {
41096
41672
  let importStatement = `import(${JSON.stringify(importPath)})`;
41097
41673
  if (importKey)
41098
41674
  importStatement += `.then(m => m[${JSON.stringify(importKey)}])`;
41099
- if (!isProduction && isCSS) {
41100
- objectProps.push(`${JSON.stringify(filePath)}: () => { ${createCssDefaultImportWarning(globs, options)} return ${importStatement}}`);
41101
- }
41102
- else {
41103
- objectProps.push(`${JSON.stringify(filePath)}: () => ${importStatement}`);
41104
- }
41675
+ objectProps.push(`${JSON.stringify(filePath)}: () => ${importStatement}`);
41105
41676
  }
41106
41677
  });
41107
41678
  files.forEach((i) => matchedFiles.add(i));
@@ -41109,19 +41680,7 @@ async function transformGlobImport(code, id, root, resolveId, isProduction, rest
41109
41680
  const lineBreaks = originalLineBreakCount > 0
41110
41681
  ? '\n'.repeat(originalLineBreakCount)
41111
41682
  : '';
41112
- let replacement;
41113
- if (!isProduction && includesCSS) {
41114
- replacement =
41115
- '/* #__PURE__ */ Object.assign(' +
41116
- '(() => {' +
41117
- `let ${warnedCSSDefaultImportVarName} = false;` +
41118
- `return {${objectProps.join(',')}${lineBreaks}};` +
41119
- '})()' +
41120
- ')';
41121
- }
41122
- else {
41123
- replacement = `/* #__PURE__ */ Object.assign({${objectProps.join(',')}${lineBreaks}})`;
41124
- }
41683
+ const replacement = `/* #__PURE__ */ Object.assign({${objectProps.join(',')}${lineBreaks}})`;
41125
41684
  s.overwrite(start, end, replacement);
41126
41685
  return staticImports;
41127
41686
  }))).flat();
@@ -41218,7 +41777,9 @@ const debugHmr = createDebugger('vite:hmr');
41218
41777
  const whitespaceRE = /\s/;
41219
41778
  const normalizedClientDir = normalizePath$3(CLIENT_DIR);
41220
41779
  function getShortName(file, root) {
41221
- return file.startsWith(root + '/') ? path$o.posix.relative(root, file) : file;
41780
+ return file.startsWith(withTrailingSlash(root))
41781
+ ? path$o.posix.relative(root, file)
41782
+ : file;
41222
41783
  }
41223
41784
  async function handleHMRUpdate(file, server, configOnly) {
41224
41785
  const { ws, config, moduleGraph } = server;
@@ -41245,7 +41806,7 @@ async function handleHMRUpdate(file, server, configOnly) {
41245
41806
  }
41246
41807
  debugHmr?.(`[file change] ${colors$1.dim(shortFile)}`);
41247
41808
  // (dev only) the client itself cannot be hot updated.
41248
- if (file.startsWith(normalizedClientDir)) {
41809
+ if (file.startsWith(withTrailingSlash(normalizedClientDir))) {
41249
41810
  ws.send({
41250
41811
  type: 'full-reload',
41251
41812
  path: '*',
@@ -41599,7 +42160,7 @@ async function readModifiedFile(file) {
41599
42160
  }
41600
42161
  }
41601
42162
 
41602
- const debug$a = createDebugger('vite:import-analysis');
42163
+ const debug$b = createDebugger('vite:import-analysis');
41603
42164
  const clientDir = normalizePath$3(CLIENT_DIR);
41604
42165
  const skipRE = /\.(?:map|json)(?:$|\?)/;
41605
42166
  const canSkipImportAnalysis = (id) => skipRE.test(id) || isDirectCSSRequest(id);
@@ -41717,7 +42278,7 @@ function importAnalysisPlugin(config) {
41717
42278
  const ssr = options?.ssr === true;
41718
42279
  const prettyImporter = prettifyUrl(importer, root);
41719
42280
  if (canSkipImportAnalysis(importer)) {
41720
- debug$a?.(colors$1.dim(`[skipped] ${prettyImporter}`));
42281
+ debug$b?.(colors$1.dim(`[skipped] ${prettyImporter}`));
41721
42282
  return null;
41722
42283
  }
41723
42284
  const start = performance.now();
@@ -41757,7 +42318,7 @@ function importAnalysisPlugin(config) {
41757
42318
  }
41758
42319
  if (!imports.length && !this._addedImports) {
41759
42320
  importerModule.isSelfAccepting = false;
41760
- debug$a?.(`${timeFrom(start)} ${colors$1.dim(`[no imports] ${prettyImporter}`)}`);
42321
+ debug$b?.(`${timeFrom(start)} ${colors$1.dim(`[no imports] ${prettyImporter}`)}`);
41761
42322
  return source;
41762
42323
  }
41763
42324
  let hasHMR = false;
@@ -41806,7 +42367,7 @@ function importAnalysisPlugin(config) {
41806
42367
  const isSelfImport = !isRelative && cleanUrl(url) === cleanUrl(importer);
41807
42368
  // normalize all imports into resolved URLs
41808
42369
  // e.g. `import 'foo'` -> `import '/@fs/.../node_modules/foo/index.js'`
41809
- if (resolved.id.startsWith(root + '/')) {
42370
+ if (resolved.id.startsWith(withTrailingSlash(root))) {
41810
42371
  // in root: infer short absolute path from root
41811
42372
  url = resolved.id.slice(root.length);
41812
42373
  }
@@ -41945,26 +42506,6 @@ function importAnalysisPlugin(config) {
41945
42506
  }
41946
42507
  // normalize
41947
42508
  const [url, resolvedId] = await normalizeUrl(specifier, start);
41948
- if (!isDynamicImport &&
41949
- specifier &&
41950
- !specifier.includes('?') && // ignore custom queries
41951
- isCSSRequest(resolvedId) &&
41952
- !isModuleCSSRequest(resolvedId)) {
41953
- const sourceExp = source.slice(expStart, start);
41954
- if (sourceExp.includes('from') && // check default and named imports
41955
- !sourceExp.includes('__vite_glob_') // glob handles deprecation message itself
41956
- ) {
41957
- const newImport = sourceExp + specifier + `?inline` + source.slice(end, expEnd);
41958
- this.warn(`\n` +
41959
- colors$1.cyan(importerModule.file) +
41960
- `\n` +
41961
- colors$1.reset(generateCodeFrame(source, start)) +
41962
- `\n` +
41963
- colors$1.yellow(`Default and named imports from CSS files are deprecated. ` +
41964
- `Use the ?inline query instead. ` +
41965
- `For example: ${newImport}`));
41966
- }
41967
- }
41968
42509
  // record as safe modules
41969
42510
  // safeModulesPath should not include the base prefix.
41970
42511
  // See https://github.com/vitejs/vite/issues/9438#issuecomment-1465270409
@@ -41988,7 +42529,7 @@ function importAnalysisPlugin(config) {
41988
42529
  }
41989
42530
  }
41990
42531
  else if (needsInterop) {
41991
- debug$a?.(`${url} needs interop`);
42532
+ debug$b?.(`${url} needs interop`);
41992
42533
  interopNamedImports(str(), importSpecifier, url, index, importer, config);
41993
42534
  rewriteDone = true;
41994
42535
  }
@@ -42038,8 +42579,8 @@ function importAnalysisPlugin(config) {
42038
42579
  });
42039
42580
  }
42040
42581
  }
42041
- else if (!importer.startsWith(clientDir)) {
42042
- if (!isInNodeModules(importer)) {
42582
+ else if (!importer.startsWith(withTrailingSlash(clientDir))) {
42583
+ if (!isInNodeModules$1(importer)) {
42043
42584
  // check @vite-ignore which suppresses dynamic import warning
42044
42585
  const hasViteIgnore = hasViteIgnoreRE.test(
42045
42586
  // complete expression inside parens
@@ -42124,7 +42665,7 @@ function importAnalysisPlugin(config) {
42124
42665
  handlePrunedModules(prunedImports, server);
42125
42666
  }
42126
42667
  }
42127
- debug$a?.(`${timeFrom(start)} ${colors$1.dim(`[${importedUrls.size} imports rewritten] ${prettyImporter}`)}`);
42668
+ debug$b?.(`${timeFrom(start)} ${colors$1.dim(`[${importedUrls.size} imports rewritten] ${prettyImporter}`)}`);
42128
42669
  if (s) {
42129
42670
  return transformStableResult(s, importer, config);
42130
42671
  }
@@ -42147,23 +42688,32 @@ function mergeAcceptedUrls(orderedUrls) {
42147
42688
  function interopNamedImports(str, importSpecifier, rewrittenUrl, importIndex, importer, config) {
42148
42689
  const source = str.original;
42149
42690
  const { s: start, e: end, ss: expStart, se: expEnd, d: dynamicIndex, } = importSpecifier;
42691
+ const exp = source.slice(expStart, expEnd);
42150
42692
  if (dynamicIndex > -1) {
42151
42693
  // rewrite `import('package')` to expose the default directly
42152
- str.overwrite(expStart, expEnd, `import('${rewrittenUrl}').then(m => m.default && m.default.__esModule ? m.default : ({ ...m.default, default: m.default }))`, { contentOnly: true });
42694
+ str.overwrite(expStart, expEnd, `import('${rewrittenUrl}').then(m => m.default && m.default.__esModule ? m.default : ({ ...m.default, default: m.default }))` +
42695
+ getLineBreaks(exp), { contentOnly: true });
42153
42696
  }
42154
42697
  else {
42155
- const exp = source.slice(expStart, expEnd);
42156
42698
  const rawUrl = source.slice(start, end);
42157
42699
  const rewritten = transformCjsImport(exp, rewrittenUrl, rawUrl, importIndex, importer, config);
42158
42700
  if (rewritten) {
42159
- str.overwrite(expStart, expEnd, rewritten, { contentOnly: true });
42701
+ str.overwrite(expStart, expEnd, rewritten + getLineBreaks(exp), {
42702
+ contentOnly: true,
42703
+ });
42160
42704
  }
42161
42705
  else {
42162
42706
  // #1439 export * from '...'
42163
- str.overwrite(start, end, rewrittenUrl, { contentOnly: true });
42707
+ str.overwrite(start, end, rewrittenUrl + getLineBreaks(source.slice(start, end)), {
42708
+ contentOnly: true,
42709
+ });
42164
42710
  }
42165
42711
  }
42166
42712
  }
42713
+ // get line breaks to preserve line count for not breaking source maps
42714
+ function getLineBreaks(str) {
42715
+ return str.includes('\n') ? '\n'.repeat(str.split('\n').length - 1) : '';
42716
+ }
42167
42717
  /**
42168
42718
  * Detect import statements to a known optimized CJS dependency and provide
42169
42719
  * ES named imports interop. We do this by rewriting named imports to a variable
@@ -42350,7 +42900,7 @@ function serializeDefine(define) {
42350
42900
  return res + `}`;
42351
42901
  }
42352
42902
 
42353
- const wasmHelperId = '\0vite/wasm-helper';
42903
+ const wasmHelperId = '\0vite/wasm-helper.js';
42354
42904
  const wasmHelper = async (opts = {}, url) => {
42355
42905
  let result;
42356
42906
  if (url.startsWith('data:')) {
@@ -42615,9 +43165,15 @@ function webWorkerPlugin(config) {
42615
43165
  injectEnv = module?.transformResult?.code || '';
42616
43166
  }
42617
43167
  }
42618
- return {
42619
- code: injectEnv + raw,
42620
- };
43168
+ if (injectEnv) {
43169
+ const s = new MagicString(raw);
43170
+ s.prepend(injectEnv);
43171
+ return {
43172
+ code: s.toString(),
43173
+ map: s.generateMap({ hires: 'boundary' }),
43174
+ };
43175
+ }
43176
+ return;
42621
43177
  }
42622
43178
  if (query == null ||
42623
43179
  (query && (query.worker ?? query.sharedworker) == null)) {
@@ -42632,7 +43188,10 @@ function webWorkerPlugin(config) {
42632
43188
  ? 'module'
42633
43189
  : 'classic'
42634
43190
  : 'module';
42635
- const workerTypeOption = workerType === 'classic' ? undefined : 'module';
43191
+ const workerTypeOption = `{
43192
+ ${workerType === 'module' ? `type: "module",` : ''}
43193
+ name: options?.name
43194
+ }`;
42636
43195
  if (isBuild) {
42637
43196
  getDepsOptimizer(config, ssr)?.registerWorkersSource(id);
42638
43197
  if (query.inline != null) {
@@ -42642,33 +43201,39 @@ function webWorkerPlugin(config) {
42642
43201
  // Using blob URL for SharedWorker results in multiple instances of a same worker
42643
43202
  workerConstructor === 'Worker'
42644
43203
  ? `${encodedJs}
42645
- const blob = typeof window !== "undefined" && window.Blob && new Blob([atob(encodedJs)], { type: "text/javascript;charset=utf-8" });
43204
+ const blob = typeof window !== "undefined" && window.Blob && new Blob([${workerType === 'classic'
43205
+ ? ''
43206
+ : // `URL` is always available, in `Worker[type="module"]`
43207
+ `'URL.revokeObjectURL(import.meta.url);'+`}atob(encodedJs)], { type: "text/javascript;charset=utf-8" });
42646
43208
  export default function WorkerWrapper(options) {
42647
43209
  let objURL;
42648
43210
  try {
42649
43211
  objURL = blob && (window.URL || window.webkitURL).createObjectURL(blob);
42650
43212
  if (!objURL) throw ''
42651
- return new ${workerConstructor}(objURL, { name: options?.name })
43213
+ const worker = new ${workerConstructor}(objURL, ${workerTypeOption});
43214
+ worker.addEventListener("error", () => {
43215
+ (window.URL || window.webkitURL).revokeObjectURL(objURL);
43216
+ });
43217
+ return worker;
42652
43218
  } catch(e) {
42653
43219
  return new ${workerConstructor}(
42654
43220
  "data:application/javascript;base64," + encodedJs,
42655
- {
42656
- ${workerTypeOption ? `type: "${workerTypeOption}",` : ''}
42657
- name: options?.name
42658
- }
43221
+ ${workerTypeOption}
42659
43222
  );
42660
- } finally {
42661
- objURL && (window.URL || window.webkitURL).revokeObjectURL(objURL);
42662
- }
43223
+ }${
43224
+ // For module workers, we should not revoke the URL until the worker runs,
43225
+ // otherwise the worker fails to run
43226
+ workerType === 'classic'
43227
+ ? ` finally {
43228
+ objURL && (window.URL || window.webkitURL).revokeObjectURL(objURL);
43229
+ }`
43230
+ : ''}
42663
43231
  }`
42664
43232
  : `${encodedJs}
42665
43233
  export default function WorkerWrapper(options) {
42666
43234
  return new ${workerConstructor}(
42667
43235
  "data:application/javascript;base64," + encodedJs,
42668
- {
42669
- ${workerTypeOption ? `type: "${workerTypeOption}",` : ''}
42670
- name: options?.name
42671
- }
43236
+ ${workerTypeOption}
42672
43237
  );
42673
43238
  }
42674
43239
  `;
@@ -42697,10 +43262,7 @@ function webWorkerPlugin(config) {
42697
43262
  code: `export default function WorkerWrapper(options) {
42698
43263
  return new ${workerConstructor}(
42699
43264
  ${JSON.stringify(url)},
42700
- {
42701
- ${workerTypeOption ? `type: "${workerTypeOption}",` : ''}
42702
- name: options?.name
42703
- }
43265
+ ${workerTypeOption}
42704
43266
  );
42705
43267
  }`,
42706
43268
  map: { mappings: '' }, // Empty sourcemap to suppress Rollup warning
@@ -42789,7 +43351,7 @@ function preAliasPlugin(config) {
42789
43351
  fs$l.existsSync(resolvedId) &&
42790
43352
  !moduleListContains(optimizeDeps.exclude, id) &&
42791
43353
  path$o.isAbsolute(resolvedId) &&
42792
- (isInNodeModules(resolvedId) ||
43354
+ (isInNodeModules$1(resolvedId) ||
42793
43355
  optimizeDeps.include?.includes(id)) &&
42794
43356
  isOptimizable(resolvedId, optimizeDeps) &&
42795
43357
  !(isBuild && ssr && isConfiguredAsExternal(id, importer)) &&
@@ -42828,7 +43390,7 @@ function matches(pattern, importee) {
42828
43390
  if (importee === pattern) {
42829
43391
  return true;
42830
43392
  }
42831
- return importee.startsWith(pattern + '/');
43393
+ return importee.startsWith(withTrailingSlash(pattern));
42832
43394
  }
42833
43395
  function getAliasPatterns(entries) {
42834
43396
  if (!entries) {
@@ -43098,7 +43660,9 @@ function workerImportMetaUrlPlugin(config) {
43098
43660
  builtUrl = injectQuery(builtUrl, WORKER_FILE_ID);
43099
43661
  builtUrl = injectQuery(builtUrl, `type=${workerType}`);
43100
43662
  }
43101
- s.update(urlIndex, urlIndex + exp.length, `new URL(${JSON.stringify(builtUrl)}, self.location)`);
43663
+ s.update(urlIndex, urlIndex + exp.length,
43664
+ // add `'' +` to skip vite:asset-import-meta-url plugin
43665
+ `new URL('' + ${JSON.stringify(builtUrl)}, import.meta.url)`);
43102
43666
  }
43103
43667
  if (s) {
43104
43668
  return transformStableResult(s, id, config);
@@ -43175,11 +43739,7 @@ function assetImportMetaUrlPlugin(config) {
43175
43739
  // A hack to allow 'as' & 'query' exist at the same time
43176
43740
  query: injectQuery(queryString, 'url'),
43177
43741
  };
43178
- // Note: native import.meta.url is not supported in the baseline
43179
- // target so we use the global location here. It can be
43180
- // window.location or self.location in case it is used in a Web Worker.
43181
- // @see https://developer.mozilla.org/en-US/docs/Web/API/Window/self
43182
- s.update(index, index + exp.length, `new URL((import.meta.glob(${JSON.stringify(pattern)}, ${JSON.stringify(globOptions)}))[${pureUrl}], self.location)`);
43742
+ s.update(index, index + exp.length, `new URL((import.meta.glob(${JSON.stringify(pattern)}, ${JSON.stringify(globOptions)}))[${pureUrl}], import.meta.url)`);
43183
43743
  continue;
43184
43744
  }
43185
43745
  }
@@ -43224,7 +43784,7 @@ function assetImportMetaUrlPlugin(config) {
43224
43784
  config.logger.warnOnce(`\n${rawExp} doesn't exist at build time, it will remain unchanged to be resolved at runtime`);
43225
43785
  builtUrl = url;
43226
43786
  }
43227
- s.update(index, index + exp.length, `new URL(${JSON.stringify(builtUrl)}, self.location)`);
43787
+ s.update(index, index + exp.length, `new URL(${JSON.stringify(builtUrl)}, import.meta.url)`);
43228
43788
  }
43229
43789
  if (s) {
43230
43790
  return transformStableResult(s, id, config);
@@ -43422,7 +43982,7 @@ function dynamicImportToGlob(node, sourceString) {
43422
43982
  return glob;
43423
43983
  }
43424
43984
 
43425
- const dynamicImportHelperId = '\0vite/dynamic-import-helper';
43985
+ const dynamicImportHelperId = '\0vite/dynamic-import-helper.js';
43426
43986
  const relativePathRE = /^\.{1,2}\//;
43427
43987
  // fast path to check if source contains a dynamic import. we check for a
43428
43988
  // trailing slash too as a dynamic import statement can have comments between
@@ -43827,7 +44387,7 @@ function throwClosedServerError() {
43827
44387
  // send a 504 status code request timeout
43828
44388
  throw err;
43829
44389
  }
43830
- let parser = Parser$1;
44390
+ let parser = Parser$1.extend(importAssertions);
43831
44391
  async function createPluginContainer(config, moduleGraph, watcher) {
43832
44392
  const { plugins, logger, root, build: { rollupOptions }, } = config;
43833
44393
  const { getSortedPluginHooks, getSortedPlugins } = createPluginHookUtils(plugins);
@@ -44208,7 +44768,7 @@ async function createPluginContainer(config, moduleGraph, watcher) {
44208
44768
  (await handleHookPromise(optionsHook.call(minimalContext, options))) || options;
44209
44769
  }
44210
44770
  if (options.acornInjectPlugins) {
44211
- parser = Parser$1.extend(...arraify(options.acornInjectPlugins));
44771
+ parser = Parser$1.extend(importAssertions, ...arraify(options.acornInjectPlugins));
44212
44772
  }
44213
44773
  return {
44214
44774
  acorn,
@@ -44362,7 +44922,7 @@ async function createPluginContainer(config, moduleGraph, watcher) {
44362
44922
  return container;
44363
44923
  }
44364
44924
 
44365
- const debug$9 = createDebugger('vite:deps');
44925
+ const debug$a = createDebugger('vite:deps');
44366
44926
  const htmlTypesRE = /\.(html|vue|svelte|astro|imba)$/;
44367
44927
  // A simple regex to detect import sources. This is only used on
44368
44928
  // <script lang="ts"> blocks in vue (setup only) or svelte files, since
@@ -44392,7 +44952,7 @@ function scanImports(config) {
44392
44952
  }
44393
44953
  if (scanContext.cancelled)
44394
44954
  return;
44395
- debug$9?.(`Crawling dependencies using entries: ${entries
44955
+ debug$a?.(`Crawling dependencies using entries: ${entries
44396
44956
  .map((entry) => `\n ${colors$1.dim(entry)}`)
44397
44957
  .join('')}`);
44398
44958
  return prepareEsbuildScanner(config, entries, deps, missing, scanContext);
@@ -44445,13 +45005,13 @@ function scanImports(config) {
44445
45005
  throw e;
44446
45006
  })
44447
45007
  .finally(() => {
44448
- if (debug$9) {
45008
+ if (debug$a) {
44449
45009
  const duration = (performance.now() - start).toFixed(2);
44450
45010
  const depsStr = Object.keys(orderedDependencies(deps))
44451
45011
  .sort()
44452
45012
  .map((id) => `\n ${colors$1.cyan(id)} -> ${colors$1.dim(deps[id])}`)
44453
45013
  .join('') || colors$1.dim('no dependencies found');
44454
- debug$9(`Scan completed in ${duration}ms: ${depsStr}`);
45014
+ debug$a(`Scan completed in ${duration}ms: ${depsStr}`);
44455
45015
  }
44456
45016
  });
44457
45017
  return {
@@ -44575,7 +45135,7 @@ function esbuildScanPlugin(config, container, depImports, missing, entries) {
44575
45135
  else {
44576
45136
  transpiledContents = contents;
44577
45137
  }
44578
- const result = await transformGlobImport(transpiledContents, id, config.root, resolve, config.isProduction);
45138
+ const result = await transformGlobImport(transpiledContents, id, config.root, resolve);
44579
45139
  return result?.s.toString() || transpiledContents;
44580
45140
  };
44581
45141
  return {
@@ -44611,7 +45171,7 @@ function esbuildScanPlugin(config, container, depImports, missing, entries) {
44611
45171
  // It is possible for the scanner to scan html types in node_modules.
44612
45172
  // If we can optimize this html type, skip it so it's handled by the
44613
45173
  // bare import resolve, and recorded as optimization dep.
44614
- if (isInNodeModules(resolved) &&
45174
+ if (isInNodeModules$1(resolved) &&
44615
45175
  isOptimizable(resolved, config.optimizeDeps))
44616
45176
  return;
44617
45177
  return {
@@ -44734,7 +45294,7 @@ function esbuildScanPlugin(config, container, depImports, missing, entries) {
44734
45294
  if (shouldExternalizeDep(resolved, id)) {
44735
45295
  return externalUnlessEntry({ path: id });
44736
45296
  }
44737
- if (isInNodeModules(resolved) || include?.includes(id)) {
45297
+ if (isInNodeModules$1(resolved) || include?.includes(id)) {
44738
45298
  // dependency or forced included, externalize and stop crawling
44739
45299
  if (isOptimizable(resolved, config.optimizeDeps)) {
44740
45300
  depImports[id] = resolved;
@@ -44918,7 +45478,7 @@ function expandGlobIds(id, config) {
44918
45478
  }
44919
45479
  const possibleExportPaths = [];
44920
45480
  for (const key in exports) {
44921
- if (key.startsWith('.')) {
45481
+ if (key[0] === '.') {
44922
45482
  if (key.includes('*')) {
44923
45483
  // "./glob/*": {
44924
45484
  // "browser": "./dist/glob/*-browser/*.js", <-- get this one
@@ -45012,7 +45572,7 @@ function nestedResolveBasedir(id, basedir, preserveSymlinks = false) {
45012
45572
  return basedir;
45013
45573
  }
45014
45574
 
45015
- const debug$8 = createDebugger('vite:deps');
45575
+ const debug$9 = createDebugger('vite:deps');
45016
45576
  /**
45017
45577
  * The amount to wait for requests to register newly found dependencies before triggering
45018
45578
  * a re-bundle + page reload
@@ -45148,7 +45708,7 @@ async function createDepsOptimizer(config, server) {
45148
45708
  depsOptimizer.scanProcessing = new Promise((resolve) => {
45149
45709
  (async () => {
45150
45710
  try {
45151
- debug$8?.(colors$1.green(`scanning for dependencies...`));
45711
+ debug$9?.(colors$1.green(`scanning for dependencies...`));
45152
45712
  discover = discoverProjectDependencies(config);
45153
45713
  const deps = await discover.result;
45154
45714
  discover = undefined;
@@ -45291,7 +45851,7 @@ async function createDepsOptimizer(config, server) {
45291
45851
  };
45292
45852
  if (!needsReload) {
45293
45853
  await commitProcessing();
45294
- if (!debug$8) {
45854
+ if (!debug$9) {
45295
45855
  if (newDepsToLogHandle)
45296
45856
  clearTimeout(newDepsToLogHandle);
45297
45857
  newDepsToLogHandle = setTimeout(() => {
@@ -45300,7 +45860,7 @@ async function createDepsOptimizer(config, server) {
45300
45860
  }, 2 * debounceMs);
45301
45861
  }
45302
45862
  else {
45303
- debug$8(colors$1.green(`✨ ${!isRerun
45863
+ debug$9(colors$1.green(`✨ ${!isRerun
45304
45864
  ? `dependencies optimized`
45305
45865
  : `optimized dependencies unchanged`}`));
45306
45866
  }
@@ -45312,11 +45872,11 @@ async function createDepsOptimizer(config, server) {
45312
45872
  // We don't resolve the processing promise, as they will be resolved
45313
45873
  // once a rerun is committed
45314
45874
  processingResult.cancel();
45315
- debug$8?.(colors$1.green(`✨ delaying reload as new dependencies have been found...`));
45875
+ debug$9?.(colors$1.green(`✨ delaying reload as new dependencies have been found...`));
45316
45876
  }
45317
45877
  else {
45318
45878
  await commitProcessing();
45319
- if (!debug$8) {
45879
+ if (!debug$9) {
45320
45880
  if (newDepsToLogHandle)
45321
45881
  clearTimeout(newDepsToLogHandle);
45322
45882
  newDepsToLogHandle = undefined;
@@ -45362,7 +45922,7 @@ async function createDepsOptimizer(config, server) {
45362
45922
  // optimizeDeps processing is finished
45363
45923
  const deps = Object.keys(metadata.discovered);
45364
45924
  const depsString = depsLogString(deps);
45365
- debug$8?.(colors$1.green(`new dependencies found: ${depsString}`));
45925
+ debug$9?.(colors$1.green(`new dependencies found: ${depsString}`));
45366
45926
  runOptimizer();
45367
45927
  }
45368
45928
  function getDiscoveredBrowserHash(hash, deps, missing) {
@@ -45447,11 +46007,10 @@ async function createDepsOptimizer(config, server) {
45447
46007
  // On build time, a missing dep appearing after onCrawlEnd is an internal error
45448
46008
  // On dev, switch after this point to a simple debounce strategy
45449
46009
  crawlEndFinder = undefined;
45450
- debug$8?.(colors$1.green(`✨ static imports crawl ended`));
46010
+ debug$9?.(colors$1.green(`✨ static imports crawl ended`));
45451
46011
  if (closed) {
45452
46012
  return;
45453
46013
  }
45454
- const crawlDeps = Object.keys(metadata.discovered);
45455
46014
  // Await for the scan+optimize step running in the background
45456
46015
  // It normally should be over by the time crawling of user code ended
45457
46016
  await depsOptimizer.scanProcessing;
@@ -45459,9 +46018,10 @@ async function createDepsOptimizer(config, server) {
45459
46018
  const result = await optimizationResult.result;
45460
46019
  optimizationResult = undefined;
45461
46020
  currentlyProcessing = false;
46021
+ const crawlDeps = Object.keys(metadata.discovered);
45462
46022
  const scanDeps = Object.keys(result.metadata.optimized);
45463
46023
  if (scanDeps.length === 0 && crawlDeps.length === 0) {
45464
- debug$8?.(colors$1.green(`✨ no dependencies found by the scanner or crawling static imports`));
46024
+ debug$9?.(colors$1.green(`✨ no dependencies found by the scanner or crawling static imports`));
45465
46025
  result.cancel();
45466
46026
  firstRunCalled = true;
45467
46027
  return;
@@ -45479,21 +46039,22 @@ async function createDepsOptimizer(config, server) {
45479
46039
  }
45480
46040
  }
45481
46041
  if (scannerMissedDeps) {
45482
- debug$8?.(colors$1.yellow(`✨ new dependencies were found while crawling that weren't detected by the scanner`));
46042
+ debug$9?.(colors$1.yellow(`✨ new dependencies were found while crawling that weren't detected by the scanner`));
45483
46043
  }
45484
- debug$8?.(colors$1.green(`✨ re-running optimizer`));
46044
+ debug$9?.(colors$1.green(`✨ re-running optimizer`));
45485
46045
  debouncedProcessing(0);
45486
46046
  }
45487
46047
  else {
45488
- debug$8?.(colors$1.green(`✨ using post-scan optimizer result, the scanner found every used dependency`));
46048
+ debug$9?.(colors$1.green(`✨ using post-scan optimizer result, the scanner found every used dependency`));
45489
46049
  startNextDiscoveredBatch();
45490
46050
  runOptimizer(result);
45491
46051
  }
45492
46052
  }
45493
46053
  else {
46054
+ const crawlDeps = Object.keys(metadata.discovered);
45494
46055
  currentlyProcessing = false;
45495
46056
  if (crawlDeps.length === 0) {
45496
- debug$8?.(colors$1.green(`✨ no dependencies found while crawling the static imports`));
46057
+ debug$9?.(colors$1.green(`✨ no dependencies found while crawling the static imports`));
45497
46058
  firstRunCalled = true;
45498
46059
  }
45499
46060
  else {
@@ -45624,14 +46185,14 @@ function findInteropMismatches(discovered, optimized) {
45624
46185
  // This only happens when a discovered dependency has mixed ESM and CJS syntax
45625
46186
  // and it hasn't been manually added to optimizeDeps.needsInterop
45626
46187
  needsInteropMismatch.push(dep);
45627
- debug$8?.(colors$1.cyan(`✨ needsInterop mismatch detected for ${dep}`));
46188
+ debug$9?.(colors$1.cyan(`✨ needsInterop mismatch detected for ${dep}`));
45628
46189
  }
45629
46190
  }
45630
46191
  }
45631
46192
  return needsInteropMismatch;
45632
46193
  }
45633
46194
 
45634
- const debug$7 = createDebugger('vite:deps');
46195
+ const debug$8 = createDebugger('vite:deps');
45635
46196
  const jsExtensionRE = /\.js$/i;
45636
46197
  const jsMapExtensionRE = /\.js\.map$/i;
45637
46198
  /**
@@ -45639,7 +46200,7 @@ const jsMapExtensionRE = /\.js\.map$/i;
45639
46200
  * Used by Vite CLI when running `vite optimize`.
45640
46201
  */
45641
46202
  async function optimizeDeps(config, force = config.optimizeDeps.force, asCommand = false) {
45642
- const log = asCommand ? config.logger.info : debug$7;
46203
+ const log = asCommand ? config.logger.info : debug$8;
45643
46204
  const ssr = config.command === 'build' && !!config.build.ssr;
45644
46205
  const cachedMetadata = await loadCachedDepOptimizationMetadata(config, ssr, force, asCommand);
45645
46206
  if (cachedMetadata) {
@@ -45702,7 +46263,7 @@ let firstLoadCachedDepOptimizationMetadata = true;
45702
46263
  * if it exists and pre-bundling isn't forced
45703
46264
  */
45704
46265
  async function loadCachedDepOptimizationMetadata(config, ssr, force = config.optimizeDeps.force, asCommand = false) {
45705
- const log = asCommand ? config.logger.info : debug$7;
46266
+ const log = asCommand ? config.logger.info : debug$8;
45706
46267
  if (firstLoadCachedDepOptimizationMetadata) {
45707
46268
  firstLoadCachedDepOptimizationMetadata = false;
45708
46269
  // Fire up a clean up of stale processing deps dirs if older process exited early
@@ -45910,7 +46471,7 @@ function runOptimizeDeps(resolvedConfig, depsInfo, ssr = resolvedConfig.command
45910
46471
  }
45911
46472
  }
45912
46473
  }
45913
- debug$7?.(`Dependencies bundled in ${(performance.now() - start).toFixed(2)}ms`);
46474
+ debug$8?.(`Dependencies bundled in ${(performance.now() - start).toFixed(2)}ms`);
45914
46475
  return successfulResult;
45915
46476
  })
45916
46477
  .catch((e) => {
@@ -46269,7 +46830,7 @@ async function extractExportsData(filePath, config, ssr) {
46269
46830
  }
46270
46831
  catch {
46271
46832
  const loader = esbuildOptions.loader?.[path$o.extname(filePath)] || 'jsx';
46272
- debug$7?.(`Unable to parse: ${filePath}.\n Trying again with a ${loader} transform.`);
46833
+ debug$8?.(`Unable to parse: ${filePath}.\n Trying again with a ${loader} transform.`);
46273
46834
  const transformed = await transformWithEsbuild(entryContent, filePath, {
46274
46835
  loader,
46275
46836
  });
@@ -46479,7 +47040,7 @@ var index$1 = {
46479
47040
  const isModernFlag = `__VITE_IS_MODERN__`;
46480
47041
  const preloadMethod = `__vitePreload`;
46481
47042
  const preloadMarker = `__VITE_PRELOAD__`;
46482
- const preloadHelperId = '\0vite/preload-helper';
47043
+ const preloadHelperId = '\0vite/preload-helper.js';
46483
47044
  const preloadMarkerWithQuote = new RegExp(`['"]${preloadMarker}['"]`);
46484
47045
  const dynamicImportPrefixRE = /import\s*\(/;
46485
47046
  // TODO: abstract
@@ -46613,7 +47174,7 @@ function buildImportAnalysisPlugin(config) {
46613
47174
  }
46614
47175
  },
46615
47176
  async transform(source, importer) {
46616
- if (isInNodeModules(importer) && !dynamicImportPrefixRE.test(source)) {
47177
+ if (isInNodeModules$1(importer) && !dynamicImportPrefixRE.test(source)) {
46617
47178
  return;
46618
47179
  }
46619
47180
  await init;
@@ -46658,7 +47219,7 @@ function buildImportAnalysisPlugin(config) {
46658
47219
  }
46659
47220
  // normalize all imports into resolved URLs
46660
47221
  // e.g. `import 'foo'` -> `import '/@fs/.../node_modules/foo/index.js'`
46661
- if (resolved.id.startsWith(root + '/')) {
47222
+ if (resolved.id.startsWith(withTrailingSlash(root))) {
46662
47223
  // in root: infer short absolute path from root
46663
47224
  url = resolved.id.slice(root.length);
46664
47225
  }
@@ -46724,24 +47285,6 @@ function buildImportAnalysisPlugin(config) {
46724
47285
  }
46725
47286
  }
46726
47287
  }
46727
- // Differentiate CSS imports that use the default export from those that
46728
- // do not by injecting a ?used query - this allows us to avoid including
46729
- // the CSS string when unnecessary (esbuild has trouble tree-shaking
46730
- // them)
46731
- if (specifier &&
46732
- isCSSRequest(specifier) &&
46733
- // always inject ?used query when it is a dynamic import
46734
- // because there is no way to check whether the default export is used
46735
- (source.slice(expStart, start).includes('from') || isDynamicImport) &&
46736
- // already has ?used query (by import.meta.glob)
46737
- !specifier.match(/\?used(&|$)/) &&
46738
- // don't append ?used when SPECIAL_QUERY_RE exists
46739
- !specifier.match(SPECIAL_QUERY_RE) &&
46740
- // edge case for package names ending with .css (e.g normalize.css)
46741
- !(bareImportRE.test(specifier) && !specifier.includes('/'))) {
46742
- const url = specifier.replace(/\?|$/, (m) => `?used${m ? '&' : ''}`);
46743
- str().update(start, end, isDynamicImport ? `'${url}'` : url);
46744
- }
46745
47288
  }
46746
47289
  if (needPreloadHelper &&
46747
47290
  insertPreload &&
@@ -47232,6 +47775,9 @@ function stattag (stat) {
47232
47775
 
47233
47776
  var getEtag = /*@__PURE__*/getDefaultExportFromCjs(etag_1);
47234
47777
 
47778
+ const debug$7 = createDebugger('vite:send', {
47779
+ onlyWhenFocused: true,
47780
+ });
47235
47781
  const alias = {
47236
47782
  js: 'application/javascript',
47237
47783
  css: 'text/css',
@@ -47262,11 +47808,22 @@ function send$2(req, res, content, type, options) {
47262
47808
  content = getCodeWithSourcemap(type, content.toString(), map);
47263
47809
  }
47264
47810
  }
47265
- else {
47266
- if (type === 'js' && (!map || map.mappings !== '')) {
47811
+ // inject fallback sourcemap for js for improved debugging
47812
+ // https://github.com/vitejs/vite/pull/13514#issuecomment-1592431496
47813
+ else if (type === 'js' && (!map || map.mappings !== '')) {
47814
+ const code = content.toString();
47815
+ // if the code has existing inline sourcemap, assume it's correct and skip
47816
+ if (convertSourceMap.mapFileCommentRegex.test(code)) {
47817
+ debug$7?.(`Skipped injecting fallback sourcemap for ${req.url}`);
47818
+ }
47819
+ else {
47267
47820
  const urlWithoutTimestamp = removeTimestampQuery(req.url);
47268
- const ms = new MagicString(content.toString());
47269
- content = getCodeWithSourcemap(type, content.toString(), ms.generateMap({ source: urlWithoutTimestamp, hires: 'boundary' }));
47821
+ const ms = new MagicString(code);
47822
+ content = getCodeWithSourcemap(type, code, ms.generateMap({
47823
+ source: path$o.basename(urlWithoutTimestamp),
47824
+ hires: 'boundary',
47825
+ includeContent: true,
47826
+ }));
47270
47827
  }
47271
47828
  }
47272
47829
  res.statusCode = 200;
@@ -47274,6 +47831,63 @@ function send$2(req, res, content, type, options) {
47274
47831
  return;
47275
47832
  }
47276
47833
 
47834
+ // https://github.com/vitejs/vite/issues/2820#issuecomment-812495079
47835
+ const ROOT_FILES = [
47836
+ // '.git',
47837
+ // https://pnpm.io/workspaces/
47838
+ 'pnpm-workspace.yaml',
47839
+ // https://rushjs.io/pages/advanced/config_files/
47840
+ // 'rush.json',
47841
+ // https://nx.dev/latest/react/getting-started/nx-setup
47842
+ // 'workspace.json',
47843
+ // 'nx.json',
47844
+ // https://github.com/lerna/lerna#lernajson
47845
+ 'lerna.json',
47846
+ ];
47847
+ // npm: https://docs.npmjs.com/cli/v7/using-npm/workspaces#installing-workspaces
47848
+ // yarn: https://classic.yarnpkg.com/en/docs/workspaces/#toc-how-to-use-it
47849
+ function hasWorkspacePackageJSON(root) {
47850
+ const path = join$2(root, 'package.json');
47851
+ if (!isFileReadable(path)) {
47852
+ return false;
47853
+ }
47854
+ const content = JSON.parse(fs$l.readFileSync(path, 'utf-8')) || {};
47855
+ return !!content.workspaces;
47856
+ }
47857
+ function hasRootFile(root) {
47858
+ return ROOT_FILES.some((file) => fs$l.existsSync(join$2(root, file)));
47859
+ }
47860
+ function hasPackageJSON(root) {
47861
+ const path = join$2(root, 'package.json');
47862
+ return fs$l.existsSync(path);
47863
+ }
47864
+ /**
47865
+ * Search up for the nearest `package.json`
47866
+ */
47867
+ function searchForPackageRoot(current, root = current) {
47868
+ if (hasPackageJSON(current))
47869
+ return current;
47870
+ const dir = dirname$2(current);
47871
+ // reach the fs root
47872
+ if (!dir || dir === current)
47873
+ return root;
47874
+ return searchForPackageRoot(dir, root);
47875
+ }
47876
+ /**
47877
+ * Search up for the nearest workspace root
47878
+ */
47879
+ function searchForWorkspaceRoot(current, root = searchForPackageRoot(current)) {
47880
+ if (hasRootFile(current))
47881
+ return current;
47882
+ if (hasWorkspacePackageJSON(current))
47883
+ return current;
47884
+ const dir = dirname$2(current);
47885
+ // reach the fs root
47886
+ if (!dir || dir === current)
47887
+ return root;
47888
+ return searchForWorkspaceRoot(dir, root);
47889
+ }
47890
+
47277
47891
  function totalist(dir, callback, pre='') {
47278
47892
  dir = resolve$3('.', dir);
47279
47893
  let arr = readdirSync(dir);
@@ -47664,7 +48278,7 @@ function serveStaticMiddleware(dir, server) {
47664
48278
  }
47665
48279
  if (redirectedPathname) {
47666
48280
  // dir is pre-normalized to posix style
47667
- if (redirectedPathname.startsWith(dir)) {
48281
+ if (redirectedPathname.startsWith(withTrailingSlash(dir))) {
47668
48282
  redirectedPathname = redirectedPathname.slice(dir.length);
47669
48283
  }
47670
48284
  }
@@ -47672,7 +48286,7 @@ function serveStaticMiddleware(dir, server) {
47672
48286
  let fileUrl = path$o.resolve(dir, removeLeadingSlash(resolvedPathname));
47673
48287
  if (resolvedPathname[resolvedPathname.length - 1] === '/' &&
47674
48288
  fileUrl[fileUrl.length - 1] !== '/') {
47675
- fileUrl = fileUrl + '/';
48289
+ fileUrl = withTrailingSlash(fileUrl);
47676
48290
  }
47677
48291
  if (!ensureServingAccess(fileUrl, server, res, next)) {
47678
48292
  return;
@@ -47854,7 +48468,7 @@ function resolveBuildOptions(raw, logger, root) {
47854
48468
  if (resolved.minify === 'false') {
47855
48469
  resolved.minify = false;
47856
48470
  }
47857
- if (resolved.minify === true) {
48471
+ else if (resolved.minify === true) {
47858
48472
  resolved.minify = 'esbuild';
47859
48473
  }
47860
48474
  if (resolved.cssMinify == null) {
@@ -48076,7 +48690,7 @@ function prepareOutDir(outDirs, emptyOutDir, config) {
48076
48690
  if (emptyOutDir == null) {
48077
48691
  for (const outDir of nonDuplicateDirs) {
48078
48692
  if (fs$l.existsSync(outDir) &&
48079
- !normalizePath$3(outDir).startsWith(config.root + '/')) {
48693
+ !normalizePath$3(outDir).startsWith(withTrailingSlash(config.root))) {
48080
48694
  // warn if outDir is outside of root
48081
48695
  config.logger.warn(colors$1.yellow(`\n${colors$1.bold(`(!)`)} outDir ${colors$1.white(colors$1.dim(outDir))} is not inside project root and will not be emptied.\n` +
48082
48696
  `Use --emptyOutDir to override.\n`));
@@ -48440,7 +49054,9 @@ const toOutputFilePathInHtml = toOutputFilePathWithoutRuntime;
48440
49054
  function areSeparateFolders(a, b) {
48441
49055
  const na = normalizePath$3(a);
48442
49056
  const nb = normalizePath$3(b);
48443
- return na !== nb && !na.startsWith(nb + '/') && !nb.startsWith(na + '/');
49057
+ return (na !== nb &&
49058
+ !na.startsWith(withTrailingSlash(nb)) &&
49059
+ !nb.startsWith(withTrailingSlash(na)));
48444
49060
  }
48445
49061
 
48446
49062
  var build$1 = {
@@ -55066,6 +55682,63 @@ function createConvertSourceMapReadMap(originalFileName) {
55066
55682
  };
55067
55683
  }
55068
55684
 
55685
+ /**
55686
+ * @param {import('estree').Node} param
55687
+ * @returns {string[]}
55688
+ */
55689
+ function extract_names(param) {
55690
+ return extract_identifiers(param).map((node) => node.name);
55691
+ }
55692
+
55693
+ /**
55694
+ * @param {import('estree').Node} param
55695
+ * @param {import('estree').Identifier[]} nodes
55696
+ * @returns {import('estree').Identifier[]}
55697
+ */
55698
+ function extract_identifiers(param, nodes = []) {
55699
+ switch (param.type) {
55700
+ case 'Identifier':
55701
+ nodes.push(param);
55702
+ break;
55703
+
55704
+ case 'MemberExpression':
55705
+ let object = param;
55706
+ while (object.type === 'MemberExpression') {
55707
+ object = /** @type {any} */ (object.object);
55708
+ }
55709
+ nodes.push(/** @type {any} */ (object));
55710
+ break;
55711
+
55712
+ case 'ObjectPattern':
55713
+ for (const prop of param.properties) {
55714
+ if (prop.type === 'RestElement') {
55715
+ extract_identifiers(prop.argument, nodes);
55716
+ } else {
55717
+ extract_identifiers(prop.value, nodes);
55718
+ }
55719
+ }
55720
+
55721
+ break;
55722
+
55723
+ case 'ArrayPattern':
55724
+ for (const element of param.elements) {
55725
+ if (element) extract_identifiers(element, nodes);
55726
+ }
55727
+
55728
+ break;
55729
+
55730
+ case 'RestElement':
55731
+ extract_identifiers(param.argument, nodes);
55732
+ break;
55733
+
55734
+ case 'AssignmentPattern':
55735
+ extract_identifiers(param.left, nodes);
55736
+ break;
55737
+ }
55738
+
55739
+ return nodes;
55740
+ }
55741
+
55069
55742
  /**
55070
55743
  * @typedef { import('estree').Node} Node
55071
55744
  * @typedef {{
@@ -55298,71 +55971,6 @@ function walk$1(ast, { enter, leave }) {
55298
55971
  return instance.visit(ast, null);
55299
55972
  }
55300
55973
 
55301
- /**
55302
- * @param {import('estree').Node} param
55303
- * @returns {string[]}
55304
- */
55305
- function extract_names(param) {
55306
- return extract_identifiers(param).map(node => node.name);
55307
- }
55308
-
55309
- /**
55310
- * @param {import('estree').Node} param
55311
- * @param {import('estree').Identifier[]} nodes
55312
- * @returns {import('estree').Identifier[]}
55313
- */
55314
- function extract_identifiers(param, nodes = []) {
55315
- switch (param.type) {
55316
- case 'Identifier':
55317
- nodes.push(param);
55318
- break;
55319
-
55320
- case 'MemberExpression':
55321
- let object = param;
55322
- while (object.type === 'MemberExpression') {
55323
- object = /** @type {any} */ (object.object);
55324
- }
55325
- nodes.push(/** @type {any} */ (object));
55326
- break;
55327
-
55328
- case 'ObjectPattern':
55329
- /** @param {import('estree').Property | import('estree').RestElement} prop */
55330
- const handle_prop = (prop) => {
55331
- if (prop.type === 'RestElement') {
55332
- extract_identifiers(prop.argument, nodes);
55333
- } else {
55334
- extract_identifiers(prop.value, nodes);
55335
- }
55336
- };
55337
-
55338
- param.properties.forEach(handle_prop);
55339
- break;
55340
-
55341
- case 'ArrayPattern':
55342
- /** @param {import('estree').Node} element */
55343
- const handle_element = (element) => {
55344
- if (element) extract_identifiers(element, nodes);
55345
- };
55346
-
55347
- param.elements.forEach((element) => {
55348
- if (element) {
55349
- handle_element(element);
55350
- }
55351
- });
55352
- break;
55353
-
55354
- case 'RestElement':
55355
- extract_identifiers(param.argument, nodes);
55356
- break;
55357
-
55358
- case 'AssignmentPattern':
55359
- extract_identifiers(param.left, nodes);
55360
- break;
55361
- }
55362
-
55363
- return nodes;
55364
- }
55365
-
55366
55974
  const ssrModuleExportsKey = `__vite_ssr_exports__`;
55367
55975
  const ssrImportKey = `__vite_ssr_import__`;
55368
55976
  const ssrDynamicImportKey = `__vite_ssr_dynamic_import__`;
@@ -57265,7 +57873,7 @@ function execAsync(command, options) {
57265
57873
  });
57266
57874
  }
57267
57875
 
57268
- function bindShortcuts(server, opts) {
57876
+ function bindCLIShortcuts(server, opts) {
57269
57877
  if (!server.httpServer || !process.stdin.isTTY || process.env.CI) {
57270
57878
  return;
57271
57879
  }
@@ -61982,7 +62590,7 @@ function baseMiddleware({ config, }) {
61982
62590
  }
61983
62591
  else if (req.headers.accept?.includes('text/html')) {
61984
62592
  // non-based page visit
61985
- const redirectPath = url + '/' !== base ? joinUrlSegments(base, url) : base;
62593
+ const redirectPath = withTrailingSlash(url) !== base ? joinUrlSegments(base, url) : base;
61986
62594
  res.writeHead(404, {
61987
62595
  'Content-Type': 'text/html',
61988
62596
  });
@@ -64370,10 +64978,10 @@ function transformMiddleware(server) {
64370
64978
  // check if public dir is inside root dir
64371
64979
  const publicDir = normalizePath$3(server.config.publicDir);
64372
64980
  const rootDir = normalizePath$3(server.config.root);
64373
- if (publicDir.startsWith(rootDir)) {
64981
+ if (publicDir.startsWith(withTrailingSlash(rootDir))) {
64374
64982
  const publicPath = `${publicDir.slice(rootDir.length)}/`;
64375
64983
  // warn explicit public paths
64376
- if (url.startsWith(publicPath)) {
64984
+ if (url.startsWith(withTrailingSlash(publicPath))) {
64377
64985
  let warning;
64378
64986
  if (isImportRequest(url)) {
64379
64987
  const rawUrl = removeImportQuery(url);
@@ -65164,6 +65772,9 @@ async function _createServer(inlineConfig = {}, options) {
65164
65772
  throw new Error('cannot print server URLs before server.listen is called.');
65165
65773
  }
65166
65774
  },
65775
+ bindCLIShortcuts(options) {
65776
+ bindCLIShortcuts(server, options);
65777
+ },
65167
65778
  async restart(forceOptimize) {
65168
65779
  if (!server._restartPromise) {
65169
65780
  server._forceOptimizeOnRestart = !!forceOptimize;
@@ -65407,7 +66018,7 @@ function resolveServerOptions(root, raw, logger) {
65407
66018
  ...raw,
65408
66019
  sourcemapIgnoreList: raw?.sourcemapIgnoreList === false
65409
66020
  ? () => false
65410
- : raw?.sourcemapIgnoreList || isInNodeModules,
66021
+ : raw?.sourcemapIgnoreList || isInNodeModules$1,
65411
66022
  middlewareMode: !!raw?.middlewareMode,
65412
66023
  };
65413
66024
  let allowDirs = server.fs?.allow;
@@ -65477,7 +66088,7 @@ async function restartServer(server) {
65477
66088
  }
65478
66089
  if (shortcutsOptions) {
65479
66090
  shortcutsOptions.print = false;
65480
- bindShortcuts(newServer, shortcutsOptions);
66091
+ bindCLIShortcuts(newServer, shortcutsOptions);
65481
66092
  }
65482
66093
  }
65483
66094
  async function updateCjsSsrExternals(server) {
@@ -65663,6 +66274,9 @@ async function preview(inlineConfig = {}) {
65663
66274
  throw new Error('cannot print server URLs before server is listening.');
65664
66275
  }
65665
66276
  },
66277
+ bindCLIShortcuts(options) {
66278
+ bindCLIShortcuts(server, options);
66279
+ },
65666
66280
  };
65667
66281
  // apply server hooks from plugins
65668
66282
  const postHooks = [];
@@ -65821,6 +66435,9 @@ async function resolveConfig(inlineConfig, command, defaultMode = 'development',
65821
66435
  });
65822
66436
  // resolve root
65823
66437
  const resolvedRoot = normalizePath$3(config.root ? path$o.resolve(config.root) : process.cwd());
66438
+ if (resolvedRoot.includes('#')) {
66439
+ logger.warn(colors$1.yellow(`The project root contains the "#" character (${colors$1.cyan(resolvedRoot)}), which may not work when running Vite. Consider renaming the directory to remove the "#".`));
66440
+ }
65824
66441
  const clientAlias = [
65825
66442
  {
65826
66443
  find: /^\/?@vite\/env/,
@@ -65961,7 +66578,7 @@ async function resolveConfig(inlineConfig, command, defaultMode = 'development',
65961
66578
  configFileDependencies: configFileDependencies.map((name) => normalizePath$3(path$o.resolve(name))),
65962
66579
  inlineConfig,
65963
66580
  root: resolvedRoot,
65964
- base: resolvedBase.endsWith('/') ? resolvedBase : resolvedBase + '/',
66581
+ base: withTrailingSlash(resolvedBase),
65965
66582
  rawBase: resolvedBase,
65966
66583
  resolve: resolveOptions,
65967
66584
  publicDir: resolvedPublicDir,
@@ -66042,7 +66659,7 @@ async function resolveConfig(inlineConfig, command, defaultMode = 'development',
66042
66659
  if (middlewareMode === 'ssr') {
66043
66660
  logger.warn(colors$1.yellow(`Setting server.middlewareMode to 'ssr' is deprecated, set server.middlewareMode to \`true\`${config.appType === 'custom' ? '' : ` and appType to 'custom'`} instead`));
66044
66661
  }
66045
- if (middlewareMode === 'html') {
66662
+ else if (middlewareMode === 'html') {
66046
66663
  logger.warn(colors$1.yellow(`Setting server.middlewareMode to 'html' is deprecated, set server.middlewareMode to \`true\` instead`));
66047
66664
  }
66048
66665
  if (config.server?.force &&
@@ -66084,7 +66701,7 @@ assetFileNames isn't equal for every build.rollupOptions.output. A single patter
66084
66701
  if (config.legacy?.buildSsrCjsExternalHeuristics ||
66085
66702
  config.ssr?.format === 'cjs') {
66086
66703
  resolved.logger.warn(colors$1.yellow(`
66087
- (!) Experimental legacy.buildSsrCjsExternalHeuristics and ssr.format: 'cjs' are going to be removed in Vite 5.
66704
+ (!) Experimental legacy.buildSsrCjsExternalHeuristics and ssr.format: 'cjs' are going to be removed in Vite 5.
66088
66705
  Find more information and give feedback at https://github.com/vitejs/vite/discussions/13816.
66089
66706
  `));
66090
66707
  }
@@ -66378,4 +66995,4 @@ function isDepsOptimizerEnabled(config, ssr) {
66378
66995
  (command === 'serve' && disabled === 'dev'));
66379
66996
  }
66380
66997
 
66381
- export { loadEnv as A, resolveEnvPrefix as B, colors$1 as C, bindShortcuts as D, getDefaultExportFromCjs as E, commonjsGlobal as F, index$1 as G, build$1 as H, index as I, preview$1 as J, preprocessCSS as a, build as b, createServer as c, resolvePackageData as d, buildErrorMessage as e, formatPostcssSourceMap as f, defineConfig as g, resolveConfig as h, isInNodeModules as i, resolveBaseUrl as j, getDepOptimizationConfig as k, loadConfigFromFile as l, isDepsOptimizerEnabled as m, normalizePath$3 as n, optimizeDeps as o, preview as p, mergeConfig as q, resolvePackageEntry as r, sortUserPlugins as s, transformWithEsbuild as t, mergeAlias as u, createFilter as v, send$2 as w, createLogger as x, searchForWorkspaceRoot as y, isFileServingAllowed as z };
66998
+ export { loadEnv as A, resolveEnvPrefix as B, colors$1 as C, getDefaultExportFromCjs as D, commonjsGlobal as E, index$1 as F, build$1 as G, index as H, preview$1 as I, preprocessCSS as a, build as b, createServer as c, resolvePackageData as d, buildErrorMessage as e, formatPostcssSourceMap as f, defineConfig as g, resolveConfig as h, isInNodeModules$1 as i, resolveBaseUrl as j, getDepOptimizationConfig as k, loadConfigFromFile as l, isDepsOptimizerEnabled as m, normalizePath$3 as n, optimizeDeps as o, preview as p, mergeConfig as q, resolvePackageEntry as r, sortUserPlugins as s, transformWithEsbuild as t, mergeAlias as u, createFilter as v, send$2 as w, createLogger as x, searchForWorkspaceRoot as y, isFileServingAllowed as z };