@nuxt/nitro-server-nightly 4.3.0-29461891.8f4fbecd → 4.3.0-29466366.fa21bb17

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 (63) hide show
  1. package/dist/index.d.mts +178 -80
  2. package/dist/index.mjs +664 -810
  3. package/dist/runtime/handlers/{error.d.ts → error.d.mts} +1 -1
  4. package/dist/runtime/handlers/error.mjs +77 -0
  5. package/dist/runtime/handlers/island.d.mts +2 -0
  6. package/dist/runtime/handlers/island.mjs +120 -0
  7. package/dist/runtime/handlers/renderer.d.mts +2 -0
  8. package/dist/runtime/handlers/renderer.mjs +298 -0
  9. package/dist/runtime/middleware/no-ssr.d.mts +2 -0
  10. package/dist/runtime/middleware/no-ssr.mjs +7 -0
  11. package/dist/runtime/plugins/dev-server-logs.d.mts +2 -0
  12. package/dist/runtime/plugins/dev-server-logs.mjs +94 -0
  13. package/dist/runtime/templates/error-500.mjs +15 -0
  14. package/dist/runtime/utils/app-config.d.mts +3 -0
  15. package/dist/runtime/utils/app-config.mjs +31 -0
  16. package/dist/runtime/utils/cache.d.mts +5 -0
  17. package/dist/runtime/utils/{cache.js → cache.mjs} +13 -12
  18. package/dist/runtime/utils/config.d.mts +1 -0
  19. package/dist/runtime/utils/{dev.d.ts → dev.d.mts} +1 -1
  20. package/dist/runtime/utils/{dev.js → dev.mjs} +15 -27
  21. package/dist/runtime/utils/error.d.mts +6 -0
  22. package/dist/runtime/utils/error.mjs +15 -0
  23. package/dist/runtime/utils/paths.mjs +19 -0
  24. package/dist/runtime/utils/renderer/{app.d.ts → app.d.mts} +4 -4
  25. package/dist/runtime/utils/renderer/app.mjs +39 -0
  26. package/dist/runtime/utils/renderer/build-files.d.mts +18 -0
  27. package/dist/runtime/utils/renderer/build-files.mjs +100 -0
  28. package/dist/runtime/utils/renderer/{inline-styles.d.ts → inline-styles.d.mts} +1 -1
  29. package/dist/runtime/utils/renderer/inline-styles.mjs +13 -0
  30. package/dist/runtime/utils/renderer/{islands.d.ts → islands.d.mts} +5 -5
  31. package/dist/runtime/utils/renderer/islands.mjs +87 -0
  32. package/dist/runtime/utils/renderer/payload.d.mts +24 -0
  33. package/dist/runtime/utils/renderer/payload.mjs +64 -0
  34. package/package.json +8 -8
  35. package/dist/index.d.ts +0 -87
  36. package/dist/runtime/handlers/error.js +0 -65
  37. package/dist/runtime/handlers/island.d.ts +0 -4
  38. package/dist/runtime/handlers/island.js +0 -101
  39. package/dist/runtime/handlers/renderer.d.ts +0 -2
  40. package/dist/runtime/handlers/renderer.js +0 -237
  41. package/dist/runtime/middleware/no-ssr.d.ts +0 -2
  42. package/dist/runtime/middleware/no-ssr.js +0 -7
  43. package/dist/runtime/plugins/dev-server-logs.d.ts +0 -3
  44. package/dist/runtime/plugins/dev-server-logs.js +0 -82
  45. package/dist/runtime/templates/error-500.js +0 -6
  46. package/dist/runtime/utils/app-config.d.ts +0 -3
  47. package/dist/runtime/utils/app-config.js +0 -25
  48. package/dist/runtime/utils/cache-driver.d.ts +0 -6
  49. package/dist/runtime/utils/cache.d.ts +0 -8
  50. package/dist/runtime/utils/config.d.ts +0 -1
  51. package/dist/runtime/utils/error.d.ts +0 -6
  52. package/dist/runtime/utils/error.js +0 -11
  53. package/dist/runtime/utils/paths.js +0 -16
  54. package/dist/runtime/utils/renderer/app.js +0 -34
  55. package/dist/runtime/utils/renderer/build-files.d.ts +0 -16
  56. package/dist/runtime/utils/renderer/build-files.js +0 -86
  57. package/dist/runtime/utils/renderer/inline-styles.js +0 -13
  58. package/dist/runtime/utils/renderer/islands.js +0 -82
  59. package/dist/runtime/utils/renderer/payload.d.ts +0 -24
  60. package/dist/runtime/utils/renderer/payload.js +0 -67
  61. /package/dist/runtime/templates/{error-500.d.ts → error-500.d.mts} +0 -0
  62. /package/dist/runtime/utils/{config.js → config.mjs} +0 -0
  63. /package/dist/runtime/utils/{paths.d.ts → paths.d.mts} +0 -0
package/dist/index.mjs CHANGED
@@ -1,107 +1,87 @@
1
- import { fileURLToPath, pathToFileURL } from 'node:url';
2
- import { existsSync, promises, readFileSync } from 'node:fs';
3
- import { cpus } from 'node:os';
4
- import process from 'node:process';
5
- import { readFile, mkdir, writeFile } from 'node:fs/promises';
6
- import { randomUUID } from 'node:crypto';
7
- import { findAllRoutes, createRouter, addRoute } from 'rou3';
8
- import { compileRouterToString } from 'rou3/compiler';
9
- import { dirname, relative, resolve, join, isAbsolute } from 'pathe';
10
- import { readPackageJSON } from 'pkg-types';
11
- import { withTrailingSlash, joinURL } from 'ufo';
12
- import { hash } from 'ohash';
13
- import { createNitro, scanHandlers, writeTypes, copyPublicAssets, prepare, build, prerender, createDevServer } from 'nitropack';
14
- import { getLayerDirectories, getDirectory, resolveNuxtModule, addTemplate, resolveAlias, addPlugin, resolveIgnorePatterns, createIsIgnored, addVitePlugin, logger, findPath } from '@nuxt/kit';
15
- import escapeRE from 'escape-string-regexp';
16
- import { defu } from 'defu';
17
- import { dynamicEventHandler, defineEventHandler } from 'h3';
18
- import { isWindows } from 'std-env';
19
- import { ImpoundPlugin } from 'impound';
20
- import { resolveModulePath } from 'exsolve';
1
+ import { fileURLToPath, pathToFileURL } from "node:url";
2
+ import { existsSync, promises, readFileSync } from "node:fs";
3
+ import { cpus } from "node:os";
4
+ import process from "node:process";
5
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
6
+ import { randomUUID } from "node:crypto";
7
+ import { addRoute, createRouter, findAllRoutes } from "rou3";
8
+ import { compileRouterToString } from "rou3/compiler";
9
+ import { dirname, isAbsolute, join, relative, resolve } from "pathe";
10
+ import { readPackageJSON } from "pkg-types";
11
+ import { joinURL, withTrailingSlash } from "ufo";
12
+ import { hash } from "ohash";
13
+ import { build, copyPublicAssets, createDevServer, createNitro, prepare, prerender, scanHandlers, writeTypes } from "nitropack";
14
+ import { addPlugin, addTemplate, addVitePlugin, createIsIgnored, findPath, getDirectory, getLayerDirectories, logger, resolveAlias, resolveIgnorePatterns, resolveNuxtModule } from "@nuxt/kit";
15
+ import escapeRE from "escape-string-regexp";
16
+ import { defu } from "defu";
17
+ import { defineEventHandler, dynamicEventHandler } from "h3";
18
+ import { isWindows } from "std-env";
19
+ import { ImpoundPlugin } from "impound";
20
+ import { resolveModulePath } from "exsolve";
21
21
 
22
- const version = "4.3.0-29461891.8f4fbecd";
23
- const nitroBuilder = {
24
- version: version};
22
+ //#region package.json
23
+ var version = "4.3.0-29466366.fa21bb17";
25
24
 
25
+ //#endregion
26
+ //#region src/utils.ts
26
27
  function toArray(value) {
27
- return Array.isArray(value) ? value : [value];
28
+ return Array.isArray(value) ? value : [value];
28
29
  }
29
30
  let _distDir = dirname(fileURLToPath(import.meta.url));
30
- if (/(?:chunks|shared)$/.test(_distDir)) {
31
- _distDir = dirname(_distDir);
32
- }
31
+ if (/(?:chunks|shared)$/.test(_distDir)) _distDir = dirname(_distDir);
33
32
  const distDir = _distDir;
34
33
 
34
+ //#endregion
35
+ //#region ../ui-templates/dist/templates/spa-loading-icon.ts
35
36
  const template = () => {
36
- return '<svg xmlns="http://www.w3.org/2000/svg" width="80" fill="none" class="nuxt-spa-loading" viewBox="0 0 37 25"><path d="M24.236 22.006h10.742L25.563 5.822l-8.979 14.31a4 4 0 0 1-3.388 1.874H2.978l11.631-20 5.897 10.567"/></svg><style>.nuxt-spa-loading{left:50%;position:fixed;top:50%;transform:translate(-50%,-50%)}.nuxt-spa-loading>path{animation:nuxt-spa-loading-move 3s linear infinite;fill:none;stroke:#00dc82;stroke-dasharray:128;stroke-dashoffset:128;stroke-linecap:round;stroke-linejoin:round;stroke-width:4px}@keyframes nuxt-spa-loading-move{to{stroke-dashoffset:-128}}</style>';
37
+ return "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"80\" fill=\"none\" class=\"nuxt-spa-loading\" viewBox=\"0 0 37 25\"><path d=\"M24.236 22.006h10.742L25.563 5.822l-8.979 14.31a4 4 0 0 1-3.388 1.874H2.978l11.631-20 5.897 10.567\"/></svg><style>.nuxt-spa-loading{left:50%;position:fixed;top:50%;transform:translate(-50%,-50%)}.nuxt-spa-loading>path{animation:nuxt-spa-loading-move 3s linear infinite;fill:none;stroke:#00dc82;stroke-dasharray:128;stroke-dashoffset:128;stroke-linecap:round;stroke-linejoin:round;stroke-width:4px}@keyframes nuxt-spa-loading-move{to{stroke-dashoffset:-128}}</style>";
37
38
  };
38
39
 
