nitro-nightly 3.0.260429-beta → 3.0.260603-beta

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.
Files changed (76) hide show
  1. package/dist/THIRD-PARTY-LICENSES.md.gz +0 -0
  2. package/dist/_build/common.mjs +142 -35
  3. package/dist/_build/rolldown.mjs +12 -8
  4. package/dist/_build/rollup.mjs +11 -11
  5. package/dist/_build/vite.build.mjs +3 -3
  6. package/dist/_build/vite.dev.mjs +149 -0
  7. package/dist/_build/vite.env.mjs +177 -0
  8. package/dist/_chunks/nitro.mjs +252 -17
  9. package/dist/_chunks/nitro2.mjs +117 -90
  10. package/dist/_chunks/utils.mjs +4 -4
  11. package/dist/_common.mjs +1 -1
  12. package/dist/_dev.d.mts +1 -1
  13. package/dist/_dev.mjs +5 -5
  14. package/dist/_libs/c12+rc9.mjs +11 -10
  15. package/dist/_libs/c12+readdirp+chokidar.d.mts +7 -8
  16. package/dist/_libs/citty.mjs +1 -1
  17. package/dist/_libs/common.d.mts +37 -0
  18. package/dist/_libs/commondir+is-reference.mjs +5 -5
  19. package/dist/_libs/compatx.d.mts +1 -1
  20. package/dist/_libs/compatx.mjs +1 -1
  21. package/dist/_libs/estree+pluginutils.d.mts +1 -1
  22. package/dist/_libs/estree-walker.mjs +1 -1
  23. package/dist/_libs/hasown+resolve+deepmerge.mjs +15 -15
  24. package/dist/_libs/httpxy.d.mts +2 -1
  25. package/dist/_libs/httpxy.mjs +8 -4
  26. package/dist/_libs/klona.mjs +1 -1
  27. package/dist/_libs/magic-string.d.mts +1 -1
  28. package/dist/_libs/mlly.d.mts +1 -1
  29. package/dist/_libs/nypm+tinyexec.mjs +150 -434
  30. package/dist/_libs/openapi-types.d.mts +730 -0
  31. package/dist/_libs/perfect-debounce.mjs +1 -1
  32. package/dist/_libs/pkg-types.d.mts +1 -1
  33. package/dist/_libs/plugin-alias.mjs +2 -2
  34. package/dist/_libs/plugin-inject.mjs +3 -3
  35. package/dist/_libs/plugin-json.mjs +2 -2
  36. package/dist/_libs/pluginutils.mjs +16 -5
  37. package/dist/_libs/readdirp+chokidar.mjs +2 -2
  38. package/dist/_libs/remapping.mjs +2 -2
  39. package/dist/_libs/resolve-uri+gen-mapping.mjs +2 -5
  40. package/dist/_libs/rou3.d.mts +1 -1
  41. package/dist/_libs/rou3.mjs +1 -1
  42. package/dist/_libs/std-env.d.mts +1 -1
  43. package/dist/_libs/tsconfck.mjs +1 -1
  44. package/dist/_libs/ultrahtml.mjs +1 -1
  45. package/dist/_libs/undici+jsonc-parser.d.mts +2418 -0
  46. package/dist/_libs/{unimport+unplugin+oxc-parser.mjs → unimport+unplugin.mjs} +18 -8
  47. package/dist/_libs/unplugin+unimport.d.mts +3 -3
  48. package/dist/_libs/unwasm.d.mts +1 -1
  49. package/dist/_presets.mjs +131 -91
  50. package/dist/builder.d.mts +1 -1
  51. package/dist/builder.mjs +3 -3
  52. package/dist/cli/_chunks/build.mjs +3 -3
  53. package/dist/cli/_chunks/common.mjs +1 -1
  54. package/dist/cli/_chunks/deploy.mjs +2 -2
  55. package/dist/cli/_chunks/dev.mjs +4 -4
  56. package/dist/cli/_chunks/docs.mjs +1 -1
  57. package/dist/cli/_chunks/list.mjs +2 -2
  58. package/dist/cli/_chunks/prepare.mjs +3 -3
  59. package/dist/cli/_chunks/preview.mjs +4 -4
  60. package/dist/cli/_chunks/run.mjs +2 -2
  61. package/dist/cli/_chunks/task.mjs +1 -1
  62. package/dist/cli/index.mjs +1 -1
  63. package/dist/docs/1.deploy/2.providers/2.aws-amplify.md +3 -3
  64. package/dist/docs/1.deploy/2.providers/21.vercel.md +6 -0
  65. package/dist/docs/2.config/0.index/index.md +14 -0
  66. package/dist/docs/3.examples/27.vite-ssr-tsr-react.md +1 -1
  67. package/dist/presets/vercel/runtime/queue.dev.mjs +41 -0
  68. package/dist/runtime/internal/app.mjs +4 -111
  69. package/dist/runtime/virtual/app.d.mts +4 -0
  70. package/dist/runtime/virtual/app.mjs +32 -0
  71. package/dist/types/index.d.mts +51 -1756
  72. package/dist/vite.mjs +29 -339
  73. package/package.json +39 -41
  74. package/dist/THIRD-PARTY-LICENSES.md +0 -1676
  75. package/dist/_chunks/nitro3.mjs +0 -136
  76. package/dist/_chunks/nitro4.mjs +0 -127
Binary file
@@ -1,4 +1,4 @@
1
- import { i as __toESM$1, n as __exportAll, r as __require$1, t as __commonJSMin } from "../_common.mjs";
1
+ import { __commonJSMin, __exportAll, __require as __require$1, __toESM as __toESM$1 } from "../_common.mjs";
2
2
  import { builtinModules, createRequire } from "node:module";
3
3
  import consola from "consola";
4
4
  import { pkgDir, runtimeDependencies, runtimeDir, version } from "nitro/meta";
@@ -188,7 +188,6 @@ const parse$1 = function(p) {
188
188
  name: base.slice(0, base.length - extension.length)
189
189
  };
190
190
  };
