@nuxt/nitro-server 4.2.2 → 4.3.0

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