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