191
- globalThis.process?.platform;
192
191
  const nodeBuiltins = [
193
192
  "_http_agent",
194
193
  "_http_client",
@@ -948,8 +947,8 @@ function moduleResolve$1(specifier, base, conditions, preserveSymlinks) {
948
947
  return finalizeResolution$1(resolved, base, preserveSymlinks);
949
948
  }
950
949
  const DEFAULT_CONDITIONS_SET$2 = /* @__PURE__ */ new Set(["node", "import"]);
951
- const isWindows = process.platform === "win32";
952
- const globalCache = globalThis["__EXSOLVE_CACHE__"] ||= /* @__PURE__ */ new Map();
950
+ const isWindows = /* @__PURE__ */ (() => process.platform === "win32")();
951
+ const globalCache = /* @__PURE__ */ (() => globalThis["__EXSOLVE_CACHE__"] ||= /* @__PURE__ */ new Map())();
953
952
  function resolveModuleURL(input, options) {
954
953
  const parsedInput = _parseInput(input);
955
954
  if ("external" in parsedInput) return parsedInput.external;
@@ -4281,7 +4280,7 @@ function toPathRegExp(input) {
4281
4280
  if (typeof input === "string") return new RegExp(pathRegExp(input));
4282
4281
  throw new TypeError("Expected a string or RegExp", { cause: input });
4283
4282
  }
4284
- const isObject$2 = (value) => {
4283
+ const isObject$3 = (value) => {
4285
4284
  const type = typeof value;
4286
4285
  return value !== null && (type === "object" || type === "function");
4287
4286
  };
@@ -4402,7 +4401,7 @@ function normalizePath$3(path) {
4402
4401
  return [];
4403
4402
  }
4404
4403
  function getProperty(object, path, value) {
4405
- if (!isObject$2(object) || typeof path !== "string" && !Array.isArray(path)) return value === void 0 ? object : value;
4404
+ if (!isObject$3(object) || typeof path !== "string" && !Array.isArray(path)) return value === void 0 ? object : value;
4406
4405
  const pathArray = normalizePath$3(path);
4407
4406
  if (pathArray.length === 0) return value;
4408
4407
  for (let index = 0; index < pathArray.length; index++) {
@@ -6511,6 +6510,7 @@ var require_picomatch = /* @__PURE__ */ __commonJSMin(((exports, module) => {
6511
6510
  var import_picomatch = /* @__PURE__ */ __toESM$1(require_picomatch(), 1);
6512
6511
  const isReadonlyArray = Array.isArray;
6513
6512
  const BACKSLASHES = /\\/g;
6513
+ const DRIVE_RELATIVE_PATH = /^[A-Za-z]:$/;
6514
6514
  const isWin = process.platform === "win32";
6515
6515
  const ONLY_PARENT_DIRECTORIES = /^(\/?\.\.)+$/;
6516
6516
  function getPartialMatcher(patterns, options = {}) {
@@ -6576,6 +6576,9 @@ function buildRelative(cwd, root) {
6576
6576
  return p[p.length - 1] === "/" && result !== "" ? `${result}/` : result || ".";
6577
6577
  };
6578
6578
  }
6579
+ function ensureNonDriveRelativePath(path) {
6580
+ return path.replace(DRIVE_RELATIVE_PATH, (match) => `${match}/`);
6581
+ }
6579
6582
  const splitPatternOptions = { parts: true };
6580
6583
  function splitPattern(path) {
6581
6584
  var _result$parts;
@@ -6620,7 +6623,7 @@ function normalizePattern(pattern, opts, props, isIgnore) {
6620
6623
  }
6621
6624
  const potentialRoot = posix.join(cwd, parentDir.slice(i * 3));
6622
6625
  if (potentialRoot[0] !== "." && props.root.length > potentialRoot.length) {
6623
- props.root = potentialRoot;
6626
+ props.root = ensureNonDriveRelativePath(potentialRoot);
6624
6627
  props.depthOffset = -n + i;
6625
6628
  }
6626
6629
  }
@@ -6640,7 +6643,7 @@ function normalizePattern(pattern, opts, props, isIgnore) {
6640
6643
  }
6641
6644
  props.depthOffset = newCommonPath.length;
6642
6645
  props.commonPath = newCommonPath;
6643
- props.root = newCommonPath.length > 0 ? posix.join(cwd, ...newCommonPath) : cwd;
6646
+ props.root = ensureNonDriveRelativePath(newCommonPath.length > 0 ? posix.join(cwd, ...newCommonPath) : cwd);
6644
6647
  }
6645
6648
  return result;
6646
6649
  }
@@ -6729,18 +6732,15 @@ function formatPaths(paths, mapper) {
6729
6732
  }
6730
6733
  const defaultOptions$1 = {
6731
6734
  caseSensitiveMatch: true,
6732
- cwd: process.cwd(),
6733
6735
  debug: !!process.env.TINYGLOBBY_DEBUG,
6734
6736
  expandDirectories: true,
6735
6737
  followSymbolicLinks: true,
6736
6738
  onlyFiles: true
6737
6739
  };
6738
6740
  function getOptions$1(options) {
6739
- const opts = {
6740
- ...defaultOptions$1,
6741
- ...options
6742
- };
6743
- opts.cwd = (opts.cwd instanceof URL ? fileURLToPath$1(opts.cwd) : resolve$1(opts.cwd)).replace(BACKSLASHES, "/");
6741
+ const opts = Object.assign({}, options);
6742
+ for (const key in defaultOptions$1) if (opts[key] === void 0) Object.assign(opts, { [key]: defaultOptions$1[key] });
6743
+ opts.cwd = (opts.cwd instanceof URL ? fileURLToPath$1(opts.cwd) : resolve$1(opts.cwd || process.cwd())).replace(BACKSLASHES, "/");
6744
6744
  opts.ignore = ensureStringArray(opts.ignore);
6745
6745
  opts.fs && (opts.fs = {
6746
6746
  readdir: opts.fs.readdir || readdir$1,
@@ -15681,6 +15681,9 @@ const BUILTIN_MODULES = new Set(builtinModules);
15681
15681
  function normalizeSlash(path) {
15682
15682
  return path.replace(/\\/g, "/");
15683
15683
  }
15684
+ function isObject$2(value) {
15685
+ return value !== null && typeof value === "object";
15686
+ }
15684
15687
  function matchAll(regex, string, addition) {
15685
15688
  const matches = [];
15686
15689
  for (const match of string.matchAll(regex)) matches.push({
@@ -16739,6 +16742,23 @@ function _isIdentifierBeforeAngleBracket(str, i) {
16739
16742
  const wordStart = j + 1;
16740
16743
  return wordStart < i && /[A-Za-z_$]/.test(str[wordStart]);
16741
16744
  }
16745
+ function interopDefault(sourceModule, opts = {}) {
16746
+ if (!isObject$2(sourceModule) || !("default" in sourceModule)) return sourceModule;
16747
+ const defaultValue = sourceModule.default;
16748
+ if (defaultValue === void 0 || defaultValue === null) return sourceModule;
16749
+ const _defaultType = typeof defaultValue;
16750
+ if (_defaultType !== "object" && !(_defaultType === "function" && !opts.preferNamespace)) return opts.preferNamespace ? sourceModule : defaultValue;
16751
+ for (const key in sourceModule) try {
16752
+ if (!(key in defaultValue)) Object.defineProperty(defaultValue, key, {
16753
+ enumerable: key !== "default",
16754
+ configurable: key !== "default",
16755
+ get() {
16756
+ return sourceModule[key];
16757
+ }
16758
+ });
16759
+ } catch {}
16760
+ return defaultValue;
16761
+ }
16742
16762
  const ESM_RE = /(?:[\s;]|^)(?:import[\s\w*,{}]*from|import\s*["'*{]|export\b\s*(?:[*{]|default|class|type|function|const|var|let|async function)|import\.meta\b)/m;
16743
16763
  const CJS_RE = /(?:[\s;]|^)(?:module\.exports\b|exports\.\w|require\s*\(|global\.\w)/m;
16744
16764
  const COMMENT_RE = /\/\*.+?\*\/|\/\/.*(?=[nr])/g;
@@ -17480,7 +17500,7 @@ function getBtoa() {
17480
17500
  throw new Error("Unsupported environment: `window.btoa` or `Buffer` should be supported.");
17481
17501
  };
17482
17502
  }
17483
- const btoa = /* @__PURE__ */ getBtoa();
17503
+ const btoa = /*#__PURE__*/ getBtoa();
17484
17504
  var SourceMap = class {
17485
17505
  constructor(properties) {
17486
17506
  this.version = 3;
@@ -19301,6 +19321,14 @@ function resolveModule(name, options = {}) {
19301
19321
  return;
19302
19322
  }
19303
19323
  }
19324
+ async function importModule(path) {
19325
+ const i = await import(path);
19326
+ if (i) return interopDefault(i);
19327
+ return i;
19328
+ }
19329
+ function isPackageExists(name, options = {}) {
19330
+ return !!resolvePackage(name, options);
19331
+ }
19304
19332
  function getPackageJsonPath(name, options = {}) {
19305
19333
  const entry = resolvePackage(name, options);
19306
19334
  if (!entry) return;
@@ -19359,7 +19387,7 @@ quansync(function* (name, cwd) {
19359
19387
  const pkg = (yield loadPackageJSON(cwd)) || {};
19360
19388
  return name in (pkg.dependencies || {}) || name in (pkg.devDependencies || {});
19361
19389
  }).sync;
19362
- const version$1 = "6.2.0";
19390
+ const version$1 = "6.3.0";
19363
19391
  function configureAddons(opts) {
19364
19392
  const addons = [];
19365
19393
  if (Array.isArray(opts.addons)) addons.push(...opts.addons);
@@ -19455,8 +19483,8 @@ function parseVirtualImportsRegex(strippedCode, importMap, virtualImports) {
19455
19483
  }
19456
19484
  async function detectImports(code, ctx, options) {
19457
19485
  switch (options?.parser) {
19458
- case "acorn": return import("../_libs/unimport+unplugin+oxc-parser.mjs").then((n) => n.r).then((r) => r.detectImportsAcorn(code, ctx, options));
19459
- case "oxc": return import("../_libs/unimport+unplugin+oxc-parser.mjs").then((n) => n.n).then((r) => r.detectImportsOxc(code, ctx, options));
19486
+ case "acorn": return import("../_libs/unimport+unplugin.mjs").then((n) => n.detect_acorn_exports).then((r) => r.detectImportsAcorn(code, ctx, options));
19487
+ case "oxc": return import("../_libs/unimport+unplugin.mjs").then((n) => n.detect_oxc_exports).then((r) => r.detectImportsOxc(code, ctx, options));
19460
19488
  default: return detectImportsRegex(code, ctx, options);
19461
19489
  }
19462
19490
  }
@@ -19567,7 +19595,8 @@ async function scanFilesFromDir(dir, options) {
19567
19595
  expandDirectories: false
19568
19596
  })).map((i) => normalize$2(i));
19569
19597
  const fileFilter = options?.fileFilter || (() => true);
19570
- const indexOfDirs = (file) => dirGlobs.findIndex((glob2) => import_picomatch.default.isMatch(file, glob2));
19598
+ const dirMatchers = dirGlobs.map((glob2) => (0, import_picomatch.default)(glob2));
19599
+ const indexOfDirs = (file) => dirMatchers.findIndex((match) => match(file));
19571
19600
  return files.reduce((acc, file) => {
19572
19601
  const index = indexOfDirs(file);
19573
19602
  if (acc[index]) acc[index].push(normalize$2(file));
@@ -19578,8 +19607,8 @@ async function scanFilesFromDir(dir, options) {
19578
19607
  async function scanDirExports(dirs, options) {
19579
19608
  const normalizedDirs = normalizeScanDirs(dirs, options);
19580
19609
  const files = await scanFilesFromDir(normalizedDirs, options);
19581
- const includeTypesDirs = normalizedDirs.filter((dir) => !dir.glob.startsWith("!") && dir.types);
19582
- const isIncludeTypes = (file) => includeTypesDirs.some((dir) => import_picomatch.default.isMatch(file, dir.glob));
19610
+ const includeTypesMatchers = normalizedDirs.filter((dir) => !dir.glob.startsWith("!") && dir.types).map((dir) => (0, import_picomatch.default)(dir.glob));
19611
+ const isIncludeTypes = (file) => includeTypesMatchers.some((match) => match(file));
19583
19612
  return dedupeDtsExports((await Promise.all(files.map((file) => scanExports(file, isIncludeTypes(file))))).flat());
19584
19613
  }
19585
19614
  function dedupeDtsExports(exports) {
@@ -20885,7 +20914,7 @@ async function writeTypes(nitro) {
20885
20914
  for (const alias in tsConfig.compilerOptions.paths) {
20886
20915
  const paths = await Promise.all(tsConfig.compilerOptions.paths[alias].map(async (path) => {
20887
20916
  if (!isAbsolute$2(path)) return path;
20888
- return relativeWithDot(tsconfigDir, (await promises.stat(path).catch(() => null))?.isFile() ? path.replace(/(?<=\w)\.\w+$/g, "") : path);
20917
+ return relativeWithDot(tsconfigDir, (await promises.stat(path).catch(() => null))?.isFile() ? stripPathsExt(path) : path);
20889
20918
  }));
20890
20919
  tsConfig.compilerOptions.paths[alias] = [...new Set(paths)];
20891
20920
  }
@@ -20907,6 +20936,10 @@ function relativeWithDot(from, to) {
20907
20936
  const rel = relative$2(from, to);
20908
20937
  return RELATIVE_RE.test(rel) ? rel : "./" + rel;
20909
20938
  }
20939
+ const PATHS_STRIPPABLE_EXT_RE = /\.(?:tsx?|jsx?|[cm]js)$/;
20940
+ function stripPathsExt(path) {
20941
+ return path.replace(PATHS_STRIPPABLE_EXT_RE, "");
20942
+ }
20910
20943
  const presetsWithConfig = [
20911
20944
  "awsAmplify",
20912
20945
  "awsLambda",
@@ -21104,6 +21137,72 @@ function joinPkgNames(moduleIds) {
21104
21137
  function routeToFsPath(route) {
21105
21138
  return route.split("/").slice(1).map((s) => s.replace(/:(\w+)/g, "[$1]").replace(/\*+/g, "[...]").replace(/[^a-zA-Z0-9_.[\]]/g, "_")).join("/") || "index";
21106
21139
  }
21140
+ function app(nitro) {
21141
+ return {
21142
+ id: "#nitro/virtual/app",
21143
+ template: () => {
21144
+ const hasRoutes = nitro.routing.routes.hasRoutes();
21145
+ const hasRouteRules = nitro.routing.routeRules.hasRoutes();
21146
+ const hasRoutedMiddleware = nitro.routing.routedMiddleware.hasRoutes();
21147
+ const hasGlobalMiddleware = nitro.routing.globalMiddleware.length > 0;
21148
+ const hasPlugins = nitro.options.plugins.length > 0;
21149
+ const hasHooks = nitro.options.features?.runtimeHooks ?? hasPlugins;
21150
+ const hasGetMiddleware = hasRouteRules || hasRoutedMiddleware;
21151
+ const hasAsyncContext = !!nitro.options.experimental.asyncContext;
21152
+ const routingImports = [
21153
+ hasRoutes && "findRoute",
21154
+ hasRoutedMiddleware && "findRoutedMiddleware",
21155
+ hasGlobalMiddleware && "globalMiddleware"
21156
+ ].filter(Boolean);
21157
+ const imports = [];
21158
+ const code = [];
21159
+ imports.push(`import { H3Core } from "h3";`, `import errorHandler from "#nitro/virtual/error-handler";`);
21160
+ code.push(``, `export function createNitroApp() {`);
21161
+ if (hasHooks) {
21162
+ imports.push(`import { HookableCore } from "hookable";`);
21163
+ code.push(` const hooks = new HookableCore();`);
21164
+ }
21165
+ code.push(``, `const captureError = (error, errorCtx) => {`);
21166
+ if (hasHooks) code.push(` const promise = hooks.callHook("error", error, errorCtx)?.catch?.((hookError) => {`, ` console.error("Error while capturing another error", hookError);`, ` });`);
21167
+ code.push(` if (errorCtx?.event) {`, ` const errors = errorCtx.event.req.context?.nitro?.errors;`, ` if (errors) {`, ` errors.push({ error, context: errorCtx });`, ` }`);
21168
+ if (hasHooks) code.push(` if (promise && typeof errorCtx.event.req.waitUntil === "function") {`, ` errorCtx.event.req.waitUntil(promise);`, ` }`);
21169
+ code.push(` }`, ` };`);
21170
+ code.push(``, ` const h3App = createH3App({`, ` onError(error, event) {`);
21171
+ if (hasHooks) code.push(` captureError(error, { event });`);
21172
+ code.push(` return errorHandler(error, event);`, ` },`, ` });`);
21173
+ if (hasHooks) code.push(``, ` h3App.config.onRequest = (event) => {`, ` return hooks.callHook("request", event)?.catch?.((error) => {`, ` captureError(error, { event, tags: ["request"] });`, ` });`, ` };`, ` h3App.config.onResponse = (res, event) => {`, ` return hooks.callHook("response", res, event)?.catch?.((error) => {`, ` captureError(error, { event, tags: ["response"] });`, ` });`, ` };`);
21174
+ code.push(``, ` let appHandler = (req) => {`, ` req.context ||= {};`, ` req.context.nitro = req.context.nitro || { errors: [] };`, ` return h3App.fetch(req);`, ` };`);
21175
+ if (hasAsyncContext) {
21176
+ imports.push(`import { nitroAsyncContext } from "#nitro/runtime/context";`);
21177
+ code.push(``, ` const originalHandler = appHandler;`, ` appHandler = (req) => {`, ` return nitroAsyncContext.callAsync({ request: req }, () => originalHandler(req));`, ` };`);
21178
+ }
21179
+ code.push(``, ` return {`, ` fetch: appHandler,`, ` h3: h3App,`, ` hooks: ${hasHooks ? "hooks" : "undefined"},`, ` captureError,`, ` };`, `}`);
21180
+ code.push(``, `export function initNitroPlugins(app) {`);
21181
+ if (hasPlugins) {
21182
+ imports.push(`import { plugins } from "#nitro/virtual/plugins";`);
21183
+ code.push(` for (const plugin of plugins) {`, ` try {`, ` plugin(app);`, ` } catch (error) {`, ` app.captureError?.(error, { tags: ["plugin"] });`, ` throw error;`, ` }`, ` }`);
21184
+ }
21185
+ code.push(` return app;`, `}`);
21186
+ if (routingImports.length) imports.push(`import { ${routingImports.join(", ")} } from "#nitro/virtual/routing";`);
21187
+ code.push(``, `function createH3App(config) {`, ` const h3App = new H3Core(config);`);
21188
+ if (hasRoutes) code.push(` h3App["~findRoute"] = (event) => findRoute(event.req.method, event.url.pathname);`);
21189
+ if (hasGlobalMiddleware) code.push(` h3App["~middleware"].push(...globalMiddleware);`);
21190
+ if (hasGetMiddleware) {
21191
+ code.push(` h3App["~getMiddleware"] = (event, route) => {`, ` const pathname = event.url.pathname;`, ` const method = event.req.method;`, ` const middleware = [];`);
21192
+ if (hasRouteRules) {
21193
+ imports.push(`import { getRouteRules } from "#nitro/runtime/app";`);
21194
+ code.push(` const routeRules = getRouteRules(method, pathname);`, ` event.context.routeRules = routeRules?.routeRules;`, ` if (routeRules?.routeRuleMiddleware.length) {`, ` middleware.push(...routeRules.routeRuleMiddleware);`, ` }`);
21195
+ }
21196
+ if (hasGlobalMiddleware) code.push(` middleware.push(...h3App["~middleware"]);`);
21197
+ if (hasRoutedMiddleware) code.push(` middleware.push(...findRoutedMiddleware(method, pathname).map((r) => r.data));`);
21198
+ if (hasRoutes) code.push(` if (route?.data?.middleware?.length) {`, ` middleware.push(...route.data.middleware);`, ` }`);
21199
+ code.push(` return middleware;`, ` };`);
21200
+ }
21201
+ code.push(` return h3App;`, `}`);
21202
+ return [...imports, ...code].join("\n");
21203
+ }
21204
+ };
21205
+ }
21107
21206
  function database(nitro) {
21108
21207
  return {
21109
21208
  id: "#nitro/virtual/database",
@@ -21413,10 +21512,11 @@ function routing(nitro) {
21413
21512
  ...Object.values(nitro.routing.routedMiddleware.routes).map((h) => h.data),
21414
21513
  ...nitro.routing.globalMiddleware
21415
21514
  ], "_importHash");
21515
+ const traceH3 = !!nitro.options.tracingChannel?.h3;
21416
21516
  return `
21417
21517
  import * as __routeRules__ from "#nitro/runtime/route-rules";
21418
21518
  import * as srvxNode from "srvx/node"
21419
- import * as h3 from "h3";
21519
+ import * as h3 from "h3";${traceH3 ? `\nimport { wrapHandlerWithTracing } from "h3/tracing";` : ""}
21420
21520
 
21421
21521
  export const findRouteRules = ${nitro.routing.routeRules.compileToString({
21422
21522
  serialize: serializeRouteRule,
@@ -21433,7 +21533,7 @@ ${allHandlers.filter((h) => !h.lazy).map((h) => `import ${h._importHash} from "$
21433
21533
 
21434
21534
  ${allHandlers.filter((h) => h.lazy).map((h) => `const ${h._importHash} = h3.defineLazyEventHandler(() => import("${h.handler}")${h.format === "node" ? ".then(m => srvxNode.toFetchHandler(m.default))" : ""});`).join("\n")}
21435
21535
 
21436
- export const findRoute = ${nitro.routing.routes.compileToString({ serialize: serializeHandler })}
21536
+ export const findRoute = ${nitro.routing.routes.compileToString({ serialize: (h) => serializeHandler(h, { tracing: traceH3 }) })}
21437
21537
 
21438
21538
  export const findRoutedMiddleware = ${nitro.routing.routedMiddleware.compileToString({
21439
21539
  serialize: serializeHandler,
@@ -21450,13 +21550,14 @@ export const globalMiddleware = [
21450
21550
  function uniqueBy(arr, key) {
21451
21551
  return [...new Map(arr.map((item) => [item[key], item])).values()];
21452
21552
  }
21453
- function serializeHandler(h) {
21553
+ function serializeHandler(h, opts = {}) {
21454
21554
  const meta = Array.isArray(h) ? h[0] : h;
21555
+ const handler = Array.isArray(h) ? `multiHandler(${h.map((handler) => serializeHandlerFn(handler)).join(",")})` : serializeHandlerFn(h);
21455
21556
  return `{${[
21456
21557
  `route:${JSON.stringify(meta.route)}`,
21457
21558
  meta.method && `method:${JSON.stringify(meta.method)}`,
21458
21559
  meta.meta && `meta:${JSON.stringify(meta.meta)}`,
21459
- `handler:${Array.isArray(h) ? `multiHandler(${h.map((handler) => serializeHandlerFn(handler)).join(",")})` : serializeHandlerFn(h)}`
21560
+ `handler:${opts.tracing ? `wrapHandlerWithTracing(${handler})` : handler}`
21460
21561
  ].filter(Boolean).join(",")}}`;
21461
21562
  }
21462
21563
  function serializeHandlerFn(h) {
@@ -21640,6 +21741,7 @@ function tracing(nitro) {
21640
21741
  }
21641
21742
  function virtualTemplates(nitro, _polyfills) {
21642
21743
  const nitroTemplates = [
21744
+ app,
21643
21745
  database,
21644
21746
  errorHandler,
21645
21747
  featureFlags,
@@ -21938,6 +22040,7 @@ function isWellFormedString(input) {
21938
22040
  if (hasStringIsWellFormed) return input.isWellFormed();
21939
22041
  return !/\p{Surrogate}/u.test(input);
21940
22042
  }
22043
+ const identifierNameRE = /^[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*$/u;
21941
22044
  const dataToEsm = function dataToEsm(data, options = {}) {
21942
22045
  var _a, _b;
21943
22046
  const t = options.compact ? "" : "indent" in options ? options.indent : " ";
@@ -21963,10 +22066,13 @@ const dataToEsm = function dataToEsm(data, options = {}) {
21963
22066
  namedExportCode += `export ${declarationType} ${key}${_}=${_}${serialize(value, options.compact ? null : t, "")};${n}`;
21964
22067
  } else {
21965
22068
  defaultExportRows.push(`${stringify(key)}:${_}${serialize(value, options.compact ? null : t, "")}`);
21966
- if (options.includeArbitraryNames && isWellFormedString(key)) {
21967
- const variableName = `${arbitraryNamePrefix}${arbitraryNameExportRows.length}`;
21968
- namedExportCode += `${declarationType} ${variableName}${_}=${_}${serialize(value, options.compact ? null : t, "")};${n}`;
21969
- arbitraryNameExportRows.push(`${variableName} as ${JSON.stringify(key)}`);
22069
+ if (key !== "default") {
22070
+ const isIdentifierName = identifierNameRE.test(key);
22071
+ if (isIdentifierName || options.includeArbitraryNames && isWellFormedString(key)) {
22072
+ const variableName = `${arbitraryNamePrefix}${arbitraryNameExportRows.length}`;
22073
+ namedExportCode += `${declarationType} ${variableName}${_}=${_}${serialize(value, options.compact ? null : t, "")};${n}`;
22074
+ arbitraryNameExportRows.push(`${variableName} as ${isIdentifierName ? key : JSON.stringify(key)}`);
22075
+ }
21970
22076
  }
21971
22077
  }
21972
22078
  const arbitraryExportCode = arbitraryNameExportRows.length > 0 ? `export${_}{${n}${t}${arbitraryNameExportRows.join(`,${n}${t}`)}${n}};${n}` : "";
@@ -27829,7 +27935,7 @@ function unwasm(opts) {
27829
27935
  order: "pre",
27830
27936
  filter: { id: [
27831
27937
  /* @__PURE__ */ new RegExp("^" + escapeRegExp(UMWASM_HELPERS_ID) + "$"),
27832
- /* @__PURE__ */ new RegExp("^" + UNWASM_EXTERNAL_PREFIX),
27938
+ /* @__PURE__ */ new RegExp("^\0unwasm:external:"),
27833
27939
  WASM_ID_RE
27834
27940
  ] },
27835
27941
  async handler(id, importer) {
@@ -28187,10 +28293,11 @@ function externals(opts) {
28187
28293
  if (exclude.some((r) => r.test(id))) return false;
28188
28294
  return true;
28189
28295
  };
28296
+ const resolveConditions = opts.conditions.includes("import") ? opts.conditions : [...opts.conditions, "import"];
28190
28297
  const tryResolve = (id, from) => resolveModulePath(id, {
28191
28298
  try: true,
28192
28299
  from: from && isAbsolute$2(from) ? from : opts.rootDir,
28193
- conditions: opts.conditions
28300
+ conditions: resolveConditions
28194
28301
  });
28195
28302
  const tracedPaths = /* @__PURE__ */ new Set();
28196
28303
  if (opts.trace && !resolved?.includePattern) return { name: PLUGIN_NAME };
@@ -28222,7 +28329,7 @@ function externals(opts) {
28222
28329
  let importId = toImport(id) || toImport(resolvedPath);
28223
28330
  if (!importId) return resolved;
28224
28331
  if (!tryResolve(importId, importer)) {
28225
- const guessed = await guessSubpath(resolvedPath, opts.conditions);
28332
+ const guessed = await guessSubpath(resolvedPath, resolveConditions);
28226
28333
  if (!guessed) return resolved;
28227
28334
  importId = guessed;
28228
28335
  }
@@ -28349,7 +28456,7 @@ async function baseBuildPlugins(nitro, base) {
28349
28456
  nitro.vfs = virtualPlugin.api.modules;
28350
28457
  plugins.push(virtualPlugin, virtualDeps());
28351
28458
  if (nitro.options.imports) {
28352
- const unimportPlugin = await import("../_libs/unimport+unplugin+oxc-parser.mjs").then((n) => n.t);
28459
+ const unimportPlugin = await import("../_libs/unimport+unplugin.mjs").then((n) => n.unplugin_exports);
28353
28460
  plugins.push(unimportPlugin.default.rollup(nitro.options.imports));
28354
28461
  }
28355
28462
  if (nitro.options.wasm !== false) plugins.push(unwasm(nitro.options.wasm || {}));
@@ -28400,4 +28507,4 @@ async function oxc(options) {
28400
28507
  }
28401
28508
  };
28402
28509
  }
28403
- export { yaml_exports as $, src_default as A, _$2 as B, decode as C, copyPublicAssets as D, prepare as E, prettyPath as F, findFile$1 as G, m$2 as H, resolveNitroPath as I, readGitConfig as J, findNearestFile$1 as K, writeFile$1 as L, glob as M, require_picomatch as N, scanUnprefixedPublicAssets as O, Builder as P, a$3 as Q, escapeRegExp$1 as R, MagicString as S, parse as T, v$2 as U, f$1 as V, dist_exports$1 as W, i$3 as X, readPackageJSON$1 as Y, toml_exports as Z, writeTypes as _, dataToEsm as a, basename$2 as at, getMagicString as b, walk as c, isAbsolute$2 as ct, libChunkName as d, relative$2 as dt, jsonc_exports as et, baseBuildConfig as f, resolve$3 as ft, writeDevBuildInfo as g, writeBuildInfo as h, createFilter as i, resolveModuleURL as it, build as j, compressPublicAssets as k, NODE_MODULES_RE$1 as l, join$2 as lt, getBuildInfo as m, baseBuildPlugins as n, json5_exports as nt, extractAssignedNames as o, dirname$2 as ot, runParallel as p, findWorkspaceDir as q, attachScopes as r, resolveModulePath as rt, makeLegalIdentifier as s, extname$4 as st, oxc as t, r$5 as tt, getChunkName as u, normalize$2 as ut, dist_exports as v, encode as w, stripLiteral as x, createUnimport as y, R$1 as z };
28510
+ export { Builder, MagicString, NODE_MODULES_RE$1 as NODE_MODULES_RE, R$1 as R, _$2 as _, a$3 as a, attachScopes, baseBuildConfig, baseBuildPlugins, basename$2 as basename, build, compressPublicAssets, copyPublicAssets, createFilter, createUnimport, dataToEsm, decode, dirname$2 as dirname, dist_exports, encode, escapeRegExp$1 as escapeRegExp, extname$4 as extname, extractAssignedNames, f$1 as f, findFile$1 as findFile, findNearestFile$1 as findNearestFile, findWorkspaceDir, getBuildInfo, getChunkName, getMagicString, glob, i$3 as i, importModule, isAbsolute$2 as isAbsolute, isPackageExists, join$2 as join, json5_exports, jsonc_exports, libChunkName, m$2 as m, makeLegalIdentifier, normalize$2 as normalize, oxc, parse, prepare, prettyPath, r$5 as r, readGitConfig, readPackageJSON$1 as readPackageJSON, relative$2 as relative, require_picomatch, resolve$3 as resolve, resolveModulePath, resolveModuleURL, resolveNitroPath, runParallel, scanUnprefixedPublicAssets, src_default, stripLiteral, toml_exports, v$2 as v, walk, writeBuildInfo, writeDevBuildInfo, writeFile$1 as writeFile, writeTypes, yaml_exports };
@@ -1,9 +1,9 @@
1
- import { _ as writeTypes, at as basename, d as libChunkName, dt as relative, f as baseBuildConfig, h as writeBuildInfo, l as NODE_MODULES_RE, lt as join, n as baseBuildPlugins, u as getChunkName } from "./common.mjs";
2
- import { t as formatCompatibilityDate } from "../_libs/compatx.mjs";
3
- import { n as scanHandlers } from "../_chunks/nitro2.mjs";
4
- import { n as watch } from "../_libs/readdirp+chokidar.mjs";
5
- import { t as debounce } from "../_libs/perfect-debounce.mjs";
6
- import { n as generateFSTree } from "../_chunks/utils.mjs";
1
+ import { NODE_MODULES_RE, baseBuildConfig, baseBuildPlugins, basename, getChunkName, join, libChunkName, relative, writeBuildInfo, writeTypes } from "./common.mjs";
2
+ import { formatCompatibilityDate } from "../_libs/compatx.mjs";
3
+ import { scanHandlers } from "../_chunks/nitro.mjs";
4
+ import { watch } from "../_libs/readdirp+chokidar.mjs";
5
+ import { debounce } from "../_libs/perfect-debounce.mjs";
6
+ import { generateFSTree } from "../_chunks/utils.mjs";
7
7
  import { builtinModules } from "node:module";
8
8
  import { defu } from "defu";
9
9
  const getRolldownConfig = async (nitro) => {
@@ -150,8 +150,12 @@ async function buildProduction(nitro, config) {
150
150
  const rewriteRelativePaths = (input) => {
151
151
  return input.replace(/([\s:])\.\/(\S*)/g, `$1${rOutput}/$2`);
152
152
  };
153
- nitro.logger.success("You can preview this build using `npx nitro preview`");
154
- if (buildInfo.commands.deploy) nitro.logger.success(rewriteRelativePaths("You can deploy this build using `npx nitro deploy --prebuilt`"));
153
+ const previewCommand = nitro.options.framework.previewCommand || "npx nitro preview";
154
+ nitro.logger.success(`You can preview this build using \`${previewCommand}\``);
155
+ if (buildInfo.commands.deploy) {
156
+ const deployCommand = nitro.options.framework.deployCommand || "npx nitro deploy --prebuilt";
157
+ nitro.logger.success(rewriteRelativePaths(`You can deploy this build using \`${deployCommand}\``));
158
+ }
155
159
  }
156
160
  async function rolldownBuild(nitro) {
157
161
  await nitro.hooks.callHook("build:before", nitro);
@@ -1,14 +1,14 @@
1
- import { _ as writeTypes, at as basename, ct as isAbsolute, d as libChunkName, dt as relative, f as baseBuildConfig, h as writeBuildInfo, l as NODE_MODULES_RE, lt as join, n as baseBuildPlugins, t as oxc, u as getChunkName } from "./common.mjs";
2
- import { t as formatCompatibilityDate } from "../_libs/compatx.mjs";
3
- import { n as scanHandlers } from "../_chunks/nitro2.mjs";
4
- import { n as watch } from "../_libs/readdirp+chokidar.mjs";
5
- import { t as debounce } from "../_libs/perfect-debounce.mjs";
6
- import { t as alias } from "../_libs/plugin-alias.mjs";
7
- import { n as inject } from "../_libs/plugin-inject.mjs";
8
- import { n as generateFSTree } from "../_chunks/utils.mjs";
9
- import { t as commonjs } from "../_libs/commondir+is-reference.mjs";
10
- import { t as json } from "../_libs/plugin-json.mjs";
11
- import { t as nodeResolve } from "../_libs/hasown+resolve+deepmerge.mjs";
1
+ import { NODE_MODULES_RE, baseBuildConfig, baseBuildPlugins, basename, getChunkName, isAbsolute, join, libChunkName, oxc, relative, writeBuildInfo, writeTypes } from "./common.mjs";
2
+ import { formatCompatibilityDate } from "../_libs/compatx.mjs";
3
+ import { scanHandlers } from "../_chunks/nitro.mjs";
4
+ import { watch } from "../_libs/readdirp+chokidar.mjs";
5
+ import { debounce } from "../_libs/perfect-debounce.mjs";
6
+ import { alias } from "../_libs/plugin-alias.mjs";
7
+ import { inject } from "../_libs/plugin-inject.mjs";
8
+ import { generateFSTree } from "../_chunks/utils.mjs";
9
+ import { commonjs } from "../_libs/commondir+is-reference.mjs";
10
+ import { json } from "../_libs/plugin-json.mjs";
11
+ import { nodeResolve } from "../_libs/hasown+resolve+deepmerge.mjs";
12
12
  import { defu } from "defu";
13
13
  const getRollupConfig = async (nitro) => {
14
14
  const base = baseBuildConfig(nitro);
@@ -1,12 +1,12 @@
1
- import { U as v } from "./common.mjs";
1
+ import { resolveModulePath, v } from "./common.mjs";
2
2
  import { nitro } from "nitro/vite";
3
3
  async function viteBuild(nitro$1) {
4
4
  if (nitro$1.options.dev) throw new Error("Nitro dev CLI does not supports vite. Please use `vite dev` instead.");
5
- const { createBuilder } = await import(nitro$1.options.__vitePkg__ || "vite");
5
+ const { createBuilder } = await import(resolveModulePath(nitro$1.options.__vitePkg__ || "vite", { from: nitro$1.options.rootDir }));
6
6
  const pluginInstance = nitro({ _nitro: nitro$1 });
7
7
  globalThis.__nitro_build__ = true;
8
8
  const builder = await createBuilder({
9
- base: nitro$1.options.rootDir,
9
+ root: nitro$1.options.rootDir,
10
10
  plugins: [pluginInstance],
11
11
  logLevel: v ? "warn" : void 0
12
12
  });
@@ -0,0 +1,149 @@
1
+ import { join } from "./common.mjs";
2
+ import { scanHandlers } from "../_chunks/nitro.mjs";
3
+ import { watch as watch$1 } from "../_libs/readdirp+chokidar.mjs";
4
+ import { debounce } from "../_libs/perfect-debounce.mjs";
5
+ import { getEnvRunner } from "./vite.env.mjs";
6
+ import { watch } from "node:fs";
7
+ import { withBase } from "ufo";
8
+ import { NodeRequest, sendNodeResponse } from "srvx/node";
9
+ import "node:http";
10
+ import { DevEnvironment } from "vite";
11
+ import { createViteHotChannel } from "env-runner/vite";
12
+ const ASSET_EXT_RE = /^(?:[jt]sx?|mjs|cjs|css|s[ac]ss|less|styl|vue|svelte|astro|mdx?|map|wasm|png|jpe?g|gif|svg|webp|avif|ico|bmp|woff2?|ttf|otf|eot|mp[34]|webm|wav|ogg|m4a)$/i;
13
+ function createFetchableDevEnvironment(name, config, devServer, entry, opts) {
14
+ return new FetchableDevEnvironment(name, config, {
15
+ hot: true,
16
+ transport: createViteHotChannel(devServer, name)
17
+ }, devServer, entry, opts);
18
+ }
19
+ var FetchableDevEnvironment = class extends DevEnvironment {
20
+ devServer;
21
+ #entry;
22
+ #preventExternalize;
23
+ constructor(name, config, context, devServer, entry, opts) {
24
+ super(name, config, context);
25
+ this.devServer = devServer;
26
+ this.#entry = entry;
27
+ this.#preventExternalize = opts?.preventExternalize ?? false;
28
+ }
29
+ async fetchModule(id, importer, options) {
30
+ if (this.#preventExternalize && !id.startsWith("file://") && importer && id[0] !== "." && id[0] !== "/") {
31
+ const resolved = await this.pluginContainer.resolveId(id, importer);
32
+ if (resolved && !resolved.external) return super.fetchModule(resolved.id, importer, options);
33
+ }
34
+ return super.fetchModule(id, importer, options);
35
+ }
36
+ async dispatchFetch(request) {
37
+ return this.devServer.fetch(request);
38
+ }
39
+ async init(...args) {
40
+ await this.devServer.init?.();
41
+ await super.init(...args);
42
+ this.devServer.sendMessage({
43
+ type: "custom",
44
+ event: "nitro:vite-env",
45
+ data: {
46
+ name: this.name,
47
+ entry: this.#entry
48
+ }
49
+ });
50
+ }
51
+ };
52
+ async function configureViteDevServer(ctx, server) {
53
+ const nitro = ctx.nitro;
54
+ const nitroEnv = server.environments.nitro;
55
+ const nitroConfigFile = nitro.options._c12.configFile;
56
+ if (nitroConfigFile) server.config.configFileDependencies.push(nitroConfigFile);
57
+ if (nitro.options.features.websocket ?? nitro.options.experimental.websocket) server.httpServer.on("upgrade", (req, socket, head) => {
58
+ if (req.headers["sec-websocket-protocol"]?.startsWith("vite-")) return;
59
+ getEnvRunner(ctx).upgrade?.({ node: {
60
+ req,
61
+ socket,
62
+ head
63
+ } });
64
+ });
65
+ const reload = debounce(async () => {
66
+ await scanHandlers(nitro);
67
+ nitro.routing.sync();
68
+ nitroEnv.moduleGraph.invalidateAll();
69
+ nitroEnv.hot.send({ type: "full-reload" });
70
+ });
71
+ const scanDirs = nitro.options.scanDirs.flatMap((dir) => [
72
+ join(dir, nitro.options.apiDir || "api"),
73
+ join(dir, nitro.options.routesDir || "routes"),
74
+ join(dir, "middleware"),
75
+ join(dir, "plugins"),
76
+ join(dir, "modules")
77
+ ]);
78
+ const watchReloadEvents = new Set([
79
+ "add",
80
+ "addDir",
81
+ "unlink",
82
+ "unlinkDir"
83
+ ]);
84
+ const scanDirsWatcher = watch$1(scanDirs, { ignoreInitial: true }).on("all", (event, path, stat) => {
85
+ if (watchReloadEvents.has(event)) reload();
86
+ });
87
+ const rootDirWatcher = watch(nitro.options.rootDir, { persistent: false }, (_event, filename) => {
88
+ if (filename && /^server\.[mc]?[jt]sx?$/.test(filename)) reload();
89
+ });
90
+ nitro.hooks.hook("close", () => {
91
+ scanDirsWatcher.close();
92
+ rootDirWatcher.close();
93
+ });
94
+ nitroEnv.devServer.onMessage(async (message) => {
95
+ if (message?.__rpc === "transformHTML") try {
96
+ const html = (await server.transformIndexHtml("/", message.data)).replace("<!--ssr-outlet-->", `{{{ globalThis.__nitro_vite_envs__?.["ssr"]?.fetch($REQUEST) || "" }}}`);
97
+ nitroEnv.devServer.sendMessage({
98
+ __rpc_id: message.__rpc_id,
99
+ data: html
100
+ });
101
+ } catch (error) {
102
+ nitroEnv.devServer.sendMessage({
103
+ __rpc_id: message.__rpc_id,
104
+ error: error instanceof Error ? error.message : String(error)
105
+ });
106
+ }
107
+ });
108
+ const nitroDevMiddleware = async (nodeReq, nodeRes, next) => {
109
+ if (!nodeReq.url || /^\/@(?:vite|fs|id)\//.test(nodeReq.url) || nodeReq._nitroHandled || server.middlewares.stack.map((mw) => mw.route).some((base) => base && nodeReq.url.startsWith(base))) return next();
110
+ nodeReq._nitroHandled = true;
111
+ const baseURL = nitro.options.baseURL || "/";
112
+ const originalURL = nodeReq.url;
113
+ if (baseURL !== "/") nodeReq.url = withBase(nodeReq.url, baseURL);
114
+ try {
115
+ const req = new NodeRequest({
116
+ req: nodeReq,
117
+ res: nodeRes
118
+ });
119
+ const devAppRes = await ctx.devApp.fetch(req);
120
+ if (nodeRes.writableEnded || nodeRes.headersSent) return;
121
+ if (devAppRes.status !== 404) return await sendNodeResponse(nodeRes, devAppRes);
122
+ const envRes = await nitroEnv.dispatchFetch(req);
123
+ if (nodeRes.writableEnded || nodeRes.headersSent) return;
124
+ return await sendNodeResponse(nodeRes, envRes);
125
+ } catch (error) {
126
+ return next(error);
127
+ } finally {
128
+ if (baseURL !== "/") nodeReq.url = originalURL;
129
+ }
130
+ };
131
+ server.middlewares.use(function nitroDevMiddlewarePre(req, res, next) {
132
+ if (/^\/(?:__|@)/.test(req.url)) return next();
133
+ const match = nitro.routing.routes.match(req.method || "", new URL(withBase(req.url, nitro.options.baseURL), "http://localhost").pathname);
134
+ const matchedHandlers = match ? Array.isArray(match) ? match : [match] : [];
135
+ if (matchedHandlers.some((h) => h?.route && h.route !== "/**" && !h.route.startsWith("/**:"))) return nitroDevMiddleware(req, res, next);
136
+ res.setHeader("vary", "sec-fetch-dest, accept");
137
+ const fetchDest = req.headers["sec-fetch-dest"];
138
+ const ext = req.url.split(/[?#]/, 1)[0].match(/\.([a-z0-9]+)$/i)?.[1];
139
+ const isAssetByExt = !!ext && ASSET_EXT_RE.test(ext) && !/\btext\/html\b/.test(req.headers["accept"] || "");
140
+ const isAsset = typeof fetchDest === "string" && fetchDest !== "empty" ? !/^(?:document|iframe|frame)$/.test(fetchDest) : isAssetByExt;
141
+ if (!isAsset && (matchedHandlers.length > 0 || !ext)) return nitroDevMiddleware(req, res, next);
142
+ if (isAsset) req._nitroHandled = true;
143
+ next();
144
+ });
145
+ return () => {
146
+ server.middlewares.use(nitroDevMiddleware);
147
+ };
148
+ }
149
+ export { configureViteDevServer, createFetchableDevEnvironment };