vite 3.0.0-alpha.7 → 3.0.0-alpha.8

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.
@@ -11567,7 +11567,7 @@ function writeFile(filename, content) {
11567
11567
  fs__default.writeFileSync(filename, content);
11568
11568
  }
11569
11569
  /**
11570
- * Use instead of fs.existsSync(filename)
11570
+ * Use fs.statSync(filename) instead of fs.existsSync(filename)
11571
11571
  * #2051 if we don't have read permission on a directory, existsSync() still
11572
11572
  * works and will result in massively slow subsequent checks (which are
11573
11573
  * unnecessary in the first place)
@@ -11939,6 +11939,14 @@ function normalizeSingleAlias({ find, replacement, customResolver }) {
11939
11939
  }
11940
11940
  return alias;
11941
11941
  }
11942
+ function transformResult(s, id, config) {
11943
+ const isBuild = config.command === 'build';
11944
+ const needSourceMap = !isBuild || config.build.sourcemap;
11945
+ return {
11946
+ code: s.toString(),
11947
+ map: needSourceMap ? s.generateMap({ hires: true, source: id }) : null
11948
+ };
11949
+ }
11942
11950
 
11943
11951
  /* eslint no-console: 0 */
11944
11952
  const LogLevels = {
@@ -14682,7 +14690,7 @@ const debug$c = createDebugger('vite:resolve-details', {
14682
14690
  onlyWhenFocused: true
14683
14691
  });
14684
14692
  function resolvePlugin(baseOptions) {
14685
- const { root, isProduction, asSrc, ssrConfig, preferRelative = false } = baseOptions;
14693
+ const { root, isBuild, isProduction, asSrc, ssrConfig, preferRelative = false } = baseOptions;
14686
14694
  const { target: ssrTarget, noExternal: ssrNoExternal } = ssrConfig ?? {};
14687
14695
  return {
14688
14696
  name: 'vite:resolve',
@@ -14809,18 +14817,20 @@ function resolvePlugin(baseOptions) {
14809
14817
  }
14810
14818
  // bare package imports, perform node resolve
14811
14819
  if (bareImportRE.test(id)) {
14812
- if (asSrc &&
14820
+ const external = options.shouldExternalize?.(id);
14821
+ if (!external &&
14822
+ asSrc &&
14813
14823
  depsOptimizer &&
14814
- !ssr &&
14824
+ (isBuild || !ssr) &&
14815
14825
  !options.scan &&
14816
14826
  (res = await tryOptimizedResolve(depsOptimizer, id, importer))) {
14817
14827
  return res;
14818
14828
  }
14819
14829
  if (targetWeb &&
14820
- (res = tryResolveBrowserMapping(id, importer, options, false))) {
14830
+ (res = tryResolveBrowserMapping(id, importer, options, false, external))) {
14821
14831
  return res;
14822
14832
  }
14823
- if ((res = tryNodeResolve(id, importer, options, targetWeb, depsOptimizer, ssr))) {
14833
+ if ((res = tryNodeResolve(id, importer, options, targetWeb, depsOptimizer, ssr, external))) {
14824
14834
  return res;
14825
14835
  }
14826
14836
  // node built-ins.
@@ -14951,7 +14961,7 @@ function tryResolveFile(file, postfix, options, tryIndex, targetWeb, tryPrefix,
14951
14961
  }
14952
14962
  }
14953
14963
  const idToPkgMap = new Map();
14954
- function tryNodeResolve(id, importer, options, targetWeb, depsOptimizer, ssr) {
14964
+ function tryNodeResolve(id, importer, options, targetWeb, depsOptimizer, ssr, externalize) {
14955
14965
  const { root, dedupe, isBuild, preserveSymlinks, packageCache } = options;
14956
14966
  // split id by last '>' for nested selected packages, for example:
14957
14967
  // 'foo > bar > baz' => 'foo > bar' & 'baz'
@@ -15005,7 +15015,8 @@ function tryNodeResolve(id, importer, options, targetWeb, depsOptimizer, ssr) {
15005
15015
  }
15006
15016
  let resolveId = resolvePackageEntry;
15007
15017
  let unresolvedId = pkgId;
15008
- if (unresolvedId !== nestedPath) {
15018
+ const isDeepImport = unresolvedId !== nestedPath;
15019
+ if (isDeepImport) {
15009
15020
  resolveId = resolveDeepImport;
15010
15021
  unresolvedId = '.' + nestedPath.slice(pkgId.length);
15011
15022
  }
@@ -15029,15 +15040,23 @@ function tryNodeResolve(id, importer, options, targetWeb, depsOptimizer, ssr) {
15029
15040
  if (!resolved) {
15030
15041
  return;
15031
15042
  }
15043
+ const processResult = (resolved) => {
15044
+ if (!externalize) {
15045
+ return resolved;
15046
+ }
15047
+ const resolvedExt = path$p.extname(resolved.id);
15048
+ const resolvedId = isDeepImport && path$p.extname(id) !== resolvedExt ? id + resolvedExt : id;
15049
+ return { ...resolved, id: resolvedId, external: true };
15050
+ };
15032
15051
  // link id to pkg for browser field mapping check
15033
15052
  idToPkgMap.set(resolved, pkg);
15034
- if (isBuild && !depsOptimizer) {
15053
+ if ((isBuild && !depsOptimizer) || externalize) {
15035
15054
  // Resolve package side effects for build so that rollup can better
15036
15055
  // perform tree-shaking
15037
- return {
15056
+ return processResult({
15038
15057
  id: resolved,
15039
15058
  moduleSideEffects: pkg.hasSideEffects(resolved)
15040
- };
15059
+ });
15041
15060
  }
15042
15061
  if (!resolved.includes('node_modules') || // linked
15043
15062
  !depsOptimizer || // resolving before listening to the server
@@ -15053,7 +15072,7 @@ function tryNodeResolve(id, importer, options, targetWeb, depsOptimizer, ssr) {
15053
15072
  exclude?.includes(pkgId) ||
15054
15073
  exclude?.includes(nestedPath) ||
15055
15074
  SPECIAL_QUERY_RE.test(resolved) ||
15056
- ssr) {
15075
+ (!isBuild && ssr)) {
15057
15076
  // excluded from optimization
15058
15077
  // Inject a version query to npm deps so that the browser
15059
15078
  // can cache it without re-validation, but only do so for known js types.
@@ -15067,7 +15086,6 @@ function tryNodeResolve(id, importer, options, targetWeb, depsOptimizer, ssr) {
15067
15086
  }
15068
15087
  }
15069
15088
  else {
15070
- // TODO: depsBuild
15071
15089
  // this is a missing import, queue optimize-deps re-run and
15072
15090
  // get a resolved its optimized info
15073
15091
  const optimizedInfo = depsOptimizer.registerMissingImport(id, resolved);
@@ -15282,7 +15300,7 @@ function resolveDeepImport(id, { webResolvedImports, setResolvedCache, getResolv
15282
15300
  }
15283
15301
  }
15284
15302
  }
15285
- function tryResolveBrowserMapping(id, importer, options, isFilePath) {
15303
+ function tryResolveBrowserMapping(id, importer, options, isFilePath, externalize) {
15286
15304
  let res;
15287
15305
  const pkg = importer && idToPkgMap.get(importer);
15288
15306
  if (pkg && isObject$2(pkg.data.browser)) {
@@ -15294,10 +15312,11 @@ function tryResolveBrowserMapping(id, importer, options, isFilePath) {
15294
15312
  isDebug$4 &&
15295
15313
  debug$c(`[browser mapped] ${colors$1.cyan(id)} -> ${colors$1.dim(res)}`);
15296
15314
  idToPkgMap.set(res, pkg);
15297
- return {
15315
+ const result = {
15298
15316
  id: res,
15299
15317
  moduleSideEffects: pkg.hasSideEffects(res)
15300
15318
  };
15319
+ return externalize ? { ...result, external: true } : result;
15301
15320
  }
15302
15321
  }
15303
15322
  else if (browserMappedPath === false) {
@@ -26228,10 +26247,7 @@ function importGlobPlugin(config) {
26228
26247
  server.watcher.add(dirname(file));
26229
26248
  });
26230
26249
  }
26231
- return {
26232
- code: result.s.toString(),
26233
- map: config.build.sourcemap ? result.s.generateMap() : null
26234
- };
26250
+ return transformResult(result.s, id, config);
26235
26251
  }
26236
26252
  }
26237
26253
  };
@@ -27603,12 +27619,22 @@ function depsFromOptimizedDepInfo(depsInfo) {
27603
27619
  function getOptimizedDepPath(id, config) {
27604
27620
  return normalizePath$3(path$p.resolve(getDepsCacheDir(config), flattenId(id) + '.js'));
27605
27621
  }
27622
+ function getDepsCacheSuffix(config) {
27623
+ let suffix = '';
27624
+ if (config.command === 'build') {
27625
+ suffix += '_build';
27626
+ if (config.build.ssr) {
27627
+ suffix += '_ssr';
27628
+ }
27629
+ }
27630
+ return suffix;
27631
+ }
27606
27632
  function getDepsCacheDir(config) {
27607
- const dirName = config.command === 'build' ? 'depsBuild' : 'deps';
27633
+ const dirName = 'deps' + getDepsCacheSuffix(config);
27608
27634
  return normalizePath$3(path$p.resolve(config.cacheDir, dirName));
27609
27635
  }
27610
27636
  function getProcessingDepsCacheDir(config) {
27611
- const dirName = config.command === 'build' ? 'processingBuild' : 'processing';
27637
+ const dirName = 'deps' + getDepsCacheSuffix(config) + '_temp';
27612
27638
  return normalizePath$3(path$p.resolve(config.cacheDir, dirName));
27613
27639
  }
27614
27640
  function isOptimizedDepFile(id, config) {
@@ -35878,7 +35904,7 @@ const assetAttrsConfig = {
35878
35904
  const isAsyncScriptMap = new WeakMap();
35879
35905
  async function traverseHtml(html, filePath, visitor) {
35880
35906
  // lazy load compiler
35881
- const { parse, transform } = await import('./dep-3a62832d.js').then(function (n) { return n.c; });
35907
+ const { parse, transform } = await import('./dep-cfa39351.js').then(function (n) { return n.c; });
35882
35908
  // @vue/compiler-core doesn't like lowercase doctypes
35883
35909
  html = html.replace(/<!doctype\s/i, '<!DOCTYPE ');
35884
35910
  try {
@@ -36983,7 +37009,7 @@ async function compileCSS(id, code, config, urlReplacer, atImportResolvers, serv
36983
37009
  logger: config.logger
36984
37010
  }));
36985
37011
  if (isModule) {
36986
- postcssPlugins.unshift((await import('./dep-16fa9be9.js').then(function (n) { return n.i; })).default({
37012
+ postcssPlugins.unshift((await import('./dep-6b269949.js').then(function (n) { return n.i; })).default({
36987
37013
  ...modulesOptions,
36988
37014
  getJSON(cssFileName, _modules, outputFileName) {
36989
37015
  modules = _modules;
@@ -37955,7 +37981,7 @@ function lexAcceptedHmrDeps(code, start, urls) {
37955
37981
  return false;
37956
37982
  }
37957
37983
  function error$1(pos) {
37958
- const err = new Error(`import.meta.accept() can only accept string literals or an ` +
37984
+ const err = new Error(`import.meta.hot.accept() can only accept string literals or an ` +
37959
37985
  `Array of string literals.`);
37960
37986
  err.pos = pos;
37961
37987
  throw err;
@@ -38002,7 +38028,7 @@ function stripNesting(packages) {
38002
38028
  * Heuristics for determining whether a dependency should be externalized for
38003
38029
  * server-side rendering.
38004
38030
  */
38005
- function resolveSSRExternal(config, knownImports) {
38031
+ function cjsSsrResolveExternals(config, knownImports) {
38006
38032
  // strip nesting since knownImports may be passed in from optimizeDeps which
38007
38033
  // supports a "parent > child" syntax
38008
38034
  knownImports = stripNesting(knownImports);
@@ -38016,7 +38042,7 @@ function resolveSSRExternal(config, knownImports) {
38016
38042
  ssrExternals.add(id);
38017
38043
  seen.add(id);
38018
38044
  });
38019
- collectExternals(config.root, config.resolve.preserveSymlinks, ssrExternals, seen, config.logger);
38045
+ cjsSsrCollectExternals(config.root, config.resolve.preserveSymlinks, ssrExternals, seen, config.logger);
38020
38046
  const importedDeps = knownImports.map(getNpmPackageName).filter(isDefined);
38021
38047
  for (const dep of importedDeps) {
38022
38048
  // Assume external if not yet seen
@@ -38038,8 +38064,71 @@ function resolveSSRExternal(config, knownImports) {
38038
38064
  const CJS_CONTENT_RE = /\bmodule\.exports\b|\bexports[.\[]|\brequire\s*\(|\bObject\.(defineProperty|defineProperties|assign)\s*\(\s*exports\b/;
38039
38065
  // TODO: use import()
38040
38066
  const _require$2 = createRequire$1(import.meta.url);
38041
- // do we need to do this ahead of time or could we do it lazily?
38042
- function collectExternals(root, preserveSymlinks, ssrExternals, seen, logger) {
38067
+ const isSsrExternalCache = new WeakMap();
38068
+ function shouldExternalizeForSSR(id, config) {
38069
+ let isSsrExternal = isSsrExternalCache.get(config);
38070
+ if (!isSsrExternal) {
38071
+ isSsrExternal = createIsSsrExternal(config);
38072
+ isSsrExternalCache.set(config, isSsrExternal);
38073
+ }
38074
+ return isSsrExternal(id);
38075
+ }
38076
+ function createIsSsrExternal(config) {
38077
+ const processedIds = new Map();
38078
+ const { ssr, root } = config;
38079
+ const noExternal = ssr?.noExternal;
38080
+ const noExternalFilter = noExternal !== 'undefined' &&
38081
+ typeof noExternal !== 'boolean' &&
38082
+ createFilter$1(undefined, noExternal, { resolve: false });
38083
+ const isConfiguredAsExternal = (id) => {
38084
+ const { ssr } = config;
38085
+ if (!ssr || ssr.external?.includes(id)) {
38086
+ return true;
38087
+ }
38088
+ if (typeof noExternal === 'boolean') {
38089
+ return !noExternal;
38090
+ }
38091
+ if (noExternalFilter) {
38092
+ return noExternalFilter(id);
38093
+ }
38094
+ return true;
38095
+ };
38096
+ const resolveOptions = {
38097
+ root,
38098
+ preserveSymlinks: config.resolve.preserveSymlinks,
38099
+ isProduction: false,
38100
+ isBuild: true
38101
+ };
38102
+ const isPackageEntry = (id) => {
38103
+ if (!bareImportRE.test(id) || id.includes('\0')) {
38104
+ return false;
38105
+ }
38106
+ if (tryNodeResolve(id, undefined, resolveOptions, ssr?.target === 'webworker', undefined, true)) {
38107
+ return true;
38108
+ }
38109
+ try {
38110
+ // no main entry, but deep imports may be allowed
38111
+ if (resolveFrom(`${id}/package.json`, root)) {
38112
+ return true;
38113
+ }
38114
+ }
38115
+ catch { }
38116
+ return false;
38117
+ };
38118
+ return (id) => {
38119
+ if (processedIds.has(id)) {
38120
+ return processedIds.get(id);
38121
+ }
38122
+ const external = !id.startsWith('.') &&
38123
+ !path$p.isAbsolute(id) &&
38124
+ (isBuiltin(id) || (isConfiguredAsExternal(id) && isPackageEntry(id)));
38125
+ processedIds.set(id, external);
38126
+ return external;
38127
+ };
38128
+ }
38129
+ // When ssr.format is 'cjs', this function is used reverting to the Vite 2.9
38130
+ // SSR externalization heuristics
38131
+ function cjsSsrCollectExternals(root, preserveSymlinks, ssrExternals, seen, logger) {
38043
38132
  const rootPkgContent = lookupFile(root, ['package.json']);
38044
38133
  if (!rootPkgContent) {
38045
38134
  return;
@@ -38123,10 +38212,13 @@ function collectExternals(root, preserveSymlinks, ssrExternals, seen, logger) {
38123
38212
  }
38124
38213
  }
38125
38214
  for (const depRoot of depsToTrace) {
38126
- collectExternals(depRoot, preserveSymlinks, ssrExternals, seen, logger);
38215
+ cjsSsrCollectExternals(depRoot, preserveSymlinks, ssrExternals, seen, logger);
38127
38216
  }
38128
38217
  }
38129
- function shouldExternalizeForSSR(id, externals) {
38218
+ function cjsShouldExternalizeForSSR(id, externals) {
38219
+ if (!externals) {
38220
+ return false;
38221
+ }
38130
38222
  const should = externals.some((e) => {
38131
38223
  if (id === e) {
38132
38224
  return true;
@@ -40038,8 +40130,12 @@ function importAnalysisPlugin(config) {
40038
40130
  }
40039
40131
  // skip ssr external
40040
40132
  if (ssr) {
40041
- if (server._ssrExternals &&
40042
- shouldExternalizeForSSR(specifier, server._ssrExternals)) {
40133
+ if (config.ssr?.format === 'cjs') {
40134
+ if (cjsShouldExternalizeForSSR(specifier, server._ssrExternals)) {
40135
+ continue;
40136
+ }
40137
+ }
40138
+ else if (shouldExternalizeForSSR(specifier, config)) {
40043
40139
  continue;
40044
40140
  }
40045
40141
  if (isBuiltin(specifier)) {
@@ -40222,10 +40318,7 @@ function importAnalysisPlugin(config) {
40222
40318
  });
40223
40319
  }
40224
40320
  if (s) {
40225
- return {
40226
- code: s.toString(),
40227
- map: config.build.sourcemap ? s.generateMap({ hires: true }) : null
40228
- };
40321
+ return transformResult(s, importer, config);
40229
40322
  }
40230
40323
  else {
40231
40324
  return source;
@@ -40739,7 +40832,7 @@ function ssrManifestPlugin(config) {
40739
40832
  const chunk = bundle[filename];
40740
40833
  if (chunk) {
40741
40834
  chunk.viteMetadata.importedCss.forEach((file) => {
40742
- deps.push(`/${file}`);
40835
+ deps.push(join$1(config.base, file));
40743
40836
  });
40744
40837
  chunk.imports.forEach(addDeps);
40745
40838
  }
@@ -40818,10 +40911,7 @@ function assetImportMetaUrlPlugin(config) {
40818
40911
  s.overwrite(index, index + exp.length, `new URL(${JSON.stringify(builtUrl)}, self.location)`, { contentOnly: true });
40819
40912
  }
40820
40913
  if (s) {
40821
- return {
40822
- code: s.toString(),
40823
- map: config.build.sourcemap ? s.generateMap({ hires: true }) : null
40824
- };
40914
+ return transformResult(s, id, config);
40825
40915
  }
40826
40916
  }
40827
40917
  return null;
@@ -40948,7 +41038,7 @@ function resolveBuildPlugins(config) {
40948
41038
  pre: [
40949
41039
  ...(options.watch ? [ensureWatchPlugin()] : []),
40950
41040
  watchPackageDataPlugin(config),
40951
- ...(!isDepsOptimizerEnabled(config) || options.ssr
41041
+ ...(!isDepsOptimizerEnabled(config)
40952
41042
  ? [commonjs(options.commonjsOptions)]
40953
41043
  : []),
40954
41044
  dataURIPlugin(),
@@ -41012,25 +41102,15 @@ async function doBuild(inlineConfig = {}) {
41012
41102
  const outDir = resolve(options.outDir);
41013
41103
  // inject ssr arg to plugin load/transform hooks
41014
41104
  const plugins = (ssr ? config.plugins.map((p) => injectSsrFlagToHooks(p)) : config.plugins);
41015
- // inject ssrExternal if present
41016
41105
  const userExternal = options.rollupOptions?.external;
41017
41106
  let external = userExternal;
41018
- if (ssr) {
41019
- // see if we have cached deps data available
41020
- let knownImports;
41021
- const dataPath = path$p.join(getDepsCacheDir(config), '_metadata.json');
41022
- try {
41023
- const data = JSON.parse(fs__default.readFileSync(dataPath, 'utf-8'));
41024
- knownImports = Object.keys(data.optimized);
41025
- }
41026
- catch (e) { }
41027
- if (!knownImports) {
41028
- // no dev deps optimization data, do a fresh scan
41029
- knownImports = await findKnownImports(config);
41030
- }
41031
- external = resolveExternal(resolveSSRExternal(config, knownImports), userExternal);
41107
+ // In CJS, we can pass the externals to rollup as is. In ESM, we need to
41108
+ // do it in the resolve plugin so we can add the resolved extension for
41109
+ // deep node_modules imports
41110
+ if (ssr && config.ssr?.format === 'cjs') {
41111
+ external = await cjsSsrResolveExternal(config, userExternal);
41032
41112
  }
41033
- if (isDepsOptimizerEnabled(config) && !ssr) {
41113
+ if (isDepsOptimizerEnabled(config)) {
41034
41114
  await initDepsOptimizer(config);
41035
41115
  }
41036
41116
  const rollupOptions = {
@@ -41060,20 +41140,26 @@ async function doBuild(inlineConfig = {}) {
41060
41140
  };
41061
41141
  try {
41062
41142
  const buildOutputOptions = (output = {}) => {
41143
+ const cjsSsrBuild = ssr && config.ssr?.format === 'cjs';
41144
+ const format = output.format || (cjsSsrBuild ? 'cjs' : 'es');
41145
+ const jsExt = (ssr && config.ssr?.target !== 'webworker') || libOptions
41146
+ ? resolveOutputJsExtension(format, getPkgJson(config.root)?.type)
41147
+ : 'js';
41063
41148
  return {
41064
41149
  dir: outDir,
41065
- format: ssr ? 'cjs' : 'es',
41066
- exports: ssr ? 'named' : 'auto',
41150
+ // Default format is 'es' for regular and for SSR builds
41151
+ format,
41152
+ exports: cjsSsrBuild ? 'named' : 'auto',
41067
41153
  sourcemap: options.sourcemap,
41068
41154
  name: libOptions ? libOptions.name : undefined,
41069
41155
  generatedCode: 'es2015',
41070
41156
  entryFileNames: ssr
41071
- ? `[name].js`
41157
+ ? `[name].${jsExt}`
41072
41158
  : libOptions
41073
- ? resolveLibFilename(libOptions, output.format || 'es', config.root)
41159
+ ? resolveLibFilename(libOptions, format, config.root, jsExt)
41074
41160
  : path$p.posix.join(options.assetsDir, `[name].[hash].js`),
41075
41161
  chunkFileNames: libOptions
41076
- ? `[name].[hash].js`
41162
+ ? `[name].[hash].${jsExt}`
41077
41163
  : path$p.posix.join(options.assetsDir, `[name].[hash].js`),
41078
41164
  assetFileNames: libOptions
41079
41165
  ? `[name].[ext]`
@@ -41185,7 +41271,15 @@ function getPkgJson(root) {
41185
41271
  function getPkgName(name) {
41186
41272
  return name?.startsWith('@') ? name.split('/')[1] : name;
41187
41273
  }
41188
- function resolveLibFilename(libOptions, format, root) {
41274
+ function resolveOutputJsExtension(format, type = 'commonjs') {
41275
+ if (type === 'module') {
41276
+ return format === 'cjs' || format === 'umd' ? 'cjs' : 'js';
41277
+ }
41278
+ else {
41279
+ return format === 'es' ? 'mjs' : 'js';
41280
+ }
41281
+ }
41282
+ function resolveLibFilename(libOptions, format, root, extension) {
41189
41283
  if (typeof libOptions.fileName === 'function') {
41190
41284
  return libOptions.fileName(format);
41191
41285
  }
@@ -41193,13 +41287,7 @@ function resolveLibFilename(libOptions, format, root) {
41193
41287
  const name = libOptions.fileName || getPkgName(packageJson.name);
41194
41288
  if (!name)
41195
41289
  throw new Error('Name in package.json is required if option "build.lib.fileName" is not provided.');
41196
- let extension;
41197
- if (packageJson?.type === 'module') {
41198
- extension = format === 'cjs' || format === 'umd' ? 'cjs' : 'js';
41199
- }
41200
- else {
41201
- extension = format === 'es' ? 'mjs' : 'js';
41202
- }
41290
+ extension ?? (extension = resolveOutputJsExtension(format, packageJson.type));
41203
41291
  if (format === 'cjs' || format === 'es') {
41204
41292
  return `${name}.${extension}`;
41205
41293
  }
@@ -41261,24 +41349,41 @@ function onRollupWarning(warning, warn, config) {
41261
41349
  }
41262
41350
  }
41263
41351
  }
41264
- function resolveExternal(ssrExternals, user) {
41352
+ async function cjsSsrResolveExternal(config, user) {
41353
+ // see if we have cached deps data available
41354
+ let knownImports;
41355
+ const dataPath = path$p.join(getDepsCacheDir(config), '_metadata.json');
41356
+ try {
41357
+ const data = JSON.parse(fs__default.readFileSync(dataPath, 'utf-8'));
41358
+ knownImports = Object.keys(data.optimized);
41359
+ }
41360
+ catch (e) { }
41361
+ if (!knownImports) {
41362
+ // no dev deps optimization data, do a fresh scan
41363
+ knownImports = await findKnownImports(config);
41364
+ }
41365
+ const ssrExternals = cjsSsrResolveExternals(config, knownImports);
41265
41366
  return (id, parentId, isResolved) => {
41266
- if (shouldExternalizeForSSR(id, ssrExternals)) {
41367
+ const isExternal = cjsShouldExternalizeForSSR(id, ssrExternals);
41368
+ if (isExternal) {
41267
41369
  return true;
41268
41370
  }
41269
41371
  if (user) {
41270
- if (typeof user === 'function') {
41271
- return user(id, parentId, isResolved);
41272
- }
41273
- else if (Array.isArray(user)) {
41274
- return user.some((test) => isExternal(id, test));
41275
- }
41276
- else {
41277
- return isExternal(id, user);
41278
- }
41372
+ return resolveUserExternal(user, id, parentId, isResolved);
41279
41373
  }
41280
41374
  };
41281
41375
  }
41376
+ function resolveUserExternal(user, id, parentId, isResolved) {
41377
+ if (typeof user === 'function') {
41378
+ return user(id, parentId, isResolved);
41379
+ }
41380
+ else if (Array.isArray(user)) {
41381
+ return user.some((test) => isExternal(id, test));
41382
+ }
41383
+ else {
41384
+ return isExternal(id, user);
41385
+ }
41386
+ }
41282
41387
  function isExternal(id, test) {
41283
41388
  if (typeof test === 'string') {
41284
41389
  return id === test;
@@ -47287,12 +47392,21 @@ var guess = function guessEditor (specifiedEditor) {
47287
47392
  if (specifiedEditor) {
47288
47393
  return shellQuote.parse(specifiedEditor)
47289
47394
  }
47395
+
47396
+ if (process.versions.webcontainer) {
47397
+ return [process.env.EDITOR || 'code']
47398
+ }
47399
+
47290
47400
  // We can find out which editor is currently running by:
47291
47401
  // `ps x` on macOS and Linux
47292
47402
  // `Get-Process` on Windows
47293
47403
  try {
47294
47404
  if (process.platform === 'darwin') {
47295
- const output = childProcess$2.execSync('ps x').toString();
47405
+ const output = childProcess$2
47406
+ .execSync('ps x', {
47407
+ stdio: ['pipe', 'pipe', 'ignore']
47408
+ })
47409
+ .toString();
47296
47410
  const processNames = Object.keys(COMMON_EDITORS_OSX);
47297
47411
  for (let i = 0; i < processNames.length; i++) {
47298
47412
  const processName = processNames[i];
@@ -47325,7 +47439,9 @@ var guess = function guessEditor (specifiedEditor) {
47325
47439
  // x List all processes owned by you
47326
47440
  // -o comm Need only names column
47327
47441
  const output = childProcess$2
47328
- .execSync('ps x --no-heading -o comm --sort=comm')
47442
+ .execSync('ps x --no-heading -o comm --sort=comm', {
47443
+ stdio: ['pipe', 'pipe', 'ignore']
47444
+ })
47329
47445
  .toString();
47330
47446
  const processNames = Object.keys(COMMON_EDITORS_LINUX);
47331
47447
  for (let i = 0; i < processNames.length; i++) {
@@ -47640,7 +47756,7 @@ async function getCertificate(cacheDir) {
47640
47756
  return content;
47641
47757
  }
47642
47758
  catch {
47643
- const content = (await import('./dep-395deadd.js')).createCertificate();
47759
+ const content = (await import('./dep-8259d5f4.js')).createCertificate();
47644
47760
  promises
47645
47761
  .mkdir(cacheDir, { recursive: true })
47646
47762
  .then(() => promises.writeFile(cachePath, content))
@@ -47682,8 +47798,10 @@ async function httpServerStart(httpServer, serverOptions) {
47682
47798
  */
47683
47799
  function ssrRequireHookPlugin(config) {
47684
47800
  if (config.command !== 'build' ||
47801
+ !config.build.ssr ||
47685
47802
  !config.resolve.dedupe?.length ||
47686
47803
  config.ssr?.noExternal === true ||
47804
+ config.ssr?.format !== 'cjs' ||
47687
47805
  isBuildOutputEsm(config)) {
47688
47806
  return null;
47689
47807
  }
@@ -51165,6 +51283,7 @@ function initAsClient(websocket, address, protocols, options) {
51165
51283
 
51166
51284
  if (opts.followRedirects) {
51167
51285
  if (websocket._redirects === 0) {
51286
+ websocket._originalSecure = isSecure;
51168
51287
  websocket._originalHost = parsedUrl.host;
51169
51288
 
51170
51289
  const headers = options && options.headers;
@@ -51180,18 +51299,21 @@ function initAsClient(websocket, address, protocols, options) {
51180
51299
  options.headers[key.toLowerCase()] = value;
51181
51300
  }
51182
51301
  }
51183
- } else if (
51184
- websocket.listenerCount('redirect') === 0 &&
51185
- parsedUrl.host !== websocket._originalHost
51186
- ) {
51187
- //
51188
- // Match curl 7.77.0 behavior and drop the following headers. These
51189
- // headers are also dropped when following a redirect to a subdomain.
51190
- //
51191
- delete opts.headers.authorization;
51192
- delete opts.headers.cookie;
51193
- delete opts.headers.host;
51194
- opts.auth = undefined;
51302
+ } else if (websocket.listenerCount('redirect') === 0) {
51303
+ const isSameHost = parsedUrl.host === websocket._originalHost;
51304
+
51305
+ if (!isSameHost || (websocket._originalSecure && !isSecure)) {
51306
+ //
51307
+ // Match curl 7.77.0 behavior and drop the following headers. These
51308
+ // headers are also dropped when following a redirect to a subdomain.
51309
+ //
51310
+ delete opts.headers.authorization;
51311
+ delete opts.headers.cookie;
51312
+
51313
+ if (!isSameHost) delete opts.headers.host;
51314
+
51315
+ opts.auth = undefined;
51316
+ }
51195
51317
  }
51196
51318
 
51197
51319
  //
@@ -51283,6 +51405,11 @@ function initAsClient(websocket, address, protocols, options) {
51283
51405
 
51284
51406
  req = websocket._req = null;
51285
51407
 
51408
+ if (res.headers.upgrade.toLowerCase() !== 'websocket') {
51409
+ abortHandshake$1(websocket, socket, 'Invalid Upgrade header');
51410
+ return;
51411
+ }
51412
+
51286
51413
  const digest = createHash$1('sha1')
51287
51414
  .update(key + GUID$1)
51288
51415
  .digest('base64');
@@ -51968,21 +52095,36 @@ class WebSocketServer extends EventEmitter {
51968
52095
  handleUpgrade(req, socket, head, cb) {
51969
52096
  socket.on('error', socketOnError);
51970
52097
 
51971
- const key =
51972
- req.headers['sec-websocket-key'] !== undefined
51973
- ? req.headers['sec-websocket-key']
51974
- : false;
52098
+ const key = req.headers['sec-websocket-key'];
51975
52099
  const version = +req.headers['sec-websocket-version'];
51976
52100
 
51977
- if (
51978
- req.method !== 'GET' ||
51979
- req.headers.upgrade.toLowerCase() !== 'websocket' ||
51980
- !key ||
51981
- !keyRegex.test(key) ||
51982
- (version !== 8 && version !== 13) ||
51983
- !this.shouldHandle(req)
51984
- ) {
51985
- return abortHandshake(socket, 400);
52101
+ if (req.method !== 'GET') {
52102
+ const message = 'Invalid HTTP method';
52103
+ abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
52104
+ return;
52105
+ }
52106
+
52107
+ if (req.headers.upgrade.toLowerCase() !== 'websocket') {
52108
+ const message = 'Invalid Upgrade header';
52109
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
52110
+ return;
52111
+ }
52112
+
52113
+ if (!key || !keyRegex.test(key)) {
52114
+ const message = 'Missing or invalid Sec-WebSocket-Key header';
52115
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
52116
+ return;
52117
+ }
52118
+
52119
+ if (version !== 8 && version !== 13) {
52120
+ const message = 'Missing or invalid Sec-WebSocket-Version header';
52121
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
52122
+ return;
52123
+ }
52124
+
52125
+ if (!this.shouldHandle(req)) {
52126
+ abortHandshake(socket, 400);
52127
+ return;
51986
52128
  }
51987
52129
 
51988
52130
  const secWebSocketProtocol = req.headers['sec-websocket-protocol'];
@@ -51992,7 +52134,9 @@ class WebSocketServer extends EventEmitter {
51992
52134
  try {
51993
52135
  protocols = subprotocol.parse(secWebSocketProtocol);
51994
52136
  } catch (err) {
51995
- return abortHandshake(socket, 400);
52137
+ const message = 'Invalid Sec-WebSocket-Protocol header';
52138
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
52139
+ return;
51996
52140
  }
51997
52141
  }
51998
52142
 
@@ -52017,7 +52161,10 @@ class WebSocketServer extends EventEmitter {
52017
52161
  extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
52018
52162
  }
52019
52163
  } catch (err) {
52020
- return abortHandshake(socket, 400);
52164
+ const message =
52165
+ 'Invalid or unacceptable Sec-WebSocket-Extensions header';
52166
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
52167
+ return;
52021
52168
  }
52022
52169
  }
52023
52170
 
@@ -52184,7 +52331,7 @@ function emitClose(server) {
52184
52331
  }
52185
52332
 
52186
52333
  /**
52187
- * Handle premature socket errors.
52334
+ * Handle socket errors.
52188
52335
  *
52189
52336
  * @private
52190
52337
  */
@@ -52202,27 +52349,54 @@ function socketOnError() {
52202
52349
  * @private
52203
52350
  */
52204
52351
  function abortHandshake(socket, code, message, headers) {
52205
- if (socket.writable) {
52206
- message = message || http$2.STATUS_CODES[code];
52207
- headers = {
52208
- Connection: 'close',
52209
- 'Content-Type': 'text/html',
52210
- 'Content-Length': Buffer.byteLength(message),
52211
- ...headers
52212
- };
52352
+ //
52353
+ // The socket is writable unless the user destroyed or ended it before calling
52354
+ // `server.handleUpgrade()` or in the `verifyClient` function, which is a user
52355
+ // error. Handling this does not make much sense as the worst that can happen
52356
+ // is that some of the data written by the user might be discarded due to the
52357
+ // call to `socket.end()` below, which triggers an `'error'` event that in
52358
+ // turn causes the socket to be destroyed.
52359
+ //
52360
+ message = message || http$2.STATUS_CODES[code];
52361
+ headers = {
52362
+ Connection: 'close',
52363
+ 'Content-Type': 'text/html',
52364
+ 'Content-Length': Buffer.byteLength(message),
52365
+ ...headers
52366
+ };
52213
52367
 
52214
- socket.write(
52215
- `HTTP/1.1 ${code} ${http$2.STATUS_CODES[code]}\r\n` +
52216
- Object.keys(headers)
52217
- .map((h) => `${h}: ${headers[h]}`)
52218
- .join('\r\n') +
52219
- '\r\n\r\n' +
52220
- message
52221
- );
52222
- }
52368
+ socket.once('finish', socket.destroy);
52223
52369
 
52224
- socket.removeListener('error', socketOnError);
52225
- socket.destroy();
52370
+ socket.end(
52371
+ `HTTP/1.1 ${code} ${http$2.STATUS_CODES[code]}\r\n` +
52372
+ Object.keys(headers)
52373
+ .map((h) => `${h}: ${headers[h]}`)
52374
+ .join('\r\n') +
52375
+ '\r\n\r\n' +
52376
+ message
52377
+ );
52378
+ }
52379
+
52380
+ /**
52381
+ * Emit a `'wsClientError'` event on a `WebSocketServer` if there is at least
52382
+ * one listener for it, otherwise call `abortHandshake()`.
52383
+ *
52384
+ * @param {WebSocketServer} server The WebSocket server
52385
+ * @param {http.IncomingMessage} req The request object
52386
+ * @param {(net.Socket|tls.Socket)} socket The socket of the upgrade request
52387
+ * @param {Number} code The HTTP response status code
52388
+ * @param {String} message The HTTP response body
52389
+ * @private
52390
+ */
52391
+ function abortHandshakeOrEmitwsClientError(server, req, socket, code, message) {
52392
+ if (server.listenerCount('wsClientError')) {
52393
+ const err = new Error(message);
52394
+ Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
52395
+
52396
+ server.emit('wsClientError', err, socket, req);
52397
+ } else {
52398
+ abortHandshake(socket, code, message);
52399
+ }
52226
52400
  }
52227
52401
 
52228
52402
  const HMR_HEADER = 'vite-hmr';
@@ -54817,8 +54991,19 @@ function transformMiddleware(server) {
54817
54991
  const publicPath = `${publicDir.slice(rootDir.length)}/`;
54818
54992
  // warn explicit public paths
54819
54993
  if (url.startsWith(publicPath)) {
54820
- logger.warn(colors$1.yellow(`files in the public directory are served at the root path.\n` +
54821
- `Instead of ${colors$1.cyan(url)}, use ${colors$1.cyan(url.replace(publicPath, '/'))}.`));
54994
+ let warning;
54995
+ if (isImportRequest(url)) {
54996
+ const rawUrl = removeImportQuery(url);
54997
+ warning =
54998
+ 'Assets in public cannot be imported from JavaScript.\n' +
54999
+ `Instead of ${colors$1.cyan(rawUrl)}, put the file in the src directory, and use ${colors$1.cyan(rawUrl.replace(publicPath, '/src/'))} instead.`;
55000
+ }
55001
+ else {
55002
+ warning =
55003
+ `files in the public directory are served at the root path.\n` +
55004
+ `Instead of ${colors$1.cyan(url)}, use ${colors$1.cyan(url.replace(publicPath, '/'))}.`;
55005
+ }
55006
+ logger.warn(colors$1.yellow(warning));
54822
55007
  }
54823
55008
  }
54824
55009
  if (isJSRequest(url) ||
@@ -56459,18 +56644,7 @@ async function createServer(inlineConfig = {}) {
56459
56644
  },
56460
56645
  transformIndexHtml: null,
56461
56646
  async ssrLoadModule(url, opts) {
56462
- if (!server._ssrExternals) {
56463
- let knownImports = [];
56464
- const depsOptimizer = getDepsOptimizer(config);
56465
- if (depsOptimizer) {
56466
- await depsOptimizer.scanProcessing;
56467
- knownImports = [
56468
- ...Object.keys(depsOptimizer.metadata.optimized),
56469
- ...Object.keys(depsOptimizer.metadata.discovered)
56470
- ];
56471
- }
56472
- server._ssrExternals = resolveSSRExternal(config, knownImports);
56473
- }
56647
+ await updateCjsSsrExternals(server);
56474
56648
  return ssrLoadModule(url, server, undefined, undefined, opts?.fixStacktrace);
56475
56649
  },
56476
56650
  ssrFixStacktrace(e) {
@@ -56816,6 +56990,20 @@ async function restartServer(server) {
56816
56990
  // new server (the current server) can restart now
56817
56991
  newServer._restartPromise = null;
56818
56992
  }
56993
+ async function updateCjsSsrExternals(server) {
56994
+ if (!server._ssrExternals) {
56995
+ let knownImports = [];
56996
+ const depsOptimizer = getDepsOptimizer(server.config);
56997
+ if (depsOptimizer) {
56998
+ await depsOptimizer.scanProcessing;
56999
+ knownImports = [
57000
+ ...Object.keys(depsOptimizer.metadata.optimized),
57001
+ ...Object.keys(depsOptimizer.metadata.discovered)
57002
+ ];
57003
+ }
57004
+ server._ssrExternals = cjsSsrResolveExternals(server.config, knownImports);
57005
+ }
57006
+ }
56819
57007
 
56820
57008
  var index = {
56821
57009
  __proto__: null,
@@ -59038,10 +59226,7 @@ function workerImportMetaUrlPlugin(config) {
59038
59226
  });
59039
59227
  }
59040
59228
  if (s) {
59041
- return {
59042
- code: s.toString(),
59043
- map: config.build.sourcemap ? s.generateMap({ hires: true }) : null
59044
- };
59229
+ return transformResult(s, id, config);
59045
59230
  }
59046
59231
  return null;
59047
59232
  }
@@ -59295,10 +59480,7 @@ function dynamicImportVarsPlugin(config) {
59295
59480
  if (needDynamicImportHelper) {
59296
59481
  s.prepend(`import __variableDynamicImportRuntimeHelper from "${dynamicImportHelperId}";`);
59297
59482
  }
59298
- return {
59299
- code: s.toString(),
59300
- map: config.build.sourcemap ? s.generateMap({ hires: true }) : null
59301
- };
59483
+ return transformResult(s, importer, config);
59302
59484
  }
59303
59485
  }
59304
59486
  };
@@ -59334,7 +59516,10 @@ async function resolvePlugins(config, prePlugins, normalPlugins, postPlugins) {
59334
59516
  packageCache: config.packageCache,
59335
59517
  ssrConfig: config.ssr,
59336
59518
  asSrc: true,
59337
- getDepsOptimizer: () => getDepsOptimizer(config)
59519
+ getDepsOptimizer: () => getDepsOptimizer(config),
59520
+ shouldExternalize: isBuild && config.build.ssr && config.ssr?.format !== 'cjs'
59521
+ ? (id) => shouldExternalizeForSSR(id, config)
59522
+ : undefined
59338
59523
  }),
59339
59524
  htmlInlineProxyPlugin(config),
59340
59525
  cssPlugin(config),