40
+ //#endregion
41
+ //#region ../nuxt/src/core/plugins/import-protection.ts
39
42
  function createImportProtectionPatterns(nuxt, options) {
40
- const patterns = [];
41
- const context = contextFlags[options.context];
42
- patterns.push([
43
- /^(nuxt|nuxt3|nuxt-nightly)$/,
44
- `\`nuxt\`, or \`nuxt-nightly\` cannot be imported directly in ${context}.` + (options.context === "nuxt-app" ? " Instead, import runtime Nuxt composables from `#app` or `#imports`." : "")
45
- ]);
46
- patterns.push([
47
- /^((~|~~|@|@@)?\/)?nuxt\.config(\.|$)/,
48
- "Importing directly from a `nuxt.config` file is not allowed. Instead, use runtime config or a module."
49
- ]);
50
- patterns.push([/(^|node_modules\/)@vue\/composition-api/]);
51
- for (const mod of nuxt.options._installedModules) {
52
- if (mod.entryPath) {
53
- patterns.push([
54
- new RegExp(`^${escapeRE(mod.entryPath)}$`),
55
- "Importing directly from module entry-points is not allowed."
56
- ]);
57
- }
58
- }
59
- for (const i of [/(^|node_modules\/)@nuxt\/(cli|kit|test-utils)/, /(^|node_modules\/)nuxi/, /(^|node_modules\/)nitro(?:pack)?(?:-nightly)?(?:$|\/)(?!(?:dist\/)?(?:node_modules|presets|runtime|types))/, /(^|node_modules\/)nuxt\/(config|kit|schema)/]) {
60
- patterns.push([i, `This module cannot be imported in ${context}.`]);
61
- }
62
- if (options.context === "nitro-app" || options.context === "shared") {
63
- for (const i of ["#app", /^#build(\/|$)/]) {
64
- patterns.push([i, `Vue app aliases are not allowed in ${context}.`]);
65
- }
66
- }
67
- if (options.context === "nuxt-app" || options.context === "shared") {
68
- patterns.push([
69
- new RegExp(escapeRE(relative(nuxt.options.srcDir, resolve(nuxt.options.srcDir, nuxt.options.serverDir || "server"))) + "\\/(api|routes|middleware|plugins)\\/"),
70
- `Importing from server is not allowed in ${context}.`
71
- ]);
72
- patterns.push([
73
- /^#server(\/|$)/,
74
- `Server aliases are not allowed in ${context}.`
75
- ]);
76
- }
77
- return patterns;
43
+ const patterns = [];
44
+ const context = contextFlags[options.context];
45
+ patterns.push([/^(nuxt|nuxt3|nuxt-nightly)$/, `\`nuxt\`, or \`nuxt-nightly\` cannot be imported directly in ${context}.` + (options.context === "nuxt-app" ? " Instead, import runtime Nuxt composables from `#app` or `#imports`." : "")]);
46
+ patterns.push([/^((~|~~|@|@@)?\/)?nuxt\.config(\.|$)/, "Importing directly from a `nuxt.config` file is not allowed. Instead, use runtime config or a module."]);
47
+ patterns.push([/(^|node_modules\/)@vue\/composition-api/]);
48
+ for (const mod of nuxt.options._installedModules) if (mod.entryPath) patterns.push([/* @__PURE__ */ new RegExp(`^${escapeRE(mod.entryPath)}$`), "Importing directly from module entry-points is not allowed."]);
49
+ for (const i of [
50
+ /(^|node_modules\/)@nuxt\/(cli|kit|test-utils)/,
51
+ /(^|node_modules\/)nuxi/,
52
+ /(^|node_modules\/)nitro(?:pack)?(?:-nightly)?(?:$|\/)(?!(?:dist\/)?(?:node_modules|presets|runtime|types))/,
53
+ /(^|node_modules\/)nuxt\/(config|kit|schema)/
54
+ ]) patterns.push([i, `This module cannot be imported in ${context}.`]);
55
+ if (options.context === "nitro-app" || options.context === "shared") for (const i of ["#app", /^#build(\/|$)/]) patterns.push([i, `Vue app aliases are not allowed in ${context}.`]);
56
+ if (options.context === "nuxt-app" || options.context === "shared") {
57
+ patterns.push([/* @__PURE__ */ new RegExp(escapeRE(relative(nuxt.options.srcDir, resolve(nuxt.options.srcDir, nuxt.options.serverDir || "server"))) + "\\/(api|routes|middleware|plugins)\\/"), `Importing from server is not allowed in ${context}.`]);
58
+ patterns.push([/^#server(\/|$)/, `Server aliases are not allowed in ${context}.`]);
59
+ }
60
+ return patterns;
78
61
  }
79
62
  const contextFlags = {
80
- "nitro-app": "server runtime",
81
- "nuxt-app": "the Vue part of your app",
82
- "shared": "the #shared directory"
63
+ "nitro-app": "server runtime",
64
+ "nuxt-app": "the Vue part of your app",
65
+ "shared": "the #shared directory"
83
66
  };
84
67
 
68
+ //#endregion
69
+ //#region src/templates.ts
85
70
  const nitroSchemaTemplate = {
86
- filename: "types/nitro-nuxt.d.ts",
87
- async getContents({ nuxt }) {
88
- const references = [];
89
- const declarations = [];
90
- await nuxt.callHook("nitro:prepare:types", { references, declarations });
91
- const sourceDir = join(nuxt.options.buildDir, "types");
92
- const lines = [
93
- ...references.map((ref) => {
94
- if ("path" in ref && isAbsolute(ref.path)) {
95
- ref.path = relative(sourceDir, ref.path);
96
- }
97
- return `/// <reference ${renderAttrs(ref)} />`;
98
- }),
99
- ...declarations
100
- ];
101
- return (
102
- /* typescript */
103
- `
104
- ${lines.join("\n")}
71
+ filename: "types/nitro-nuxt.d.ts",
72
+ async getContents({ nuxt }) {
73
+ const references = [];
74
+ const declarations = [];
75
+ await nuxt.callHook("nitro:prepare:types", {
76
+ references,
77
+ declarations
78
+ });
79
+ const sourceDir = join(nuxt.options.buildDir, "types");
80
+ return `
81
+ ${[...references.map((ref) => {
82
+ if ("path" in ref && isAbsolute(ref.path)) ref.path = relative(sourceDir, ref.path);
83
+ return `/// <reference ${renderAttrs(ref)} />`;
84
+ }), ...declarations].join("\n")}
105
85
 
106
86
  import type { RuntimeConfig } from 'nuxt/schema'
107
87
  import type { H3Event } from 'h3'
@@ -160,748 +140,622 @@ declare module 'nitropack/types' {
160
140
  'render:island': (islandResponse: NuxtIslandResponse, context: { event: H3Event, islandContext: NuxtIslandContext }) => void | Promise<void>
161
141
  }
162
142
  }
163
- `
164
- );
165
- }
143
+ `;
144
+ }
166
145
  };
167
146
  function renderAttr(key, value) {
168
- return value ? `${key}="${value}"` : "";
147
+ return value ? `${key}="${value}"` : "";
169
148
  }
170
149
  function renderAttrs(obj) {
171
- const attrs = [];
172
- for (const key in obj) {
173
- attrs.push(renderAttr(key, obj[key]));
174
- }
175
- return attrs.join(" ");
150
+ const attrs = [];
151
+ for (const key in obj) attrs.push(renderAttr(key, obj[key]));
152
+ return attrs.join(" ");
176
153
  }
177
154
 
155
+ //#endregion
156
+ //#region src/index.ts
178
157
  const logLevelMapReverse = {
179
- silent: 0,
180
- info: 3,
181
- verbose: 3
158
+ silent: 0,
159
+ info: 3,
160
+ verbose: 3
182
161
  };
183
162
  const NODE_MODULES_RE = /(?<=\/)node_modules\/(.+)$/;
184
163
  const PNPM_NODE_MODULES_RE = /\.pnpm\/.+\/node_modules\/(.+)$/;
185
164
  async function bundle(nuxt) {
186
- const layerDirs = getLayerDirectories(nuxt);
187
- const excludePaths = [];
188
- for (const dirs of layerDirs) {
189
- const paths = [
190
- dirs.root.match(NODE_MODULES_RE)?.[1]?.replace(/\/$/, ""),
191
- dirs.root.match(PNPM_NODE_MODULES_RE)?.[1]?.replace(/\/$/, "")
192
- ];
193
- for (const dir of paths) {
194
- if (dir) {
195
- excludePaths.push(escapeRE(dir));
196
- }
197
- }
198
- }
199
- const layerPublicAssetsDirs = [];
200
- for (const dirs of layerDirs) {
201
- if (existsSync(dirs.public)) {
202
- layerPublicAssetsDirs.push({ dir: dirs.public });
203
- }
204
- }
205
- const excludePattern = excludePaths.length ? [new RegExp(`node_modules\\/(?!${excludePaths.join("|")})`)] : [/node_modules/];
206
- const rootDirWithSlash = withTrailingSlash(nuxt.options.rootDir);
207
- const moduleEntryPaths = [];
208
- for (const m of nuxt.options._installedModules) {
209
- const path = m.meta?.rawPath || m.entryPath;
210
- if (path) {
211
- moduleEntryPaths.push(getDirectory(path));
212
- }
213
- }
214
- const modules = await resolveNuxtModule(rootDirWithSlash, moduleEntryPaths);
215
- addTemplate(nitroSchemaTemplate);
216
- const sharedDirs = /* @__PURE__ */ new Set();
217
- if (nuxt.options.nitro.imports !== false && nuxt.options.imports.scan !== false) {
218
- for (const layer of nuxt.options._layers) {
219
- if (layer.config?.imports?.scan === false) {
220
- continue;
221
- }
222
- sharedDirs.add(resolve(layer.config.rootDir, layer.config.dir?.shared ?? "shared", "utils"));
223
- sharedDirs.add(resolve(layer.config.rootDir, layer.config.dir?.shared ?? "shared", "types"));
224
- }
225
- }
226
- nuxt.options.nitro.plugins ||= [];
227
- nuxt.options.nitro.plugins = nuxt.options.nitro.plugins.map((plugin) => plugin ? resolveAlias(plugin, nuxt.options.alias) : plugin);
228
- if (nuxt.options.dev && nuxt.options.features.devLogs) {
229
- addPlugin(resolve(nuxt.options.appDir, "plugins/dev-server-logs"));
230
- nuxt.options.nitro.plugins.push(resolve(distDir, "runtime/plugins/dev-server-logs"));
231
- nuxt.options.nitro.externals = defu(nuxt.options.nitro.externals, {
232
- inline: [/#internal\/dev-server-logs-options/]
233
- });
234
- nuxt.options.nitro.virtual = defu(nuxt.options.nitro.virtual, {
235
- "#internal/dev-server-logs-options": () => `export const rootDir = ${JSON.stringify(nuxt.options.rootDir)};`
236
- });
237
- }
238
- if (nuxt.options.experimental.componentIslands) {
239
- nuxt.options.nitro.virtual ||= {};
240
- nuxt.options.nitro.virtual["#internal/nuxt/island-renderer.mjs"] = () => {
241
- if (nuxt.options.dev || nuxt.options.experimental.componentIslands !== "auto" || nuxt.apps.default?.pages?.some((p) => p.mode === "server") || nuxt.apps.default?.components?.some((c) => c.mode === "server" && !nuxt.apps.default?.components.some((other) => other.pascalName === c.pascalName && other.mode === "client"))) {
242
- return `export { default } from '${resolve(distDir, "runtime/handlers/island")}'`;
243
- }
244
- return `import { defineEventHandler } from 'h3'; export default defineEventHandler(() => {});`;
245
- };
246
- nuxt.options.nitro.handlers ||= [];
247
- nuxt.options.nitro.handlers.push({
248
- route: "/__nuxt_island/**",
249
- handler: "#internal/nuxt/island-renderer.mjs"
250
- });
251
- if (!nuxt.options.ssr && nuxt.options.experimental.componentIslands !== "auto") {
252
- nuxt.options.ssr = true;
253
- nuxt.options.nitro.routeRules ||= {};
254
- nuxt.options.nitro.routeRules["/**"] = defu(nuxt.options.nitro.routeRules["/**"], { ssr: false });
255
- }
256
- }
257
- const mockProxy = resolveModulePath("mocked-exports/proxy", { from: import.meta.url });
258
- const { version: nuxtVersion } = await readPackageJSON("nuxt", { from: import.meta.url });
259
- const nitroConfig = defu(nuxt.options.nitro, {
260
- debug: nuxt.options.debug ? nuxt.options.debug.nitro : false,
261
- rootDir: nuxt.options.rootDir,
262
- workspaceDir: nuxt.options.workspaceDir,
263
- srcDir: nuxt.options.serverDir,
264
- dev: nuxt.options.dev,
265
- buildDir: nuxt.options.buildDir,
266
- experimental: {
267
- asyncContext: nuxt.options.experimental.asyncContext,
268
- typescriptBundlerResolution: nuxt.options.future.typescriptBundlerResolution || nuxt.options.typescript?.tsConfig?.compilerOptions?.moduleResolution?.toLowerCase() === "bundler" || nuxt.options.nitro.typescript?.tsConfig?.compilerOptions?.moduleResolution?.toLowerCase() === "bundler"
269
- },
270
- framework: {
271
- name: "nuxt",
272
- version: nuxtVersion || nitroBuilder.version
273
- },
274
- imports: {
275
- autoImport: nuxt.options.imports.autoImport,
276
- dirs: [...sharedDirs],
277
- imports: [
278
- {
279
- as: "__buildAssetsURL",
280
- name: "buildAssetsURL",
281
- from: resolve(distDir, "runtime/utils/paths")
282
- },
283
- {
284
- as: "__publicAssetsURL",
285
- name: "publicAssetsURL",
286
- from: resolve(distDir, "runtime/utils/paths")
287
- },
288
- {
289
- // TODO: Remove after https://github.com/nitrojs/nitro/issues/1049
290
- as: "defineAppConfig",
291
- name: "defineAppConfig",
292
- from: resolve(distDir, "runtime/utils/config"),
293
- priority: -1
294
- }
295
- ],
296
- exclude: [...excludePattern, /[\\/]\.git[\\/]/]
297
- },
298
- esbuild: {
299
- options: { exclude: excludePattern }
300
- },
301
- analyze: !nuxt.options.test && nuxt.options.build.analyze && (nuxt.options.build.analyze === true || nuxt.options.build.analyze.enabled) ? {
302
- template: "treemap",
303
- projectRoot: nuxt.options.rootDir,
304
- filename: join(nuxt.options.analyzeDir, "{name}.html")
305
- } : false,
306
- scanDirs: layerDirs.map((dirs) => dirs.server),
307
- renderer: resolve(distDir, "runtime/handlers/renderer"),
308
- nodeModulesDirs: nuxt.options.modulesDir,
309
- handlers: nuxt.options.serverHandlers,
310
- devHandlers: [],
311
- baseURL: nuxt.options.app.baseURL,
312
- virtual: {
313
- "#internal/nuxt.config.mjs": () => nuxt.vfs["#build/nuxt.config.mjs"] || "",
314
- "#internal/nuxt/app-config": () => nuxt.vfs["#build/app.config.mjs"]?.replace(/\/\*\* client \*\*\/[\s\S]*\/\*\* client-end \*\*\//, "") || "",
315
- "#spa-template": async () => `export const template = ${JSON.stringify(await spaLoadingTemplate(nuxt))}`,
316
- // this will be overridden in vite plugin
317
- "#internal/entry-chunk.mjs": () => `export const entryFileName = undefined`,
318
- "#internal/nuxt/entry-ids.mjs": () => `export default []`,
319
- "#internal/nuxt/nitro-config.mjs": () => {
320
- const hasCachedRoutes = Object.values(nitro.options.routeRules).some((r) => r.isr || r.cache);
321
- return [
322
- `export const NUXT_NO_SSR = ${nuxt.options.ssr === false}`,
323
- `export const NUXT_EARLY_HINTS = ${nuxt.options.experimental.writeEarlyHints !== false}`,
324
- `export const NUXT_NO_SCRIPTS = ${nuxt.options.features.noScripts === "all" || !!nuxt.options.features.noScripts && !nuxt.options.dev}`,
325
- `export const NUXT_INLINE_STYLES = ${!!nuxt.options.features.inlineStyles}`,
326
- `export const PARSE_ERROR_DATA = ${!!nuxt.options.experimental.parseErrorData}`,
327
- `export const NUXT_JSON_PAYLOADS = ${!!nuxt.options.experimental.renderJsonPayloads}`,
328
- `export const NUXT_ASYNC_CONTEXT = ${!!nuxt.options.experimental.asyncContext}`,
329
- `export const NUXT_SHARED_DATA = ${!!nuxt.options.experimental.sharedPrerenderData}`,
330
- `export const NUXT_PAYLOAD_EXTRACTION = ${!!nuxt.options.experimental.payloadExtraction}`,
331
- `export const NUXT_RUNTIME_PAYLOAD_EXTRACTION = ${hasCachedRoutes}`
332
- ].join("\n");
333
- }
334
- },
335
- routeRules: {
336
- "/__nuxt_error": { cache: false }
337
- },
338
- appConfig: nuxt.options.appConfig,
339
- appConfigFiles: layerDirs.map((dirs) => join(dirs.app, "app.config")),
340
- typescript: {
341
- strict: true,
342
- generateTsConfig: true,
343
- tsconfigPath: "tsconfig.server.json",
344
- tsConfig: {
345
- compilerOptions: {
346
- lib: ["esnext", "webworker", "dom.iterable"],
347
- skipLibCheck: true,
348
- noUncheckedIndexedAccess: true
349
- },
350
- include: [
351
- join(nuxt.options.buildDir, "types/nitro-nuxt.d.ts"),
352
- ...modules.flatMap((m) => {
353
- const moduleDir = relativeWithDot(nuxt.options.buildDir, m);
354
- return [
355
- join(moduleDir, "runtime/server"),
356
- join(moduleDir, "dist/runtime/server")
357
- ];
358
- }),
359
- ...layerDirs.map((dirs) => relativeWithDot(nuxt.options.buildDir, join(dirs.server, "**/*"))),
360
- ...layerDirs.map((dirs) => relativeWithDot(nuxt.options.buildDir, join(dirs.shared, "**/*.d.ts")))
361
- ],
362
- exclude: [
363
- ...nuxt.options.modulesDir.map((m) => relativeWithDot(nuxt.options.buildDir, m)),
364
- relativeWithDot(nuxt.options.buildDir, resolve(nuxt.options.rootDir, "dist"))
365
- ]
366
- }
367
- },
368
- publicAssets: [
369
- nuxt.options.dev ? { dir: resolve(nuxt.options.buildDir, "dist/client") } : {
370
- dir: join(nuxt.options.buildDir, "dist/client", nuxt.options.app.buildAssetsDir),
371
- maxAge: 31536e3,
372
- baseURL: nuxt.options.app.buildAssetsDir
373
- },
374
- ...layerPublicAssetsDirs
375
- ],
376
- prerender: {
377
- ignoreUnprefixedPublicAssets: true,
378
- failOnError: true,
379
- concurrency: cpus().length * 4 || 4,
380
- routes: [].concat(nuxt.options.generate.routes)
381
- },
382
- sourceMap: nuxt.options.sourcemap.server,
383
- externals: {
384
- inline: [
385
- ...nuxt.options.dev ? [] : [
386
- ...nuxt.options.experimental.externalVue ? [] : ["vue", "@vue/"],
387
- "@nuxt/",
388
- nuxt.options.buildDir
389
- ],
390
- ...nuxt.options.build.transpile.filter((i) => typeof i === "string"),
391
- "nuxt/dist",
392
- "nuxt3/dist",
393
- "nuxt-nightly/dist",
394
- distDir,
395
- // Ensure app config files have auto-imports injected even if they are pure .js files
396
- ...layerDirs.map((dirs) => join(dirs.app, "app.config"))
397
- ],
398
- traceInclude: [
399
- // force include files used in generated code from the runtime-compiler
400
- ...nuxt.options.vue.runtimeCompiler && !nuxt.options.experimental.externalVue ? [
401
- ...nuxt.options.modulesDir.reduce((targets, path) => {
402
- const serverRendererPath = resolve(path, "vue/server-renderer/index.js");
403
- if (existsSync(serverRendererPath)) {
404
- targets.push(serverRendererPath);
405
- }
406
- return targets;
407
- }, [])
408
- ] : []
409
- ]
410
- },
411
- alias: {
412
- // Vue 3 mocks
413
- ...nuxt.options.vue.runtimeCompiler || nuxt.options.experimental.externalVue ? {} : {
414
- "estree-walker": mockProxy,
415
- "@babel/parser": mockProxy,
416
- "@vue/compiler-core": mockProxy,
417
- "@vue/compiler-dom": mockProxy,
418
- "@vue/compiler-ssr": mockProxy
419
- },
420
- "@vue/devtools-api": "vue-devtools-stub",
421
- // Nuxt aliases
422
- ...nuxt.options.alias,
423
- // Paths
424
- "#internal/nuxt/paths": resolve(distDir, "runtime/utils/paths")
425
- },
426
- replace: {
427
- "__VUE_PROD_DEVTOOLS__": String(false)
428
- },
429
- rollupConfig: {
430
- output: {
431
- generatedCode: {
432
- symbols: true
433
- // temporary fix for https://github.com/vuejs/core/issues/8351
434
- }
435
- },
436
- plugins: []
437
- },
438
- logLevel: logLevelMapReverse[nuxt.options.logLevel]
439
- });
440
- if (nuxt.options.experimental.serverAppConfig && nitroConfig.imports) {
441
- nitroConfig.imports.imports ||= [];
442
- nitroConfig.imports.imports.push({
443
- name: "useAppConfig",
444
- from: resolve(distDir, "runtime/utils/app-config"),
445
- priority: -1
446
- });
447
- }
448
- if (!nitroConfig.errorHandler && (nuxt.options.dev || !nuxt.options.experimental.noVueServer)) {
449
- nitroConfig.errorHandler = resolve(distDir, "runtime/handlers/error");
450
- }
451
- nitroConfig.srcDir = resolve(nuxt.options.rootDir, nuxt.options.srcDir, nitroConfig.srcDir);
452
- nitroConfig.ignore ||= [];
453
- nitroConfig.ignore.push(
454
- ...resolveIgnorePatterns(nitroConfig.srcDir),
455
- `!${join(nuxt.options.buildDir, "dist/client", nuxt.options.app.buildAssetsDir, "**/*")}`
456
- );
457
- const validManifestKeys = ["prerender", "redirect", "appMiddleware", "appLayout"];
458
- function getRouteRulesRouter() {
459
- const routeRulesRouter = createRouter();
460
- if (nuxt._nitro) {
461
- for (const [route, rules] of Object.entries(nuxt._nitro.options.routeRules)) {
462
- if (route === "/__nuxt_error") {
463
- continue;
464
- }
465
- if (validManifestKeys.every((key) => !(key in rules))) {
466
- continue;
467
- }
468
- addRoute(routeRulesRouter, void 0, route, rules);
469
- }
470
- }
471
- return routeRulesRouter;
472
- }
473
- const cachedMatchers = {};
474
- addTemplate({
475
- filename: "route-rules.mjs",
476
- getContents() {
477
- const key = hash(nuxt._nitro?.options.routeRules || {});
478
- if (cachedMatchers[key]) {
479
- return cachedMatchers[key];
480
- }
481
- const matcher = compileRouterToString(getRouteRulesRouter(), "", {
482
- matchAll: true,
483
- serialize(routeRules) {
484
- return `{${Object.entries(routeRules).filter(([name, value]) => value !== void 0 && validManifestKeys.includes(name)).map(([name, value]) => {
485
- if (name === "redirect") {
486
- const redirectOptions = value;
487
- value = typeof redirectOptions === "string" ? redirectOptions : redirectOptions.to;
488
- }
489
- if (name === "appMiddleware") {
490
- const appMiddlewareOptions = value;
491
- if (typeof appMiddlewareOptions === "string") {
492
- value = { [appMiddlewareOptions]: true };
493
- } else if (Array.isArray(appMiddlewareOptions)) {
494
- const normalizedRules = {};
495
- for (const middleware of appMiddlewareOptions) {
496
- normalizedRules[middleware] = true;
497
- }
498
- value = normalizedRules;
499
- }
500
- }
501
- if (name === "cache" || name === "isr") {
502
- name = "payload";
503
- value = Boolean(value);
504
- }
505
- return `${name}: ${JSON.stringify(value)}`;
506
- }).join(",")}}`;
507
- }
508
- });
509
- return cachedMatchers[key] = `
165
+ const layerDirs = getLayerDirectories(nuxt);
166
+ const excludePaths = [];
167
+ for (const dirs of layerDirs) {
168
+ const paths = [dirs.root.match(NODE_MODULES_RE)?.[1]?.replace(/\/$/, ""), dirs.root.match(PNPM_NODE_MODULES_RE)?.[1]?.replace(/\/$/, "")];
169
+ for (const dir of paths) if (dir) excludePaths.push(escapeRE(dir));
170
+ }
171
+ const layerPublicAssetsDirs = [];
172
+ for (const dirs of layerDirs) if (existsSync(dirs.public)) layerPublicAssetsDirs.push({ dir: dirs.public });
173
+ const excludePattern = excludePaths.length ? [/* @__PURE__ */ new RegExp(`node_modules\\/(?!${excludePaths.join("|")})`)] : [/node_modules/];
174
+ const rootDirWithSlash = withTrailingSlash(nuxt.options.rootDir);
175
+ const moduleEntryPaths = [];
176
+ for (const m of nuxt.options._installedModules) {
177
+ const path = m.meta?.rawPath || m.entryPath;
178
+ if (path) moduleEntryPaths.push(getDirectory(path));
179
+ }
180
+ const modules = await resolveNuxtModule(rootDirWithSlash, moduleEntryPaths);
181
+ addTemplate(nitroSchemaTemplate);
182
+ const sharedDirs = /* @__PURE__ */ new Set();
183
+ if (nuxt.options.nitro.imports !== false && nuxt.options.imports.scan !== false) for (const layer of nuxt.options._layers) {
184
+ if (layer.config?.imports?.scan === false) continue;
185
+ sharedDirs.add(resolve(layer.config.rootDir, layer.config.dir?.shared ?? "shared", "utils"));
186
+ sharedDirs.add(resolve(layer.config.rootDir, layer.config.dir?.shared ?? "shared", "types"));
187
+ }
188
+ nuxt.options.nitro.plugins ||= [];
189
+ nuxt.options.nitro.plugins = nuxt.options.nitro.plugins.map((plugin) => plugin ? resolveAlias(plugin, nuxt.options.alias) : plugin);
190
+ if (nuxt.options.dev && nuxt.options.features.devLogs) {
191
+ addPlugin(resolve(nuxt.options.appDir, "plugins/dev-server-logs"));
192
+ nuxt.options.nitro.plugins.push(resolve(distDir, "runtime/plugins/dev-server-logs"));
193
+ nuxt.options.nitro.externals = defu(nuxt.options.nitro.externals, { inline: [/#internal\/dev-server-logs-options/] });
194
+ nuxt.options.nitro.virtual = defu(nuxt.options.nitro.virtual, { "#internal/dev-server-logs-options": () => `export const rootDir = ${JSON.stringify(nuxt.options.rootDir)};` });
195
+ }
196
+ if (nuxt.options.experimental.componentIslands) {
197
+ nuxt.options.nitro.virtual ||= {};
198
+ nuxt.options.nitro.virtual["#internal/nuxt/island-renderer.mjs"] = () => {
199
+ if (nuxt.options.dev || nuxt.options.experimental.componentIslands !== "auto" || nuxt.apps.default?.pages?.some((p) => p.mode === "server") || nuxt.apps.default?.components?.some((c) => c.mode === "server" && !nuxt.apps.default?.components.some((other) => other.pascalName === c.pascalName && other.mode === "client"))) return `export { default } from '${resolve(distDir, "runtime/handlers/island")}'`;
200
+ return `import { defineEventHandler } from 'h3'; export default defineEventHandler(() => {});`;
201
+ };
202
+ nuxt.options.nitro.handlers ||= [];
203
+ nuxt.options.nitro.handlers.push({
204
+ route: "/__nuxt_island/**",
205
+ handler: "#internal/nuxt/island-renderer.mjs"
206
+ });
207
+ if (!nuxt.options.ssr && nuxt.options.experimental.componentIslands !== "auto") {
208
+ nuxt.options.ssr = true;
209
+ nuxt.options.nitro.routeRules ||= {};
210
+ nuxt.options.nitro.routeRules["/**"] = defu(nuxt.options.nitro.routeRules["/**"], { ssr: false });
211
+ }
212
+ }
213
+ const mockProxy = resolveModulePath("mocked-exports/proxy", { from: import.meta.url });
214
+ const { version: nuxtVersion } = await readPackageJSON("nuxt", { from: import.meta.url });
215
+ const nitroConfig = defu(nuxt.options.nitro, {
216
+ debug: nuxt.options.debug ? nuxt.options.debug.nitro : false,
217
+ rootDir: nuxt.options.rootDir,
218
+ workspaceDir: nuxt.options.workspaceDir,
219
+ srcDir: nuxt.options.serverDir,
220
+ dev: nuxt.options.dev,
221
+ buildDir: nuxt.options.buildDir,
222
+ experimental: {
223
+ asyncContext: nuxt.options.experimental.asyncContext,
224
+ typescriptBundlerResolution: nuxt.options.future.typescriptBundlerResolution || nuxt.options.typescript?.tsConfig?.compilerOptions?.moduleResolution?.toLowerCase() === "bundler" || nuxt.options.nitro.typescript?.tsConfig?.compilerOptions?.moduleResolution?.toLowerCase() === "bundler"
225
+ },
226
+ framework: {
227
+ name: "nuxt",
228
+ version: nuxtVersion || version
229
+ },
230
+ imports: nuxt.options.experimental.nitroAutoImports === false ? false : {
231
+ autoImport: nuxt.options.imports.autoImport,
232
+ dirs: [...sharedDirs],
233
+ imports: [
234
+ {
235
+ as: "__buildAssetsURL",
236
+ name: "buildAssetsURL",
237
+ from: resolve(distDir, "runtime/utils/paths")
238
+ },
239
+ {
240
+ as: "__publicAssetsURL",
241
+ name: "publicAssetsURL",
242
+ from: resolve(distDir, "runtime/utils/paths")
243
+ },
244
+ {
245
+ as: "defineAppConfig",
246
+ name: "defineAppConfig",
247
+ from: resolve(distDir, "runtime/utils/config"),
248
+ priority: -1
249
+ }
250
+ ],
251
+ exclude: [...excludePattern, /[\\/]\.git[\\/]/]
252
+ },
253
+ esbuild: { options: { exclude: excludePattern } },
254
+ analyze: !nuxt.options.test && nuxt.options.build.analyze && (nuxt.options.build.analyze === true || nuxt.options.build.analyze.enabled) ? {
255
+ template: "treemap",
256
+ projectRoot: nuxt.options.rootDir,
257
+ filename: join(nuxt.options.analyzeDir, "{name}.html")
258
+ } : false,
259
+ scanDirs: layerDirs.map((dirs) => dirs.server),
260
+ renderer: resolve(distDir, "runtime/handlers/renderer"),
261
+ nodeModulesDirs: nuxt.options.modulesDir,
262
+ handlers: nuxt.options.serverHandlers,
263
+ devHandlers: [],
264
+ baseURL: nuxt.options.app.baseURL,
265
+ virtual: {
266
+ "#internal/nuxt.config.mjs": () => nuxt.vfs["#build/nuxt.config.mjs"] || "",
267
+ "#internal/nuxt/app-config": () => nuxt.vfs["#build/app.config.mjs"]?.replace(/\/\*\* client \*\*\/[\s\S]*\/\*\* client-end \*\*\//, "") || "",
268
+ "#spa-template": async () => `export const template = ${JSON.stringify(await spaLoadingTemplate(nuxt))}`,
269
+ "#internal/entry-chunk.mjs": () => `export const entryFileName = undefined`,
270
+ "#internal/nuxt/entry-ids.mjs": () => `export default []`,
271
+ "#internal/nuxt/nitro-config.mjs": () => {
272
+ const hasCachedRoutes = Object.values(nitro.options.routeRules).some((r) => r.isr || r.cache);
273
+ return [
274
+ `export const NUXT_NO_SSR = ${nuxt.options.ssr === false}`,
275
+ `export const NUXT_EARLY_HINTS = ${nuxt.options.experimental.writeEarlyHints !== false}`,
276
+ `export const NUXT_NO_SCRIPTS = ${nuxt.options.features.noScripts === "all" || !!nuxt.options.features.noScripts && !nuxt.options.dev}`,
277
+ `export const NUXT_INLINE_STYLES = ${!!nuxt.options.features.inlineStyles}`,
278
+ `export const PARSE_ERROR_DATA = ${!!nuxt.options.experimental.parseErrorData}`,
279
+ `export const NUXT_JSON_PAYLOADS = ${!!nuxt.options.experimental.renderJsonPayloads}`,
280
+ `export const NUXT_ASYNC_CONTEXT = ${!!nuxt.options.experimental.asyncContext}`,
281
+ `export const NUXT_SHARED_DATA = ${!!nuxt.options.experimental.sharedPrerenderData}`,
282
+ `export const NUXT_PAYLOAD_EXTRACTION = ${!!nuxt.options.experimental.payloadExtraction}`,
283
+ `export const NUXT_RUNTIME_PAYLOAD_EXTRACTION = ${hasCachedRoutes}`
284
+ ].join("\n");
285
+ }
286
+ },
287
+ routeRules: { "/__nuxt_error": { cache: false } },
288
+ appConfig: nuxt.options.appConfig,
289
+ appConfigFiles: layerDirs.map((dirs) => join(dirs.app, "app.config")),
290
+ typescript: {
291
+ strict: true,
292
+ generateTsConfig: true,
293
+ tsconfigPath: "tsconfig.server.json",
294
+ tsConfig: {
295
+ compilerOptions: {
296
+ lib: [
297
+ "esnext",
298
+ "webworker",
299
+ "dom.iterable"
300
+ ],
301
+ skipLibCheck: true,
302
+ noUncheckedIndexedAccess: true
303
+ },
304
+ include: [
305
+ join(nuxt.options.buildDir, "types/nitro-nuxt.d.ts"),
306
+ ...modules.flatMap((m) => {
307
+ const moduleDir = relativeWithDot(nuxt.options.buildDir, m);
308
+ return [join(moduleDir, "runtime/server"), join(moduleDir, "dist/runtime/server")];
309
+ }),
310
+ ...layerDirs.map((dirs) => relativeWithDot(nuxt.options.buildDir, join(dirs.server, "**/*"))),
311
+ ...layerDirs.map((dirs) => relativeWithDot(nuxt.options.buildDir, join(dirs.shared, "**/*.d.ts")))
312
+ ],
313
+ exclude: [...nuxt.options.modulesDir.map((m) => relativeWithDot(nuxt.options.buildDir, m)), relativeWithDot(nuxt.options.buildDir, resolve(nuxt.options.rootDir, "dist"))]
314
+ }
315
+ },
316
+ publicAssets: [nuxt.options.dev ? { dir: resolve(nuxt.options.buildDir, "dist/client") } : {
317
+ dir: join(nuxt.options.buildDir, "dist/client", nuxt.options.app.buildAssetsDir),
318
+ maxAge: 31536e3,
319
+ baseURL: nuxt.options.app.buildAssetsDir
320
+ }, ...layerPublicAssetsDirs],
321
+ prerender: {
322
+ ignoreUnprefixedPublicAssets: true,
323
+ failOnError: true,
324
+ concurrency: cpus().length * 4 || 4,
325
+ routes: [].concat(nuxt.options.generate.routes)
326
+ },
327
+ sourceMap: nuxt.options.sourcemap.server,
328
+ externals: {
329
+ inline: [
330
+ ...nuxt.options.dev ? [] : [
331
+ ...nuxt.options.experimental.externalVue ? [] : ["vue", "@vue/"],
332
+ "@nuxt/",
333
+ nuxt.options.buildDir
334
+ ],
335
+ ...nuxt.options.build.transpile.filter((i) => typeof i === "string"),
336
+ "nuxt/dist",
337
+ "nuxt3/dist",
338
+ "nuxt-nightly/dist",
339
+ distDir,
340
+ ...layerDirs.map((dirs) => join(dirs.app, "app.config"))
341
+ ],
342
+ traceInclude: [...nuxt.options.vue.runtimeCompiler && !nuxt.options.experimental.externalVue ? [...nuxt.options.modulesDir.reduce((targets, path) => {
343
+ const serverRendererPath = resolve(path, "vue/server-renderer/index.js");
344
+ if (existsSync(serverRendererPath)) targets.push(serverRendererPath);
345
+ return targets;
346
+ }, [])] : []]
347
+ },
348
+ alias: {
349
+ ...nuxt.options.vue.runtimeCompiler || nuxt.options.experimental.externalVue ? {} : {
350
+ "estree-walker": mockProxy,
351
+ "@babel/parser": mockProxy,
352
+ "@vue/compiler-core": mockProxy,
353
+ "@vue/compiler-dom": mockProxy,
354
+ "@vue/compiler-ssr": mockProxy
355
+ },
356
+ "@vue/devtools-api": "vue-devtools-stub",
357
+ ...nuxt.options.alias,
358
+ "#internal/nuxt/paths": resolve(distDir, "runtime/utils/paths")
359
+ },
360
+ replace: { "__VUE_PROD_DEVTOOLS__": String(false) },
361
+ rollupConfig: {
362
+ output: { generatedCode: { symbols: true } },
363
+ plugins: []
364
+ },
365
+ logLevel: logLevelMapReverse[nuxt.options.logLevel]
366
+ });
367
+ if (nuxt.options.experimental.serverAppConfig === true && nitroConfig.imports) {
368
+ nitroConfig.imports.imports ||= [];
369
+ nitroConfig.imports.imports.push({
370
+ name: "useAppConfig",
371
+ from: resolve(distDir, "runtime/utils/app-config"),
372
+ priority: -1
373
+ });
374
+ }
375
+ if (!nitroConfig.errorHandler && (nuxt.options.dev || !nuxt.options.experimental.noVueServer)) nitroConfig.errorHandler = resolve(distDir, "runtime/handlers/error");
376
+ nitroConfig.srcDir = resolve(nuxt.options.rootDir, nuxt.options.srcDir, nitroConfig.srcDir);
377
+ nitroConfig.ignore ||= [];
378
+ nitroConfig.ignore.push(...resolveIgnorePatterns(nitroConfig.srcDir), `!${join(nuxt.options.buildDir, "dist/client", nuxt.options.app.buildAssetsDir, "**/*")}`);
379
+ const validManifestKeys = [
380
+ "prerender",
381
+ "redirect",
382
+ "appMiddleware",
383
+ "appLayout"
384
+ ];
385
+ function getRouteRulesRouter() {
386
+ const routeRulesRouter = createRouter();
387
+ if (nuxt._nitro) for (const [route, rules] of Object.entries(nuxt._nitro.options.routeRules)) {
388
+ if (route === "/__nuxt_error") continue;
389
+ if (validManifestKeys.every((key) => !(key in rules))) continue;
390
+ addRoute(routeRulesRouter, void 0, route, rules);
391
+ }
392
+ return routeRulesRouter;
393
+ }
394
+ const cachedMatchers = {};
395
+ addTemplate({
396
+ filename: "route-rules.mjs",
397
+ getContents() {
398
+ const key = hash(nuxt._nitro?.options.routeRules || {});
399
+ if (cachedMatchers[key]) return cachedMatchers[key];
400
+ return cachedMatchers[key] = `
510
401
  import { defu } from 'defu'
511
- const matcher = ${matcher}
402
+ const matcher = ${compileRouterToString(getRouteRulesRouter(), "", {
403
+ matchAll: true,
404
+ serialize(routeRules) {
405
+ return `{${Object.entries(routeRules).filter(([name, value]) => value !== void 0 && validManifestKeys.includes(name)).map(([name, value]) => {
406
+ if (name === "redirect") {
407
+ const redirectOptions = value;
408
+ value = typeof redirectOptions === "string" ? redirectOptions : redirectOptions.to;
409
+ }
410
+ if (name === "appMiddleware") {
411
+ const appMiddlewareOptions = value;
412
+ if (typeof appMiddlewareOptions === "string") value = { [appMiddlewareOptions]: true };
413
+ else if (Array.isArray(appMiddlewareOptions)) {
414
+ const normalizedRules = {};
415
+ for (const middleware of appMiddlewareOptions) normalizedRules[middleware] = true;
416
+ value = normalizedRules;
417
+ }
418
+ }
419
+ if (name === "cache" || name === "isr") {
420
+ name = "payload";
421
+ value = Boolean(value);
422
+ }
423
+ return `${name}: ${JSON.stringify(value)}`;
424
+ }).join(",")}}`;
425
+ }
426
+ })}
512
427
  export default (path) => defu({}, ...matcher('', path).map(r => r.data).reverse())
513
428
  `;
514
- }
515
- });
516
- if (nuxt.options.experimental.payloadExtraction) {
517
- if (nuxt.options.dev) {
518
- nuxt.hook("nitro:config", (nitroConfig2) => {
519
- nitroConfig2.prerender ||= {};
520
- nitroConfig2.prerender.routes ||= [];
521
- nitroConfig2.routeRules ||= {};
522
- for (const route of nitroConfig2.prerender.routes) {
523
- if (!route) {
524
- continue;
525
- }
526
- nitroConfig2.routeRules[route] = defu(nitroConfig2.routeRules[route], { prerender: true });
527
- }
528
- });
529
- }
530
- nuxt.hook("nitro:init", (nitro2) => {
531
- nitro2.hooks.hook("build:before", (nitro3) => {
532
- for (const [route, value] of Object.entries(nitro3.options.routeRules)) {
533
- if (!route.endsWith("*") && !route.endsWith("/_payload.json")) {
534
- if (value.isr || value.cache || value.prerender && nuxt.options.dev) {
535
- const payloadKey = route + "/_payload.json";
536
- const defaults = {};
537
- for (const key of ["isr", "cache", ...nuxt.options.dev ? ["prerender"] : []]) {
538
- if (key in value) {
539
- defaults[key] = value[key];
540
- }
541
- }
542
- nitro3.options.routeRules[payloadKey] = defu(nitro3.options.routeRules[payloadKey], defaults);
543
- }
544
- }
545
- }
546
- });
547
- });
548
- }
549
- if (nuxt.options.experimental.appManifest) {
550
- const buildId = nuxt.options.runtimeConfig.app.buildId ||= nuxt.options.buildId;
551
- const buildTimestamp = Date.now();
552
- const manifestPrefix = joinURL(nuxt.options.app.buildAssetsDir, "builds");
553
- const tempDir = join(nuxt.options.buildDir, "manifest");
554
- nitroConfig.prerender ||= {};
555
- nitroConfig.prerender.ignore ||= [];
556
- nitroConfig.prerender.ignore.push(joinURL(nuxt.options.app.baseURL, manifestPrefix));
557
- nitroConfig.publicAssets.unshift(
558
- // build manifest
559
- {
560
- dir: join(tempDir, "meta"),
561
- maxAge: 31536e3,
562
- baseURL: joinURL(manifestPrefix, "meta")
563
- },
564
- // latest build
565
- {
566
- dir: tempDir,
567
- maxAge: 1,
568
- baseURL: manifestPrefix
569
- }
570
- );
571
- nuxt.options.alias["#app-manifest"] = join(tempDir, `meta/${buildId}.json`);
572
- if (!nuxt.options.dev) {
573
- nuxt.hook("build:before", async () => {
574
- await promises.mkdir(join(tempDir, "meta"), { recursive: true });
575
- await promises.writeFile(join(tempDir, `meta/${buildId}.json`), JSON.stringify({}));
576
- });
577
- }
578
- nuxt.hook("nitro:config", (config) => {
579
- config.alias ||= {};
580
- config.alias["#app-manifest"] = join(tempDir, `meta/${buildId}.json`);
581
- });
582
- nuxt.hook("nitro:init", (nitro2) => {
583
- nitro2.hooks.hook("rollup:before", async (nitro3) => {
584
- const prerenderedRoutes = /* @__PURE__ */ new Set();
585
- const routeRulesMatcher = getRouteRulesRouter();
586
- if (nitro3._prerenderedRoutes?.length) {
587
- const payloadSuffix = nuxt.options.experimental.renderJsonPayloads ? "/_payload.json" : "/_payload.js";
588
- for (const route of nitro3._prerenderedRoutes) {
589
- if (!route.error && route.route.endsWith(payloadSuffix)) {
590
- const url = route.route.slice(0, -payloadSuffix.length) || "/";
591
- const rules = defu({}, ...findAllRoutes(routeRulesMatcher, void 0, url).reverse());
592
- if (!rules.prerender) {
593
- prerenderedRoutes.add(url);
594
- }
595
- }
596
- }
597
- }
598
- const manifest = {
599
- id: buildId,
600
- timestamp: buildTimestamp,
601
- prerendered: nuxt.options.dev ? [] : [...prerenderedRoutes]
602
- };
603
- await promises.mkdir(join(tempDir, "meta"), { recursive: true });
604
- await promises.writeFile(join(tempDir, "latest.json"), JSON.stringify({
605
- id: buildId,
606
- timestamp: buildTimestamp
607
- }));
608
- await promises.writeFile(join(tempDir, `meta/${buildId}.json`), JSON.stringify(manifest));
609
- });
610
- });
611
- }
612
- if (!nuxt.options.experimental.appManifest) {
613
- nuxt.options.alias["#app-manifest"] = mockProxy;
614
- }
615
- const FORWARD_SLASH_RE = /\//g;
616
- if (!nuxt.options.ssr) {
617
- nitroConfig.virtual["#build/dist/server/server.mjs"] = "export default () => {}";
618
- if (process.platform === "win32") {
619
- nitroConfig.virtual["#build/dist/server/server.mjs".replace(FORWARD_SLASH_RE, "\\")] = "export default () => {}";
620
- }
621
- }
622
- if (nuxt.options.dev) {
623
- nitroConfig.virtual["#build/dist/server/styles.mjs"] = "export default {}";
624
- if (process.platform === "win32") {
625
- nitroConfig.virtual["#build/dist/server/styles.mjs".replace(FORWARD_SLASH_RE, "\\")] = "export default {}";
626
- }
627
- }
628
- nitroConfig.rollupConfig.plugins = await nitroConfig.rollupConfig.plugins || [];
629
- nitroConfig.rollupConfig.plugins = toArray(nitroConfig.rollupConfig.plugins);
630
- const sharedDir = withTrailingSlash(resolve(nuxt.options.rootDir, nuxt.options.dir.shared));
631
- const relativeSharedDir = withTrailingSlash(relative(nuxt.options.rootDir, resolve(nuxt.options.rootDir, nuxt.options.dir.shared)));
632
- const sharedPatterns = [/^#shared\//, new RegExp("^" + escapeRE(sharedDir)), new RegExp("^" + escapeRE(relativeSharedDir))];
633
- nitroConfig.rollupConfig.plugins.push(
634
- ImpoundPlugin.rollup({
635
- cwd: nuxt.options.rootDir,
636
- include: sharedPatterns,
637
- patterns: createImportProtectionPatterns(nuxt, { context: "shared" })
638
- }),
639
- ImpoundPlugin.rollup({
640
- cwd: nuxt.options.rootDir,
641
- patterns: createImportProtectionPatterns(nuxt, { context: "nitro-app" }),
642
- exclude: [/node_modules[\\/]nitro(?:pack)?(?:-nightly)?[\\/]|(packages|@nuxt)[\\/]nitro-server(?:-nightly)?[\\/](src|dist)[\\/]runtime[\\/]/, ...sharedPatterns]
643
- })
644
- );
645
- const isIgnored = createIsIgnored(nuxt);
646
- nitroConfig.devStorage ??= {};
647
- nitroConfig.devStorage.root ??= {
648
- driver: "fs",
649
- readOnly: true,
650
- base: nitroConfig.rootDir,
651
- watchOptions: {
652
- ignored: [isIgnored]
653
- }
654
- };
655
- nitroConfig.devStorage.src ??= {
656
- driver: "fs",
657
- readOnly: true,
658
- base: nitroConfig.srcDir,
659
- watchOptions: {
660
- ignored: [isIgnored]
661
- }
662
- };
663
- await nuxt.callHook("nitro:config", nitroConfig);
664
- if (nitroConfig.static && nuxt.options.dev) {
665
- nitroConfig.routeRules ||= {};
666
- nitroConfig.routeRules["/**"] = defu(nitroConfig.routeRules["/**"], { prerender: true });
667
- }
668
- const excludedAlias = [/^@vue\/.*$/, "vue", /vue-router/, "vite/client", "#imports", "vue-demi", /^#app/, "~", "@", "~~", "@@"];
669
- const basePath = nitroConfig.typescript.tsConfig.compilerOptions?.baseUrl ? resolve(nuxt.options.buildDir, nitroConfig.typescript.tsConfig.compilerOptions?.baseUrl) : nuxt.options.buildDir;
670
- const aliases = nitroConfig.alias;
671
- const tsConfig = nitroConfig.typescript.tsConfig;
672
- tsConfig.compilerOptions ||= {};
673
- tsConfig.compilerOptions.paths ||= {};
674
- for (const _alias in aliases) {
675
- const alias = _alias;
676
- if (excludedAlias.some((pattern) => typeof pattern === "string" ? alias === pattern : pattern.test(alias))) {
677
- continue;
678
- }
679
- if (alias in tsConfig.compilerOptions.paths) {
680
- continue;
681
- }
682
- const absolutePath = resolve(basePath, aliases[alias]);
683
- const isDirectory = aliases[alias].endsWith("/") || await promises.stat(absolutePath).then((r) => r.isDirectory()).catch(
684
- () => null
685
- /* file does not exist */
686
- );
687
- tsConfig.compilerOptions.paths[alias] = [absolutePath];
688
- if (isDirectory) {
689
- tsConfig.compilerOptions.paths[`${alias}/*`] = [`${absolutePath}/*`];
690
- }
691
- }
692
- const nitro = await createNitro(nitroConfig, {
693
- compatibilityDate: nuxt.options.compatibilityDate,
694
- dotenv: nuxt.options._loadOptions?.dotenv
695
- });
696
- const spaLoadingTemplateFilePath = await spaLoadingTemplatePath(nuxt);
697
- nuxt.hook("builder:watch", async (_event, relativePath) => {
698
- const path = resolve(nuxt.options.srcDir, relativePath);
699
- if (path === spaLoadingTemplateFilePath) {
700
- await nitro.hooks.callHook("rollup:reload");
701
- }
702
- });
703
- const cacheDir = resolve(nuxt.options.buildDir, "cache/nitro/prerender");
704
- const cacheDriverPath = join(distDir, "runtime/utils/cache-driver.js");
705
- await promises.rm(cacheDir, { recursive: true, force: true }).catch(() => {
706
- });
707
- nitro.options._config.storage = defu(nitro.options._config.storage, {
708
- "internal:nuxt:prerender": {
709
- // TODO: resolve upstream where file URLs are not being resolved/inlined correctly
710
- driver: isWindows ? pathToFileURL(cacheDriverPath).href : cacheDriverPath,
711
- base: cacheDir
712
- }
713
- });
714
- nuxt._nitro = nitro;
715
- await nuxt.callHook("nitro:init", nitro);
716
- nitro.vfs = nuxt.vfs = nitro.vfs || nuxt.vfs || {};
717
- nuxt.hook("close", () => nitro.hooks.callHook("close"));
718
- nitro.hooks.hook("prerender:routes", (routes) => {
719
- return nuxt.callHook("prerender:routes", { routes });
720
- });
721
- if (nuxt.options.vue.runtimeCompiler) {
722
- addVitePlugin({
723
- name: "nuxt:vue:runtime-compiler",
724
- applyToEnvironment: (environment) => environment.name === "client",
725
- enforce: "pre",
726
- resolveId(id, importer) {
727
- if (id === "vue") {
728
- return this.resolve("vue/dist/vue.esm-bundler", importer, { skipSelf: true });
729
- }
730
- }
731
- });
732
- for (const hook of ["webpack:config", "rspack:config"]) {
733
- nuxt.hook(hook, (configuration) => {
734
- const clientConfig = configuration.find((config) => config.name === "client");
735
- if (!clientConfig.resolve) {
736
- clientConfig.resolve.alias = {};
737
- }
738
- if (Array.isArray(clientConfig.resolve.alias)) {
739
- clientConfig.resolve.alias.push({
740
- name: "vue",
741
- alias: "vue/dist/vue.esm-bundler"
742
- });
743
- } else {
744
- clientConfig.resolve.alias.vue = "vue/dist/vue.esm-bundler";
745
- }
746
- });
747
- }
748
- }
749
- const devMiddlewareHandler = dynamicEventHandler();
750
- nitro.options.devHandlers.unshift({ handler: devMiddlewareHandler });
751
- nitro.options.devHandlers.push(...nuxt.options.devServerHandlers);
752
- nitro.options.handlers.unshift({
753
- route: "/__nuxt_error",
754
- lazy: true,
755
- handler: resolve(distDir, "runtime/handlers/renderer")
756
- });
757
- if (nuxt.options.experimental.chromeDevtoolsProjectSettings) {
758
- const cacheDir2 = resolve(nuxt.options.rootDir, "node_modules/.cache/nuxt");
759
- let projectConfiguration = await readFile(join(cacheDir2, "chrome-workspace.json"), "utf-8").then((r) => JSON.parse(r)).catch(() => null);
760
- if (!projectConfiguration) {
761
- projectConfiguration = { uuid: randomUUID() };
762
- await mkdir(cacheDir2, { recursive: true });
763
- await writeFile(join(cacheDir2, "chrome-workspace.json"), JSON.stringify(projectConfiguration), "utf-8");
764
- }
765
- nitro.options.devHandlers.push({
766
- route: "/.well-known/appspecific/com.chrome.devtools.json",
767
- handler: defineEventHandler(() => ({
768
- workspace: {
769
- ...projectConfiguration,
770
- root: nuxt.options.rootDir
771
- }
772
- }))
773
- });
774
- }
775
- if (!nuxt.options.dev && nuxt.options.experimental.noVueServer) {
776
- nitro.hooks.hook("rollup:before", (nitro2) => {
777
- if (nitro2.options.preset === "nitro-prerender") {
778
- nitro2.options.errorHandler = resolve(distDir, "runtime/handlers/error");
779
- return;
780
- }
781
- const nuxtErrorHandler = nitro2.options.handlers.findIndex((h) => h.route === "/__nuxt_error");
782
- if (nuxtErrorHandler >= 0) {
783
- nitro2.options.handlers.splice(nuxtErrorHandler, 1);
784
- }
785
- nitro2.options.renderer = void 0;
786
- });
787
- }
788
- nitro.hooks.hook("types:extend", (types) => {
789
- types.tsConfig ||= {};
790
- const rootDirGlob = relativeWithDot(nuxt.options.buildDir, join(nuxt.options.rootDir, "**/*"));
791
- types.tsConfig.include = types.tsConfig.include?.filter((i) => i !== rootDirGlob);
792
- });
793
- nuxt.hook("prepare:types", async (opts) => {
794
- if (!nuxt.options.dev) {
795
- await scanHandlers(nitro);
796
- await writeTypes(nitro);
797
- }
798
- opts.tsConfig.exclude ||= [];
799
- opts.tsConfig.exclude.push(relative(nuxt.options.buildDir, resolve(nuxt.options.rootDir, nitro.options.output.dir)));
800
- opts.tsConfig.exclude.push(relative(nuxt.options.buildDir, resolve(nuxt.options.rootDir, nuxt.options.serverDir)));
801
- opts.references.push({ path: resolve(nuxt.options.buildDir, "types/nitro.d.ts") });
802
- opts.sharedTsConfig.compilerOptions ||= {};
803
- opts.sharedTsConfig.compilerOptions.paths ||= {};
804
- for (const key in nuxt.options.alias) {
805
- if (nitro.options.alias[key] && nitro.options.alias[key] === nuxt.options.alias[key]) {
806
- const dirKey = join(key, "*");
807
- if (opts.tsConfig.compilerOptions?.paths[key]) {
808
- opts.sharedTsConfig.compilerOptions.paths[key] = opts.tsConfig.compilerOptions.paths[key];
809
- }
810
- if (opts.tsConfig.compilerOptions?.paths[dirKey]) {
811
- opts.sharedTsConfig.compilerOptions.paths[dirKey] = opts.tsConfig.compilerOptions.paths[dirKey];
812
- }
813
- }
814
- }
815
- });
816
- if (nitro.options.static) {
817
- nitro.hooks.hook("prerender:routes", (routes) => {
818
- for (const route of ["/200.html", "/404.html"]) {
819
- routes.add(route);
820
- }
821
- if (!nuxt.options.ssr) {
822
- routes.add("/index.html");
823
- }
824
- });
825
- }
826
- if (!nuxt.options.dev) {
827
- nitro.hooks.hook("rollup:before", async (nitro2) => {
828
- await copyPublicAssets(nitro2);
829
- await nuxt.callHook("nitro:build:public-assets", nitro2);
830
- });
831
- }
832
- async function symlinkDist() {
833
- if (nitro.options.static) {
834
- const distDir2 = resolve(nuxt.options.rootDir, "dist");
835
- if (!existsSync(distDir2)) {
836
- await promises.symlink(nitro.options.output.publicDir, distDir2, "junction").catch(() => {
837
- });
838
- }
839
- }
840
- }
841
- nuxt.hook("build:done", async () => {
842
- await nuxt.callHook("nitro:build:before", nitro);
843
- await prepare(nitro);
844
- if (nuxt.options.dev) {
845
- return build(nitro);
846
- }
847
- await prerender(nitro);
848
- logger.restoreAll();
849
- await build(nitro);
850
- logger.wrapAll();
851
- await symlinkDist();
852
- });
853
- if (nuxt.options.dev) {
854
- for (const builder of ["webpack", "rspack"]) {
855
- nuxt.hook(`${builder}:compile`, ({ name, compiler }) => {
856
- if (name === "server") {
857
- const memfs = compiler.outputFileSystem;
858
- nitro.options.virtual["#build/dist/server/server.mjs"] = () => memfs.readFileSync(join(nuxt.options.buildDir, "dist/server/server.mjs"), "utf-8");
859
- }
860
- });
861
- nuxt.hook(`${builder}:compiled`, () => {
862
- nuxt.server.reload();
863
- });
864
- }
865
- nuxt.hook("vite:compiled", () => {
866
- nuxt.server.reload();
867
- });
868
- nuxt.hook("server:devHandler", (h) => {
869
- devMiddlewareHandler.set(h);
870
- });
871
- nuxt.server = createDevServer(nitro);
872
- const waitUntilCompile = new Promise((resolve2) => nitro.hooks.hook("compiled", () => resolve2()));
873
- nuxt.hook("build:done", () => waitUntilCompile);
874
- }
429
+ }
430
+ });
431
+ if (nuxt.options.experimental.payloadExtraction) {
432
+ if (nuxt.options.dev) nuxt.hook("nitro:config", (nitroConfig$1) => {
433
+ nitroConfig$1.prerender ||= {};
434
+ nitroConfig$1.prerender.routes ||= [];
435
+ nitroConfig$1.routeRules ||= {};
436
+ for (const route of nitroConfig$1.prerender.routes) {
437
+ if (!route) continue;
438
+ nitroConfig$1.routeRules[route] = defu(nitroConfig$1.routeRules[route], { prerender: true });
439
+ }
440
+ });
441
+ nuxt.hook("nitro:init", (nitro$1) => {
442
+ nitro$1.hooks.hook("build:before", (nitro$2) => {
443
+ for (const [route, value] of Object.entries(nitro$2.options.routeRules)) if (!route.endsWith("*") && !route.endsWith("/_payload.json")) {
444
+ if (value.isr || value.cache || value.prerender && nuxt.options.dev) {
445
+ const payloadKey = route + "/_payload.json";
446
+ const defaults = {};
447
+ for (const key of [
448
+ "isr",
449
+ "cache",
450
+ ...nuxt.options.dev ? ["prerender"] : []
451
+ ]) if (key in value) defaults[key] = value[key];
452
+ nitro$2.options.routeRules[payloadKey] = defu(nitro$2.options.routeRules[payloadKey], defaults);
453
+ }
454
+ }
455
+ });
456
+ });
457
+ }
458
+ if (nuxt.options.experimental.appManifest) {
459
+ const buildId = nuxt.options.runtimeConfig.app.buildId ||= nuxt.options.buildId;
460
+ const buildTimestamp = Date.now();
461
+ const manifestPrefix = joinURL(nuxt.options.app.buildAssetsDir, "builds");
462
+ const tempDir = join(nuxt.options.buildDir, "manifest");
463
+ nitroConfig.prerender ||= {};
464
+ nitroConfig.prerender.ignore ||= [];
465
+ nitroConfig.prerender.ignore.push(joinURL(nuxt.options.app.baseURL, manifestPrefix));
466
+ nitroConfig.publicAssets.unshift({
467
+ dir: join(tempDir, "meta"),
468
+ maxAge: 31536e3,
469
+ baseURL: joinURL(manifestPrefix, "meta")
470
+ }, {
471
+ dir: tempDir,
472
+ maxAge: 1,
473
+ baseURL: manifestPrefix
474
+ });
475
+ nuxt.options.alias["#app-manifest"] = join(tempDir, `meta/${buildId}.json`);
476
+ if (!nuxt.options.dev) nuxt.hook("build:before", async () => {
477
+ await promises.mkdir(join(tempDir, "meta"), { recursive: true });
478
+ await promises.writeFile(join(tempDir, `meta/${buildId}.json`), JSON.stringify({}));
479
+ });
480
+ nuxt.hook("nitro:config", (config) => {
481
+ config.alias ||= {};
482
+ config.alias["#app-manifest"] = join(tempDir, `meta/${buildId}.json`);
483
+ });
484
+ nuxt.hook("nitro:init", (nitro$1) => {
485
+ nitro$1.hooks.hook("rollup:before", async (nitro$2) => {
486
+ const prerenderedRoutes = /* @__PURE__ */ new Set();
487
+ const routeRulesMatcher = getRouteRulesRouter();
488
+ if (nitro$2._prerenderedRoutes?.length) {
489
+ const payloadSuffix = nuxt.options.experimental.renderJsonPayloads ? "/_payload.json" : "/_payload.js";
490
+ for (const route of nitro$2._prerenderedRoutes) if (!route.error && route.route.endsWith(payloadSuffix)) {
491
+ const url = route.route.slice(0, -payloadSuffix.length) || "/";
492
+ if (!defu({}, ...findAllRoutes(routeRulesMatcher, void 0, url).reverse()).prerender) prerenderedRoutes.add(url);
493
+ }
494
+ }
495
+ const manifest = {
496
+ id: buildId,
497
+ timestamp: buildTimestamp,
498
+ prerendered: nuxt.options.dev ? [] : [...prerenderedRoutes]
499
+ };
500
+ await promises.mkdir(join(tempDir, "meta"), { recursive: true });
501
+ await promises.writeFile(join(tempDir, "latest.json"), JSON.stringify({
502
+ id: buildId,
503
+ timestamp: buildTimestamp
504
+ }));
505
+ await promises.writeFile(join(tempDir, `meta/${buildId}.json`), JSON.stringify(manifest));
506
+ });
507
+ });
508
+ }
509
+ if (!nuxt.options.experimental.appManifest) nuxt.options.alias["#app-manifest"] = mockProxy;
510
+ const FORWARD_SLASH_RE = /\//g;
511
+ if (!nuxt.options.ssr) {
512
+ nitroConfig.virtual["#build/dist/server/server.mjs"] = "export default () => {}";
513
+ if (process.platform === "win32") nitroConfig.virtual["#build/dist/server/server.mjs".replace(FORWARD_SLASH_RE, "\\")] = "export default () => {}";
514
+ }
515
+ if (nuxt.options.dev) {
516
+ nitroConfig.virtual["#build/dist/server/styles.mjs"] = "export default {}";
517
+ if (process.platform === "win32") nitroConfig.virtual["#build/dist/server/styles.mjs".replace(FORWARD_SLASH_RE, "\\")] = "export default {}";
518
+ }
519
+ nitroConfig.rollupConfig.plugins = await nitroConfig.rollupConfig.plugins || [];
520
+ nitroConfig.rollupConfig.plugins = toArray(nitroConfig.rollupConfig.plugins);
521
+ const sharedDir = withTrailingSlash(resolve(nuxt.options.rootDir, nuxt.options.dir.shared));
522
+ const relativeSharedDir = withTrailingSlash(relative(nuxt.options.rootDir, resolve(nuxt.options.rootDir, nuxt.options.dir.shared)));
523
+ const sharedPatterns = [
524
+ /^#shared\//,
525
+ /* @__PURE__ */ new RegExp("^" + escapeRE(sharedDir)),
526
+ /* @__PURE__ */ new RegExp("^" + escapeRE(relativeSharedDir))
527
+ ];
528
+ nitroConfig.rollupConfig.plugins.push(ImpoundPlugin.rollup({
529
+ cwd: nuxt.options.rootDir,
530
+ include: sharedPatterns,
531
+ patterns: createImportProtectionPatterns(nuxt, { context: "shared" })
532
+ }), ImpoundPlugin.rollup({
533
+ cwd: nuxt.options.rootDir,
534
+ patterns: createImportProtectionPatterns(nuxt, { context: "nitro-app" }),
535
+ exclude: [/node_modules[\\/]nitro(?:pack)?(?:-nightly)?[\\/]|(packages|@nuxt)[\\/]nitro-server(?:-nightly)?[\\/](src|dist)[\\/]runtime[\\/]/, ...sharedPatterns]
536
+ }));
537
+ const isIgnored = createIsIgnored(nuxt);
538
+ nitroConfig.devStorage ??= {};
539
+ nitroConfig.devStorage.root ??= {
540
+ driver: "fs",
541
+ readOnly: true,
542
+ base: nitroConfig.rootDir,
543
+ watchOptions: { ignored: [isIgnored] }
544
+ };
545
+ nitroConfig.devStorage.src ??= {
546
+ driver: "fs",
547
+ readOnly: true,
548
+ base: nitroConfig.srcDir,
549
+ watchOptions: { ignored: [isIgnored] }
550
+ };
551
+ nuxt.options.typescript.hoist.push("nitro/types", "nitro/runtime", "nitropack/types", "nitropack/runtime", "nitropack", "defu", "h3", "consola", "ofetch", "crossws");
552
+ await nuxt.callHook("nitro:config", nitroConfig);
553
+ if (nitroConfig.static && nuxt.options.dev) {
554
+ nitroConfig.routeRules ||= {};
555
+ nitroConfig.routeRules["/**"] = defu(nitroConfig.routeRules["/**"], { prerender: true });
556
+ }
557
+ const excludedAlias = [
558
+ /^@vue\/.*$/,
559
+ "vue",
560
+ /vue-router/,
561
+ "vite/client",
562
+ "#imports",
563
+ "vue-demi",
564
+ /^#app/,
565
+ "~",
566
+ "@",
567
+ "~~",
568
+ "@@"
569
+ ];
570
+ const basePath = nitroConfig.typescript.tsConfig.compilerOptions?.baseUrl ? resolve(nuxt.options.buildDir, nitroConfig.typescript.tsConfig.compilerOptions?.baseUrl) : nuxt.options.buildDir;
571
+ const aliases = nitroConfig.alias;
572
+ const tsConfig = nitroConfig.typescript.tsConfig;
573
+ tsConfig.compilerOptions ||= {};
574
+ tsConfig.compilerOptions.paths ||= {};
575
+ for (const _alias in aliases) {
576
+ const alias = _alias;
577
+ if (excludedAlias.some((pattern) => typeof pattern === "string" ? alias === pattern : pattern.test(alias))) continue;
578
+ if (alias in tsConfig.compilerOptions.paths) continue;
579
+ const absolutePath = resolve(basePath, aliases[alias]);
580
+ const isDirectory = aliases[alias].endsWith("/") || await promises.stat(absolutePath).then((r) => r.isDirectory()).catch(() => null);
581
+ tsConfig.compilerOptions.paths[alias] = [absolutePath];
582
+ if (isDirectory) tsConfig.compilerOptions.paths[`${alias}/*`] = [`${absolutePath}/*`];
583
+ }
584
+ const nitro = await createNitro(nitroConfig, {
585
+ compatibilityDate: nuxt.options.compatibilityDate,
586
+ dotenv: nuxt.options._loadOptions?.dotenv
587
+ });
588
+ if (nuxt.options.experimental.serverAppConfig === false && nitro.options.imports) {
589
+ nitro.options.imports.presets ||= [];
590
+ nitro.options.imports.presets = nitro.options.imports.presets.map((preset) => typeof preset === "string" || !("imports" in preset) ? preset : {
591
+ ...preset,
592
+ imports: preset.imports.filter((i) => i !== "useAppConfig")
593
+ });
594
+ }
595
+ if (nitro.options.static && nuxt.options.experimental.payloadExtraction === void 0) {
596
+ logger.warn("Using experimental payload extraction for full-static output. You can opt-out by setting `experimental.payloadExtraction` to `false`.");
597
+ nuxt.options.experimental.payloadExtraction = true;
598
+ }
599
+ const spaLoadingTemplateFilePath = await spaLoadingTemplatePath(nuxt);
600
+ nuxt.hook("builder:watch", async (_event, relativePath) => {
601
+ if (resolve(nuxt.options.srcDir, relativePath) === spaLoadingTemplateFilePath) await nitro.hooks.callHook("rollup:reload");
602
+ });
603
+ const cacheDir = resolve(nuxt.options.buildDir, "cache/nitro/prerender");
604
+ const cacheDriverPath = join(distDir, "runtime/utils/cache-driver.js");
605
+ await promises.rm(cacheDir, {
606
+ recursive: true,
607
+ force: true
608
+ }).catch(() => {});
609
+ nitro.options._config.storage = defu(nitro.options._config.storage, { "internal:nuxt:prerender": {
610
+ driver: isWindows ? pathToFileURL(cacheDriverPath).href : cacheDriverPath,
611
+ base: cacheDir
612
+ } });
613
+ nuxt._nitro = nitro;
614
+ await nuxt.callHook("nitro:init", nitro);
615
+ nitro.vfs = nuxt.vfs = nitro.vfs || nuxt.vfs || {};
616
+ nuxt.hook("close", () => nitro.hooks.callHook("close"));
617
+ nitro.hooks.hook("prerender:routes", (routes) => {
618
+ return nuxt.callHook("prerender:routes", { routes });
619
+ });
620
+ if (nuxt.options.vue.runtimeCompiler) {
621
+ addVitePlugin({
622
+ name: "nuxt:vue:runtime-compiler",
623
+ applyToEnvironment: (environment) => environment.name === "client",
624
+ enforce: "pre",
625
+ resolveId(id, importer) {
626
+ if (id === "vue") return this.resolve("vue/dist/vue.esm-bundler", importer, { skipSelf: true });
627
+ }
628
+ });
629
+ for (const hook of ["webpack:config", "rspack:config"]) nuxt.hook(hook, (configuration) => {
630
+ const clientConfig = configuration.find((config) => config.name === "client");
631
+ if (!clientConfig.resolve) clientConfig.resolve.alias = {};
632
+ if (Array.isArray(clientConfig.resolve.alias)) clientConfig.resolve.alias.push({
633
+ name: "vue",
634
+ alias: "vue/dist/vue.esm-bundler"
635
+ });
636
+ else clientConfig.resolve.alias.vue = "vue/dist/vue.esm-bundler";
637
+ });
638
+ }
639
+ const devMiddlewareHandler = dynamicEventHandler();
640
+ nitro.options.devHandlers.unshift({ handler: devMiddlewareHandler });
641
+ nitro.options.devHandlers.push(...nuxt.options.devServerHandlers);
642
+ nitro.options.handlers.unshift({
643
+ route: "/__nuxt_error",
644
+ lazy: true,
645
+ handler: resolve(distDir, "runtime/handlers/renderer")
646
+ });
647
+ if (nuxt.options.experimental.chromeDevtoolsProjectSettings) {
648
+ const cacheDir$1 = resolve(nuxt.options.rootDir, "node_modules/.cache/nuxt");
649
+ let projectConfiguration = await readFile(join(cacheDir$1, "chrome-workspace.json"), "utf-8").then((r) => JSON.parse(r)).catch(() => null);
650
+ if (!projectConfiguration) {
651
+ projectConfiguration = { uuid: randomUUID() };
652
+ await mkdir(cacheDir$1, { recursive: true });
653
+ await writeFile(join(cacheDir$1, "chrome-workspace.json"), JSON.stringify(projectConfiguration), "utf-8");
654
+ }
655
+ nitro.options.devHandlers.push({
656
+ route: "/.well-known/appspecific/com.chrome.devtools.json",
657
+ handler: defineEventHandler(() => ({ workspace: {
658
+ ...projectConfiguration,
659
+ root: nuxt.options.rootDir
660
+ } }))
661
+ });
662
+ }
663
+ if (!nuxt.options.dev && nuxt.options.experimental.noVueServer) nitro.hooks.hook("rollup:before", (nitro$1) => {
664
+ if (nitro$1.options.preset === "nitro-prerender") {
665
+ nitro$1.options.errorHandler = resolve(distDir, "runtime/handlers/error");
666
+ return;
667
+ }
668
+ const nuxtErrorHandler = nitro$1.options.handlers.findIndex((h) => h.route === "/__nuxt_error");
669
+ if (nuxtErrorHandler >= 0) nitro$1.options.handlers.splice(nuxtErrorHandler, 1);
670
+ nitro$1.options.renderer = void 0;
671
+ });
672
+ nitro.hooks.hook("types:extend", (types) => {
673
+ types.tsConfig ||= {};
674
+ const rootDirGlob = relativeWithDot(nuxt.options.buildDir, join(nuxt.options.rootDir, "**/*"));
675
+ types.tsConfig.include = types.tsConfig.include?.filter((i) => i !== rootDirGlob);
676
+ });
677
+ nuxt.hook("prepare:types", async (opts) => {
678
+ if (!nuxt.options.dev) {
679
+ await scanHandlers(nitro);
680
+ await writeTypes(nitro);
681
+ }
682
+ opts.tsConfig.exclude ||= [];
683
+ opts.tsConfig.exclude.push(relative(nuxt.options.buildDir, resolve(nuxt.options.rootDir, nitro.options.output.dir)));
684
+ opts.tsConfig.exclude.push(relative(nuxt.options.buildDir, resolve(nuxt.options.rootDir, nuxt.options.serverDir)));
685
+ opts.references.push({ path: resolve(nuxt.options.buildDir, "types/nitro.d.ts") });
686
+ opts.sharedTsConfig.compilerOptions ||= {};
687
+ opts.sharedTsConfig.compilerOptions.paths ||= {};
688
+ for (const key in nuxt.options.alias) if (nitro.options.alias[key] && nitro.options.alias[key] === nuxt.options.alias[key]) {
689
+ const dirKey = join(key, "*");
690
+ if (opts.tsConfig.compilerOptions?.paths[key]) opts.sharedTsConfig.compilerOptions.paths[key] = opts.tsConfig.compilerOptions.paths[key];
691
+ if (opts.tsConfig.compilerOptions?.paths[dirKey]) opts.sharedTsConfig.compilerOptions.paths[dirKey] = opts.tsConfig.compilerOptions.paths[dirKey];
692
+ }
693
+ });
694
+ if (nitro.options.static) nitro.hooks.hook("prerender:routes", (routes) => {
695
+ for (const route of ["/200.html", "/404.html"]) routes.add(route);
696
+ if (!nuxt.options.ssr) routes.add("/index.html");
697
+ });
698
+ if (!nuxt.options.dev) nitro.hooks.hook("rollup:before", async (nitro$1) => {
699
+ await copyPublicAssets(nitro$1);
700
+ await nuxt.callHook("nitro:build:public-assets", nitro$1);
701
+ });
702
+ async function symlinkDist() {
703
+ if (nitro.options.static) {
704
+ const distDir$1 = resolve(nuxt.options.rootDir, "dist");
705
+ if (!existsSync(distDir$1)) await promises.symlink(nitro.options.output.publicDir, distDir$1, "junction").catch(() => {});
706
+ }
707
+ }
708
+ nuxt.hook("build:done", async () => {
709
+ await nuxt.callHook("nitro:build:before", nitro);
710
+ await prepare(nitro);
711
+ if (nuxt.options.dev) return build(nitro);
712
+ await prerender(nitro);
713
+ logger.restoreAll();
714
+ await build(nitro);
715
+ logger.wrapAll();
716
+ await symlinkDist();
717
+ });
718
+ if (nuxt.options.dev) {
719
+ for (const builder of ["webpack", "rspack"]) {
720
+ nuxt.hook(`${builder}:compile`, ({ name, compiler }) => {
721
+ if (name === "server") {
722
+ const memfs = compiler.outputFileSystem;
723
+ nitro.options.virtual["#build/dist/server/server.mjs"] = () => memfs.readFileSync(join(nuxt.options.buildDir, "dist/server/server.mjs"), "utf-8");
724
+ }
725
+ });
726
+ nuxt.hook(`${builder}:compiled`, () => {
727
+ nuxt.server.reload();
728
+ });
729
+ }
730
+ nuxt.hook("vite:compiled", () => {
731
+ nuxt.server.reload();
732
+ });
733
+ nuxt.hook("server:devHandler", (h) => {
734
+ devMiddlewareHandler.set(h);
735
+ });
736
+ nuxt.server = createDevServer(nitro);
737
+ const waitUntilCompile = new Promise((resolve$1) => nitro.hooks.hook("compiled", () => resolve$1()));
738
+ nuxt.hook("build:done", () => waitUntilCompile);
739
+ }
875
740
  }
876
741
  const RELATIVE_RE = /^([^.])/;
877
742
  function relativeWithDot(from, to) {
878
- return relative(from, to).replace(RELATIVE_RE, "./$1") || ".";
743
+ return relative(from, to).replace(RELATIVE_RE, "./$1") || ".";
879
744
  }
880
745
  async function spaLoadingTemplatePath(nuxt) {
881
- if (typeof nuxt.options.spaLoadingTemplate === "string") {
882
- return resolve(nuxt.options.srcDir, nuxt.options.spaLoadingTemplate);
883
- }
884
- const possiblePaths = nuxt.options._layers.map((layer) => resolve(layer.config.srcDir, layer.config.dir?.app || "app", "spa-loading-template.html"));
885
- return await findPath(possiblePaths) ?? resolve(nuxt.options.srcDir, nuxt.options.dir?.app || "app", "spa-loading-template.html");
746
+ if (typeof nuxt.options.spaLoadingTemplate === "string") return resolve(nuxt.options.srcDir, nuxt.options.spaLoadingTemplate);
747
+ return await findPath(nuxt.options._layers.map((layer) => resolve(layer.config.srcDir, layer.config.dir?.app || "app", "spa-loading-template.html"))) ?? resolve(nuxt.options.srcDir, nuxt.options.dir?.app || "app", "spa-loading-template.html");
886
748
  }
887
749
  async function spaLoadingTemplate(nuxt) {
888
- if (nuxt.options.spaLoadingTemplate === false) {
889
- return "";
890
- }
891
- const spaLoadingTemplate2 = await spaLoadingTemplatePath(nuxt);
892
- try {
893
- if (existsSync(spaLoadingTemplate2)) {
894
- return readFileSync(spaLoadingTemplate2, "utf-8").trim();
895
- }
896
- } catch {
897
- }
898
- if (nuxt.options.spaLoadingTemplate === true) {
899
- return template();
900
- }
901
- if (nuxt.options.spaLoadingTemplate) {
902
- logger.warn(`Could not load custom \`spaLoadingTemplate\` path as it does not exist: \`${nuxt.options.spaLoadingTemplate}\`.`);
903
- }
904
- return "";
750
+ if (nuxt.options.spaLoadingTemplate === false) return "";
751
+ const spaLoadingTemplate$1 = await spaLoadingTemplatePath(nuxt);
752
+ try {
753
+ if (existsSync(spaLoadingTemplate$1)) return readFileSync(spaLoadingTemplate$1, "utf-8").trim();
754
+ } catch {}
755
+ if (nuxt.options.spaLoadingTemplate === true) return template();
756
+ if (nuxt.options.spaLoadingTemplate) logger.warn(`Could not load custom \`spaLoadingTemplate\` path as it does not exist: \`${nuxt.options.spaLoadingTemplate}\`.`);
757
+ return "";
905
758
  }
906
759
 
907
- export { bundle };
760
+ //#endregion
761
+ export { bundle };