@nuxt/vite-builder-nightly 4.3.0-29465977.c4f46c64 → 4.3.0-29466372.7f503428

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.
package/dist/index.mjs CHANGED
@@ -1,2505 +1,2126 @@
1
- import fs, { existsSync, readFileSync } from 'node:fs';
2
- import { performance } from 'node:perf_hooks';
3
- import * as vite from 'vite';
4
- import { isCSSRequest, createLogger, mergeConfig, createBuilder, createServer } from 'vite';
5
- import { normalize, join, relative, dirname, basename, resolve, isAbsolute } from 'pathe';
6
- import { tryUseNuxt, useNitro, logger, useNuxt, resolvePath, getLayerDirectories, resolveAlias, directoryToURL, tryImportModule, createIsIgnored } from '@nuxt/kit';
7
- import { findStaticImports, parseNodeModulePath, sanitizeFilePath } from 'mlly';
8
- import viteJsxPlugin from '@vitejs/plugin-vue-jsx';
9
- import vuePlugin from '@vitejs/plugin-vue';
10
- import { parseURL, parseQuery, joinURL, getQuery, withLeadingSlash, withTrailingSlash, withoutLeadingSlash, withoutBase } from 'ufo';
11
- import { filename as filename$1 } from 'pathe/utils';
12
- import { resolveModulePath } from 'exsolve';
13
- import { pathToFileURL, fileURLToPath } from 'node:url';
14
- import MagicString from 'magic-string';
15
- import process from 'node:process';
16
- import { unlink, mkdir, writeFile, rm, readFile } from 'node:fs/promises';
17
- import net from 'node:net';
18
- import os from 'node:os';
19
- import { Buffer } from 'node:buffer';
20
- import { createError, defineLazyEventHandler, defineEventHandler, handleCors, setHeader } from 'h3';
21
- import { ViteNodeServer } from 'vite-node/server';
22
- import { normalizeViteManifest, precomputeDependencies } from 'vue-bundle-renderer';
23
- import { provider, hasTTY, isCI } from 'std-env';
24
- import { colorize } from 'consola/utils';
25
- import escapeStringRegexp from 'escape-string-regexp';
26
- import { transform } from 'esbuild';
27
- import { defu } from 'defu';
28
- import { getPort } from 'get-port-please';
29
- import { resolveTSConfig, readTSConfig } from 'pkg-types';
30
- import { serialize } from 'seroval';
31
- import { isBuiltin } from 'node:module';
32
- import { createJiti } from 'jiti';
33
- import { genImport, genArrayFromRaw, genObjectFromRawEntries } from 'knitwork';
34
- import replacePlugin from '@rollup/plugin-replace';
35
- import { defineEnv } from 'unenv';
36
- import { runtimeDependencies } from 'nuxt/meta';
1
+ import { isBuiltin } from "node:module";
2
+ import fs, { existsSync, readFileSync } from "node:fs";
3
+ import { performance } from "node:perf_hooks";
4
+ import * as vite from "vite";
5
+ import { createBuilder, createLogger, createServer, isCSSRequest, mergeConfig } from "vite";
6
+ import { basename, dirname, isAbsolute, join, normalize, relative, resolve } from "pathe";
7
+ import { createIsIgnored, directoryToURL, getLayerDirectories, logger, resolveAlias, resolvePath, tryImportModule, tryUseNuxt, useNitro, useNuxt } from "@nuxt/kit";
8
+ import { findStaticImports, parseNodeModulePath, sanitizeFilePath } from "mlly";
9
+ import viteJsxPlugin from "@vitejs/plugin-vue-jsx";
10
+ import vuePlugin from "@vitejs/plugin-vue";
11
+ import { getQuery, joinURL, parseQuery, parseURL, withLeadingSlash, withTrailingSlash, withoutBase, withoutLeadingSlash } from "ufo";
12
+ import { filename } from "pathe/utils";
13
+ import { resolveModulePath } from "exsolve";
14
+ import { fileURLToPath, pathToFileURL } from "node:url";
15
+ import MagicString from "magic-string";
16
+ import process from "node:process";
17
+ import { mkdir, readFile, rm, unlink, writeFile } from "node:fs/promises";
18
+ import net from "node:net";
19
+ import os from "node:os";
20
+ import { Buffer } from "node:buffer";
21
+ import { createError, defineEventHandler, defineLazyEventHandler, handleCors, setHeader } from "h3";
22
+ import { ViteNodeServer } from "vite-node/server";
23
+ import { normalizeViteManifest, precomputeDependencies } from "vue-bundle-renderer";
24
+ import { hasTTY, isCI, provider } from "std-env";
25
+ import { colorize } from "consola/utils";
26
+ import escapeStringRegexp from "escape-string-regexp";
27
+ import { transform } from "esbuild";
28
+ import { defu } from "defu";
29
+ import { getPort } from "get-port-please";
30
+ import { readTSConfig, resolveTSConfig } from "pkg-types";
31
+ import { serialize } from "seroval";
32
+ import { createJiti } from "jiti";
33
+ import { genArrayFromRaw, genImport, genObjectFromRawEntries } from "knitwork";
34
+ import replacePlugin from "@rollup/plugin-replace";
35
+ import { defineEnv } from "unenv";
36
+ import { runtimeDependencies } from "nuxt/meta";
37
37
 
38
+ //#region ../nuxt/src/core/utils/plugins.ts
38
39
  function isVue(id, opts = {}) {
39
- const { search } = parseURL(decodeURIComponent(pathToFileURL(id).href));
40
- if (id.endsWith(".vue") && !search) {
41
- return true;
42
- }
43
- if (!search) {
44
- return false;
45
- }
46
- const query = parseQuery(search);
47
- if (query.nuxt_component) {
48
- return false;
49
- }
50
- if (query.macro && (search === "?macro=true" || !opts.type || opts.type.includes("script"))) {
51
- return true;
52
- }
53
- const type = "setup" in query ? "script" : query.type;
54
- if (!("vue" in query) || opts.type && !opts.type.includes(type)) {
55
- return false;
56
- }
57
- return true;
40
+ const { search } = parseURL(decodeURIComponent(pathToFileURL(id).href));
41
+ if (id.endsWith(".vue") && !search) return true;
42
+ if (!search) return false;
43
+ const query = parseQuery(search);
44
+ if (query.nuxt_component) return false;
45
+ if (query.macro && (search === "?macro=true" || !opts.type || opts.type.includes("script"))) return true;
46
+ const type = "setup" in query ? "script" : query.type;
47
+ if (!("vue" in query) || opts.type && !opts.type.includes(type)) return false;
48
+ return true;
58
49
  }
59
50
 
51
+ //#endregion
52
+ //#region src/utils/index.ts
60
53
  const IS_CSS_RE = /\.(?:css|scss|sass|postcss|pcss|less|stylus|styl)(?:\?[^.]+)?$/;
61
54
  function isCSS(file) {
62
- return IS_CSS_RE.test(file);
55
+ return IS_CSS_RE.test(file);
63
56
  }
57
+ /** @since 3.9.0 */
64
58
  function toArray(value) {
65
- return Array.isArray(value) ? value : [value];
59
+ return Array.isArray(value) ? value : [value];
66
60
  }
67
61
 
62
+ //#endregion
63
+ //#region src/plugins/dev-style-ssr.ts
68
64
  function DevStyleSSRPlugin(options) {
69
- return {
70
- name: "nuxt:dev-style-ssr",
71
- apply: "serve",
72
- enforce: "post",
73
- applyToEnvironment: (environment) => environment.name === "client",
74
- transform(code, id) {
75
- if (!isCSS(id) || !code.includes("import.meta.hot")) {
76
- return;
77
- }
78
- let moduleId = id;
79
- if (moduleId.startsWith(options.srcDir)) {
80
- moduleId = moduleId.slice(options.srcDir.length);
81
- }
82
- const selectors = [joinURL(options.buildAssetsURL, moduleId), joinURL(options.buildAssetsURL, "@fs", moduleId)];
83
- return code + selectors.map((selector) => `
84
- document.querySelectorAll(\`link[href="${selector}"]\`).forEach(i=>i.remove())`).join("");
85
- }
86
- };
65
+ return {
66
+ name: "nuxt:dev-style-ssr",
67
+ apply: "serve",
68
+ enforce: "post",
69
+ applyToEnvironment: (environment) => environment.name === "client",
70
+ transform(code, id) {
71
+ if (!isCSS(id) || !code.includes("import.meta.hot")) return;
72
+ let moduleId = id;
73
+ if (moduleId.startsWith(options.srcDir)) moduleId = moduleId.slice(options.srcDir.length);
74
+ return code + [joinURL(options.buildAssetsURL, moduleId), joinURL(options.buildAssetsURL, "@fs", moduleId)].map((selector) => `\ndocument.querySelectorAll(\`link[href="${selector}"]\`).forEach(i=>i.remove())`).join("");
75
+ }
76
+ };
87
77
  }
88
78
 
79
+ //#endregion
80
+ //#region src/plugins/runtime-paths.ts
89
81
  const VITE_ASSET_RE = /__VITE_ASSET__|__VITE_PUBLIC_ASSET__/;
90
82
  function RuntimePathsPlugin() {
91
- let sourcemap;
92
- return {
93
- name: "nuxt:runtime-paths-dep",
94
- enforce: "post",
95
- applyToEnvironment: (environment) => environment.name === "client",
96
- configResolved(config) {
97
- sourcemap = !!config.build.sourcemap;
98
- },
99
- transform(code, id) {
100
- const { pathname, search } = parseURL(decodeURIComponent(pathToFileURL(id).href));
101
- if (isCSS(pathname)) {
102
- return;
103
- }
104
- if (pathname.endsWith(".vue")) {
105
- if (search && parseQuery(search).type === "style") {
106
- return;
107
- }
108
- }
109
- if (VITE_ASSET_RE.test(code)) {
110
- const s = new MagicString(code);
111
- s.prepend('import "#internal/nuxt/paths";');
112
- return {
113
- code: s.toString(),
114
- map: sourcemap ? s.generateMap({ hires: true }) : void 0
115
- };
116
- }
117
- }
118
- };
83
+ let sourcemap;
84
+ return {
85
+ name: "nuxt:runtime-paths-dep",
86
+ enforce: "post",
87
+ applyToEnvironment: (environment) => environment.name === "client",
88
+ configResolved(config) {
89
+ sourcemap = !!config.build.sourcemap;
90
+ },
91
+ transform(code, id) {
92
+ const { pathname, search } = parseURL(decodeURIComponent(pathToFileURL(id).href));
93
+ if (isCSS(pathname)) return;
94
+ if (pathname.endsWith(".vue")) {
95
+ if (search && parseQuery(search).type === "style") return;
96
+ }
97
+ if (VITE_ASSET_RE.test(code)) {
98
+ const s = new MagicString(code);
99
+ s.prepend("import \"#internal/nuxt/paths\";");
100
+ return {
101
+ code: s.toString(),
102
+ map: sourcemap ? s.generateMap({ hires: true }) : void 0
103
+ };
104
+ }
105
+ }
106
+ };
119
107
  }
120
108
 
109
+ //#endregion
110
+ //#region src/utils/config.ts
121
111
  function resolveClientEntry(config) {
122
- const input = config.environments.client?.build.rollupOptions.input ?? config.build.rollupOptions.input;
123
- if (input) {
124
- if (typeof input === "string") {
125
- return input;
126
- }
127
- if (!Array.isArray(input) && input.entry) {
128
- return input.entry;
129
- }
130
- }
131
- throw new Error("No entry found in rollupOptions.input");
112
+ const input = config.environments.client?.build.rollupOptions.input ?? config.build.rollupOptions.input;
113
+ if (input) {
114
+ if (typeof input === "string") return input;
115
+ if (!Array.isArray(input) && input.entry) return input.entry;
116
+ }
117
+ throw new Error("No entry found in rollupOptions.input");
132
118
  }
133
119
  function resolveServerEntry(config) {
134
- const input = config.environments.ssr?.build.rollupOptions.input ?? config.build.rollupOptions.input;
135
- if (input) {
136
- if (typeof input === "string") {
137
- return input;
138
- }
139
- if (!Array.isArray(input) && input.server) {
140
- return input.server;
141
- }
142
- }
143
- throw new Error("No entry found in rollupOptions.input");
120
+ const input = config.environments.ssr?.build.rollupOptions.input ?? config.build.rollupOptions.input;
121
+ if (input) {
122
+ if (typeof input === "string") return input;
123
+ if (!Array.isArray(input) && input.server) return input.server;
124
+ }
125
+ throw new Error("No entry found in rollupOptions.input");
144
126
  }
145
127
 
128
+ //#endregion
129
+ //#region src/plugins/type-check.ts
146
130
  const QUERY_RE$2 = /\?.+$/;
147
131
  function TypeCheckPlugin(nuxt) {
148
- let entry;
149
- let sourcemap;
150
- return {
151
- name: "nuxt:type-check",
152
- applyToEnvironment: (environment) => environment.name === "client" && !environment.config.isProduction,
153
- apply: () => {
154
- return !nuxt.options.test && nuxt.options.typescript.typeCheck === true;
155
- },
156
- configResolved(config) {
157
- try {
158
- entry = resolveClientEntry(config);
159
- sourcemap = !!config.build.sourcemap;
160
- } catch {
161
- console.debug("[nuxt:type-check] Could not resolve client entry, type checking will not be applied.");
162
- }
163
- },
164
- transform(code, id) {
165
- if (id.replace(QUERY_RE$2, "") !== entry) {
166
- return;
167
- }
168
- const s = new MagicString(code);
169
- s.prepend('import "/@vite-plugin-checker-runtime-entry";\n');
170
- return {
171
- code: s.toString(),
172
- map: sourcemap ? s.generateMap({ hires: true }) : void 0
173
- };
174
- }
175
- };
132
+ let entry;
133
+ let sourcemap;
134
+ return {
135
+ name: "nuxt:type-check",
136
+ applyToEnvironment: (environment) => environment.name === "client" && !environment.config.isProduction,
137
+ apply: () => {
138
+ return !nuxt.options.test && nuxt.options.typescript.typeCheck === true;
139
+ },
140
+ configResolved(config) {
141
+ try {
142
+ entry = resolveClientEntry(config);
143
+ sourcemap = !!config.build.sourcemap;
144
+ } catch {
145
+ console.debug("[nuxt:type-check] Could not resolve client entry, type checking will not be applied.");
146
+ }
147
+ },
148
+ transform(code, id) {
149
+ if (id.replace(QUERY_RE$2, "") !== entry) return;
150
+ const s = new MagicString(code);
151
+ s.prepend("import \"/@vite-plugin-checker-runtime-entry\";\n");
152
+ return {
153
+ code: s.toString(),
154
+ map: sourcemap ? s.generateMap({ hires: true }) : void 0
155
+ };
156
+ }
157
+ };
176
158
  }
177
159
 
160
+ //#endregion
161
+ //#region src/plugins/module-preload-polyfill.ts
178
162
  const QUERY_RE$1 = /\?.+$/;
179
163
  function ModulePreloadPolyfillPlugin() {
180
- let isDisabled = false;
181
- let entry;
182
- let sourcemap;
183
- return {
184
- name: "nuxt:module-preload-polyfill",
185
- applyToEnvironment: (environment) => environment.name === "client",
186
- configResolved(config) {
187
- try {
188
- isDisabled = config.build.modulePreload === false || config.build.modulePreload.polyfill === false;
189
- sourcemap = !!config.build.sourcemap;
190
- entry = resolveClientEntry(config);
191
- } catch {
192
- console.debug("[nuxt:module-preload-polyfill] Could not resolve client entry, module preload polyfill will not be injected.");
193
- }
194
- },
195
- transform(code, id) {
196
- if (isDisabled || id.replace(QUERY_RE$1, "") !== entry) {
197
- return;
198
- }
199
- const s = new MagicString(code);
200
- s.prepend('import "vite/modulepreload-polyfill";\n');
201
- return {
202
- code: s.toString(),
203
- map: sourcemap ? s.generateMap({ hires: true }) : void 0
204
- };
205
- }
206
- };
164
+ let isDisabled = false;
165
+ let entry;
166
+ let sourcemap;
167
+ return {
168
+ name: "nuxt:module-preload-polyfill",
169
+ applyToEnvironment: (environment) => environment.name === "client",
170
+ configResolved(config) {
171
+ try {
172
+ isDisabled = config.build.modulePreload === false || config.build.modulePreload.polyfill === false;
173
+ sourcemap = !!config.build.sourcemap;
174
+ entry = resolveClientEntry(config);
175
+ } catch {
176
+ console.debug("[nuxt:module-preload-polyfill] Could not resolve client entry, module preload polyfill will not be injected.");
177
+ }
178
+ },
179
+ transform(code, id) {
180
+ if (isDisabled || id.replace(QUERY_RE$1, "") !== entry) return;
181
+ const s = new MagicString(code);
182
+ s.prepend("import \"vite/modulepreload-polyfill\";\n");
183
+ return {
184
+ code: s.toString(),
185
+ map: sourcemap ? s.generateMap({ hires: true }) : void 0
186
+ };
187
+ }
188
+ };
207
189
  }
208
190
 
191
+ //#endregion
192
+ //#region src/plugins/vite-node.ts
209
193
  function getManifest(nuxt, viteServer, clientEntry) {
210
- const css = /* @__PURE__ */ new Set();
211
- const ssrServer = nuxt.options.experimental.viteEnvironmentApi ? viteServer.environments.ssr : viteServer;
212
- for (const key of ssrServer.moduleGraph.urlToModuleMap.keys()) {
213
- if (isCSS(key)) {
214
- const query = getQuery(key);
215
- if ("raw" in query) {
216
- continue;
217
- }
218
- const importers = ssrServer.moduleGraph.urlToModuleMap.get(key)?.importers;
219
- if (importers && [...importers].every((i) => i.id && "raw" in getQuery(i.id))) {
220
- continue;
221
- }
222
- css.add(key);
223
- }
224
- }
225
- const manifest = normalizeViteManifest({
226
- "@vite/client": {
227
- file: "@vite/client",
228
- css: [...css],
229
- module: true,
230
- isEntry: true
231
- },
232
- ...nuxt.options.features.noScripts === "all" ? {} : {
233
- [clientEntry]: {
234
- file: clientEntry,
235
- isEntry: true,
236
- module: true,
237
- resourceType: "script"
238
- }
239
- }
240
- });
241
- return manifest;
194
+ const css = /* @__PURE__ */ new Set();
195
+ const ssrServer = nuxt.options.experimental.viteEnvironmentApi ? viteServer.environments.ssr : viteServer;
196
+ for (const key of ssrServer.moduleGraph.urlToModuleMap.keys()) if (isCSS(key)) {
197
+ if ("raw" in getQuery(key)) continue;
198
+ const importers = ssrServer.moduleGraph.urlToModuleMap.get(key)?.importers;
199
+ if (importers && [...importers].every((i) => i.id && "raw" in getQuery(i.id))) continue;
200
+ css.add(key);
201
+ }
202
+ return normalizeViteManifest({
203
+ "@vite/client": {
204
+ file: "@vite/client",
205
+ css: [...css],
206
+ module: true,
207
+ isEntry: true
208
+ },
209
+ ...nuxt.options.features.noScripts === "all" ? {} : { [clientEntry]: {
210
+ file: clientEntry,
211
+ isEntry: true,
212
+ module: true,
213
+ resourceType: "script"
214
+ } }
215
+ });
242
216
  }
243
217
  function generateSocketPath() {
244
- const uniqueSuffix = `${process.pid}-${Date.now()}`;
245
- const socketName = `nuxt-vite-node-${uniqueSuffix}`;
246
- if (process.platform === "win32") {
247
- return join(String.raw`\\.\pipe`, socketName);
248
- }
249
- if (process.platform === "linux") {
250
- const nodeMajor = Number.parseInt(process.versions.node.split(".")[0], 10);
251
- if (nodeMajor >= 20 && provider !== "stackblitz") {
252
- let isDocker = false;
253
- try {
254
- isDocker = fs.existsSync("/.dockerenv") || fs.existsSync("/proc/1/cgroup") && fs.readFileSync("/proc/1/cgroup", "utf8").includes("docker");
255
- } catch {
256
- }
257
- if (!isDocker) {
258
- return `\0${socketName}.sock`;
259
- }
260
- }
261
- }
262
- return join(os.tmpdir(), `${socketName}.sock`);
218
+ const socketName = `nuxt-vite-node-${`${process.pid}-${Date.now()}`}`;
219
+ if (process.platform === "win32") return join(String.raw`\\.\pipe`, socketName);
220
+ if (process.platform === "linux") {
221
+ if (Number.parseInt(process.versions.node.split(".")[0], 10) >= 20 && provider !== "stackblitz") {
222
+ let isDocker = false;
223
+ try {
224
+ isDocker = fs.existsSync("/.dockerenv") || fs.existsSync("/proc/1/cgroup") && fs.readFileSync("/proc/1/cgroup", "utf8").includes("docker");
225
+ } catch {}
226
+ if (!isDocker) return `\0${socketName}.sock`;
227
+ }
228
+ }
229
+ return join(os.tmpdir(), `${socketName}.sock`);
263
230
  }
264
231
  function useInvalidates() {
265
- const invalidates = /* @__PURE__ */ new Set();
266
- function markInvalidate(mod) {
267
- if (!mod.id) {
268
- return;
269
- }
270
- if (invalidates.has(mod.id)) {
271
- return;
272
- }
273
- invalidates.add(mod.id);
274
- markInvalidates(mod.importers);
275
- }
276
- function markInvalidates(mods) {
277
- if (!mods) {
278
- return;
279
- }
280
- for (const mod of mods) {
281
- markInvalidate(mod);
282
- }
283
- }
284
- return {
285
- invalidates,
286
- markInvalidate,
287
- markInvalidates
288
- };
232
+ const invalidates = /* @__PURE__ */ new Set();
233
+ function markInvalidate(mod) {
234
+ if (!mod.id) return;
235
+ if (invalidates.has(mod.id)) return;
236
+ invalidates.add(mod.id);
237
+ markInvalidates(mod.importers);
238
+ }
239
+ function markInvalidates(mods) {
240
+ if (!mods) return;
241
+ for (const mod of mods) markInvalidate(mod);
242
+ }
243
+ return {
244
+ invalidates,
245
+ markInvalidate,
246
+ markInvalidates
247
+ };
289
248
  }
290
249
  function ViteNodePlugin(nuxt) {
291
- let socketServer;
292
- const socketPath = generateSocketPath();
293
- const { invalidates, markInvalidate, markInvalidates } = useInvalidates();
294
- async function cleanupSocket() {
295
- if (socketServer && socketServer.listening) {
296
- await new Promise((resolveClose) => socketServer.close(() => resolveClose()));
297
- }
298
- if (socketPath && !socketPath.startsWith("\\\\.\\pipe\\")) {
299
- try {
300
- await unlink(socketPath);
301
- } catch {
302
- }
303
- }
304
- }
305
- return {
306
- name: "nuxt:vite-node-server",
307
- enforce: "post",
308
- configureServer(clientServer) {
309
- if (!tryUseNuxt()) {
310
- return;
311
- }
312
- function resolveServer(ssrServer) {
313
- const viteNodeServerOptions = {
314
- socketPath,
315
- root: nuxt.options.srcDir,
316
- entryPath: resolveServerEntry(ssrServer.config),
317
- base: ssrServer.config.base || "/_nuxt/",
318
- maxRetryAttempts: nuxt.options.vite.viteNode?.maxRetryAttempts,
319
- baseRetryDelay: nuxt.options.vite.viteNode?.baseRetryDelay,
320
- maxRetryDelay: nuxt.options.vite.viteNode?.maxRetryDelay,
321
- requestTimeout: nuxt.options.vite.viteNode?.requestTimeout,
322
- // TODO: remove baseURL in future
323
- baseURL: nuxt.options.devServer.url
324
- };
325
- process.env.NUXT_VITE_NODE_OPTIONS = JSON.stringify(viteNodeServerOptions);
326
- socketServer = createViteNodeSocketServer(nuxt, ssrServer, clientServer, invalidates, viteNodeServerOptions);
327
- }
328
- if (nuxt.options.experimental.viteEnvironmentApi) {
329
- resolveServer(clientServer);
330
- } else {
331
- nuxt.hook("vite:serverCreated", (ssrServer, ctx) => ctx.isServer ? resolveServer(ssrServer) : void 0);
332
- }
333
- nuxt.hook("close", cleanupSocket);
334
- const client = nuxt.options.experimental.viteEnvironmentApi ? clientServer.environments.client : clientServer;
335
- nuxt.hook("app:templatesGenerated", (_app, changedTemplates) => {
336
- for (const template of changedTemplates) {
337
- const mods = client.moduleGraph.getModulesByFile(`virtual:nuxt:${encodeURIComponent(template.dst)}`);
338
- for (const mod of mods || []) {
339
- markInvalidate(mod);
340
- }
341
- }
342
- });
343
- clientServer.watcher.on("all", (_event, file) => {
344
- invalidates.add(file);
345
- markInvalidates(clientServer.moduleGraph.getModulesByFile(normalize(file)));
346
- });
347
- },
348
- async buildEnd() {
349
- await cleanupSocket();
350
- }
351
- };
250
+ let socketServer;
251
+ const socketPath = generateSocketPath();
252
+ const { invalidates, markInvalidate, markInvalidates } = useInvalidates();
253
+ async function cleanupSocket() {
254
+ if (socketServer && socketServer.listening) await new Promise((resolveClose) => socketServer.close(() => resolveClose()));
255
+ if (socketPath && !socketPath.startsWith("\\\\.\\pipe\\")) try {
256
+ await unlink(socketPath);
257
+ } catch {}
258
+ }
259
+ return {
260
+ name: "nuxt:vite-node-server",
261
+ enforce: "post",
262
+ configureServer(clientServer) {
263
+ if (!tryUseNuxt()) return;
264
+ function resolveServer(ssrServer) {
265
+ const viteNodeServerOptions = {
266
+ socketPath,
267
+ root: nuxt.options.srcDir,
268
+ entryPath: resolveServerEntry(ssrServer.config),
269
+ base: ssrServer.config.base || "/_nuxt/",
270
+ maxRetryAttempts: nuxt.options.vite.viteNode?.maxRetryAttempts,
271
+ baseRetryDelay: nuxt.options.vite.viteNode?.baseRetryDelay,
272
+ maxRetryDelay: nuxt.options.vite.viteNode?.maxRetryDelay,
273
+ requestTimeout: nuxt.options.vite.viteNode?.requestTimeout,
274
+ baseURL: nuxt.options.devServer.url
275
+ };
276
+ process.env.NUXT_VITE_NODE_OPTIONS = JSON.stringify(viteNodeServerOptions);
277
+ socketServer = createViteNodeSocketServer(nuxt, ssrServer, clientServer, invalidates, viteNodeServerOptions);
278
+ }
279
+ if (nuxt.options.experimental.viteEnvironmentApi) resolveServer(clientServer);
280
+ else nuxt.hook("vite:serverCreated", (ssrServer, ctx) => ctx.isServer ? resolveServer(ssrServer) : void 0);
281
+ nuxt.hook("close", cleanupSocket);
282
+ const client = nuxt.options.experimental.viteEnvironmentApi ? clientServer.environments.client : clientServer;
283
+ nuxt.hook("app:templatesGenerated", (_app, changedTemplates) => {
284
+ for (const template of changedTemplates) {
285
+ const mods = client.moduleGraph.getModulesByFile(`virtual:nuxt:${encodeURIComponent(template.dst)}`);
286
+ for (const mod of mods || []) markInvalidate(mod);
287
+ }
288
+ });
289
+ clientServer.watcher.on("all", (_event, file) => {
290
+ invalidates.add(file);
291
+ markInvalidates(clientServer.moduleGraph.getModulesByFile(normalize(file)));
292
+ });
293
+ },
294
+ async buildEnd() {
295
+ await cleanupSocket();
296
+ }
297
+ };
352
298
  }
353
299
  let _node;
354
300
  function getNode(server) {
355
- return _node ||= new ViteNodeServer(server, {
356
- transformMode: {
357
- ssr: [/.*/],
358
- web: []
359
- }
360
- });
301
+ return _node ||= new ViteNodeServer(server, { transformMode: {
302
+ ssr: [/.*/],
303
+ web: []
304
+ } });
361
305
  }
362
306
  function createViteNodeSocketServer(nuxt, ssrServer, clientServer, invalidates, config) {
363
- const server = net.createServer((socket) => {
364
- const INITIAL_BUFFER_SIZE = 64 * 1024;
365
- const MAX_BUFFER_SIZE = 1024 * 1024 * 1024;
366
- let buffer = Buffer.alloc(INITIAL_BUFFER_SIZE);
367
- let writeOffset = 0;
368
- let readOffset = 0;
369
- socket.setNoDelay(true);
370
- socket.setKeepAlive(true, 0);
371
- async function processMessage(request) {
372
- try {
373
- switch (request.type) {
374
- case "manifest": {
375
- const manifestData = getManifest(nuxt, ssrServer, resolveClientEntry(clientServer.config));
376
- sendResponse(socket, request.id, manifestData);
377
- return;
378
- }
379
- case "invalidates": {
380
- const responsePayload = Array.from(invalidates);
381
- invalidates.clear();
382
- sendResponse(socket, request.id, responsePayload);
383
- return;
384
- }
385
- case "resolve": {
386
- const { id: resolveId, importer } = request.payload;
387
- if (!resolveId) {
388
- throw createError({ status: 400, message: "Missing id for resolve" });
389
- }
390
- const ssrNode = nuxt.options.experimental.viteEnvironmentApi ? ssrServer.environments.ssr.pluginContainer : getNode(ssrServer);
391
- const resolvedResult = await ssrNode.resolveId(resolveId, importer).catch(() => null);
392
- sendResponse(socket, request.id, resolvedResult);
393
- return;
394
- }
395
- case "module": {
396
- if (request.payload.moduleId === "/") {
397
- throw createError({ status: 400, message: "Invalid moduleId" });
398
- }
399
- const ssrNode = nuxt.options.experimental.viteEnvironmentApi ? ssrServer.environments.ssr : getNode(ssrServer);
400
- const response = await ssrNode.fetchModule(request.payload.moduleId).catch(async (err) => {
401
- const errorData = {
402
- code: "VITE_ERROR",
403
- id: request.payload.moduleId,
404
- stack: err.stack || "",
405
- message: err.message || ""
406
- };
407
- if (err.frame) {
408
- errorData.frame = err.frame;
409
- }
410
- if (!errorData.frame && err.code === "PARSE_ERROR") {
411
- try {
412
- const clientNode = nuxt.options.experimental.viteEnvironmentApi ? ssrServer.environments.client : getNode(ssrServer);
413
- errorData.frame = await clientNode.transformRequest(request.payload.moduleId).then((res) => `${err.message || ""}
414
- ${res?.code}`).catch(() => void 0);
415
- } catch {
416
- }
417
- }
418
- throw createError({ data: errorData, message: err.message || "Error fetching module" });
419
- });
420
- sendResponse(socket, request.id, response);
421
- return;
422
- }
423
- default:
424
- throw createError({ status: 400, message: `Unknown request type: ${request.type}` });
425
- }
426
- } catch (error) {
427
- sendError(socket, request.id, error);
428
- }
429
- }
430
- const resetBuffer = () => {
431
- writeOffset = 0;
432
- readOffset = 0;
433
- };
434
- const compactBuffer = () => {
435
- if (readOffset > 0) {
436
- const remainingData = writeOffset - readOffset;
437
- if (remainingData > 0) {
438
- buffer.copy(buffer, 0, readOffset, writeOffset);
439
- }
440
- writeOffset = remainingData;
441
- readOffset = 0;
442
- }
443
- };
444
- const ensureBufferCapacity = (additionalBytes) => {
445
- const requiredSize = writeOffset + additionalBytes;
446
- if (requiredSize > MAX_BUFFER_SIZE) {
447
- throw new Error(`Buffer size limit exceeded: ${requiredSize} > ${MAX_BUFFER_SIZE}`);
448
- }
449
- if (requiredSize > buffer.length) {
450
- compactBuffer();
451
- if (writeOffset + additionalBytes > buffer.length) {
452
- const newSize = Math.min(
453
- Math.max(buffer.length * 2, requiredSize),
454
- MAX_BUFFER_SIZE
455
- );
456
- const newBuffer = Buffer.alloc(newSize);
457
- buffer.copy(newBuffer, 0, 0, writeOffset);
458
- buffer = newBuffer;
459
- }
460
- }
461
- };
462
- socket.on("data", (data) => {
463
- try {
464
- ensureBufferCapacity(data.length);
465
- data.copy(buffer, writeOffset);
466
- writeOffset += data.length;
467
- while (writeOffset - readOffset >= 4) {
468
- const messageLength = buffer.readUInt32BE(readOffset);
469
- const totalLength = 4 + messageLength;
470
- if (writeOffset - readOffset < totalLength) {
471
- break;
472
- }
473
- const messageJSON = buffer.subarray(readOffset + 4, readOffset + totalLength).toString("utf-8");
474
- readOffset += totalLength;
475
- try {
476
- const request = JSON.parse(messageJSON);
477
- processMessage(request).catch((error) => {
478
- sendError(socket, request?.id || "unknown", error);
479
- });
480
- } catch (parseError) {
481
- const errorMessage = parseError instanceof Error ? parseError.message : "Unknown parse error";
482
- socket.destroy(new Error(`Invalid JSON in message: ${errorMessage}`));
483
- return;
484
- }
485
- }
486
- if (readOffset > buffer.length / 2) {
487
- compactBuffer();
488
- }
489
- } catch (error) {
490
- socket.destroy(error instanceof Error ? error : new Error("Buffer management error"));
491
- }
492
- });
493
- socket.on("error", () => {
494
- resetBuffer();
495
- });
496
- socket.on("close", () => {
497
- resetBuffer();
498
- });
499
- });
500
- const currentSocketPath = config.socketPath;
501
- if (!currentSocketPath) {
502
- throw new Error("Socket path not configured for ViteNodeSocketServer.");
503
- }
504
- if (!currentSocketPath.startsWith("\\\\.\\pipe\\")) {
505
- try {
506
- fs.unlinkSync(currentSocketPath);
507
- } catch (unlinkError) {
508
- if (unlinkError.code !== "ENOENT") ;
509
- }
510
- }
511
- server.listen(currentSocketPath);
512
- server.on("error", () => {
513
- });
514
- return server;
307
+ const server = net.createServer((socket) => {
308
+ const INITIAL_BUFFER_SIZE = 64 * 1024;
309
+ const MAX_BUFFER_SIZE = 1024 * 1024 * 1024;
310
+ let buffer = Buffer.alloc(INITIAL_BUFFER_SIZE);
311
+ let writeOffset = 0;
312
+ let readOffset = 0;
313
+ socket.setNoDelay(true);
314
+ socket.setKeepAlive(true, 0);
315
+ async function processMessage(request) {
316
+ try {
317
+ switch (request.type) {
318
+ case "manifest": {
319
+ const manifestData = getManifest(nuxt, ssrServer, resolveClientEntry(clientServer.config));
320
+ sendResponse(socket, request.id, manifestData);
321
+ return;
322
+ }
323
+ case "invalidates": {
324
+ const responsePayload = Array.from(invalidates);
325
+ invalidates.clear();
326
+ sendResponse(socket, request.id, responsePayload);
327
+ return;
328
+ }
329
+ case "resolve": {
330
+ const { id: resolveId, importer } = request.payload;
331
+ if (!resolveId) throw createError({
332
+ status: 400,
333
+ message: "Missing id for resolve"
334
+ });
335
+ const resolvedResult = await (nuxt.options.experimental.viteEnvironmentApi ? ssrServer.environments.ssr.pluginContainer : getNode(ssrServer)).resolveId(resolveId, importer).catch(() => null);
336
+ sendResponse(socket, request.id, resolvedResult);
337
+ return;
338
+ }
339
+ case "module": {
340
+ if (request.payload.moduleId === "/") throw createError({
341
+ status: 400,
342
+ message: "Invalid moduleId"
343
+ });
344
+ const response = await (nuxt.options.experimental.viteEnvironmentApi ? ssrServer.environments.ssr : getNode(ssrServer)).fetchModule(request.payload.moduleId).catch(async (err) => {
345
+ const errorData = {
346
+ code: "VITE_ERROR",
347
+ id: request.payload.moduleId,
348
+ stack: err.stack || "",
349
+ message: err.message || ""
350
+ };
351
+ if (err.frame) errorData.frame = err.frame;
352
+ if (!errorData.frame && err.code === "PARSE_ERROR") try {
353
+ errorData.frame = await (nuxt.options.experimental.viteEnvironmentApi ? ssrServer.environments.client : getNode(ssrServer)).transformRequest(request.payload.moduleId).then((res) => `${err.message || ""}\n${res?.code}`).catch(() => void 0);
354
+ } catch {}
355
+ throw createError({
356
+ data: errorData,
357
+ message: err.message || "Error fetching module"
358
+ });
359
+ });
360
+ sendResponse(socket, request.id, response);
361
+ return;
362
+ }
363
+ default: throw createError({
364
+ status: 400,
365
+ message: `Unknown request type: ${request.type}`
366
+ });
367
+ }
368
+ } catch (error) {
369
+ sendError(socket, request.id, error);
370
+ }
371
+ }
372
+ const resetBuffer = () => {
373
+ writeOffset = 0;
374
+ readOffset = 0;
375
+ };
376
+ const compactBuffer = () => {
377
+ if (readOffset > 0) {
378
+ const remainingData = writeOffset - readOffset;
379
+ if (remainingData > 0) buffer.copy(buffer, 0, readOffset, writeOffset);
380
+ writeOffset = remainingData;
381
+ readOffset = 0;
382
+ }
383
+ };
384
+ const ensureBufferCapacity = (additionalBytes) => {
385
+ const requiredSize = writeOffset + additionalBytes;
386
+ if (requiredSize > MAX_BUFFER_SIZE) throw new Error(`Buffer size limit exceeded: ${requiredSize} > ${MAX_BUFFER_SIZE}`);
387
+ if (requiredSize > buffer.length) {
388
+ compactBuffer();
389
+ if (writeOffset + additionalBytes > buffer.length) {
390
+ const newSize = Math.min(Math.max(buffer.length * 2, requiredSize), MAX_BUFFER_SIZE);
391
+ const newBuffer = Buffer.alloc(newSize);
392
+ buffer.copy(newBuffer, 0, 0, writeOffset);
393
+ buffer = newBuffer;
394
+ }
395
+ }
396
+ };
397
+ socket.on("data", (data) => {
398
+ try {
399
+ ensureBufferCapacity(data.length);
400
+ data.copy(buffer, writeOffset);
401
+ writeOffset += data.length;
402
+ while (writeOffset - readOffset >= 4) {
403
+ const totalLength = 4 + buffer.readUInt32BE(readOffset);
404
+ if (writeOffset - readOffset < totalLength) break;
405
+ const messageJSON = buffer.subarray(readOffset + 4, readOffset + totalLength).toString("utf-8");
406
+ readOffset += totalLength;
407
+ try {
408
+ const request = JSON.parse(messageJSON);
409
+ processMessage(request).catch((error) => {
410
+ sendError(socket, request?.id || "unknown", error);
411
+ });
412
+ } catch (parseError) {
413
+ const errorMessage = parseError instanceof Error ? parseError.message : "Unknown parse error";
414
+ socket.destroy(/* @__PURE__ */ new Error(`Invalid JSON in message: ${errorMessage}`));
415
+ return;
416
+ }
417
+ }
418
+ if (readOffset > buffer.length / 2) compactBuffer();
419
+ } catch (error) {
420
+ socket.destroy(error instanceof Error ? error : /* @__PURE__ */ new Error("Buffer management error"));
421
+ }
422
+ });
423
+ socket.on("error", () => {
424
+ resetBuffer();
425
+ });
426
+ socket.on("close", () => {
427
+ resetBuffer();
428
+ });
429
+ });
430
+ const currentSocketPath = config.socketPath;
431
+ if (!currentSocketPath) throw new Error("Socket path not configured for ViteNodeSocketServer.");
432
+ if (!currentSocketPath.startsWith("\\\\.\\pipe\\")) try {
433
+ fs.unlinkSync(currentSocketPath);
434
+ } catch (unlinkError) {
435
+ if (unlinkError.code !== "ENOENT") {}
436
+ }
437
+ server.listen(currentSocketPath);
438
+ server.on("error", () => {});
439
+ return server;
515
440
  }
516
441
  function sendResponse(socket, id, data) {
517
- try {
518
- const response = { id, type: "response", data };
519
- const responseJSON = JSON.stringify(response);
520
- const messageBuffer = Buffer.from(responseJSON, "utf-8");
521
- const messageLength = messageBuffer.length;
522
- const fullMessage = Buffer.alloc(4 + messageLength);
523
- fullMessage.writeUInt32BE(messageLength, 0);
524
- messageBuffer.copy(fullMessage, 4);
525
- socket.write(fullMessage, (err) => {
526
- if (err) {
527
- }
528
- });
529
- } catch (error) {
530
- sendError(socket, id, error);
531
- }
442
+ try {
443
+ const response = {
444
+ id,
445
+ type: "response",
446
+ data
447
+ };
448
+ const responseJSON = JSON.stringify(response);
449
+ const messageBuffer = Buffer.from(responseJSON, "utf-8");
450
+ const messageLength = messageBuffer.length;
451
+ const fullMessage = Buffer.alloc(4 + messageLength);
452
+ fullMessage.writeUInt32BE(messageLength, 0);
453
+ messageBuffer.copy(fullMessage, 4);
454
+ socket.write(fullMessage, (err) => {
455
+ if (err) {}
456
+ });
457
+ } catch (error) {
458
+ sendError(socket, id, error);
459
+ }
532
460
  }
533
461
  function sendError(socket, id, error) {
534
- const errorResponse = {
535
- id,
536
- type: "error",
537
- error: {
538
- message: error.message,
539
- stack: error.stack,
540
- status: error.status,
541
- statusText: error.statusText,
542
- data: error.data
543
- }
544
- };
545
- const responseJSON = JSON.stringify(errorResponse);
546
- const messageBuffer = Buffer.from(responseJSON, "utf-8");
547
- const messageLength = messageBuffer.length;
548
- const fullMessage = Buffer.alloc(4 + messageLength);
549
- fullMessage.writeUInt32BE(messageLength, 0);
550
- messageBuffer.copy(fullMessage, 4);
551
- socket.write(fullMessage, (err) => {
552
- });
462
+ const errorResponse = {
463
+ id,
464
+ type: "error",
465
+ error: {
466
+ message: error.message,
467
+ stack: error.stack,
468
+ status: error.status,
469
+ statusText: error.statusText,
470
+ data: error.data
471
+ }
472
+ };
473
+ const responseJSON = JSON.stringify(errorResponse);
474
+ const messageBuffer = Buffer.from(responseJSON, "utf-8");
475
+ const messageLength = messageBuffer.length;
476
+ const fullMessage = Buffer.alloc(4 + messageLength);
477
+ fullMessage.writeUInt32BE(messageLength, 0);
478
+ messageBuffer.copy(fullMessage, 4);
479
+ socket.write(fullMessage, (err) => {
480
+ if (err) {}
481
+ });
553
482
  }
554
483
  async function writeDevServer(nuxt) {
555
- const serverResolvedPath = resolveModulePath("#vite-node-entry", { from: import.meta.url });
556
- const fetchResolvedPath = resolveModulePath("#vite-node", { from: import.meta.url });
557
- const serverDist = join(nuxt.options.buildDir, "dist/server");
558
- await mkdir(serverDist, { recursive: true });
559
- await Promise.all([
560
- writeFile(join(serverDist, "server.mjs"), `export { default } from ${JSON.stringify(pathToFileURL(serverResolvedPath).href)}`),
561
- writeFile(join(serverDist, "client.precomputed.mjs"), `export default undefined`),
562
- writeFile(join(serverDist, "client.manifest.mjs"), `
484
+ const serverResolvedPath = resolveModulePath("#vite-node-entry", { from: import.meta.url });
485
+ const fetchResolvedPath = resolveModulePath("#vite-node", { from: import.meta.url });
486
+ const serverDist = join(nuxt.options.buildDir, "dist/server");
487
+ await mkdir(serverDist, { recursive: true });
488
+ await Promise.all([
489
+ writeFile(join(serverDist, "server.mjs"), `export { default } from ${JSON.stringify(pathToFileURL(serverResolvedPath).href)}`),
490
+ writeFile(join(serverDist, "client.precomputed.mjs"), `export default undefined`),
491
+ writeFile(join(serverDist, "client.manifest.mjs"), `
563
492
  import { viteNodeFetch } from ${JSON.stringify(pathToFileURL(fetchResolvedPath))}
564
493
  export default () => viteNodeFetch.getManifest()
565
494
  `)
566
- ]);
495
+ ]);
567
496
  }
568
497
 
498
+ //#endregion
499
+ //#region src/plugins/public-dirs.ts
569
500
  const PREFIX = "virtual:public?";
570
501
  const PREFIX_RE = /^virtual:public\?/;
571
502
  const CSS_URL_RE = /url\((\/[^)]+)\)/g;
572
503
  const CSS_URL_SINGLE_RE = /url\(\/[^)]+\)/;
573
504
  const RENDER_CHUNK_RE = /(?<= = )['"`]/;
574
505
  const PublicDirsPlugin = (options) => {
575
- const { resolveFromPublicAssets } = useResolveFromPublicAssets();
576
- let sourcemap;
577
- return [
578
- {
579
- name: "nuxt:vite-public-dir-resolution-dev",
580
- apply() {
581
- return !!options.dev && !!options.baseURL && options.baseURL !== "/";
582
- },
583
- transform(code, id) {
584
- if (!isCSSRequest(id) || !CSS_URL_SINGLE_RE.test(code)) {
585
- return;
586
- }
587
- const s = new MagicString(code);
588
- for (const [full, url] of code.matchAll(CSS_URL_RE)) {
589
- if (url && resolveFromPublicAssets(url)) {
590
- s.replace(full, `url(${options.baseURL}${url})`);
591
- }
592
- }
593
- if (s.hasChanged()) {
594
- return {
595
- code: s.toString(),
596
- map: sourcemap ? s.generateMap({ hires: true }) : void 0
597
- };
598
- }
599
- }
600
- },
601
- {
602
- name: "nuxt:vite-public-dir-resolution",
603
- configResolved(config) {
604
- sourcemap = !!config.build.sourcemap;
605
- },
606
- load: {
607
- order: "pre",
608
- filter: {
609
- id: PREFIX_RE
610
- },
611
- handler(id) {
612
- return `import { publicAssetsURL } from '#internal/nuxt/paths';export default publicAssetsURL(${JSON.stringify(decodeURIComponent(id.slice(PREFIX.length)))})`;
613
- }
614
- },
615
- resolveId: {
616
- order: "post",
617
- filter: {
618
- id: {
619
- exclude: [/^\/__skip_vite$/, /^[^/]/, /^\/@fs/]
620
- }
621
- },
622
- handler(id) {
623
- if (resolveFromPublicAssets(id)) {
624
- return PREFIX + encodeURIComponent(id);
625
- }
626
- }
627
- },
628
- renderChunk(code, chunk) {
629
- if (!chunk.facadeModuleId?.includes("?inline&used")) {
630
- return;
631
- }
632
- const s = new MagicString(code);
633
- const q = code.match(RENDER_CHUNK_RE)?.[0] || '"';
634
- for (const [full, url] of code.matchAll(CSS_URL_RE)) {
635
- if (url && resolveFromPublicAssets(url)) {
636
- s.replace(full, `url(${q} + publicAssetsURL(${q}${url}${q}) + ${q})`);
637
- }
638
- }
639
- if (s.hasChanged()) {
640
- s.prepend(`import { publicAssetsURL } from '#internal/nuxt/paths';`);
641
- return {
642
- code: s.toString(),
643
- map: sourcemap ? s.generateMap({ hires: true }) : void 0
644
- };
645
- }
646
- },
647
- generateBundle(_outputOptions, bundle) {
648
- for (const [file, chunk] of Object.entries(bundle)) {
649
- if (!file.endsWith(".css") || chunk.type !== "asset") {
650
- continue;
651
- }
652
- let css = chunk.source.toString();
653
- let wasReplaced = false;
654
- for (const [full, url] of css.matchAll(CSS_URL_RE)) {
655
- if (url && resolveFromPublicAssets(url)) {
656
- const relativeURL = relative(withLeadingSlash(dirname(file)), url);
657
- css = css.replace(full, `url(${relativeURL})`);
658
- wasReplaced = true;
659
- }
660
- }
661
- if (wasReplaced) {
662
- chunk.source = css;
663
- }
664
- }
665
- }
666
- }
667
- ];
506
+ const { resolveFromPublicAssets } = useResolveFromPublicAssets();
507
+ let sourcemap;
508
+ return [{
509
+ name: "nuxt:vite-public-dir-resolution-dev",
510
+ apply() {
511
+ return !!options.dev && !!options.baseURL && options.baseURL !== "/";
512
+ },
513
+ transform(code, id) {
514
+ if (!isCSSRequest(id) || !CSS_URL_SINGLE_RE.test(code)) return;
515
+ const s = new MagicString(code);
516
+ for (const [full, url] of code.matchAll(CSS_URL_RE)) if (url && resolveFromPublicAssets(url)) s.replace(full, `url(${options.baseURL}${url})`);
517
+ if (s.hasChanged()) return {
518
+ code: s.toString(),
519
+ map: sourcemap ? s.generateMap({ hires: true }) : void 0
520
+ };
521
+ }
522
+ }, {
523
+ name: "nuxt:vite-public-dir-resolution",
524
+ configResolved(config) {
525
+ sourcemap = !!config.build.sourcemap;
526
+ },
527
+ load: {
528
+ order: "pre",
529
+ filter: { id: PREFIX_RE },
530
+ handler(id) {
531
+ return `import { publicAssetsURL } from '#internal/nuxt/paths';export default publicAssetsURL(${JSON.stringify(decodeURIComponent(id.slice(15)))})`;
532
+ }
533
+ },
534
+ resolveId: {
535
+ order: "post",
536
+ filter: { id: { exclude: [
537
+ /^\/__skip_vite$/,
538
+ /^[^/]/,
539
+ /^\/@fs/
540
+ ] } },
541
+ handler(id) {
542
+ if (resolveFromPublicAssets(id)) return PREFIX + encodeURIComponent(id);
543
+ }
544
+ },
545
+ renderChunk(code, chunk) {
546
+ if (!chunk.facadeModuleId?.includes("?inline&used")) return;
547
+ const s = new MagicString(code);
548
+ const q = code.match(RENDER_CHUNK_RE)?.[0] || "\"";
549
+ for (const [full, url] of code.matchAll(CSS_URL_RE)) if (url && resolveFromPublicAssets(url)) s.replace(full, `url(${q} + publicAssetsURL(${q}${url}${q}) + ${q})`);
550
+ if (s.hasChanged()) {
551
+ s.prepend(`import { publicAssetsURL } from '#internal/nuxt/paths';`);
552
+ return {
553
+ code: s.toString(),
554
+ map: sourcemap ? s.generateMap({ hires: true }) : void 0
555
+ };
556
+ }
557
+ },
558
+ generateBundle(_outputOptions, bundle$1) {
559
+ for (const [file, chunk] of Object.entries(bundle$1)) {
560
+ if (!file.endsWith(".css") || chunk.type !== "asset") continue;
561
+ let css = chunk.source.toString();
562
+ let wasReplaced = false;
563
+ for (const [full, url] of css.matchAll(CSS_URL_RE)) if (url && resolveFromPublicAssets(url)) {
564
+ const relativeURL = relative(withLeadingSlash(dirname(file)), url);
565
+ css = css.replace(full, `url(${relativeURL})`);
566
+ wasReplaced = true;
567
+ }
568
+ if (wasReplaced) chunk.source = css;
569
+ }
570
+ }
571
+ }];
668
572
  };
669
573
  const PUBLIC_ASSETS_RE = /[?#].*$/;
670
574
  function useResolveFromPublicAssets() {
671
- const nitro = useNitro();
672
- function resolveFromPublicAssets(id) {
673
- for (const dir of nitro.options.publicAssets) {
674
- if (!id.startsWith(withTrailingSlash(dir.baseURL || "/"))) {
675
- continue;
676
- }
677
- const path = id.replace(PUBLIC_ASSETS_RE, "").replace(withTrailingSlash(dir.baseURL || "/"), withTrailingSlash(dir.dir));
678
- if (existsSync(path)) {
679
- return id;
680
- }
681
- }
682
- }
683
- return { resolveFromPublicAssets };
575
+ const nitro = useNitro();
576
+ function resolveFromPublicAssets(id) {
577
+ for (const dir of nitro.options.publicAssets) {
578
+ if (!id.startsWith(withTrailingSlash(dir.baseURL || "/"))) continue;
579
+ if (existsSync(id.replace(PUBLIC_ASSETS_RE, "").replace(withTrailingSlash(dir.baseURL || "/"), withTrailingSlash(dir.dir)))) return id;
580
+ }
581
+ }
582
+ return { resolveFromPublicAssets };
684
583
  }
685
584
 
585
+ //#endregion
586
+ //#region src/utils/logger.ts
686
587
  let duplicateCount = 0;
687
588
  let lastType = null;
688
589
  let lastMsg = null;
689
590
  const logLevelMap = {
690
- silent: "silent",
691
- info: "info",
692
- verbose: "info"
591
+ silent: "silent",
592
+ info: "info",
593
+ verbose: "info"
693
594
  };
694
595
  const logLevelMapReverse = {
695
- silent: 0,
696
- error: 1,
697
- warn: 2,
698
- info: 3
596
+ silent: 0,
597
+ error: 1,
598
+ warn: 2,
599
+ info: 3
699
600
  };
700
601
  const RUNTIME_RESOLVE_REF_RE = /^([^ ]+) referenced in/m;
701
602
  function createViteLogger(config, ctx = {}) {
702
- const loggedErrors = /* @__PURE__ */ new WeakSet();
703
- const canClearScreen = hasTTY && !isCI && config.clearScreen;
704
- const _logger = createLogger();
705
- const relativeOutDir = relative(config.root, config.build.outDir || "");
706
- const clear = () => {
707
- _logger.clearScreen(
708
- // @ts-expect-error silent is a log level but not a valid option for clearScreens
709
- "silent"
710
- );
711
- };
712
- const clearScreen = canClearScreen ? clear : () => {
713
- };
714
- const { resolveFromPublicAssets } = useResolveFromPublicAssets();
715
- function output(type, msg, options = {}) {
716
- if (typeof msg === "string" && !process.env.DEBUG) {
717
- if (msg.startsWith("Sourcemap") && msg.includes("node_modules")) {
718
- return;
719
- }
720
- if (msg.includes("didn't resolve at build time, it will remain unchanged to be resolved at runtime")) {
721
- const id = msg.trim().match(RUNTIME_RESOLVE_REF_RE)?.[1];
722
- if (id && resolveFromPublicAssets(id)) {
723
- return;
724
- }
725
- }
726
- if (type === "info" && ctx.hideOutput && msg.includes(relativeOutDir)) {
727
- return;
728
- }
729
- }
730
- const sameAsLast = lastType === type && lastMsg === msg;
731
- if (sameAsLast) {
732
- duplicateCount += 1;
733
- clearScreen();
734
- } else {
735
- duplicateCount = 0;
736
- lastType = type;
737
- lastMsg = msg;
738
- if (options.clear) {
739
- clearScreen();
740
- }
741
- }
742
- if (options.error) {
743
- loggedErrors.add(options.error);
744
- }
745
- const prevLevel = logger.level;
746
- logger.level = logLevelMapReverse[config.logLevel || "info"];
747
- logger[type](msg + (sameAsLast ? colorize("dim", ` (x${duplicateCount + 1})`) : ""));
748
- logger.level = prevLevel;
749
- }
750
- const warnedMessages = /* @__PURE__ */ new Set();
751
- const viteLogger = {
752
- hasWarned: false,
753
- info(msg, opts) {
754
- output("info", msg, opts);
755
- },
756
- warn(msg, opts) {
757
- viteLogger.hasWarned = true;
758
- output("warn", msg, opts);
759
- },
760
- warnOnce(msg, opts) {
761
- if (warnedMessages.has(msg)) {
762
- return;
763
- }
764
- viteLogger.hasWarned = true;
765
- output("warn", msg, opts);
766
- warnedMessages.add(msg);
767
- },
768
- error(msg, opts) {
769
- viteLogger.hasWarned = true;
770
- output("error", msg, opts);
771
- },
772
- clearScreen() {
773
- clear();
774
- },
775
- hasErrorLogged(error) {
776
- return loggedErrors.has(error);
777
- }
778
- };
779
- return viteLogger;
603
+ const loggedErrors = /* @__PURE__ */ new WeakSet();
604
+ const canClearScreen = hasTTY && !isCI && config.clearScreen;
605
+ const _logger = createLogger();
606
+ const relativeOutDir = relative(config.root, config.build.outDir || "");
607
+ const clear = () => {
608
+ _logger.clearScreen("silent");
609
+ };
610
+ const clearScreen = canClearScreen ? clear : () => {};
611
+ const { resolveFromPublicAssets } = useResolveFromPublicAssets();
612
+ function output(type, msg, options = {}) {
613
+ if (typeof msg === "string" && !process.env.DEBUG) {
614
+ if (msg.startsWith("Sourcemap") && msg.includes("node_modules")) return;
615
+ if (msg.includes("didn't resolve at build time, it will remain unchanged to be resolved at runtime")) {
616
+ const id = msg.trim().match(RUNTIME_RESOLVE_REF_RE)?.[1];
617
+ if (id && resolveFromPublicAssets(id)) return;
618
+ }
619
+ if (type === "info" && ctx.hideOutput && msg.includes(relativeOutDir)) return;
620
+ }
621
+ const sameAsLast = lastType === type && lastMsg === msg;
622
+ if (sameAsLast) {
623
+ duplicateCount += 1;
624
+ clearScreen();
625
+ } else {
626
+ duplicateCount = 0;
627
+ lastType = type;
628
+ lastMsg = msg;
629
+ if (options.clear) clearScreen();
630
+ }
631
+ if (options.error) loggedErrors.add(options.error);
632
+ const prevLevel = logger.level;
633
+ logger.level = logLevelMapReverse[config.logLevel || "info"];
634
+ logger[type](msg + (sameAsLast ? colorize("dim", ` (x${duplicateCount + 1})`) : ""));
635
+ logger.level = prevLevel;
636
+ }
637
+ const warnedMessages = /* @__PURE__ */ new Set();
638
+ const viteLogger = {
639
+ hasWarned: false,
640
+ info(msg, opts) {
641
+ output("info", msg, opts);
642
+ },
643
+ warn(msg, opts) {
644
+ viteLogger.hasWarned = true;
645
+ output("warn", msg, opts);
646
+ },
647
+ warnOnce(msg, opts) {
648
+ if (warnedMessages.has(msg)) return;
649
+ viteLogger.hasWarned = true;
650
+ output("warn", msg, opts);
651
+ warnedMessages.add(msg);
652
+ },
653
+ error(msg, opts) {
654
+ viteLogger.hasWarned = true;
655
+ output("error", msg, opts);
656
+ },
657
+ clearScreen() {
658
+ clear();
659
+ },
660
+ hasErrorLogged(error) {
661
+ return loggedErrors.has(error);
662
+ }
663
+ };
664
+ return viteLogger;
780
665
  }
781
666
 
667
+ //#endregion
668
+ //#region src/plugins/stable-entry.ts
782
669
  function StableEntryPlugin(nuxt) {
783
- let sourcemap;
784
- let entryFileName;
785
- const nitro = useNitro();
786
- nitro.options.virtual ||= {};
787
- nitro.options._config.virtual ||= {};
788
- nitro.options._config.virtual["#internal/entry-chunk.mjs"] = nitro.options.virtual["#internal/entry-chunk.mjs"] = () => `export const entryFileName = ${JSON.stringify(entryFileName)}`;
789
- return {
790
- name: "nuxt:stable-entry",
791
- configResolved(config) {
792
- sourcemap = !!config.build.sourcemap;
793
- },
794
- apply: () => !nuxt.options.dev && nuxt.options.experimental.entryImportMap,
795
- applyToEnvironment(environment) {
796
- if (environment.name !== "client") {
797
- return false;
798
- }
799
- if (environment.config.build.target) {
800
- const targets = toArray(environment.config.build.target);
801
- if (!targets.every(isSupported)) {
802
- return false;
803
- }
804
- }
805
- return toArray(environment.config.build.rollupOptions?.output).some((output) => typeof output?.entryFileNames === "string" && output?.entryFileNames.includes("[hash]"));
806
- },
807
- renderChunk(code, chunk, _options, meta) {
808
- const entry = Object.values(meta.chunks).find((chunk2) => chunk2.isEntry && chunk2.name === "entry")?.fileName;
809
- if (!entry || !chunk.imports.includes(entry)) {
810
- return;
811
- }
812
- const filename = new RegExp(`(?<=['"])[\\./]*${escapeStringRegexp(basename(entry))}`, "g");
813
- const s = new MagicString(code);
814
- s.replaceAll(filename, "#entry");
815
- if (s.hasChanged()) {
816
- return {
817
- code: s.toString(),
818
- map: sourcemap ? s.generateMap({ hires: true }) : void 0
819
- };
820
- }
821
- },
822
- writeBundle(_options, bundle) {
823
- let entry = Object.values(bundle).find((chunk) => chunk.type === "chunk" && chunk.isEntry && chunk.name === "entry")?.fileName;
824
- const prefix = withoutLeadingSlash(nuxt.options.app.buildAssetsDir);
825
- if (entry?.startsWith(prefix)) {
826
- entry = entry.slice(prefix.length);
827
- }
828
- entryFileName = entry;
829
- }
830
- };
670
+ let sourcemap;
671
+ let entryFileName;
672
+ const nitro = useNitro();
673
+ nitro.options.virtual ||= {};
674
+ nitro.options._config.virtual ||= {};
675
+ nitro.options._config.virtual["#internal/entry-chunk.mjs"] = nitro.options.virtual["#internal/entry-chunk.mjs"] = () => `export const entryFileName = ${JSON.stringify(entryFileName)}`;
676
+ return {
677
+ name: "nuxt:stable-entry",
678
+ configResolved(config) {
679
+ sourcemap = !!config.build.sourcemap;
680
+ },
681
+ apply: () => !nuxt.options.dev && nuxt.options.experimental.entryImportMap,
682
+ applyToEnvironment(environment) {
683
+ if (environment.name !== "client") return false;
684
+ if (environment.config.build.target) {
685
+ if (!toArray(environment.config.build.target).every(isSupported)) return false;
686
+ }
687
+ return toArray(environment.config.build.rollupOptions?.output).some((output) => typeof output?.entryFileNames === "string" && output?.entryFileNames.includes("[hash]"));
688
+ },
689
+ renderChunk(code, chunk, _options, meta) {
690
+ const entry = Object.values(meta.chunks).find((chunk$1) => chunk$1.isEntry && chunk$1.name === "entry")?.fileName;
691
+ if (!entry || !chunk.imports.includes(entry)) return;
692
+ const filename$2 = new RegExp(`(?<=['"])[\\./]*${escapeStringRegexp(basename(entry))}`, "g");
693
+ const s = new MagicString(code);
694
+ s.replaceAll(filename$2, "#entry");
695
+ if (s.hasChanged()) return {
696
+ code: s.toString(),
697
+ map: sourcemap ? s.generateMap({ hires: true }) : void 0
698
+ };
699
+ },
700
+ writeBundle(_options, bundle$1) {
701
+ let entry = Object.values(bundle$1).find((chunk) => chunk.type === "chunk" && chunk.isEntry && chunk.name === "entry")?.fileName;
702
+ const prefix = withoutLeadingSlash(nuxt.options.app.buildAssetsDir);
703
+ if (entry?.startsWith(prefix)) entry = entry.slice(prefix.length);
704
+ entryFileName = entry;
705
+ }
706
+ };
831
707
  }
832
708
  const supportedEnvironments = {
833
- chrome: 89,
834
- edge: 89,
835
- firefox: 108,
836
- ie: Infinity,
837
- ios: 16.4,
838
- opera: 75,
839
- safari: 16.4
709
+ chrome: 89,
710
+ edge: 89,
711
+ firefox: 108,
712
+ ie: Infinity,
713
+ ios: 16.4,
714
+ opera: 75,
715
+ safari: 16.4
840
716
  };
841
717
  function isSupported(target) {
842
- const [engine, _version] = target.split(/(?<=[a-z])(?=\d)/);
843
- const constraint = supportedEnvironments[engine];
844
- if (!constraint) {
845
- return true;
846
- }
847
- const version = Number(_version);
848
- return Number.isNaN(version) || Number(version) >= constraint;
718
+ const [engine, _version] = target.split(/(?<=[a-z])(?=\d)/);
719
+ const constraint = supportedEnvironments[engine];
720
+ if (!constraint) return true;
721
+ const version = Number(_version);
722
+ return Number.isNaN(version) || Number(version) >= constraint;
849
723
  }
850
724
 
725
+ //#endregion
726
+ //#region src/plugins/analyze.ts
851
727
  async function AnalyzePlugin(nuxt) {
852
- if (nuxt.options.test) {
853
- return;
854
- }
855
- const analyzeOptions = defu({}, nuxt.options.build.analyze);
856
- if (!analyzeOptions.enabled) {
857
- return;
858
- }
859
- const { visualizer } = await import('rollup-plugin-visualizer');
860
- return {
861
- name: "nuxt:analyze",
862
- applyToEnvironment(environment) {
863
- if (environment.name !== "client") {
864
- return false;
865
- }
866
- return [
867
- {
868
- name: "nuxt:analyze-minify",
869
- async generateBundle(_opts, outputBundle) {
870
- for (const _bundleId in outputBundle) {
871
- const bundle = outputBundle[_bundleId];
872
- if (!bundle || bundle.type !== "chunk") {
873
- continue;
874
- }
875
- const minifiedModuleEntryPromises = [];
876
- for (const [moduleId, module] of Object.entries(bundle.modules)) {
877
- minifiedModuleEntryPromises.push(
878
- transform(module.code || "", { minify: true }).then((result) => [moduleId, { ...module, code: result.code }])
879
- );
880
- }
881
- bundle.modules = Object.fromEntries(await Promise.all(minifiedModuleEntryPromises));
882
- }
883
- }
884
- },
885
- visualizer({
886
- ...analyzeOptions,
887
- filename: "filename" in analyzeOptions && analyzeOptions.filename ? analyzeOptions.filename.replace("{name}", "client") : void 0,
888
- title: "Client bundle stats",
889
- gzipSize: true,
890
- brotliSize: true
891
- })
892
- ];
893
- }
894
- };
728
+ if (nuxt.options.test) return;
729
+ const analyzeOptions = defu({}, nuxt.options.build.analyze);
730
+ if (!analyzeOptions.enabled) return;
731
+ const { visualizer } = await import("rollup-plugin-visualizer");
732
+ return {
733
+ name: "nuxt:analyze",
734
+ applyToEnvironment(environment) {
735
+ if (environment.name !== "client") return false;
736
+ return [{
737
+ name: "nuxt:analyze-minify",
738
+ async generateBundle(_opts, outputBundle) {
739
+ for (const _bundleId in outputBundle) {
740
+ const bundle$1 = outputBundle[_bundleId];
741
+ if (!bundle$1 || bundle$1.type !== "chunk") continue;
742
+ const minifiedModuleEntryPromises = [];
743
+ for (const [moduleId, module] of Object.entries(bundle$1.modules)) minifiedModuleEntryPromises.push(transform(module.code || "", { minify: true }).then((result) => [moduleId, {
744
+ ...module,
745
+ code: result.code
746
+ }]));
747
+ bundle$1.modules = Object.fromEntries(await Promise.all(minifiedModuleEntryPromises));
748
+ }
749
+ }
750
+ }, visualizer({
751
+ ...analyzeOptions,
752
+ filename: "filename" in analyzeOptions && analyzeOptions.filename ? analyzeOptions.filename.replace("{name}", "client") : void 0,
753
+ title: "Client bundle stats",
754
+ gzipSize: true,
755
+ brotliSize: true
756
+ })];
757
+ }
758
+ };
895
759
  }
896
760
 
761
+ //#endregion
762
+ //#region src/plugins/dev-server.ts
897
763
  function DevServerPlugin(nuxt) {
898
- let useViteCors = false;
899
- const nitro = useNitro();
900
- return {
901
- name: "nuxt:dev-server",
902
- async config(config) {
903
- for (const item of [config.optimizeDeps, config.environments?.client?.optimizeDeps, config.environments?.ssr?.optimizeDeps]) {
904
- if (!item) {
905
- continue;
906
- }
907
- const exclude = new Set(item.exclude ?? []);
908
- item.include = item.include?.filter((dep) => !exclude.has(dep));
909
- }
910
- if (!nuxt.options.dev && config.server) {
911
- config.server.hmr = false;
912
- }
913
- useViteCors = config.server?.cors !== void 0;
914
- if (!useViteCors) {
915
- config.server ??= {};
916
- config.server.cors = false;
917
- }
918
- if (config.server && config.server.hmr !== false) {
919
- const serverDefaults = {
920
- hmr: {
921
- protocol: nuxt.options.devServer.https ? "wss" : void 0
922
- }
923
- };
924
- if (typeof config.server.hmr !== "object" || !config.server.hmr.server) {
925
- serverDefaults.hmr ??= {};
926
- const hmrPortDefault = 24678;
927
- serverDefaults.hmr.port = await getPort({
928
- verbose: false,
929
- portRange: [hmrPortDefault, hmrPortDefault + 20]
930
- });
931
- }
932
- if (nuxt.options.devServer.https) {
933
- serverDefaults.https = nuxt.options.devServer.https === true ? {} : nuxt.options.devServer.https;
934
- }
935
- config.server = defu(config.server, serverDefaults);
936
- }
937
- },
938
- async configureServer(viteServer) {
939
- nuxt.hook("app:templatesGenerated", async (_app, changedTemplates) => {
940
- await Promise.all(changedTemplates.map(async (template) => {
941
- for (const mod of viteServer.moduleGraph.getModulesByFile(`virtual:nuxt:${encodeURIComponent(template.dst)}`) || []) {
942
- viteServer.moduleGraph.invalidateModule(mod);
943
- await viteServer.reloadModule(mod);
944
- }
945
- }));
946
- });
947
- if (nuxt.options.experimental.viteEnvironmentApi) {
948
- await nuxt.callHook("vite:serverCreated", viteServer, { isClient: true, isServer: true });
949
- }
950
- const mw = {
951
- route: "",
952
- handle: (req, res, next) => {
953
- if (req._skip_transform && req.url) {
954
- req.url = joinURL("/__skip_vite", req.url.replace(/\?.*/, ""));
955
- }
956
- next();
957
- }
958
- };
959
- const transformHandler = viteServer.middlewares.stack.findIndex((m) => m.handle instanceof Function && m.handle.name === "viteTransformMiddleware");
960
- if (transformHandler === -1) {
961
- viteServer.middlewares.stack.push(mw);
962
- } else {
963
- viteServer.middlewares.stack.splice(transformHandler, 0, mw);
964
- }
965
- const staticBases = [];
966
- for (const folder of nitro.options.publicAssets) {
967
- if (folder.baseURL && folder.baseURL !== "/" && folder.baseURL.startsWith(nuxt.options.app.buildAssetsDir)) {
968
- staticBases.push(folder.baseURL.replace(/\/?$/, "/"));
969
- }
970
- }
971
- const devHandlerRegexes = [];
972
- for (const handler of nuxt.options.devServerHandlers) {
973
- if (handler.route && handler.route !== "/" && handler.route.startsWith(nuxt.options.app.buildAssetsDir)) {
974
- devHandlerRegexes.push(new RegExp(
975
- `^${handler.route.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/:[^/]+/g, "[^/]+").replace(/\*\*/g, ".*").replace(/\*/g, "[^/]*")}$`
976
- // single wildcard (*) to match any segment
977
- ));
978
- }
979
- }
980
- const viteMiddleware = defineLazyEventHandler(() => {
981
- const proxyConfig = viteServer.config.server.proxy;
982
- const proxyPatterns = [];
983
- if (proxyConfig) {
984
- for (const key in proxyConfig) {
985
- if (key.startsWith("^")) {
986
- try {
987
- proxyPatterns.push({ type: "regex", value: new RegExp(key) });
988
- } catch {
989
- }
990
- } else {
991
- proxyPatterns.push({ type: "string", value: key });
992
- }
993
- }
994
- }
995
- function isProxyPath(path) {
996
- for (const pattern of proxyPatterns) {
997
- if (pattern.type === "regex" && pattern.value.test(path)) {
998
- return true;
999
- } else if (pattern.type === "string" && path.startsWith(pattern.value)) {
1000
- return true;
1001
- }
1002
- }
1003
- return false;
1004
- }
1005
- return defineEventHandler(async (event) => {
1006
- const isBasePath = event.path.startsWith(viteServer.config.base);
1007
- let isViteRoute = isBasePath;
1008
- if (!isViteRoute) {
1009
- for (const viteRoute of viteServer.middlewares.stack) {
1010
- if (viteRoute.route.length > 1 && event.path.startsWith(viteRoute.route)) {
1011
- isViteRoute = true;
1012
- break;
1013
- }
1014
- }
1015
- isViteRoute ||= isProxyPath(event.path);
1016
- }
1017
- if (!isViteRoute) {
1018
- event.node.req._skip_transform = true;
1019
- } else if (!useViteCors) {
1020
- const isPreflight = handleCors(event, nuxt.options.devServer.cors);
1021
- if (isPreflight) {
1022
- return null;
1023
- }
1024
- setHeader(event, "Vary", "Origin");
1025
- }
1026
- const _originalPath = event.node.req.url;
1027
- await new Promise((resolve, reject) => {
1028
- viteServer.middlewares.handle(event.node.req, event.node.res, (err) => {
1029
- event.node.req.url = _originalPath;
1030
- return err ? reject(err) : resolve(null);
1031
- });
1032
- });
1033
- const ended = event.node.res.writableEnded || event.handled;
1034
- if (!ended && event.path.startsWith(nuxt.options.app.buildAssetsDir) && !staticBases.some((baseURL) => event.path.startsWith(baseURL)) && !devHandlerRegexes.some((regex) => regex.test(event.path))) {
1035
- throw createError({ status: 404 });
1036
- }
1037
- });
1038
- });
1039
- await nuxt.callHook("server:devHandler", viteMiddleware);
1040
- }
1041
- };
764
+ let useViteCors = false;
765
+ const nitro = useNitro();
766
+ return {
767
+ name: "nuxt:dev-server",
768
+ async config(config) {
769
+ for (const item of [
770
+ config.optimizeDeps,
771
+ config.environments?.client?.optimizeDeps,
772
+ config.environments?.ssr?.optimizeDeps
773
+ ]) {
774
+ if (!item) continue;
775
+ const exclude = new Set(item.exclude ?? []);
776
+ item.include = item.include?.filter((dep) => !exclude.has(dep));
777
+ }
778
+ if (!nuxt.options.dev && config.server) config.server.hmr = false;
779
+ useViteCors = config.server?.cors !== void 0;
780
+ if (!useViteCors) {
781
+ config.server ??= {};
782
+ config.server.cors = false;
783
+ }
784
+ if (config.server && config.server.hmr !== false) {
785
+ const serverDefaults = { hmr: { protocol: nuxt.options.devServer.https ? "wss" : void 0 } };
786
+ if (typeof config.server.hmr !== "object" || !config.server.hmr.server) {
787
+ serverDefaults.hmr ??= {};
788
+ const hmrPortDefault = 24678;
789
+ serverDefaults.hmr.port = await getPort({
790
+ verbose: false,
791
+ portRange: [hmrPortDefault, hmrPortDefault + 20]
792
+ });
793
+ }
794
+ if (nuxt.options.devServer.https) serverDefaults.https = nuxt.options.devServer.https === true ? {} : nuxt.options.devServer.https;
795
+ config.server = defu(config.server, serverDefaults);
796
+ }
797
+ },
798
+ async configureServer(viteServer) {
799
+ nuxt.hook("app:templatesGenerated", async (_app, changedTemplates) => {
800
+ await Promise.all(changedTemplates.map(async (template) => {
801
+ for (const mod of viteServer.moduleGraph.getModulesByFile(`virtual:nuxt:${encodeURIComponent(template.dst)}`) || []) {
802
+ viteServer.moduleGraph.invalidateModule(mod);
803
+ await viteServer.reloadModule(mod);
804
+ }
805
+ }));
806
+ });
807
+ if (nuxt.options.experimental.viteEnvironmentApi) await nuxt.callHook("vite:serverCreated", viteServer, {
808
+ isClient: true,
809
+ isServer: true
810
+ });
811
+ const mw = {
812
+ route: "",
813
+ handle: (req, res, next) => {
814
+ if (req._skip_transform && req.url) req.url = joinURL("/__skip_vite", req.url.replace(/\?.*/, ""));
815
+ next();
816
+ }
817
+ };
818
+ const transformHandler = viteServer.middlewares.stack.findIndex((m) => m.handle instanceof Function && m.handle.name === "viteTransformMiddleware");
819
+ if (transformHandler === -1) viteServer.middlewares.stack.push(mw);
820
+ else viteServer.middlewares.stack.splice(transformHandler, 0, mw);
821
+ const staticBases = [];
822
+ for (const folder of nitro.options.publicAssets) if (folder.baseURL && folder.baseURL !== "/" && folder.baseURL.startsWith(nuxt.options.app.buildAssetsDir)) staticBases.push(folder.baseURL.replace(/\/?$/, "/"));
823
+ const devHandlerRegexes = [];
824
+ for (const handler of nuxt.options.devServerHandlers) if (handler.route && handler.route !== "/" && handler.route.startsWith(nuxt.options.app.buildAssetsDir)) devHandlerRegexes.push(/* @__PURE__ */ new RegExp(`^${handler.route.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/:[^/]+/g, "[^/]+").replace(/\*\*/g, ".*").replace(/\*/g, "[^/]*")}$`));
825
+ const viteMiddleware = defineLazyEventHandler(() => {
826
+ const proxyConfig = viteServer.config.server.proxy;
827
+ const proxyPatterns = [];
828
+ if (proxyConfig) for (const key in proxyConfig) if (key.startsWith("^")) try {
829
+ proxyPatterns.push({
830
+ type: "regex",
831
+ value: new RegExp(key)
832
+ });
833
+ } catch {}
834
+ else proxyPatterns.push({
835
+ type: "string",
836
+ value: key
837
+ });
838
+ function isProxyPath(path) {
839
+ for (const pattern of proxyPatterns) if (pattern.type === "regex" && pattern.value.test(path)) return true;
840
+ else if (pattern.type === "string" && path.startsWith(pattern.value)) return true;
841
+ return false;
842
+ }
843
+ return defineEventHandler(async (event) => {
844
+ let isViteRoute = event.path.startsWith(viteServer.config.base);
845
+ if (!isViteRoute) {
846
+ for (const viteRoute of viteServer.middlewares.stack) if (viteRoute.route.length > 1 && event.path.startsWith(viteRoute.route)) {
847
+ isViteRoute = true;
848
+ break;
849
+ }
850
+ isViteRoute ||= isProxyPath(event.path);
851
+ }
852
+ if (!isViteRoute) event.node.req._skip_transform = true;
853
+ else if (!useViteCors) {
854
+ if (handleCors(event, nuxt.options.devServer.cors)) return null;
855
+ setHeader(event, "Vary", "Origin");
856
+ }
857
+ const _originalPath = event.node.req.url;
858
+ await new Promise((resolve$1, reject) => {
859
+ viteServer.middlewares.handle(event.node.req, event.node.res, (err) => {
860
+ event.node.req.url = _originalPath;
861
+ return err ? reject(err) : resolve$1(null);
862
+ });
863
+ });
864
+ if (!(event.node.res.writableEnded || event.handled) && event.path.startsWith(nuxt.options.app.buildAssetsDir) && !staticBases.some((baseURL) => event.path.startsWith(baseURL)) && !devHandlerRegexes.some((regex) => regex.test(event.path))) throw createError({ status: 404 });
865
+ });
866
+ });
867
+ await nuxt.callHook("server:devHandler", viteMiddleware);
868
+ }
869
+ };
1042
870
  }
1043
871
 
872
+ //#endregion
873
+ //#region src/plugins/vite-plugin-checker.ts
1044
874
  async function VitePluginCheckerPlugin(nuxt, environment) {
1045
- if (!nuxt.options.test && (nuxt.options.typescript.typeCheck === true || nuxt.options.typescript.typeCheck === "build" && !nuxt.options.dev)) {
1046
- const [checker, tsconfigPath] = await Promise.all([
1047
- import('vite-plugin-checker').then((r) => r.default),
1048
- resolveTSConfig(nuxt.options.rootDir)
1049
- ]);
1050
- const supportsProjects = await readTSConfig(tsconfigPath).then((r) => !!r.references?.length);
1051
- const environments = ["client", nuxt.options.ssr ? "ssr" : void 0].filter((name) => environment ? name === environment : !!name);
1052
- return environments.map((envName) => ({
1053
- applyToEnvironment: (environment2) => environment2.name === envName,
1054
- ...checker({
1055
- vueTsc: {
1056
- tsconfigPath,
1057
- buildMode: supportsProjects
1058
- }
1059
- })
1060
- }));
1061
- }
875
+ if (!nuxt.options.test && (nuxt.options.typescript.typeCheck === true || nuxt.options.typescript.typeCheck === "build" && !nuxt.options.dev)) {
876
+ const [checker, tsconfigPath] = await Promise.all([import("vite-plugin-checker").then((r) => r.default), resolveTSConfig(nuxt.options.rootDir)]);
877
+ const supportsProjects = await readTSConfig(tsconfigPath).then((r) => !!r.references?.length);
878
+ return ["client", nuxt.options.ssr ? "ssr" : void 0].filter((name) => environment ? name === environment : !!name).map((envName) => ({
879
+ applyToEnvironment: (environment$1) => environment$1.name === envName,
880
+ ...checker({ vueTsc: {
881
+ tsconfigPath,
882
+ buildMode: supportsProjects
883
+ } })
884
+ }));
885
+ }
1062
886
  }
1063
887
 
888
+ //#endregion
889
+ //#region src/utils/transpile.ts
1064
890
  function getTranspilePatterns(envs) {
1065
- const nuxt = useNuxt();
1066
- const transpile = [];
1067
- for (let pattern of nuxt.options.build.transpile) {
1068
- if (typeof pattern === "function") {
1069
- const result = pattern(envs);
1070
- if (result) {
1071
- pattern = result;
1072
- }
1073
- }
1074
- if (typeof pattern === "string") {
1075
- transpile.push(new RegExp(escapeStringRegexp(normalize(pattern))));
1076
- } else if (pattern instanceof RegExp) {
1077
- transpile.push(pattern);
1078
- }
1079
- }
1080
- return transpile;
891
+ const nuxt = useNuxt();
892
+ const transpile = [];
893
+ for (let pattern of nuxt.options.build.transpile) {
894
+ if (typeof pattern === "function") {
895
+ const result = pattern(envs);
896
+ if (result) pattern = result;
897
+ }
898
+ if (typeof pattern === "string") transpile.push(new RegExp(escapeStringRegexp(normalize(pattern))));
899
+ else if (pattern instanceof RegExp) transpile.push(pattern);
900
+ }
901
+ return transpile;
1081
902
  }
903
+ /**
904
+ * Get transpile patterns as strings for use with Vite's optimizeDeps.exclude
905
+ * This resolves functions and filters to only string patterns
906
+ */
1082
907
  function getTranspileStrings(envs) {
1083
- const nuxt = useNuxt();
1084
- const patterns = [];
1085
- for (let pattern of nuxt.options.build.transpile) {
1086
- if (typeof pattern === "function") {
1087
- const result = pattern(envs);
1088
- if (result) {
1089
- pattern = result;
1090
- }
1091
- }
1092
- if (typeof pattern === "string") {
1093
- patterns.push(normalize(pattern));
1094
- }
1095
- }
1096
- return patterns;
908
+ const nuxt = useNuxt();
909
+ const patterns = [];
910
+ for (let pattern of nuxt.options.build.transpile) {
911
+ if (typeof pattern === "function") {
912
+ const result = pattern(envs);
913
+ if (result) pattern = result;
914
+ }
915
+ if (typeof pattern === "string") patterns.push(normalize(pattern));
916
+ }
917
+ return patterns;
1097
918
  }
1098
919
 
920
+ //#endregion
921
+ //#region src/shared/client.ts
1099
922
  const clientEnvironment = (nuxt, entry) => {
1100
- return {
1101
- optimizeDeps: {
1102
- entries: [entry],
1103
- include: [],
1104
- // We exclude Vue and Nuxt common dependencies from optimization
1105
- // as they already ship ESM.
1106
- //
1107
- // This will help to reduce the chance for users to encounter
1108
- // common chunk conflicts that causing browser reloads.
1109
- // We should also encourage module authors to add their deps to
1110
- // `exclude` if they ships bundled ESM.
1111
- //
1112
- // Also since `exclude` is inert, it's safe to always include
1113
- // all possible deps even if they are not used yet.
1114
- //
1115
- // @see https://github.com/antfu/nuxt-better-optimize-deps#how-it-works
1116
- exclude: [
1117
- // Vue
1118
- "vue",
1119
- "@vue/runtime-core",
1120
- "@vue/runtime-dom",
1121
- "@vue/reactivity",
1122
- "@vue/shared",
1123
- "@vue/devtools-api",
1124
- "@vue/test-utils",
1125
- "vue-router",
1126
- "vue-demi",
1127
- // Nuxt
1128
- "nuxt",
1129
- "nuxt/app",
1130
- "@nuxt/test-utils",
1131
- // Nuxt Deps
1132
- "@unhead/vue",
1133
- "consola",
1134
- "defu",
1135
- "devalue",
1136
- "get-port-please",
1137
- "h3",
1138
- "hookable",
1139
- "klona",
1140
- "ofetch",
1141
- "pathe",
1142
- "ufo",
1143
- "unctx",
1144
- "unenv",
1145
- // this will never be imported on the client
1146
- "#app-manifest",
1147
- // these should all be valid ESM
1148
- "#imports",
1149
- "#app",
1150
- "#build",
1151
- "#build/*",
1152
- "#components",
1153
- "#head",
1154
- "virtual:nuxt:",
1155
- "virtual:nuxt:*",
1156
- ...getTranspileStrings({ isDev: nuxt.options.dev, isClient: true })
1157
- ]
1158
- },
1159
- define: {
1160
- "process.env.NODE_ENV": JSON.stringify(nuxt.options.vite.mode),
1161
- "process.server": false,
1162
- "process.client": true,
1163
- "process.browser": true,
1164
- "process.nitro": false,
1165
- "process.prerender": false,
1166
- "import.meta.server": false,
1167
- "import.meta.client": true,
1168
- "import.meta.browser": true,
1169
- "import.meta.nitro": false,
1170
- "import.meta.prerender": false,
1171
- "module.hot": false,
1172
- ...nuxt.options.experimental.clientNodeCompat ? { global: "globalThis" } : {}
1173
- },
1174
- build: {
1175
- sourcemap: nuxt.options.sourcemap.client ? nuxt.options.vite.build?.sourcemap ?? nuxt.options.sourcemap.client : false,
1176
- manifest: "manifest.json",
1177
- outDir: resolve(nuxt.options.buildDir, "dist/client"),
1178
- rollupOptions: {
1179
- input: { entry }
1180
- }
1181
- }
1182
- };
923
+ return {
924
+ optimizeDeps: {
925
+ entries: [entry],
926
+ include: [],
927
+ exclude: [
928
+ "vue",
929
+ "@vue/runtime-core",
930
+ "@vue/runtime-dom",
931
+ "@vue/reactivity",
932
+ "@vue/shared",
933
+ "@vue/devtools-api",
934
+ "@vue/test-utils",
935
+ "vue-router",
936
+ "vue-demi",
937
+ "nuxt",
938
+ "nuxt/app",
939
+ "@nuxt/test-utils",
940
+ "@unhead/vue",
941
+ "consola",
942
+ "defu",
943
+ "devalue",
944
+ "get-port-please",
945
+ "h3",
946
+ "hookable",
947
+ "klona",
948
+ "ofetch",
949
+ "pathe",
950
+ "ufo",
951
+ "unctx",
952
+ "unenv",
953
+ "#app-manifest",
954
+ "#imports",
955
+ "#app",
956
+ "#build",
957
+ "#build/*",
958
+ "#components",
959
+ "#head",
960
+ "virtual:nuxt:",
961
+ "virtual:nuxt:*",
962
+ ...getTranspileStrings({
963
+ isDev: nuxt.options.dev,
964
+ isClient: true
965
+ })
966
+ ]
967
+ },
968
+ define: {
969
+ "process.env.NODE_ENV": JSON.stringify(nuxt.options.vite.mode),
970
+ "process.server": false,
971
+ "process.client": true,
972
+ "process.browser": true,
973
+ "process.nitro": false,
974
+ "process.prerender": false,
975
+ "import.meta.server": false,
976
+ "import.meta.client": true,
977
+ "import.meta.browser": true,
978
+ "import.meta.nitro": false,
979
+ "import.meta.prerender": false,
980
+ "module.hot": false,
981
+ ...nuxt.options.experimental.clientNodeCompat ? { global: "globalThis" } : {}
982
+ },
983
+ build: {
984
+ sourcemap: nuxt.options.sourcemap.client ? nuxt.options.vite.build?.sourcemap ?? nuxt.options.sourcemap.client : false,
985
+ manifest: "manifest.json",
986
+ outDir: resolve(nuxt.options.buildDir, "dist/client"),
987
+ rollupOptions: { input: { entry } }
988
+ }
989
+ };
1183
990
  };
1184
991
 
992
+ //#endregion
993
+ //#region src/client.ts
1185
994
  async function buildClient(nuxt, ctx) {
1186
- const clientConfig = vite.mergeConfig(ctx.config, vite.mergeConfig({
1187
- configFile: false,
1188
- base: nuxt.options.dev ? joinURL(nuxt.options.app.baseURL.replace(/^\.\//, "/") || "/", nuxt.options.app.buildAssetsDir) : "./",
1189
- css: {
1190
- devSourcemap: !!nuxt.options.sourcemap.client
1191
- },
1192
- cacheDir: resolve(nuxt.options.rootDir, ctx.config.cacheDir ?? "node_modules/.cache/vite", "client"),
1193
- plugins: [
1194
- DevStyleSSRPlugin({
1195
- srcDir: nuxt.options.srcDir,
1196
- buildAssetsURL: joinURL(nuxt.options.app.baseURL, nuxt.options.app.buildAssetsDir)
1197
- }),
1198
- RuntimePathsPlugin(),
1199
- ViteNodePlugin(nuxt),
1200
- // Type checking client panel
1201
- TypeCheckPlugin(nuxt),
1202
- ModulePreloadPolyfillPlugin(),
1203
- // ensure changes in chunks do not invalidate whole build
1204
- StableEntryPlugin(nuxt),
1205
- AnalyzePlugin(nuxt),
1206
- DevServerPlugin(nuxt),
1207
- VitePluginCheckerPlugin(nuxt, "client")
1208
- ],
1209
- appType: "custom",
1210
- server: {
1211
- warmup: {
1212
- clientFiles: [ctx.entry]
1213
- },
1214
- middlewareMode: true
1215
- },
1216
- ...clientEnvironment(nuxt, ctx.entry)
1217
- }, nuxt.options.vite.$client || {}));
1218
- clientConfig.customLogger = createViteLogger(clientConfig);
1219
- await nuxt.callHook("vite:extendConfig", clientConfig, { isClient: true, isServer: false });
1220
- clientConfig.plugins.unshift(
1221
- vuePlugin(clientConfig.vue),
1222
- viteJsxPlugin(clientConfig.vueJsx)
1223
- );
1224
- await nuxt.callHook("vite:configResolved", clientConfig, { isClient: true, isServer: false });
1225
- if (nuxt.options.dev) {
1226
- const viteServer = await vite.createServer(clientConfig);
1227
- ctx.clientServer = viteServer;
1228
- nuxt.hook("close", () => viteServer.close());
1229
- await nuxt.callHook("vite:serverCreated", viteServer, { isClient: true, isServer: false });
1230
- } else {
1231
- logger.info("Building client...");
1232
- const start = Date.now();
1233
- logger.restoreAll();
1234
- await vite.build(clientConfig);
1235
- logger.wrapAll();
1236
- await nuxt.callHook("vite:compiled");
1237
- logger.success(`Client built in ${Date.now() - start}ms`);
1238
- }
995
+ const clientConfig = vite.mergeConfig(ctx.config, vite.mergeConfig({
996
+ configFile: false,
997
+ base: nuxt.options.dev ? joinURL(nuxt.options.app.baseURL.replace(/^\.\//, "/") || "/", nuxt.options.app.buildAssetsDir) : "./",
998
+ css: { devSourcemap: !!nuxt.options.sourcemap.client },
999
+ cacheDir: resolve(nuxt.options.rootDir, ctx.config.cacheDir ?? "node_modules/.cache/vite", "client"),
1000
+ plugins: [
1001
+ DevStyleSSRPlugin({
1002
+ srcDir: nuxt.options.srcDir,
1003
+ buildAssetsURL: joinURL(nuxt.options.app.baseURL, nuxt.options.app.buildAssetsDir)
1004
+ }),
1005
+ RuntimePathsPlugin(),
1006
+ ViteNodePlugin(nuxt),
1007
+ TypeCheckPlugin(nuxt),
1008
+ ModulePreloadPolyfillPlugin(),
1009
+ StableEntryPlugin(nuxt),
1010
+ AnalyzePlugin(nuxt),
1011
+ DevServerPlugin(nuxt),
1012
+ VitePluginCheckerPlugin(nuxt, "client")
1013
+ ],
1014
+ appType: "custom",
1015
+ server: {
1016
+ warmup: { clientFiles: [ctx.entry] },
1017
+ middlewareMode: true
1018
+ },
1019
+ ...clientEnvironment(nuxt, ctx.entry)
1020
+ }, nuxt.options.vite.$client || {}));
1021
+ clientConfig.customLogger = createViteLogger(clientConfig);
1022
+ await nuxt.callHook("vite:extendConfig", clientConfig, {
1023
+ isClient: true,
1024
+ isServer: false
1025
+ });
1026
+ clientConfig.plugins.unshift(vuePlugin(clientConfig.vue), viteJsxPlugin(clientConfig.vueJsx));
1027
+ await nuxt.callHook("vite:configResolved", clientConfig, {
1028
+ isClient: true,
1029
+ isServer: false
1030
+ });
1031
+ if (nuxt.options.dev) {
1032
+ const viteServer = await vite.createServer(clientConfig);
1033
+ ctx.clientServer = viteServer;
1034
+ nuxt.hook("close", () => viteServer.close());
1035
+ await nuxt.callHook("vite:serverCreated", viteServer, {
1036
+ isClient: true,
1037
+ isServer: false
1038
+ });
1039
+ } else {
1040
+ logger.info("Building client...");
1041
+ const start = Date.now();
1042
+ logger.restoreAll();
1043
+ await vite.build(clientConfig);
1044
+ logger.wrapAll();
1045
+ await nuxt.callHook("vite:compiled");
1046
+ logger.success(`Client built in ${Date.now() - start}ms`);
1047
+ }
1239
1048
  }
1240
1049
 
1050
+ //#endregion
1051
+ //#region src/manifest.ts
1241
1052
  async function writeManifest(ctx) {
1242
- const { nuxt } = ctx;
1243
- const devClientManifest = {
1244
- "@vite/client": {
1245
- isEntry: true,
1246
- file: "@vite/client",
1247
- css: [],
1248
- module: true,
1249
- resourceType: "script"
1250
- },
1251
- ...nuxt.options.features.noScripts === "all" ? {} : {
1252
- [ctx.entry]: {
1253
- isEntry: true,
1254
- file: ctx.entry,
1255
- module: true,
1256
- resourceType: "script"
1257
- }
1258
- }
1259
- };
1260
- const clientDist = resolve(nuxt.options.buildDir, "dist/client");
1261
- const serverDist = resolve(nuxt.options.buildDir, "dist/server");
1262
- const manifestFile = resolve(clientDist, "manifest.json");
1263
- const clientManifest = nuxt.options.dev ? devClientManifest : JSON.parse(readFileSync(manifestFile, "utf-8"));
1264
- const manifestEntries = Object.values(clientManifest);
1265
- const buildAssetsDir = withTrailingSlash(withoutLeadingSlash(nuxt.options.app.buildAssetsDir));
1266
- const BASE_RE = new RegExp(`^${escapeStringRegexp(buildAssetsDir)}`);
1267
- for (const entry of manifestEntries) {
1268
- entry.file &&= entry.file.replace(BASE_RE, "");
1269
- for (const item of ["css", "assets"]) {
1270
- entry[item] &&= entry[item].map((i) => i.replace(BASE_RE, ""));
1271
- }
1272
- }
1273
- await mkdir(serverDist, { recursive: true });
1274
- if (ctx.config.build?.cssCodeSplit === false) {
1275
- for (const entry of manifestEntries) {
1276
- if (entry.file?.endsWith(".css")) {
1277
- const key = relative(ctx.config.root, ctx.entry);
1278
- clientManifest[key].css ||= [];
1279
- clientManifest[key].css.push(entry.file);
1280
- break;
1281
- }
1282
- }
1283
- }
1284
- const manifest = normalizeViteManifest(clientManifest);
1285
- await nuxt.callHook("build:manifest", manifest);
1286
- const precomputed = precomputeDependencies(manifest);
1287
- await writeFile(resolve(serverDist, "client.manifest.mjs"), "export default " + serialize(manifest), "utf8");
1288
- await writeFile(resolve(serverDist, "client.precomputed.mjs"), "export default " + serialize(precomputed), "utf8");
1289
- if (!nuxt.options.dev) {
1290
- await rm(manifestFile, { force: true });
1291
- }
1053
+ const { nuxt } = ctx;
1054
+ const devClientManifest = {
1055
+ "@vite/client": {
1056
+ isEntry: true,
1057
+ file: "@vite/client",
1058
+ css: [],
1059
+ module: true,
1060
+ resourceType: "script"
1061
+ },
1062
+ ...nuxt.options.features.noScripts === "all" ? {} : { [ctx.entry]: {
1063
+ isEntry: true,
1064
+ file: ctx.entry,
1065
+ module: true,
1066
+ resourceType: "script"
1067
+ } }
1068
+ };
1069
+ const clientDist = resolve(nuxt.options.buildDir, "dist/client");
1070
+ const serverDist = resolve(nuxt.options.buildDir, "dist/server");
1071
+ const manifestFile = resolve(clientDist, "manifest.json");
1072
+ const clientManifest = nuxt.options.dev ? devClientManifest : JSON.parse(readFileSync(manifestFile, "utf-8"));
1073
+ const manifestEntries = Object.values(clientManifest);
1074
+ const buildAssetsDir = withTrailingSlash(withoutLeadingSlash(nuxt.options.app.buildAssetsDir));
1075
+ const BASE_RE = /* @__PURE__ */ new RegExp(`^${escapeStringRegexp(buildAssetsDir)}`);
1076
+ for (const entry of manifestEntries) {
1077
+ entry.file &&= entry.file.replace(BASE_RE, "");
1078
+ for (const item of ["css", "assets"]) entry[item] &&= entry[item].map((i) => i.replace(BASE_RE, ""));
1079
+ }
1080
+ await mkdir(serverDist, { recursive: true });
1081
+ if (ctx.config.build?.cssCodeSplit === false) {
1082
+ for (const entry of manifestEntries) if (entry.file?.endsWith(".css")) {
1083
+ const key = relative(ctx.config.root, ctx.entry);
1084
+ clientManifest[key].css ||= [];
1085
+ clientManifest[key].css.push(entry.file);
1086
+ break;
1087
+ }
1088
+ }
1089
+ const manifest = normalizeViteManifest(clientManifest);
1090
+ await nuxt.callHook("build:manifest", manifest);
1091
+ const precomputed = precomputeDependencies(manifest);
1092
+ await writeFile(resolve(serverDist, "client.manifest.mjs"), "export default " + serialize(manifest), "utf8");
1093
+ await writeFile(resolve(serverDist, "client.precomputed.mjs"), "export default " + serialize(precomputed), "utf8");
1094
+ if (!nuxt.options.dev) await rm(manifestFile, { force: true });
1292
1095
  }
1293
1096
 
1097
+ //#endregion
1098
+ //#region src/plugins/sourcemap-preserver.ts
1294
1099
  const SourcemapPreserverPlugin = (nuxt) => {
1295
- let outputDir;
1296
- const ids = /* @__PURE__ */ new Set();
1297
- if (!nuxt.options.sourcemap.server || nuxt.options.dev) {
1298
- return [];
1299
- }
1300
- const nitroPlugin = () => ({
1301
- name: "nuxt:sourcemap-import",
1302
- load: {
1303
- filter: {
1304
- id: new RegExp("^(\\w:)?" + escapeStringRegexp(outputDir.replace(/\/?$/, "/")).replace(/\//g, "[\\\\/]"))
1305
- },
1306
- async handler(id) {
1307
- id = resolve(id);
1308
- if (!ids.has(id)) {
1309
- return;
1310
- }
1311
- const [code, map] = await Promise.all([
1312
- readFile(id, "utf-8").catch(() => void 0),
1313
- readFile(id + ".map.json", "utf-8").catch(() => void 0)
1314
- ]);
1315
- if (!code) {
1316
- this.warn("Failed loading file");
1317
- return null;
1318
- }
1319
- return {
1320
- code,
1321
- map
1322
- };
1323
- }
1324
- }
1325
- });
1326
- nuxt.hook("nitro:build:before", (nitro) => {
1327
- nitro.options.rollupConfig = defu(nitro.options.rollupConfig, {
1328
- plugins: [nitroPlugin]
1329
- });
1330
- });
1331
- return {
1332
- name: "nuxt:sourcemap-export",
1333
- applyToEnvironment: (environment) => {
1334
- return environment.name === "ssr" && environment.config.isProduction;
1335
- },
1336
- apply(config) {
1337
- return !!config.build?.sourcemap;
1338
- },
1339
- configResolved(config) {
1340
- outputDir = config.build.outDir;
1341
- },
1342
- async writeBundle(_options, bundle) {
1343
- for (const chunk of Object.values(bundle)) {
1344
- if (chunk.type !== "chunk" || !chunk.map) {
1345
- continue;
1346
- }
1347
- const id = resolve(outputDir, chunk.fileName);
1348
- ids.add(id);
1349
- const dest = id + ".map.json";
1350
- await mkdir(dirname(dest), { recursive: true });
1351
- await writeFile(dest, JSON.stringify({
1352
- file: chunk.map.file,
1353
- mappings: chunk.map.mappings,
1354
- names: chunk.map.names,
1355
- sources: chunk.map.sources,
1356
- sourcesContent: chunk.map.sourcesContent,
1357
- version: chunk.map.version
1358
- }));
1359
- }
1360
- }
1361
- };
1100
+ let outputDir;
1101
+ const ids = /* @__PURE__ */ new Set();
1102
+ if (!nuxt.options.sourcemap.server || nuxt.options.dev) return [];
1103
+ const nitroPlugin = () => ({
1104
+ name: "nuxt:sourcemap-import",
1105
+ load: {
1106
+ filter: { id: /* @__PURE__ */ new RegExp("^(\\w:)?" + escapeStringRegexp(outputDir.replace(/\/?$/, "/")).replace(/\//g, "[\\\\/]")) },
1107
+ async handler(id) {
1108
+ id = resolve(id);
1109
+ if (!ids.has(id)) return;
1110
+ const [code, map] = await Promise.all([readFile(id, "utf-8").catch(() => void 0), readFile(id + ".map.json", "utf-8").catch(() => void 0)]);
1111
+ if (!code) {
1112
+ this.warn("Failed loading file");
1113
+ return null;
1114
+ }
1115
+ return {
1116
+ code,
1117
+ map
1118
+ };
1119
+ }
1120
+ }
1121
+ });
1122
+ nuxt.hook("nitro:build:before", (nitro) => {
1123
+ nitro.options.rollupConfig = defu(nitro.options.rollupConfig, { plugins: [nitroPlugin] });
1124
+ });
1125
+ return {
1126
+ name: "nuxt:sourcemap-export",
1127
+ applyToEnvironment: (environment) => {
1128
+ return environment.name === "ssr" && environment.config.isProduction;
1129
+ },
1130
+ apply(config) {
1131
+ return !!config.build?.sourcemap;
1132
+ },
1133
+ configResolved(config) {
1134
+ outputDir = config.build.outDir;
1135
+ },
1136
+ async writeBundle(_options, bundle$1) {
1137
+ for (const chunk of Object.values(bundle$1)) {
1138
+ if (chunk.type !== "chunk" || !chunk.map) continue;
1139
+ const id = resolve(outputDir, chunk.fileName);
1140
+ ids.add(id);
1141
+ const dest = id + ".map.json";
1142
+ await mkdir(dirname(dest), { recursive: true });
1143
+ await writeFile(dest, JSON.stringify({
1144
+ file: chunk.map.file,
1145
+ mappings: chunk.map.mappings,
1146
+ names: chunk.map.names,
1147
+ sources: chunk.map.sources,
1148
+ sourcesContent: chunk.map.sourcesContent,
1149
+ version: chunk.map.version
1150
+ }));
1151
+ }
1152
+ }
1153
+ };
1362
1154
  };
1363
1155
 
1156
+ //#endregion
1157
+ //#region src/plugins/vue-feature-flags.ts
1364
1158
  function VueFeatureFlagsPlugin(nuxt) {
1365
- return {
1366
- name: "nuxt:nitro:vue-feature-flags",
1367
- applyToEnvironment: (environment) => environment.name === "ssr" && environment.config.isProduction,
1368
- configResolved(config) {
1369
- for (const key in config.define) {
1370
- if (key.startsWith("__VUE")) {
1371
- nuxt._nitro.options.replace[key] = config.define[key];
1372
- }
1373
- }
1374
- }
1375
- };
1159
+ return {
1160
+ name: "nuxt:nitro:vue-feature-flags",
1161
+ applyToEnvironment: (environment) => environment.name === "ssr" && environment.config.isProduction,
1162
+ configResolved(config) {
1163
+ for (const key in config.define) if (key.startsWith("__VUE")) nuxt._nitro.options.replace[key] = config.define[key];
1164
+ }
1165
+ };
1376
1166
  }
1377
1167
 
1168
+ //#endregion
1169
+ //#region src/shared/server.ts
1378
1170
  function ssr(nuxt) {
1379
- return {
1380
- external: [
1381
- "nitro/runtime",
1382
- // TODO: remove in v5
1383
- "#internal/nitro",
1384
- "#internal/nitro/utils"
1385
- ],
1386
- noExternal: [
1387
- ...getTranspilePatterns({ isServer: true, isDev: nuxt.options.dev }),
1388
- "/__vue-jsx",
1389
- "#app",
1390
- /^nuxt(\/|$)/,
1391
- /(nuxt|nuxt3|nuxt-nightly)\/(dist|src|app)/
1392
- ]
1393
- };
1171
+ return {
1172
+ external: [
1173
+ "nitro/runtime",
1174
+ "#internal/nitro",
1175
+ "#internal/nitro/utils"
1176
+ ],
1177
+ noExternal: [
1178
+ ...getTranspilePatterns({
1179
+ isServer: true,
1180
+ isDev: nuxt.options.dev
1181
+ }),
1182
+ "/__vue-jsx",
1183
+ "#app",
1184
+ /^nuxt(\/|$)/,
1185
+ /(nuxt|nuxt3|nuxt-nightly)\/(dist|src|app)/
1186
+ ]
1187
+ };
1394
1188
  }
1395
1189
  function ssrEnvironment(nuxt, serverEntry) {
1396
- return {
1397
- build: {
1398
- // we'll display this in nitro build output
1399
- reportCompressedSize: false,
1400
- sourcemap: nuxt.options.sourcemap.server ? nuxt.options.vite.build?.sourcemap ?? nuxt.options.sourcemap.server : false,
1401
- outDir: resolve(nuxt.options.buildDir, "dist/server"),
1402
- ssr: true,
1403
- rollupOptions: {
1404
- input: { server: serverEntry },
1405
- external: [
1406
- "nitro/runtime",
1407
- // TODO: remove in v5
1408
- "#internal/nitro",
1409
- "nitropack/runtime",
1410
- "#internal/nuxt/paths",
1411
- "#internal/nuxt/app-config",
1412
- "#app-manifest",
1413
- "#shared",
1414
- new RegExp("^" + escapeStringRegexp(withTrailingSlash(resolve(nuxt.options.rootDir, nuxt.options.dir.shared))))
1415
- ],
1416
- output: {
1417
- entryFileNames: "[name].mjs",
1418
- format: "module",
1419
- ...vite.rolldownVersion ? {} : {
1420
- generatedCode: {
1421
- symbols: true,
1422
- // temporary fix for https://github.com/vuejs/core/issues/8351,
1423
- constBindings: true,
1424
- // temporary fix for https://github.com/rollup/rollup/issues/5975
1425
- arrowFunctions: true
1426
- }
1427
- }
1428
- },
1429
- onwarn(warning, rollupWarn) {
1430
- if (warning.code && "UNUSED_EXTERNAL_IMPORT" === warning.code) {
1431
- return;
1432
- }
1433
- rollupWarn(warning);
1434
- }
1435
- }
1436
- },
1437
- define: {
1438
- "process.server": true,
1439
- "process.client": false,
1440
- "process.browser": false,
1441
- "import.meta.server": true,
1442
- "import.meta.client": false,
1443
- "import.meta.browser": false,
1444
- "window": "undefined",
1445
- "document": "undefined",
1446
- "navigator": "undefined",
1447
- "location": "undefined",
1448
- "XMLHttpRequest": "undefined"
1449
- },
1450
- optimizeDeps: {
1451
- noDiscovery: true,
1452
- include: void 0,
1453
- exclude: getTranspileStrings({ isDev: nuxt.options.dev, isClient: false })
1454
- },
1455
- resolve: {
1456
- conditions: useNitro().options.exportConditions
1457
- }
1458
- };
1190
+ return {
1191
+ build: {
1192
+ reportCompressedSize: false,
1193
+ sourcemap: nuxt.options.sourcemap.server ? nuxt.options.vite.build?.sourcemap ?? nuxt.options.sourcemap.server : false,
1194
+ outDir: resolve(nuxt.options.buildDir, "dist/server"),
1195
+ ssr: true,
1196
+ rollupOptions: {
1197
+ input: { server: serverEntry },
1198
+ external: [
1199
+ "nitro/runtime",
1200
+ "#internal/nitro",
1201
+ "nitropack/runtime",
1202
+ "#internal/nuxt/paths",
1203
+ "#internal/nuxt/app-config",
1204
+ "#app-manifest",
1205
+ "#shared",
1206
+ /* @__PURE__ */ new RegExp("^" + escapeStringRegexp(withTrailingSlash(resolve(nuxt.options.rootDir, nuxt.options.dir.shared))))
1207
+ ],
1208
+ output: {
1209
+ entryFileNames: "[name].mjs",
1210
+ format: "module",
1211
+ ...vite.rolldownVersion ? {} : { generatedCode: {
1212
+ symbols: true,
1213
+ constBindings: true,
1214
+ arrowFunctions: true
1215
+ } }
1216
+ },
1217
+ onwarn(warning, rollupWarn) {
1218
+ if (warning.code && "UNUSED_EXTERNAL_IMPORT" === warning.code) return;
1219
+ rollupWarn(warning);
1220
+ }
1221
+ }
1222
+ },
1223
+ define: {
1224
+ "process.server": true,
1225
+ "process.client": false,
1226
+ "process.browser": false,
1227
+ "import.meta.server": true,
1228
+ "import.meta.client": false,
1229
+ "import.meta.browser": false,
1230
+ "window": "undefined",
1231
+ "document": "undefined",
1232
+ "navigator": "undefined",
1233
+ "location": "undefined",
1234
+ "XMLHttpRequest": "undefined"
1235
+ },
1236
+ optimizeDeps: {
1237
+ noDiscovery: true,
1238
+ include: void 0,
1239
+ exclude: getTranspileStrings({
1240
+ isDev: nuxt.options.dev,
1241
+ isClient: false
1242
+ })
1243
+ },
1244
+ resolve: { conditions: useNitro().options.exportConditions }
1245
+ };
1459
1246
  }
1460
1247
 
1248
+ //#endregion
1249
+ //#region src/server.ts
1461
1250
  async function buildServer(nuxt, ctx) {
1462
- const serverEntry = nuxt.options.ssr ? ctx.entry : await resolvePath(resolve(nuxt.options.appDir, "entry-spa"));
1463
- const serverConfig = vite.mergeConfig(ctx.config, vite.mergeConfig({
1464
- configFile: false,
1465
- base: nuxt.options.dev ? joinURL(nuxt.options.app.baseURL.replace(/^\.\//, "/") || "/", nuxt.options.app.buildAssetsDir) : void 0,
1466
- css: {
1467
- devSourcemap: !!nuxt.options.sourcemap.server
1468
- },
1469
- plugins: [
1470
- VueFeatureFlagsPlugin(nuxt),
1471
- // tell rollup's nitro build about the original sources of the generated vite server build
1472
- SourcemapPreserverPlugin(nuxt),
1473
- VitePluginCheckerPlugin(nuxt, "ssr"),
1474
- {
1475
- name: "nuxt:server-hmr-port",
1476
- async config(serverConfig2) {
1477
- serverConfig2.server ||= {};
1478
- serverConfig2.server.hmr ||= {};
1479
- if (nuxt.options.dev && typeof serverConfig2.server.hmr !== "boolean") {
1480
- const hmrPortDefault = 24678;
1481
- serverConfig2.server.hmr.port ||= await getPort({
1482
- verbose: false,
1483
- portRange: [hmrPortDefault, hmrPortDefault + 20]
1484
- });
1485
- }
1486
- }
1487
- }
1488
- ],
1489
- environments: {
1490
- ssr: {
1491
- resolve: {
1492
- conditions: nuxt._nitro?.options.exportConditions
1493
- }
1494
- }
1495
- },
1496
- ssr: ssr(nuxt),
1497
- cacheDir: resolve(nuxt.options.rootDir, ctx.config.cacheDir ?? "node_modules/.cache/vite", "server"),
1498
- server: {
1499
- warmup: {
1500
- ssrFiles: [serverEntry]
1501
- },
1502
- // https://github.com/vitest-dev/vitest/issues/229#issuecomment-1002685027
1503
- preTransformRequests: false,
1504
- hmr: false
1505
- },
1506
- ...ssrEnvironment(nuxt, serverEntry)
1507
- }, nuxt.options.vite.$server || {}));
1508
- serverConfig.customLogger = createViteLogger(serverConfig, { hideOutput: !nuxt.options.dev });
1509
- await nuxt.callHook("vite:extendConfig", serverConfig, { isClient: false, isServer: true });
1510
- serverConfig.plugins.unshift(
1511
- vuePlugin(serverConfig.vue),
1512
- viteJsxPlugin(serverConfig.vueJsx)
1513
- );
1514
- await nuxt.callHook("vite:configResolved", serverConfig, { isClient: false, isServer: true });
1515
- if (!nuxt.options.dev) {
1516
- const start = Date.now();
1517
- logger.info("Building server...");
1518
- logger.restoreAll();
1519
- await vite.build(serverConfig);
1520
- logger.wrapAll();
1521
- await writeManifest(ctx);
1522
- await nuxt.callHook("vite:compiled");
1523
- logger.success(`Server built in ${Date.now() - start}ms`);
1524
- return;
1525
- }
1526
- if (!nuxt.options.ssr) {
1527
- await writeManifest(ctx);
1528
- await nuxt.callHook("vite:compiled");
1529
- return;
1530
- }
1531
- const ssrServer = await vite.createServer(serverConfig);
1532
- ctx.ssrServer = ssrServer;
1533
- nuxt.hook("close", () => ssrServer.close());
1534
- await nuxt.callHook("vite:serverCreated", ssrServer, { isClient: false, isServer: true });
1535
- nuxt.hook("app:templatesGenerated", async (_app, changedTemplates) => {
1536
- await Promise.all(changedTemplates.map(async (template) => {
1537
- for (const mod of ssrServer.moduleGraph.getModulesByFile(`virtual:nuxt:${encodeURIComponent(template.dst)}`) || []) {
1538
- ssrServer.moduleGraph.invalidateModule(mod);
1539
- await ssrServer.reloadModule(mod);
1540
- }
1541
- }));
1542
- });
1543
- await ssrServer.pluginContainer.buildStart({});
1544
- await writeDevServer(nuxt);
1251
+ const serverEntry = nuxt.options.ssr ? ctx.entry : await resolvePath(resolve(nuxt.options.appDir, "entry-spa"));
1252
+ const serverConfig = vite.mergeConfig(ctx.config, vite.mergeConfig({
1253
+ configFile: false,
1254
+ base: nuxt.options.dev ? joinURL(nuxt.options.app.baseURL.replace(/^\.\//, "/") || "/", nuxt.options.app.buildAssetsDir) : void 0,
1255
+ css: { devSourcemap: !!nuxt.options.sourcemap.server },
1256
+ plugins: [
1257
+ VueFeatureFlagsPlugin(nuxt),
1258
+ SourcemapPreserverPlugin(nuxt),
1259
+ VitePluginCheckerPlugin(nuxt, "ssr"),
1260
+ {
1261
+ name: "nuxt:server-hmr-port",
1262
+ async config(serverConfig$1) {
1263
+ serverConfig$1.server ||= {};
1264
+ serverConfig$1.server.hmr ||= {};
1265
+ if (nuxt.options.dev && typeof serverConfig$1.server.hmr !== "boolean") {
1266
+ const hmrPortDefault = 24678;
1267
+ serverConfig$1.server.hmr.port ||= await getPort({
1268
+ verbose: false,
1269
+ portRange: [hmrPortDefault, hmrPortDefault + 20]
1270
+ });
1271
+ }
1272
+ }
1273
+ }
1274
+ ],
1275
+ environments: { ssr: { resolve: { conditions: nuxt._nitro?.options.exportConditions } } },
1276
+ ssr: ssr(nuxt),
1277
+ cacheDir: resolve(nuxt.options.rootDir, ctx.config.cacheDir ?? "node_modules/.cache/vite", "server"),
1278
+ server: {
1279
+ warmup: { ssrFiles: [serverEntry] },
1280
+ preTransformRequests: false,
1281
+ hmr: false
1282
+ },
1283
+ ...ssrEnvironment(nuxt, serverEntry)
1284
+ }, nuxt.options.vite.$server || {}));
1285
+ serverConfig.customLogger = createViteLogger(serverConfig, { hideOutput: !nuxt.options.dev });
1286
+ await nuxt.callHook("vite:extendConfig", serverConfig, {
1287
+ isClient: false,
1288
+ isServer: true
1289
+ });
1290
+ serverConfig.plugins.unshift(vuePlugin(serverConfig.vue), viteJsxPlugin(serverConfig.vueJsx));
1291
+ await nuxt.callHook("vite:configResolved", serverConfig, {
1292
+ isClient: false,
1293
+ isServer: true
1294
+ });
1295
+ if (!nuxt.options.dev) {
1296
+ const start = Date.now();
1297
+ logger.info("Building server...");
1298
+ logger.restoreAll();
1299
+ await vite.build(serverConfig);
1300
+ logger.wrapAll();
1301
+ await writeManifest(ctx);
1302
+ await nuxt.callHook("vite:compiled");
1303
+ logger.success(`Server built in ${Date.now() - start}ms`);
1304
+ return;
1305
+ }
1306
+ if (!nuxt.options.ssr) {
1307
+ await writeManifest(ctx);
1308
+ await nuxt.callHook("vite:compiled");
1309
+ return;
1310
+ }
1311
+ const ssrServer = await vite.createServer(serverConfig);
1312
+ ctx.ssrServer = ssrServer;
1313
+ nuxt.hook("close", () => ssrServer.close());
1314
+ await nuxt.callHook("vite:serverCreated", ssrServer, {
1315
+ isClient: false,
1316
+ isServer: true
1317
+ });
1318
+ nuxt.hook("app:templatesGenerated", async (_app, changedTemplates) => {
1319
+ await Promise.all(changedTemplates.map(async (template) => {
1320
+ for (const mod of ssrServer.moduleGraph.getModulesByFile(`virtual:nuxt:${encodeURIComponent(template.dst)}`) || []) {
1321
+ ssrServer.moduleGraph.invalidateModule(mod);
1322
+ await ssrServer.reloadModule(mod);
1323
+ }
1324
+ }));
1325
+ });
1326
+ await ssrServer.pluginContainer.buildStart({});
1327
+ await writeDevServer(nuxt);
1545
1328
  }
1546
1329
 
1330
+ //#endregion
1331
+ //#region src/utils/warmup.ts
1547
1332
  function fileToUrl(file, root) {
1548
- const url = relative(root, file);
1549
- if (url[0] === ".") {
1550
- return join("/@fs/", normalize(file));
1551
- }
1552
- return "/" + normalize(url);
1333
+ const url = relative(root, file);
1334
+ if (url[0] === ".") return join("/@fs/", normalize(file));
1335
+ return "/" + normalize(url);
1553
1336
  }
1554
1337
  function normaliseURL(url, base) {
1555
- url = withoutBase(url, base);
1556
- if (url.startsWith("/@id/")) {
1557
- url = url.slice("/@id/".length).replace("__x00__", "\0");
1558
- }
1559
- url = url.replace(/[?&]import=?(?:&|$)/, "").replace(/[?&]$/, "");
1560
- return url;
1338
+ url = withoutBase(url, base);
1339
+ if (url.startsWith("/@id/")) url = url.slice(5).replace("__x00__", "\0");
1340
+ url = url.replace(/[?&]import=?(?:&|$)/, "").replace(/[?&]$/, "");
1341
+ return url;
1561
1342
  }
1562
1343
  async function warmupViteServer(server, entries, isServer) {
1563
- const warmedUrls = /* @__PURE__ */ new Set();
1564
- const warmup = async (url) => {
1565
- try {
1566
- url = normaliseURL(url, server.config.base);
1567
- if (warmedUrls.has(url) || isBuiltin(url)) {
1568
- return;
1569
- }
1570
- const m = await server.moduleGraph.getModuleByUrl(url, isServer);
1571
- if (m?.transformResult?.code || m?.ssrTransformResult?.code) {
1572
- return;
1573
- }
1574
- warmedUrls.add(url);
1575
- await server.transformRequest(url, { ssr: isServer });
1576
- } catch (e) {
1577
- logger.debug("[nuxt] warmup for %s failed with: %s", url, e);
1578
- }
1579
- if (isCSSRequest(url)) {
1580
- return;
1581
- }
1582
- try {
1583
- const mod = await server.moduleGraph.getModuleByUrl(url, isServer);
1584
- const deps = mod?.ssrTransformResult?.deps || (mod?.importedModules.size ? Array.from(
1585
- mod?.importedModules
1586
- /* client */
1587
- ).map((m) => m.url) : []);
1588
- await Promise.all(deps.map((m) => warmup(m)));
1589
- } catch (e) {
1590
- logger.debug("[warmup] tracking dependencies for %s failed with: %s", url, e);
1591
- }
1592
- };
1593
- await Promise.all(entries.map((entry) => warmup(fileToUrl(entry, server.config.root))));
1344
+ const warmedUrls = /* @__PURE__ */ new Set();
1345
+ const warmup = async (url) => {
1346
+ try {
1347
+ url = normaliseURL(url, server.config.base);
1348
+ if (warmedUrls.has(url) || isBuiltin(url)) return;
1349
+ const m = await server.moduleGraph.getModuleByUrl(url, isServer);
1350
+ if (m?.transformResult?.code || m?.ssrTransformResult?.code) return;
1351
+ warmedUrls.add(url);
1352
+ await server.transformRequest(url, { ssr: isServer });
1353
+ } catch (e) {
1354
+ logger.debug("[nuxt] warmup for %s failed with: %s", url, e);
1355
+ }
1356
+ if (isCSSRequest(url)) return;
1357
+ try {
1358
+ const mod = await server.moduleGraph.getModuleByUrl(url, isServer);
1359
+ const deps = mod?.ssrTransformResult?.deps || (mod?.importedModules.size ? Array.from(mod?.importedModules).map((m) => m.url) : []);
1360
+ await Promise.all(deps.map((m) => warmup(m)));
1361
+ } catch (e) {
1362
+ logger.debug("[warmup] tracking dependencies for %s failed with: %s", url, e);
1363
+ }
1364
+ };
1365
+ await Promise.all(entries.map((entry) => warmup(fileToUrl(entry, server.config.root))));
1594
1366
  }
1595
1367
 
1368
+ //#endregion
1369
+ //#region src/css.ts
1596
1370
  function sortPlugins({ plugins, order }) {
1597
- const names = Object.keys(plugins);
1598
- return typeof order === "function" ? order(names) : order || names;
1371
+ const names = Object.keys(plugins);
1372
+ return typeof order === "function" ? order(names) : order || names;
1599
1373
  }
1600
1374
  async function resolveCSSOptions(nuxt) {
1601
- const css = {
1602
- postcss: {
1603
- plugins: []
1604
- }
1605
- };
1606
- const postcssOptions = nuxt.options.postcss;
1607
- const jiti = createJiti(nuxt.options.rootDir, { alias: nuxt.options.alias });
1608
- for (const pluginName of sortPlugins(postcssOptions)) {
1609
- const pluginOptions = postcssOptions.plugins[pluginName];
1610
- if (!pluginOptions) {
1611
- continue;
1612
- }
1613
- let pluginFn;
1614
- for (const parentURL of nuxt.options.modulesDir) {
1615
- pluginFn = await jiti.import(pluginName, { parentURL: parentURL.replace(/\/node_modules\/?$/, ""), try: true, default: true });
1616
- if (typeof pluginFn === "function") {
1617
- css.postcss.plugins.push(pluginFn(pluginOptions));
1618
- break;
1619
- }
1620
- }
1621
- if (typeof pluginFn !== "function") {
1622
- console.warn(`[nuxt] could not import postcss plugin \`${pluginName}\`. Please report this as a bug.`);
1623
- }
1624
- }
1625
- return css;
1375
+ const css = { postcss: { plugins: [] } };
1376
+ const postcssOptions = nuxt.options.postcss;
1377
+ const jiti = createJiti(nuxt.options.rootDir, { alias: nuxt.options.alias });
1378
+ for (const pluginName of sortPlugins(postcssOptions)) {
1379
+ const pluginOptions = postcssOptions.plugins[pluginName];
1380
+ if (!pluginOptions) continue;
1381
+ let pluginFn;
1382
+ for (const parentURL of nuxt.options.modulesDir) {
1383
+ pluginFn = await jiti.import(pluginName, {
1384
+ parentURL: parentURL.replace(/\/node_modules\/?$/, ""),
1385
+ try: true,
1386
+ default: true
1387
+ });
1388
+ if (typeof pluginFn === "function") {
1389
+ css.postcss.plugins.push(pluginFn(pluginOptions));
1390
+ break;
1391
+ }
1392
+ }
1393
+ if (typeof pluginFn !== "function") console.warn(`[nuxt] could not import postcss plugin \`${pluginName}\`. Please report this as a bug.`);
1394
+ }
1395
+ return css;
1626
1396
  }
1627
1397
 
1398
+ //#endregion
1399
+ //#region src/plugins/ssr-styles.ts
1628
1400
  const SUPPORTED_FILES_RE = /\.(?:vue|(?:[cm]?j|t)sx?)$/;
1629
1401
  const QUERY_RE = /\?.+$/;
1630
1402
  function SSRStylesPlugin(nuxt) {
1631
- if (nuxt.options.dev) {
1632
- return;
1633
- }
1634
- const chunksWithInlinedCSS = /* @__PURE__ */ new Set();
1635
- const clientCSSMap = {};
1636
- const nitro = useNitro();
1637
- nuxt.hook("build:manifest", (manifest) => {
1638
- const entryIds = /* @__PURE__ */ new Set();
1639
- for (const id of chunksWithInlinedCSS) {
1640
- const chunk = manifest[id];
1641
- if (!chunk) {
1642
- continue;
1643
- }
1644
- if (chunk.isEntry && chunk.src) {
1645
- entryIds.add(chunk.src);
1646
- } else {
1647
- chunk.css &&= [];
1648
- }
1649
- }
1650
- nitro.options.virtual["#internal/nuxt/entry-ids.mjs"] = () => `export default ${JSON.stringify(Array.from(entryIds))}`;
1651
- nitro.options._config.virtual ||= {};
1652
- nitro.options._config.virtual["#internal/nuxt/entry-ids.mjs"] = nitro.options.virtual["#internal/nuxt/entry-ids.mjs"];
1653
- });
1654
- const cssMap = {};
1655
- const idRefMap = {};
1656
- const options = {
1657
- shouldInline: nuxt.options.features.inlineStyles,
1658
- globalCSS: nuxt.options.css
1659
- };
1660
- const relativeCache = /* @__PURE__ */ new Map();
1661
- const relativeToSrcDir = (path) => {
1662
- let cached = relativeCache.get(path);
1663
- if (cached === void 0) {
1664
- cached = relative(nuxt.options.srcDir, path);
1665
- relativeCache.set(path, cached);
1666
- }
1667
- return cached;
1668
- };
1669
- const warnCache = /* @__PURE__ */ new Set();
1670
- const components = nuxt.apps.default.components || [];
1671
- const islands = components.filter(
1672
- (component) => component.island || // .server components without a corresponding .client component will need to be rendered as an island
1673
- component.mode === "server" && !components.some((c) => c.pascalName === component.pascalName && c.mode === "client")
1674
- );
1675
- const islandPaths = new Set(islands.map((c) => c.filePath));
1676
- let entry;
1677
- return {
1678
- name: "ssr-styles",
1679
- configResolved(config) {
1680
- if (!config.build.ssr || nuxt.options.experimental.viteEnvironmentApi) {
1681
- entry = resolveClientEntry(config);
1682
- }
1683
- },
1684
- applyToEnvironment(environment) {
1685
- return {
1686
- name: `nuxt:ssr-styles:${environment.name}`,
1687
- enforce: "pre",
1688
- resolveId: {
1689
- order: "pre",
1690
- filter: {
1691
- id: {
1692
- include: [/^#build\/css$/, /\.vue$/, IS_CSS_RE]
1693
- }
1694
- },
1695
- async handler(id, importer, _options) {
1696
- if (options.shouldInline === false || typeof options.shouldInline === "function" && !options.shouldInline(importer)) {
1697
- return;
1698
- }
1699
- const res = await this.resolve(id, importer, { ..._options, skipSelf: true });
1700
- if (res) {
1701
- return {
1702
- ...res,
1703
- moduleSideEffects: false
1704
- };
1705
- }
1706
- }
1707
- },
1708
- generateBundle(outputOptions) {
1709
- if (environment.name === "client") {
1710
- return;
1711
- }
1712
- const emitted = {};
1713
- for (const [file, { files, inBundle }] of Object.entries(cssMap)) {
1714
- if (!files.length || !inBundle) {
1715
- continue;
1716
- }
1717
- const fileName = filename(file);
1718
- const base = typeof outputOptions.assetFileNames === "string" ? outputOptions.assetFileNames : outputOptions.assetFileNames({
1719
- type: "asset",
1720
- name: `${fileName}-styles.mjs`,
1721
- names: [`${fileName}-styles.mjs`],
1722
- originalFileName: `${fileName}-styles.mjs`,
1723
- originalFileNames: [`${fileName}-styles.mjs`],
1724
- source: ""
1725
- });
1726
- const baseDir = dirname(base);
1727
- const cssImports = /* @__PURE__ */ new Set();
1728
- const exportNames = /* @__PURE__ */ new Set();
1729
- const importStatements = /* @__PURE__ */ new Set();
1730
- let i = 0;
1731
- for (const css of files) {
1732
- const file2 = this.getFileName(css);
1733
- if (cssImports.has(file2)) {
1734
- continue;
1735
- }
1736
- cssImports.add(file2);
1737
- const name = `style_${i++}`;
1738
- importStatements.add(genImport(`./${relative(baseDir, file2)}`, name));
1739
- exportNames.add(name);
1740
- }
1741
- emitted[file] = this.emitFile({
1742
- type: "asset",
1743
- name: `${fileName}-styles.mjs`,
1744
- source: [
1745
- ...importStatements,
1746
- `export default ${genArrayFromRaw([...exportNames])}`
1747
- ].join("\n")
1748
- });
1749
- }
1750
- for (const key in emitted) {
1751
- chunksWithInlinedCSS.add(key);
1752
- }
1753
- this.emitFile({
1754
- type: "asset",
1755
- fileName: "styles.mjs",
1756
- originalFileName: "styles.mjs",
1757
- source: [
1758
- "const interopDefault = r => r.default || r || []",
1759
- `export default ${genObjectFromRawEntries(
1760
- Object.entries(emitted).map(([key, value]) => [key, `() => import('./${this.getFileName(value)}').then(interopDefault)`])
1761
- )}`
1762
- ].join("\n")
1763
- });
1764
- },
1765
- renderChunk(_code, chunk) {
1766
- const isEntry = chunk.facadeModuleId === entry;
1767
- if (isEntry) {
1768
- clientCSSMap[chunk.facadeModuleId] ||= /* @__PURE__ */ new Set();
1769
- }
1770
- for (const moduleId of [chunk.facadeModuleId, ...chunk.moduleIds].filter(Boolean)) {
1771
- if (environment.name === "client") {
1772
- const moduleMap = clientCSSMap[moduleId] ||= /* @__PURE__ */ new Set();
1773
- if (isCSS(moduleId)) {
1774
- if (isVue(moduleId)) {
1775
- moduleMap.add(moduleId);
1776
- const parent = moduleId.replace(/\?.+$/, "");
1777
- const parentMap = clientCSSMap[parent] ||= /* @__PURE__ */ new Set();
1778
- parentMap.add(moduleId);
1779
- }
1780
- if (isEntry && chunk.facadeModuleId) {
1781
- const facadeMap = clientCSSMap[chunk.facadeModuleId] ||= /* @__PURE__ */ new Set();
1782
- facadeMap.add(moduleId);
1783
- }
1784
- }
1785
- continue;
1786
- }
1787
- const relativePath = relativeToSrcDir(moduleId);
1788
- if (relativePath in cssMap) {
1789
- cssMap[relativePath].inBundle = cssMap[relativePath].inBundle ?? (isVue(moduleId) && !!relativePath || isEntry);
1790
- }
1791
- }
1792
- return null;
1793
- },
1794
- transform: {
1795
- filter: {
1796
- id: {
1797
- include: environment.name === "client" ? new RegExp("^" + escapeStringRegexp(entry) + "$") : void 0,
1798
- exclude: environment.name === "client" ? [] : [/\?.*macro=/, /\?.*nuxt_component=/]
1799
- }
1800
- },
1801
- async handler(code, id) {
1802
- if (environment.name === "client") {
1803
- if (id === entry && (options.shouldInline === true || typeof options.shouldInline === "function" && options.shouldInline(id))) {
1804
- const idClientCSSMap = clientCSSMap[id] ||= /* @__PURE__ */ new Set();
1805
- if (!options.globalCSS.length) {
1806
- return;
1807
- }
1808
- const s = new MagicString(code);
1809
- for (const file of options.globalCSS) {
1810
- const resolved = await this.resolve(file) ?? await this.resolve(file, id);
1811
- const res = await this.resolve(file + "?inline&used") ?? await this.resolve(file + "?inline&used", id);
1812
- if (!resolved || !res) {
1813
- if (!warnCache.has(file)) {
1814
- warnCache.add(file);
1815
- this.warn(`[nuxt] Cannot extract styles for \`${file}\`. Its styles will not be inlined when server-rendering.`);
1816
- }
1817
- s.prepend(`${genImport(file)}
1818
- `);
1819
- continue;
1820
- }
1821
- idClientCSSMap.add(resolved.id);
1822
- }
1823
- if (s.hasChanged()) {
1824
- return {
1825
- code: s.toString(),
1826
- map: s.generateMap({ hires: true })
1827
- };
1828
- }
1829
- }
1830
- return;
1831
- }
1832
- const { pathname, search } = parseURL(decodeURIComponent(pathToFileURL(id).href));
1833
- if (!(id in clientCSSMap) && !islandPaths.has(pathname)) {
1834
- return;
1835
- }
1836
- const query = parseQuery(search);
1837
- if (query.macro || query.nuxt_component) {
1838
- return;
1839
- }
1840
- if (!islandPaths.has(pathname)) {
1841
- if (options.shouldInline === false || typeof options.shouldInline === "function" && !options.shouldInline(id)) {
1842
- return;
1843
- }
1844
- }
1845
- const relativeId = relativeToSrcDir(id);
1846
- const idMap = cssMap[relativeId] ||= { files: [] };
1847
- const emittedIds = /* @__PURE__ */ new Set();
1848
- const idFilename = filename(id);
1849
- let styleCtr = 0;
1850
- const ids = clientCSSMap[id] || [];
1851
- for (const file of ids) {
1852
- if (emittedIds.has(file)) {
1853
- continue;
1854
- }
1855
- const fileInline = file + "?inline&used";
1856
- const resolved = await this.resolve(file) ?? await this.resolve(file, id);
1857
- const res = await this.resolve(fileInline) ?? await this.resolve(fileInline, id);
1858
- if (!resolved || !res) {
1859
- if (!warnCache.has(file)) {
1860
- warnCache.add(file);
1861
- this.warn(`[nuxt] Cannot extract styles for \`${file}\`. Its styles will not be inlined when server-rendering.`);
1862
- }
1863
- continue;
1864
- }
1865
- emittedIds.add(file);
1866
- const ref = this.emitFile({
1867
- type: "chunk",
1868
- name: `${idFilename}-styles-${++styleCtr}.mjs`,
1869
- id: fileInline
1870
- });
1871
- idRefMap[relativeToSrcDir(file)] = ref;
1872
- idMap.files.push(ref);
1873
- }
1874
- if (!SUPPORTED_FILES_RE.test(pathname)) {
1875
- return;
1876
- }
1877
- for (const i of findStaticImports(code)) {
1878
- if (!i.specifier.endsWith(".css") && parseQuery(i.specifier).type !== "style") {
1879
- continue;
1880
- }
1881
- const resolved = await this.resolve(i.specifier, id);
1882
- if (!resolved) {
1883
- continue;
1884
- }
1885
- const resolvedIdInline = resolved.id + "?inline&used";
1886
- if (!await this.resolve(resolvedIdInline)) {
1887
- if (!warnCache.has(resolved.id)) {
1888
- warnCache.add(resolved.id);
1889
- this.warn(`[nuxt] Cannot extract styles for \`${i.specifier}\`. Its styles will not be inlined when server-rendering.`);
1890
- }
1891
- continue;
1892
- }
1893
- if (emittedIds.has(resolved.id)) {
1894
- continue;
1895
- }
1896
- const ref = this.emitFile({
1897
- type: "chunk",
1898
- name: `${idFilename}-styles-${++styleCtr}.mjs`,
1899
- id: resolvedIdInline
1900
- });
1901
- idRefMap[relativeToSrcDir(resolved.id)] = ref;
1902
- idMap.files.push(ref);
1903
- }
1904
- }
1905
- }
1906
- };
1907
- }
1908
- };
1403
+ if (nuxt.options.dev) return;
1404
+ const chunksWithInlinedCSS = /* @__PURE__ */ new Set();
1405
+ const clientCSSMap = {};
1406
+ const nitro = useNitro();
1407
+ nuxt.hook("build:manifest", (manifest) => {
1408
+ const entryIds = /* @__PURE__ */ new Set();
1409
+ for (const id of chunksWithInlinedCSS) {
1410
+ const chunk = manifest[id];
1411
+ if (!chunk) continue;
1412
+ if (chunk.isEntry && chunk.src) entryIds.add(chunk.src);
1413
+ else chunk.css &&= [];
1414
+ }
1415
+ nitro.options.virtual["#internal/nuxt/entry-ids.mjs"] = () => `export default ${JSON.stringify(Array.from(entryIds))}`;
1416
+ nitro.options._config.virtual ||= {};
1417
+ nitro.options._config.virtual["#internal/nuxt/entry-ids.mjs"] = nitro.options.virtual["#internal/nuxt/entry-ids.mjs"];
1418
+ });
1419
+ const cssMap = {};
1420
+ const idRefMap = {};
1421
+ const options = {
1422
+ shouldInline: nuxt.options.features.inlineStyles,
1423
+ globalCSS: nuxt.options.css
1424
+ };
1425
+ const relativeCache = /* @__PURE__ */ new Map();
1426
+ const relativeToSrcDir = (path) => {
1427
+ let cached = relativeCache.get(path);
1428
+ if (cached === void 0) {
1429
+ cached = relative(nuxt.options.srcDir, path);
1430
+ relativeCache.set(path, cached);
1431
+ }
1432
+ return cached;
1433
+ };
1434
+ const warnCache = /* @__PURE__ */ new Set();
1435
+ const components = nuxt.apps.default.components || [];
1436
+ const islands = components.filter((component) => component.island || component.mode === "server" && !components.some((c) => c.pascalName === component.pascalName && c.mode === "client"));
1437
+ const islandPaths = new Set(islands.map((c) => c.filePath));
1438
+ let entry;
1439
+ return {
1440
+ name: "ssr-styles",
1441
+ configResolved(config) {
1442
+ if (!config.build.ssr || nuxt.options.experimental.viteEnvironmentApi) entry = resolveClientEntry(config);
1443
+ },
1444
+ applyToEnvironment(environment) {
1445
+ return {
1446
+ name: `nuxt:ssr-styles:${environment.name}`,
1447
+ enforce: "pre",
1448
+ resolveId: {
1449
+ order: "pre",
1450
+ filter: { id: { include: [
1451
+ /^#build\/css$/,
1452
+ /\.vue$/,
1453
+ IS_CSS_RE
1454
+ ] } },
1455
+ async handler(id, importer, _options) {
1456
+ if (options.shouldInline === false || typeof options.shouldInline === "function" && !options.shouldInline(importer)) return;
1457
+ const res = await this.resolve(id, importer, {
1458
+ ..._options,
1459
+ skipSelf: true
1460
+ });
1461
+ if (res) return {
1462
+ ...res,
1463
+ moduleSideEffects: false
1464
+ };
1465
+ }
1466
+ },
1467
+ generateBundle(outputOptions) {
1468
+ if (environment.name === "client") return;
1469
+ const emitted = {};
1470
+ for (const [file, { files, inBundle }] of Object.entries(cssMap)) {
1471
+ if (!files.length || !inBundle) continue;
1472
+ const fileName = filename$1(file);
1473
+ const baseDir = dirname(typeof outputOptions.assetFileNames === "string" ? outputOptions.assetFileNames : outputOptions.assetFileNames({
1474
+ type: "asset",
1475
+ name: `${fileName}-styles.mjs`,
1476
+ names: [`${fileName}-styles.mjs`],
1477
+ originalFileName: `${fileName}-styles.mjs`,
1478
+ originalFileNames: [`${fileName}-styles.mjs`],
1479
+ source: ""
1480
+ }));
1481
+ const cssImports = /* @__PURE__ */ new Set();
1482
+ const exportNames = /* @__PURE__ */ new Set();
1483
+ const importStatements = /* @__PURE__ */ new Set();
1484
+ let i = 0;
1485
+ for (const css of files) {
1486
+ const file$1 = this.getFileName(css);
1487
+ if (cssImports.has(file$1)) continue;
1488
+ cssImports.add(file$1);
1489
+ const name = `style_${i++}`;
1490
+ importStatements.add(genImport(`./${relative(baseDir, file$1)}`, name));
1491
+ exportNames.add(name);
1492
+ }
1493
+ emitted[file] = this.emitFile({
1494
+ type: "asset",
1495
+ name: `${fileName}-styles.mjs`,
1496
+ source: [...importStatements, `export default ${genArrayFromRaw([...exportNames])}`].join("\n")
1497
+ });
1498
+ }
1499
+ for (const key in emitted) chunksWithInlinedCSS.add(key);
1500
+ this.emitFile({
1501
+ type: "asset",
1502
+ fileName: "styles.mjs",
1503
+ originalFileName: "styles.mjs",
1504
+ source: ["const interopDefault = r => r.default || r || []", `export default ${genObjectFromRawEntries(Object.entries(emitted).map(([key, value]) => [key, `() => import('./${this.getFileName(value)}').then(interopDefault)`]))}`].join("\n")
1505
+ });
1506
+ },
1507
+ renderChunk(_code, chunk) {
1508
+ const isEntry = chunk.facadeModuleId === entry;
1509
+ if (isEntry) clientCSSMap[chunk.facadeModuleId] ||= /* @__PURE__ */ new Set();
1510
+ for (const moduleId of [chunk.facadeModuleId, ...chunk.moduleIds].filter(Boolean)) {
1511
+ if (environment.name === "client") {
1512
+ const moduleMap = clientCSSMap[moduleId] ||= /* @__PURE__ */ new Set();
1513
+ if (isCSS(moduleId)) {
1514
+ if (isVue(moduleId)) {
1515
+ moduleMap.add(moduleId);
1516
+ const parent = moduleId.replace(/\?.+$/, "");
1517
+ (clientCSSMap[parent] ||= /* @__PURE__ */ new Set()).add(moduleId);
1518
+ }
1519
+ if (isEntry && chunk.facadeModuleId) (clientCSSMap[chunk.facadeModuleId] ||= /* @__PURE__ */ new Set()).add(moduleId);
1520
+ }
1521
+ continue;
1522
+ }
1523
+ const relativePath = relativeToSrcDir(moduleId);
1524
+ if (relativePath in cssMap) cssMap[relativePath].inBundle = cssMap[relativePath].inBundle ?? (isVue(moduleId) && !!relativePath || isEntry);
1525
+ }
1526
+ return null;
1527
+ },
1528
+ transform: {
1529
+ filter: { id: {
1530
+ include: environment.name === "client" ? /* @__PURE__ */ new RegExp("^" + escapeStringRegexp(entry) + "$") : void 0,
1531
+ exclude: environment.name === "client" ? [] : [/\?.*macro=/, /\?.*nuxt_component=/]
1532
+ } },
1533
+ async handler(code, id) {
1534
+ if (environment.name === "client") {
1535
+ if (id === entry && (options.shouldInline === true || typeof options.shouldInline === "function" && options.shouldInline(id))) {
1536
+ const idClientCSSMap = clientCSSMap[id] ||= /* @__PURE__ */ new Set();
1537
+ if (!options.globalCSS.length) return;
1538
+ const s = new MagicString(code);
1539
+ for (const file of options.globalCSS) {
1540
+ const resolved = await this.resolve(file) ?? await this.resolve(file, id);
1541
+ const res = await this.resolve(file + "?inline&used") ?? await this.resolve(file + "?inline&used", id);
1542
+ if (!resolved || !res) {
1543
+ if (!warnCache.has(file)) {
1544
+ warnCache.add(file);
1545
+ this.warn(`[nuxt] Cannot extract styles for \`${file}\`. Its styles will not be inlined when server-rendering.`);
1546
+ }
1547
+ s.prepend(`${genImport(file)}\n`);
1548
+ continue;
1549
+ }
1550
+ idClientCSSMap.add(resolved.id);
1551
+ }
1552
+ if (s.hasChanged()) return {
1553
+ code: s.toString(),
1554
+ map: s.generateMap({ hires: true })
1555
+ };
1556
+ }
1557
+ return;
1558
+ }
1559
+ const { pathname, search } = parseURL(decodeURIComponent(pathToFileURL(id).href));
1560
+ if (!(id in clientCSSMap) && !islandPaths.has(pathname)) return;
1561
+ const query = parseQuery(search);
1562
+ if (query.macro || query.nuxt_component) return;
1563
+ if (!islandPaths.has(pathname)) {
1564
+ if (options.shouldInline === false || typeof options.shouldInline === "function" && !options.shouldInline(id)) return;
1565
+ }
1566
+ const relativeId = relativeToSrcDir(id);
1567
+ const idMap = cssMap[relativeId] ||= { files: [] };
1568
+ const emittedIds = /* @__PURE__ */ new Set();
1569
+ const idFilename = filename$1(id);
1570
+ let styleCtr = 0;
1571
+ const ids = clientCSSMap[id] || [];
1572
+ for (const file of ids) {
1573
+ if (emittedIds.has(file)) continue;
1574
+ const fileInline = file + "?inline&used";
1575
+ const resolved = await this.resolve(file) ?? await this.resolve(file, id);
1576
+ const res = await this.resolve(fileInline) ?? await this.resolve(fileInline, id);
1577
+ if (!resolved || !res) {
1578
+ if (!warnCache.has(file)) {
1579
+ warnCache.add(file);
1580
+ this.warn(`[nuxt] Cannot extract styles for \`${file}\`. Its styles will not be inlined when server-rendering.`);
1581
+ }
1582
+ continue;
1583
+ }
1584
+ emittedIds.add(file);
1585
+ const ref = this.emitFile({
1586
+ type: "chunk",
1587
+ name: `${idFilename}-styles-${++styleCtr}.mjs`,
1588
+ id: fileInline
1589
+ });
1590
+ idRefMap[relativeToSrcDir(file)] = ref;
1591
+ idMap.files.push(ref);
1592
+ }
1593
+ if (!SUPPORTED_FILES_RE.test(pathname)) return;
1594
+ for (const i of findStaticImports(code)) {
1595
+ if (!i.specifier.endsWith(".css") && parseQuery(i.specifier).type !== "style") continue;
1596
+ const resolved = await this.resolve(i.specifier, id);
1597
+ if (!resolved) continue;
1598
+ const resolvedIdInline = resolved.id + "?inline&used";
1599
+ if (!await this.resolve(resolvedIdInline)) {
1600
+ if (!warnCache.has(resolved.id)) {
1601
+ warnCache.add(resolved.id);
1602
+ this.warn(`[nuxt] Cannot extract styles for \`${i.specifier}\`. Its styles will not be inlined when server-rendering.`);
1603
+ }
1604
+ continue;
1605
+ }
1606
+ if (emittedIds.has(resolved.id)) continue;
1607
+ const ref = this.emitFile({
1608
+ type: "chunk",
1609
+ name: `${idFilename}-styles-${++styleCtr}.mjs`,
1610
+ id: resolvedIdInline
1611
+ });
1612
+ idRefMap[relativeToSrcDir(resolved.id)] = ref;
1613
+ idMap.files.push(ref);
1614
+ }
1615
+ }
1616
+ }
1617
+ };
1618
+ }
1619
+ };
1909
1620
  }
1910
- function filename(name) {
1911
- return filename$1(name.replace(QUERY_RE, ""));
1621
+ function filename$1(name) {
1622
+ return filename(name.replace(QUERY_RE, ""));
1912
1623
  }
1913
1624
 
1625
+ //#endregion
1626
+ //#region src/plugins/replace.ts
1914
1627
  function ReplacePlugin() {
1915
- return {
1916
- name: "nuxt:replace",
1917
- enforce: "post",
1918
- async applyToEnvironment(environment) {
1919
- const config = environment.getTopLevelConfig();
1920
- const replaceOptions = /* @__PURE__ */ Object.create(null);
1921
- for (const define of [config.define || {}, environment.config.define || {}]) {
1922
- for (const key in define) {
1923
- if (key.startsWith("import.meta.")) {
1924
- replaceOptions[key] = define[key];
1925
- }
1926
- }
1927
- }
1928
- if (config.isProduction && vite.rolldownVersion) {
1929
- const { replacePlugin: replacePlugin2 } = await import('rolldown/plugins');
1930
- return replacePlugin2(replaceOptions, { preventAssignment: true });
1931
- } else {
1932
- return replacePlugin({ ...replaceOptions, preventAssignment: true });
1933
- }
1934
- }
1935
- };
1628
+ return {
1629
+ name: "nuxt:replace",
1630
+ enforce: "post",
1631
+ async applyToEnvironment(environment) {
1632
+ const config = environment.getTopLevelConfig();
1633
+ const replaceOptions = Object.create(null);
1634
+ for (const define of [config.define || {}, environment.config.define || {}]) for (const key in define) if (key.startsWith("import.meta.")) replaceOptions[key] = define[key];
1635
+ if (config.isProduction && vite.rolldownVersion) {
1636
+ const { replacePlugin: replacePlugin$1 } = await import("rolldown/plugins");
1637
+ return replacePlugin$1(replaceOptions, { preventAssignment: true });
1638
+ } else return replacePlugin({
1639
+ ...replaceOptions,
1640
+ preventAssignment: true
1641
+ });
1642
+ }
1643
+ };
1936
1644
  }
1937
1645
 
1646
+ //#endregion
1647
+ //#region src/plugins/layer-dep-optimize.ts
1938
1648
  function LayerDepOptimizePlugin(nuxt) {
1939
- if (!nuxt.options.dev) {
1940
- return;
1941
- }
1942
- const layerDirs = [];
1943
- const delimitedRootDir = nuxt.options.rootDir + "/";
1944
- for (const dirs of getLayerDirectories(nuxt)) {
1945
- if (dirs.app !== nuxt.options.srcDir && !dirs.app.startsWith(delimitedRootDir)) {
1946
- layerDirs.push(dirs.app);
1947
- }
1948
- }
1949
- if (layerDirs.length > 0) {
1950
- layerDirs.sort().reverse();
1951
- const dirs = [...layerDirs];
1952
- return {
1953
- name: "nuxt:optimize-layer-deps",
1954
- enforce: "pre",
1955
- resolveId: {
1956
- async handler(source, _importer) {
1957
- if (!_importer) {
1958
- return;
1959
- }
1960
- const importer = normalize(_importer);
1961
- const layerIndex = dirs.findIndex((dir) => importer.startsWith(dir));
1962
- if (layerIndex !== -1) {
1963
- dirs.splice(layerIndex, 1);
1964
- await this.resolve(source, join(nuxt.options.srcDir, "index.html"), { skipSelf: true }).catch(() => null);
1965
- }
1966
- }
1967
- }
1968
- };
1969
- }
1649
+ if (!nuxt.options.dev) return;
1650
+ const layerDirs = [];
1651
+ const delimitedRootDir = nuxt.options.rootDir + "/";
1652
+ for (const dirs of getLayerDirectories(nuxt)) if (dirs.app !== nuxt.options.srcDir && !dirs.app.startsWith(delimitedRootDir)) layerDirs.push(dirs.app);
1653
+ if (layerDirs.length > 0) {
1654
+ layerDirs.sort().reverse();
1655
+ const dirs = [...layerDirs];
1656
+ return {
1657
+ name: "nuxt:optimize-layer-deps",
1658
+ enforce: "pre",
1659
+ resolveId: { async handler(source, _importer) {
1660
+ if (!_importer) return;
1661
+ const importer = normalize(_importer);
1662
+ const layerIndex = dirs.findIndex((dir) => importer.startsWith(dir));
1663
+ if (layerIndex !== -1) {
1664
+ dirs.splice(layerIndex, 1);
1665
+ await this.resolve(source, join(nuxt.options.srcDir, "index.html"), { skipSelf: true }).catch(() => null);
1666
+ }
1667
+ } }
1668
+ };
1669
+ }
1970
1670
  }
1971
1671
 
1672
+ //#endregion
1673
+ //#region src/dirs.ts
1972
1674
  let _distDir = dirname(fileURLToPath(import.meta.url));
1973
- if (/(?:chunks|shared)$/.test(_distDir)) {
1974
- _distDir = dirname(_distDir);
1975
- }
1675
+ if (/(?:chunks|shared)$/.test(_distDir)) _distDir = dirname(_distDir);
1976
1676
  const distDir = _distDir;
1977
1677
 
1678
+ //#endregion
1679
+ //#region src/plugins/environments.ts
1978
1680
  function EnvironmentsPlugin(nuxt) {
1979
- const fileNames = withoutLeadingSlash(join(nuxt.options.app.buildAssetsDir, "[hash].js"));
1980
- const clientOutputDir = join(useNitro().options.output.publicDir, nuxt.options.app.buildAssetsDir);
1981
- const clientAliases = {
1982
- "nitro/runtime": join(nuxt.options.buildDir, "nitro.client.mjs"),
1983
- // TODO: remove in v5
1984
- "#internal/nitro": join(nuxt.options.buildDir, "nitro.client.mjs"),
1985
- "nitropack/runtime": join(nuxt.options.buildDir, "nitro.client.mjs"),
1986
- // work around vite optimizer bug
1987
- "#app-manifest": resolveModulePath("mocked-exports/empty", { from: import.meta.url })
1988
- };
1989
- let viteConfig;
1990
- return {
1991
- name: "nuxt:environments",
1992
- enforce: "pre",
1993
- // run before other plugins
1994
- config(config) {
1995
- viteConfig = config;
1996
- if (!nuxt.options.dev) {
1997
- return {
1998
- base: "./"
1999
- };
2000
- }
2001
- },
2002
- configEnvironment(name, config) {
2003
- if (!nuxt.options.experimental.viteEnvironmentApi && viteConfig.ssr) {
2004
- config.optimizeDeps ||= {};
2005
- config.optimizeDeps.include = void 0;
2006
- }
2007
- if (name === "client") {
2008
- const outputConfig = config.build?.rollupOptions?.output;
2009
- return {
2010
- build: {
2011
- rollupOptions: {
2012
- output: {
2013
- chunkFileNames: outputConfig?.chunkFileNames ?? (nuxt.options.dev ? void 0 : fileNames),
2014
- entryFileNames: outputConfig?.entryFileNames ?? (nuxt.options.dev ? "entry.js" : fileNames),
2015
- sourcemapPathTransform: outputConfig?.sourcemapPathTransform ?? ((relativeSourcePath, sourcemapPath) => {
2016
- if (!isAbsolute(relativeSourcePath)) {
2017
- const absoluteSourcePath = resolve(dirname(sourcemapPath), relativeSourcePath);
2018
- return relative(clientOutputDir, absoluteSourcePath);
2019
- }
2020
- return relativeSourcePath;
2021
- })
2022
- }
2023
- }
2024
- }
2025
- };
2026
- }
2027
- if (name === "ssr") {
2028
- if (config.build?.rollupOptions?.output && !Array.isArray(config.build.rollupOptions.output)) {
2029
- config.build.rollupOptions.output.manualChunks = void 0;
2030
- if (vite.rolldownVersion) {
2031
- config.build.rollupOptions.output.advancedChunks = void 0;
2032
- }
2033
- }
2034
- }
2035
- },
2036
- applyToEnvironment(environment) {
2037
- if (environment.name === "client") {
2038
- return [
2039
- ...nuxt.options.experimental.clientNodeCompat ? [NodeCompatAliasPlugin()] : [],
2040
- {
2041
- name: "nuxt:client:aliases",
2042
- enforce: "post",
2043
- resolveId: {
2044
- filter: {
2045
- id: Object.keys(clientAliases).map((id) => new RegExp("^" + escapeStringRegexp(id) + "$"))
2046
- },
2047
- handler: (source) => clientAliases[source]
2048
- }
2049
- }
2050
- ];
2051
- } else if (environment.name === "ssr") ;
2052
- return false;
2053
- }
2054
- };
1681
+ const fileNames = withoutLeadingSlash(join(nuxt.options.app.buildAssetsDir, "[hash].js"));
1682
+ const clientOutputDir = join(useNitro().options.output.publicDir, nuxt.options.app.buildAssetsDir);
1683
+ const clientAliases = {
1684
+ "nitro/runtime": join(nuxt.options.buildDir, "nitro.client.mjs"),
1685
+ "#internal/nitro": join(nuxt.options.buildDir, "nitro.client.mjs"),
1686
+ "nitropack/runtime": join(nuxt.options.buildDir, "nitro.client.mjs"),
1687
+ "#app-manifest": resolveModulePath("mocked-exports/empty", { from: import.meta.url })
1688
+ };
1689
+ let viteConfig;
1690
+ return {
1691
+ name: "nuxt:environments",
1692
+ enforce: "pre",
1693
+ config(config) {
1694
+ viteConfig = config;
1695
+ if (!nuxt.options.dev) return { base: "./" };
1696
+ },
1697
+ configEnvironment(name, config) {
1698
+ if (!nuxt.options.experimental.viteEnvironmentApi && viteConfig.ssr) {
1699
+ config.optimizeDeps ||= {};
1700
+ config.optimizeDeps.include = void 0;
1701
+ }
1702
+ if (name === "client") {
1703
+ const outputConfig = config.build?.rollupOptions?.output;
1704
+ return { build: { rollupOptions: { output: {
1705
+ chunkFileNames: outputConfig?.chunkFileNames ?? (nuxt.options.dev ? void 0 : fileNames),
1706
+ entryFileNames: outputConfig?.entryFileNames ?? (nuxt.options.dev ? "entry.js" : fileNames),
1707
+ sourcemapPathTransform: outputConfig?.sourcemapPathTransform ?? ((relativeSourcePath, sourcemapPath) => {
1708
+ if (!isAbsolute(relativeSourcePath)) return relative(clientOutputDir, resolve(dirname(sourcemapPath), relativeSourcePath));
1709
+ return relativeSourcePath;
1710
+ })
1711
+ } } } };
1712
+ }
1713
+ if (name === "ssr") {
1714
+ if (config.build?.rollupOptions?.output && !Array.isArray(config.build.rollupOptions.output)) {
1715
+ config.build.rollupOptions.output.manualChunks = void 0;
1716
+ if (vite.rolldownVersion) config.build.rollupOptions.output.advancedChunks = void 0;
1717
+ }
1718
+ }
1719
+ },
1720
+ applyToEnvironment(environment) {
1721
+ if (environment.name === "client") return [...nuxt.options.experimental.clientNodeCompat ? [NodeCompatAliasPlugin()] : [], {
1722
+ name: "nuxt:client:aliases",
1723
+ enforce: "post",
1724
+ resolveId: {
1725
+ filter: { id: Object.keys(clientAliases).map((id) => /* @__PURE__ */ new RegExp("^" + escapeStringRegexp(id) + "$")) },
1726
+ handler: (source) => clientAliases[source]
1727
+ }
1728
+ }];
1729
+ else if (environment.name === "ssr") {}
1730
+ return false;
1731
+ }
1732
+ };
2055
1733
  }
2056
1734
  function NodeCompatAliasPlugin() {
2057
- const nodeCompatAlias = defineEnv({ nodeCompat: true, resolve: true }).env.alias;
2058
- return {
2059
- name: "nuxt:client:node-compat-aliases",
2060
- resolveId: {
2061
- order: "pre",
2062
- handler(source) {
2063
- if (source in nodeCompatAlias) {
2064
- return nodeCompatAlias[source];
2065
- }
2066
- }
2067
- }
2068
- };
1735
+ const nodeCompatAlias = defineEnv({
1736
+ nodeCompat: true,
1737
+ resolve: true
1738
+ }).env.alias;
1739
+ return {
1740
+ name: "nuxt:client:node-compat-aliases",
1741
+ resolveId: {
1742
+ order: "pre",
1743
+ handler(source) {
1744
+ if (source in nodeCompatAlias) return nodeCompatAlias[source];
1745
+ }
1746
+ }
1747
+ };
2069
1748
  }
2070
1749
 
1750
+ //#endregion
1751
+ //#region src/plugins/client-manifest.ts
2071
1752
  function ClientManifestPlugin(nuxt) {
2072
- let clientEntry;
2073
- let key;
2074
- let disableCssCodeSplit;
2075
- return {
2076
- name: "nuxt:client-manifest",
2077
- // needs to run after server build (or after client build if there is no server build)
2078
- applyToEnvironment: (environment) => environment.name === "ssr",
2079
- configResolved(config) {
2080
- clientEntry = resolveClientEntry(config);
2081
- key = relative(config.root, clientEntry);
2082
- disableCssCodeSplit = config.build?.cssCodeSplit === false;
2083
- },
2084
- async closeBundle() {
2085
- const devClientManifest = {
2086
- "@vite/client": {
2087
- isEntry: true,
2088
- file: "@vite/client",
2089
- css: [],
2090
- module: true,
2091
- resourceType: "script"
2092
- },
2093
- ...nuxt.options.features.noScripts === "all" ? {} : {
2094
- [clientEntry]: {
2095
- isEntry: true,
2096
- file: clientEntry,
2097
- module: true,
2098
- resourceType: "script"
2099
- }
2100
- }
2101
- };
2102
- const clientDist = resolve(nuxt.options.buildDir, "dist/client");
2103
- const serverDist = resolve(nuxt.options.buildDir, "dist/server");
2104
- const manifestFile = resolve(clientDist, "manifest.json");
2105
- const clientManifest = nuxt.options.dev ? devClientManifest : JSON.parse(readFileSync(manifestFile, "utf-8"));
2106
- const manifestEntries = Object.values(clientManifest);
2107
- const buildAssetsDir = withTrailingSlash(withoutLeadingSlash(nuxt.options.app.buildAssetsDir));
2108
- const BASE_RE = new RegExp(`^${escapeStringRegexp(buildAssetsDir)}`);
2109
- for (const entry of manifestEntries) {
2110
- entry.file &&= entry.file.replace(BASE_RE, "");
2111
- for (const item of ["css", "assets"]) {
2112
- entry[item] &&= entry[item].map((i) => i.replace(BASE_RE, ""));
2113
- }
2114
- }
2115
- await mkdir(serverDist, { recursive: true });
2116
- if (disableCssCodeSplit) {
2117
- for (const entry of manifestEntries) {
2118
- if (entry.file?.endsWith(".css")) {
2119
- clientManifest[key].css ||= [];
2120
- clientManifest[key].css.push(entry.file);
2121
- break;
2122
- }
2123
- }
2124
- }
2125
- const manifest = normalizeViteManifest(clientManifest);
2126
- await nuxt.callHook("build:manifest", manifest);
2127
- const precomputed = precomputeDependencies(manifest);
2128
- await writeFile(resolve(serverDist, "client.manifest.mjs"), "export default " + serialize(manifest), "utf8");
2129
- await writeFile(resolve(serverDist, "client.precomputed.mjs"), "export default " + serialize(precomputed), "utf8");
2130
- if (!nuxt.options.dev) {
2131
- await rm(manifestFile, { force: true });
2132
- }
2133
- }
2134
- };
1753
+ let clientEntry;
1754
+ let key;
1755
+ let disableCssCodeSplit;
1756
+ return {
1757
+ name: "nuxt:client-manifest",
1758
+ applyToEnvironment: (environment) => environment.name === "ssr",
1759
+ configResolved(config) {
1760
+ clientEntry = resolveClientEntry(config);
1761
+ key = relative(config.root, clientEntry);
1762
+ disableCssCodeSplit = config.build?.cssCodeSplit === false;
1763
+ },
1764
+ async closeBundle() {
1765
+ const devClientManifest = {
1766
+ "@vite/client": {
1767
+ isEntry: true,
1768
+ file: "@vite/client",
1769
+ css: [],
1770
+ module: true,
1771
+ resourceType: "script"
1772
+ },
1773
+ ...nuxt.options.features.noScripts === "all" ? {} : { [clientEntry]: {
1774
+ isEntry: true,
1775
+ file: clientEntry,
1776
+ module: true,
1777
+ resourceType: "script"
1778
+ } }
1779
+ };
1780
+ const clientDist = resolve(nuxt.options.buildDir, "dist/client");
1781
+ const serverDist = resolve(nuxt.options.buildDir, "dist/server");
1782
+ const manifestFile = resolve(clientDist, "manifest.json");
1783
+ const clientManifest = nuxt.options.dev ? devClientManifest : JSON.parse(readFileSync(manifestFile, "utf-8"));
1784
+ const manifestEntries = Object.values(clientManifest);
1785
+ const buildAssetsDir = withTrailingSlash(withoutLeadingSlash(nuxt.options.app.buildAssetsDir));
1786
+ const BASE_RE = /* @__PURE__ */ new RegExp(`^${escapeStringRegexp(buildAssetsDir)}`);
1787
+ for (const entry of manifestEntries) {
1788
+ entry.file &&= entry.file.replace(BASE_RE, "");
1789
+ for (const item of ["css", "assets"]) entry[item] &&= entry[item].map((i) => i.replace(BASE_RE, ""));
1790
+ }
1791
+ await mkdir(serverDist, { recursive: true });
1792
+ if (disableCssCodeSplit) {
1793
+ for (const entry of manifestEntries) if (entry.file?.endsWith(".css")) {
1794
+ clientManifest[key].css ||= [];
1795
+ clientManifest[key].css.push(entry.file);
1796
+ break;
1797
+ }
1798
+ }
1799
+ const manifest = normalizeViteManifest(clientManifest);
1800
+ await nuxt.callHook("build:manifest", manifest);
1801
+ const precomputed = precomputeDependencies(manifest);
1802
+ await writeFile(resolve(serverDist, "client.manifest.mjs"), "export default " + serialize(manifest), "utf8");
1803
+ await writeFile(resolve(serverDist, "client.precomputed.mjs"), "export default " + serialize(precomputed), "utf8");
1804
+ if (!nuxt.options.dev) await rm(manifestFile, { force: true });
1805
+ }
1806
+ };
2135
1807
  }
2136
1808
 
1809
+ //#endregion
1810
+ //#region src/plugins/resolve-deep-imports.ts
2137
1811
  const VIRTUAL_RE = /^\0?virtual:(?:nuxt:)?/;
2138
1812
  function ResolveDeepImportsPlugin(nuxt) {
2139
- const exclude = ["virtual:", "\0virtual:", "/__skip_vite", "@vitest/"];
2140
- const conditions = {};
2141
- function resolveConditions(environment) {
2142
- const resolvedConditions = /* @__PURE__ */ new Set([nuxt.options.dev ? "development" : "production", ...environment.config.resolve.conditions]);
2143
- if (resolvedConditions.has("browser")) {
2144
- resolvedConditions.add("web");
2145
- resolvedConditions.add("import");
2146
- resolvedConditions.add("module");
2147
- resolvedConditions.add("default");
2148
- }
2149
- if (environment.config.mode === "test") {
2150
- resolvedConditions.add("import");
2151
- resolvedConditions.add("require");
2152
- }
2153
- return [...resolvedConditions];
2154
- }
2155
- return {
2156
- name: "nuxt:resolve-bare-imports",
2157
- enforce: "post",
2158
- resolveId: {
2159
- filter: {
2160
- id: {
2161
- exclude: [
2162
- // absolute path
2163
- /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Z]:[/\\]/i,
2164
- ...exclude.map((e) => new RegExp("^" + escapeStringRegexp(e)))
2165
- ]
2166
- }
2167
- },
2168
- async handler(id, importer) {
2169
- if (!importer || !isAbsolute(importer) && !VIRTUAL_RE.test(importer)) {
2170
- return;
2171
- }
2172
- const normalisedId = resolveAlias(normalize(id), nuxt.options.alias);
2173
- const isNuxtTemplate = importer.startsWith("virtual:nuxt");
2174
- const normalisedImporter = (isNuxtTemplate ? decodeURIComponent(importer) : importer).replace(VIRTUAL_RE, "");
2175
- if (nuxt.options.experimental.templateImportResolution !== false && isNuxtTemplate) {
2176
- const template = nuxt.options.build.templates.find((t) => resolve(nuxt.options.buildDir, t.filename) === normalisedImporter);
2177
- if (template?._path) {
2178
- const res2 = await this.resolve?.(normalisedId, template._path, { skipSelf: true });
2179
- if (res2 !== void 0 && res2 !== null) {
2180
- return res2;
2181
- }
2182
- }
2183
- }
2184
- const dir = parseNodeModulePath(normalisedImporter).dir || nuxt.options.appDir;
2185
- const res = await this.resolve?.(normalisedId, dir, { skipSelf: true });
2186
- if (res !== void 0 && res !== null) {
2187
- return res;
2188
- }
2189
- const environmentConditions = conditions[this.environment.name] ||= resolveConditions(this.environment);
2190
- const path = resolveModulePath(id, {
2191
- from: [dir, ...nuxt.options.modulesDir].map((d) => directoryToURL(d)),
2192
- suffixes: ["", "index"],
2193
- conditions: environmentConditions,
2194
- try: true
2195
- });
2196
- if (!path) {
2197
- logger.debug("Could not resolve id", id, importer);
2198
- return null;
2199
- }
2200
- return normalize(path);
2201
- }
2202
- }
2203
- };
1813
+ const exclude = [
1814
+ "virtual:",
1815
+ "\0virtual:",
1816
+ "/__skip_vite",
1817
+ "@vitest/"
1818
+ ];
1819
+ const conditions = {};
1820
+ function resolveConditions(environment) {
1821
+ const resolvedConditions = new Set([nuxt.options.dev ? "development" : "production", ...environment.config.resolve.conditions]);
1822
+ if (resolvedConditions.has("browser")) {
1823
+ resolvedConditions.add("web");
1824
+ resolvedConditions.add("import");
1825
+ resolvedConditions.add("module");
1826
+ resolvedConditions.add("default");
1827
+ }
1828
+ if (environment.config.mode === "test") {
1829
+ resolvedConditions.add("import");
1830
+ resolvedConditions.add("require");
1831
+ }
1832
+ return [...resolvedConditions];
1833
+ }
1834
+ return {
1835
+ name: "nuxt:resolve-bare-imports",
1836
+ enforce: "post",
1837
+ resolveId: {
1838
+ filter: { id: { exclude: [/^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Z]:[/\\]/i, ...exclude.map((e) => /* @__PURE__ */ new RegExp("^" + escapeStringRegexp(e)))] } },
1839
+ async handler(id, importer) {
1840
+ if (!importer || !isAbsolute(importer) && !VIRTUAL_RE.test(importer)) return;
1841
+ const normalisedId = resolveAlias(normalize(id), nuxt.options.alias);
1842
+ const isNuxtTemplate = importer.startsWith("virtual:nuxt");
1843
+ const normalisedImporter = (isNuxtTemplate ? decodeURIComponent(importer) : importer).replace(VIRTUAL_RE, "");
1844
+ if (nuxt.options.experimental.templateImportResolution !== false && isNuxtTemplate) {
1845
+ const template = nuxt.options.build.templates.find((t) => resolve(nuxt.options.buildDir, t.filename) === normalisedImporter);
1846
+ if (template?._path) {
1847
+ const res$1 = await this.resolve?.(normalisedId, template._path, { skipSelf: true });
1848
+ if (res$1 !== void 0 && res$1 !== null) return res$1;
1849
+ }
1850
+ }
1851
+ const dir = parseNodeModulePath(normalisedImporter).dir || nuxt.options.appDir;
1852
+ const res = await this.resolve?.(normalisedId, dir, { skipSelf: true });
1853
+ if (res !== void 0 && res !== null) return res;
1854
+ const environmentConditions = conditions[this.environment.name] ||= resolveConditions(this.environment);
1855
+ const path = resolveModulePath(id, {
1856
+ from: [dir, ...nuxt.options.modulesDir].map((d) => directoryToURL(d)),
1857
+ suffixes: ["", "index"],
1858
+ conditions: environmentConditions,
1859
+ try: true
1860
+ });
1861
+ if (!path) {
1862
+ logger.debug("Could not resolve id", id, importer);
1863
+ return null;
1864
+ }
1865
+ return normalize(path);
1866
+ }
1867
+ }
1868
+ };
2204
1869
  }
2205
1870
 
1871
+ //#endregion
1872
+ //#region src/plugins/resolved-externals.ts
2206
1873
  function ResolveExternalsPlugin(nuxt) {
2207
- let external = /* @__PURE__ */ new Set();
2208
- const nitro = useNitro();
2209
- return {
2210
- name: "nuxt:resolve-externals",
2211
- enforce: "pre",
2212
- async config() {
2213
- const { runtimeDependencies: runtimeNitroDependencies = [] } = await tryImportModule("nitropack/runtime/meta", {
2214
- url: new URL(import.meta.url)
2215
- }) || {};
2216
- external = /* @__PURE__ */ new Set([
2217
- // explicit dependencies we use in our ssr renderer - these can be inlined (if necessary) in the nitro build
2218
- "unhead",
2219
- "@unhead/vue",
2220
- "@nuxt/devalue",
2221
- "unstorage",
2222
- // ensure we only have one version of vue if nitro is going to inline anyway
2223
- ...nitro.options.inlineDynamicImports ? ["vue", "@vue/server-renderer"] : [],
2224
- ...runtimeDependencies,
2225
- // dependencies we might share with nitro - these can be inlined (if necessary) in the nitro build
2226
- ...runtimeNitroDependencies
2227
- ]);
2228
- return {
2229
- optimizeDeps: {
2230
- exclude: Array.from(external)
2231
- }
2232
- };
2233
- },
2234
- applyToEnvironment(environment) {
2235
- if (nuxt.options.dev || environment.name !== "ssr") {
2236
- return false;
2237
- }
2238
- return {
2239
- name: "nuxt:resolve-externals:external",
2240
- resolveId: {
2241
- filter: {
2242
- id: [...external].map((dep) => new RegExp("^" + escapeStringRegexp(dep) + "$"))
2243
- },
2244
- async handler(id, importer) {
2245
- const res = await this.resolve?.(id, importer, { skipSelf: true });
2246
- if (res !== void 0 && res !== null) {
2247
- if (res.id === id) {
2248
- res.id = resolveModulePath(res.id, {
2249
- try: true,
2250
- from: importer,
2251
- extensions: nuxt.options.extensions
2252
- }) || res.id;
2253
- }
2254
- return {
2255
- ...res,
2256
- external: "absolute"
2257
- };
2258
- }
2259
- }
2260
- }
2261
- };
2262
- }
2263
- };
1874
+ let external = /* @__PURE__ */ new Set();
1875
+ const nitro = useNitro();
1876
+ return {
1877
+ name: "nuxt:resolve-externals",
1878
+ enforce: "pre",
1879
+ async config() {
1880
+ const { runtimeDependencies: runtimeNitroDependencies = [] } = await tryImportModule("nitropack/runtime/meta", { url: new URL(import.meta.url) }) || {};
1881
+ external = new Set([
1882
+ "unhead",
1883
+ "@unhead/vue",
1884
+ "@nuxt/devalue",
1885
+ "unstorage",
1886
+ ...nitro.options.inlineDynamicImports ? ["vue", "@vue/server-renderer"] : [],
1887
+ ...runtimeDependencies,
1888
+ ...runtimeNitroDependencies
1889
+ ]);
1890
+ return { optimizeDeps: { exclude: Array.from(external) } };
1891
+ },
1892
+ applyToEnvironment(environment) {
1893
+ if (nuxt.options.dev || environment.name !== "ssr") return false;
1894
+ return {
1895
+ name: "nuxt:resolve-externals:external",
1896
+ resolveId: {
1897
+ filter: { id: [...external].map((dep) => /* @__PURE__ */ new RegExp("^" + escapeStringRegexp(dep) + "$")) },
1898
+ async handler(id, importer) {
1899
+ const res = await this.resolve?.(id, importer, { skipSelf: true });
1900
+ if (res !== void 0 && res !== null) {
1901
+ if (res.id === id) res.id = resolveModulePath(res.id, {
1902
+ try: true,
1903
+ from: importer,
1904
+ extensions: nuxt.options.extensions
1905
+ }) || res.id;
1906
+ return {
1907
+ ...res,
1908
+ external: "absolute"
1909
+ };
1910
+ }
1911
+ }
1912
+ }
1913
+ };
1914
+ }
1915
+ };
2264
1916
  }
2265
1917
 
1918
+ //#endregion
1919
+ //#region src/vite.ts
2266
1920
  const bundle = async (nuxt) => {
2267
- const useAsyncEntry = nuxt.options.experimental.asyncEntry || nuxt.options.dev;
2268
- const entry = await resolvePath(resolve(nuxt.options.appDir, useAsyncEntry ? "entry.async" : "entry"));
2269
- nuxt.options.modulesDir.push(distDir);
2270
- let allowDirs = [
2271
- nuxt.options.appDir,
2272
- nuxt.options.workspaceDir,
2273
- ...nuxt.options.modulesDir,
2274
- ...getLayerDirectories(nuxt).map((d) => d.root),
2275
- ...Object.values(nuxt.apps).flatMap((app) => [
2276
- ...app.components.map((c) => dirname(c.filePath)),
2277
- ...app.plugins.map((p) => dirname(p.src)),
2278
- ...app.middleware.map((m) => dirname(m.path)),
2279
- ...Object.values(app.layouts || {}).map((l) => dirname(l.file)),
2280
- dirname(nuxt.apps.default.rootComponent),
2281
- dirname(nuxt.apps.default.errorComponent)
2282
- ])
2283
- ].filter((d) => d && existsSync(d));
2284
- for (const dir of allowDirs) {
2285
- allowDirs = allowDirs.filter((d) => !d.startsWith(dir) || d === dir);
2286
- }
2287
- const { $client, $server, ...viteConfig } = nuxt.options.vite;
2288
- if (vite.rolldownVersion) {
2289
- if (viteConfig.esbuild) {
2290
- delete viteConfig.esbuild;
2291
- }
2292
- if (viteConfig.optimizeDeps?.esbuildOptions) {
2293
- delete viteConfig.optimizeDeps.esbuildOptions;
2294
- }
2295
- }
2296
- const mockEmpty = resolveModulePath("mocked-exports/empty", { from: import.meta.url });
2297
- const helper = nuxt.options.nitro.imports !== false ? "" : "globalThis.";
2298
- const isIgnored = createIsIgnored(nuxt);
2299
- const serverEntry = nuxt.options.ssr ? entry : await resolvePath(resolve(nuxt.options.appDir, "entry-spa"));
2300
- const config = mergeConfig(
2301
- {
2302
- base: nuxt.options.dev ? joinURL(nuxt.options.app.baseURL.replace(/^\.\//, "/") || "/", nuxt.options.app.buildAssetsDir) : void 0,
2303
- logLevel: logLevelMap[nuxt.options.logLevel] ?? logLevelMap.info,
2304
- experimental: {
2305
- renderBuiltUrl: (filename2, { type, hostType, ssr: ssr2 }) => {
2306
- if (hostType !== "js") {
2307
- return { relative: true };
2308
- }
2309
- if (!ssr2) {
2310
- if (type === "asset") {
2311
- return { relative: true };
2312
- }
2313
- return { runtime: `globalThis.__publicAssetsURL(${JSON.stringify(filename2)})` };
2314
- }
2315
- if (type === "public") {
2316
- return { runtime: `${helper}__publicAssetsURL(${JSON.stringify(filename2)})` };
2317
- }
2318
- if (type === "asset") {
2319
- const relativeFilename = filename2.replace(withTrailingSlash(withoutLeadingSlash(nuxt.options.app.buildAssetsDir)), "");
2320
- return { runtime: `${helper}__buildAssetsURL(${JSON.stringify(relativeFilename)})` };
2321
- }
2322
- }
2323
- },
2324
- ...nuxt.options.experimental.viteEnvironmentApi ? {
2325
- builder: {
2326
- async buildApp(builder) {
2327
- const environments = Object.values(builder.environments);
2328
- for (const environment of environments) {
2329
- logger.restoreAll();
2330
- await builder.build(environment);
2331
- logger.wrapAll();
2332
- await nuxt.callHook("vite:compiled");
2333
- }
2334
- }
2335
- },
2336
- environments: {
2337
- client: {
2338
- consumer: "client",
2339
- keepProcessEnv: false,
2340
- dev: {
2341
- warmup: [entry]
2342
- },
2343
- ...clientEnvironment(nuxt, entry)
2344
- },
2345
- ssr: {
2346
- consumer: "server",
2347
- dev: {
2348
- warmup: [serverEntry]
2349
- },
2350
- ...ssrEnvironment(nuxt, serverEntry)
2351
- }
2352
- },
2353
- ssr: ssr(nuxt)
2354
- } : {},
2355
- resolve: {
2356
- alias: {
2357
- [basename(nuxt.options.dir.assets)]: resolve(nuxt.options.srcDir, nuxt.options.dir.assets),
2358
- ...nuxt.options.alias,
2359
- "#app": nuxt.options.appDir,
2360
- "web-streams-polyfill/ponyfill/es2018": mockEmpty,
2361
- // Cannot destructure property 'AbortController' of ..
2362
- "abort-controller": mockEmpty
2363
- },
2364
- dedupe: [
2365
- "vue"
2366
- ]
2367
- },
2368
- // TODO: devSourcemap
2369
- css: await resolveCSSOptions(nuxt),
2370
- define: {
2371
- __NUXT_VERSION__: JSON.stringify(nuxt._version),
2372
- __NUXT_ASYNC_CONTEXT__: nuxt.options.experimental.asyncContext
2373
- },
2374
- build: {
2375
- copyPublicDir: false,
2376
- rollupOptions: {
2377
- output: {
2378
- sourcemapIgnoreList: (relativeSourcePath) => {
2379
- return relativeSourcePath.includes("node_modules") || relativeSourcePath.includes(nuxt.options.buildDir);
2380
- },
2381
- sanitizeFileName: sanitizeFilePath,
2382
- // https://github.com/vitejs/vite/blob/main/packages/vite/src/node/build.ts#L464-L478
2383
- assetFileNames: nuxt.options.dev ? void 0 : (chunk) => withoutLeadingSlash(join(nuxt.options.app.buildAssetsDir, `${sanitizeFilePath(filename$1(chunk.names[0]))}.[hash].[ext]`))
2384
- }
2385
- },
2386
- // @ts-expect-error non-public property
2387
- watch: vite.rolldownVersion ? { exclude: [...nuxt.options.ignore, /[\\/]node_modules[\\/]/] } : {
2388
- chokidar: { ...nuxt.options.watchers.chokidar, ignored: [isIgnored, /[\\/]node_modules[\\/]/] },
2389
- exclude: nuxt.options.ignore
2390
- }
2391
- },
2392
- plugins: [
2393
- // add resolver for modules used in virtual files
2394
- ResolveDeepImportsPlugin(nuxt),
2395
- ResolveExternalsPlugin(nuxt),
2396
- ...nuxt.options.experimental.viteEnvironmentApi ? [
2397
- vuePlugin(viteConfig.vue),
2398
- viteJsxPlugin(viteConfig.vueJsx),
2399
- ViteNodePlugin(nuxt),
2400
- ClientManifestPlugin(nuxt),
2401
- DevServerPlugin(nuxt)
2402
- ] : [],
2403
- // add resolver for files in public assets directories
2404
- PublicDirsPlugin({
2405
- dev: nuxt.options.dev,
2406
- baseURL: nuxt.options.app.baseURL
2407
- }),
2408
- ReplacePlugin(),
2409
- LayerDepOptimizePlugin(nuxt),
2410
- SSRStylesPlugin(nuxt),
2411
- EnvironmentsPlugin(nuxt),
2412
- ...nuxt.options.experimental.viteEnvironmentApi ? [
2413
- // Add type-checking
2414
- VitePluginCheckerPlugin(nuxt),
2415
- // server-only plugins
2416
- VueFeatureFlagsPlugin(nuxt),
2417
- // tell rollup's nitro build about the original sources of the generated vite server build
2418
- SourcemapPreserverPlugin(nuxt),
2419
- // client-only plugins
2420
- DevStyleSSRPlugin({
2421
- srcDir: nuxt.options.srcDir,
2422
- buildAssetsURL: joinURL(nuxt.options.app.baseURL, nuxt.options.app.buildAssetsDir)
2423
- }),
2424
- RuntimePathsPlugin(),
2425
- // Type checking client panel
2426
- TypeCheckPlugin(nuxt),
2427
- ModulePreloadPolyfillPlugin(),
2428
- // ensure changes in chunks do not invalidate whole build
2429
- StableEntryPlugin(nuxt),
2430
- AnalyzePlugin(nuxt)
2431
- ] : []
2432
- ],
2433
- appType: "custom",
2434
- server: {
2435
- middlewareMode: true,
2436
- watch: { ...nuxt.options.watchers.chokidar, ignored: [isIgnored, /[\\/]node_modules[\\/]/] },
2437
- fs: {
2438
- allow: [...new Set(allowDirs)]
2439
- }
2440
- }
2441
- },
2442
- nuxt.options.experimental.viteEnvironmentApi ? {
2443
- ...viteConfig,
2444
- environments: {
2445
- ssr: $server,
2446
- client: $client
2447
- }
2448
- } : viteConfig
2449
- );
2450
- if (!nuxt.options.dev) {
2451
- config.server.watch = void 0;
2452
- config.build.watch = void 0;
2453
- }
2454
- const ctx = { nuxt, entry, config };
2455
- await nuxt.callHook("vite:extend", ctx);
2456
- if (nuxt.options.experimental.viteEnvironmentApi) {
2457
- await handleEnvironments(nuxt, config);
2458
- } else {
2459
- await handleSerialBuilds(nuxt, ctx);
2460
- }
1921
+ const useAsyncEntry = nuxt.options.experimental.asyncEntry || nuxt.options.dev;
1922
+ const entry = await resolvePath(resolve(nuxt.options.appDir, useAsyncEntry ? "entry.async" : "entry"));
1923
+ nuxt.options.modulesDir.push(distDir);
1924
+ let allowDirs = [
1925
+ nuxt.options.appDir,
1926
+ nuxt.options.workspaceDir,
1927
+ ...nuxt.options.modulesDir,
1928
+ ...getLayerDirectories(nuxt).map((d) => d.root),
1929
+ ...Object.values(nuxt.apps).flatMap((app) => [
1930
+ ...app.components.map((c) => dirname(c.filePath)),
1931
+ ...app.plugins.map((p) => dirname(p.src)),
1932
+ ...app.middleware.map((m) => dirname(m.path)),
1933
+ ...Object.values(app.layouts || {}).map((l) => dirname(l.file)),
1934
+ dirname(nuxt.apps.default.rootComponent),
1935
+ dirname(nuxt.apps.default.errorComponent)
1936
+ ])
1937
+ ].filter((d) => d && existsSync(d));
1938
+ for (const dir of allowDirs) allowDirs = allowDirs.filter((d) => !d.startsWith(dir) || d === dir);
1939
+ const { $client, $server, ...viteConfig } = nuxt.options.vite;
1940
+ if (vite.rolldownVersion) {
1941
+ if (viteConfig.esbuild) delete viteConfig.esbuild;
1942
+ if (viteConfig.optimizeDeps?.esbuildOptions) delete viteConfig.optimizeDeps.esbuildOptions;
1943
+ }
1944
+ const mockEmpty = resolveModulePath("mocked-exports/empty", { from: import.meta.url });
1945
+ const helper = nuxt.options.nitro.imports !== false ? "" : "globalThis.";
1946
+ const isIgnored = createIsIgnored(nuxt);
1947
+ const serverEntry = nuxt.options.ssr ? entry : await resolvePath(resolve(nuxt.options.appDir, "entry-spa"));
1948
+ const config = mergeConfig({
1949
+ base: nuxt.options.dev ? joinURL(nuxt.options.app.baseURL.replace(/^\.\//, "/") || "/", nuxt.options.app.buildAssetsDir) : void 0,
1950
+ logLevel: logLevelMap[nuxt.options.logLevel] ?? logLevelMap.info,
1951
+ experimental: { renderBuiltUrl: (filename$2, { type, hostType, ssr: ssr$1 }) => {
1952
+ if (hostType !== "js") return { relative: true };
1953
+ if (!ssr$1) {
1954
+ if (type === "asset") return { relative: true };
1955
+ return { runtime: `globalThis.__publicAssetsURL(${JSON.stringify(filename$2)})` };
1956
+ }
1957
+ if (type === "public") return { runtime: `${helper}__publicAssetsURL(${JSON.stringify(filename$2)})` };
1958
+ if (type === "asset") {
1959
+ const relativeFilename = filename$2.replace(withTrailingSlash(withoutLeadingSlash(nuxt.options.app.buildAssetsDir)), "");
1960
+ return { runtime: `${helper}__buildAssetsURL(${JSON.stringify(relativeFilename)})` };
1961
+ }
1962
+ } },
1963
+ ...nuxt.options.experimental.viteEnvironmentApi ? {
1964
+ builder: { async buildApp(builder) {
1965
+ const environments = Object.values(builder.environments);
1966
+ for (const environment of environments) {
1967
+ logger.restoreAll();
1968
+ await builder.build(environment);
1969
+ logger.wrapAll();
1970
+ await nuxt.callHook("vite:compiled");
1971
+ }
1972
+ } },
1973
+ environments: {
1974
+ client: {
1975
+ consumer: "client",
1976
+ keepProcessEnv: false,
1977
+ dev: { warmup: [entry] },
1978
+ ...clientEnvironment(nuxt, entry)
1979
+ },
1980
+ ssr: {
1981
+ consumer: "server",
1982
+ dev: { warmup: [serverEntry] },
1983
+ ...ssrEnvironment(nuxt, serverEntry)
1984
+ }
1985
+ },
1986
+ ssr: ssr(nuxt)
1987
+ } : {},
1988
+ resolve: {
1989
+ alias: {
1990
+ [basename(nuxt.options.dir.assets)]: resolve(nuxt.options.srcDir, nuxt.options.dir.assets),
1991
+ ...nuxt.options.alias,
1992
+ "#app": nuxt.options.appDir,
1993
+ "web-streams-polyfill/ponyfill/es2018": mockEmpty,
1994
+ "abort-controller": mockEmpty
1995
+ },
1996
+ dedupe: ["vue"]
1997
+ },
1998
+ css: await resolveCSSOptions(nuxt),
1999
+ define: {
2000
+ __NUXT_VERSION__: JSON.stringify(nuxt._version),
2001
+ __NUXT_ASYNC_CONTEXT__: nuxt.options.experimental.asyncContext
2002
+ },
2003
+ build: {
2004
+ copyPublicDir: false,
2005
+ rollupOptions: { output: {
2006
+ sourcemapIgnoreList: (relativeSourcePath) => {
2007
+ return relativeSourcePath.includes("node_modules") || relativeSourcePath.includes(nuxt.options.buildDir);
2008
+ },
2009
+ sanitizeFileName: sanitizeFilePath,
2010
+ assetFileNames: nuxt.options.dev ? void 0 : (chunk) => withoutLeadingSlash(join(nuxt.options.app.buildAssetsDir, `${sanitizeFilePath(filename(chunk.names[0]))}.[hash].[ext]`))
2011
+ } },
2012
+ watch: vite.rolldownVersion ? { exclude: [...nuxt.options.ignore, /[\\/]node_modules[\\/]/] } : {
2013
+ chokidar: {
2014
+ ...nuxt.options.watchers.chokidar,
2015
+ ignored: [isIgnored, /[\\/]node_modules[\\/]/]
2016
+ },
2017
+ exclude: nuxt.options.ignore
2018
+ }
2019
+ },
2020
+ plugins: [
2021
+ ResolveDeepImportsPlugin(nuxt),
2022
+ ResolveExternalsPlugin(nuxt),
2023
+ ...nuxt.options.experimental.viteEnvironmentApi ? [
2024
+ vuePlugin(viteConfig.vue),
2025
+ viteJsxPlugin(viteConfig.vueJsx),
2026
+ ViteNodePlugin(nuxt),
2027
+ ClientManifestPlugin(nuxt),
2028
+ DevServerPlugin(nuxt)
2029
+ ] : [],
2030
+ PublicDirsPlugin({
2031
+ dev: nuxt.options.dev,
2032
+ baseURL: nuxt.options.app.baseURL
2033
+ }),
2034
+ ReplacePlugin(),
2035
+ LayerDepOptimizePlugin(nuxt),
2036
+ SSRStylesPlugin(nuxt),
2037
+ EnvironmentsPlugin(nuxt),
2038
+ ...nuxt.options.experimental.viteEnvironmentApi ? [
2039
+ VitePluginCheckerPlugin(nuxt),
2040
+ VueFeatureFlagsPlugin(nuxt),
2041
+ SourcemapPreserverPlugin(nuxt),
2042
+ DevStyleSSRPlugin({
2043
+ srcDir: nuxt.options.srcDir,
2044
+ buildAssetsURL: joinURL(nuxt.options.app.baseURL, nuxt.options.app.buildAssetsDir)
2045
+ }),
2046
+ RuntimePathsPlugin(),
2047
+ TypeCheckPlugin(nuxt),
2048
+ ModulePreloadPolyfillPlugin(),
2049
+ StableEntryPlugin(nuxt),
2050
+ AnalyzePlugin(nuxt)
2051
+ ] : []
2052
+ ],
2053
+ appType: "custom",
2054
+ server: {
2055
+ middlewareMode: true,
2056
+ watch: {
2057
+ ...nuxt.options.watchers.chokidar,
2058
+ ignored: [isIgnored, /[\\/]node_modules[\\/]/]
2059
+ },
2060
+ fs: { allow: [...new Set(allowDirs)] }
2061
+ }
2062
+ }, nuxt.options.experimental.viteEnvironmentApi ? {
2063
+ ...viteConfig,
2064
+ environments: {
2065
+ ssr: $server,
2066
+ client: $client
2067
+ }
2068
+ } : viteConfig);
2069
+ if (!nuxt.options.dev) {
2070
+ config.server.watch = void 0;
2071
+ config.build.watch = void 0;
2072
+ }
2073
+ const ctx = {
2074
+ nuxt,
2075
+ entry,
2076
+ config
2077
+ };
2078
+ await nuxt.callHook("vite:extend", ctx);
2079
+ if (nuxt.options.experimental.viteEnvironmentApi) await handleEnvironments(nuxt, config);
2080
+ else await handleSerialBuilds(nuxt, ctx);
2461
2081
  };
2462
2082
  async function handleEnvironments(nuxt, config) {
2463
- config.customLogger = createViteLogger(config);
2464
- config.configFile = false;
2465
- for (const environment of ["client", "ssr"]) {
2466
- const environments = { [environment]: config.environments[environment] };
2467
- const strippedConfig = { ...config, environments };
2468
- const ctx = { isServer: environment === "ssr", isClient: environment === "client" };
2469
- await nuxt.hooks.callHook("vite:extendConfig", strippedConfig, ctx);
2470
- await nuxt.hooks.callHook("vite:configResolved", strippedConfig, ctx);
2471
- }
2472
- if (!nuxt.options.dev) {
2473
- const builder = await createBuilder(config);
2474
- await builder.buildApp();
2475
- return;
2476
- }
2477
- await withLogs(async () => {
2478
- const server = await createServer(config);
2479
- await server.environments.ssr.pluginContainer.buildStart({});
2480
- }, "Vite dev server built");
2481
- await writeDevServer(nuxt);
2083
+ config.customLogger = createViteLogger(config);
2084
+ config.configFile = false;
2085
+ for (const environment of ["client", "ssr"]) {
2086
+ const environments = { [environment]: config.environments[environment] };
2087
+ const strippedConfig = {
2088
+ ...config,
2089
+ environments
2090
+ };
2091
+ const ctx = {
2092
+ isServer: environment === "ssr",
2093
+ isClient: environment === "client"
2094
+ };
2095
+ await nuxt.hooks.callHook("vite:extendConfig", strippedConfig, ctx);
2096
+ await nuxt.hooks.callHook("vite:configResolved", strippedConfig, ctx);
2097
+ }
2098
+ if (!nuxt.options.dev) {
2099
+ await (await createBuilder(config)).buildApp();
2100
+ return;
2101
+ }
2102
+ await withLogs(async () => {
2103
+ await (await createServer(config)).environments.ssr.pluginContainer.buildStart({});
2104
+ }, "Vite dev server built");
2105
+ await writeDevServer(nuxt);
2482
2106
  }
2483
2107
  async function handleSerialBuilds(nuxt, ctx) {
2484
- nuxt.hook("vite:serverCreated", (server, env) => {
2485
- if (nuxt.options.vite.warmupEntry !== false) {
2486
- useNitro().hooks.hookOnce("compiled", () => {
2487
- const start = Date.now();
2488
- warmupViteServer(server, [ctx.entry], env.isServer).then(() => logger.info(`Vite ${env.isClient ? "client" : "server"} warmed up in ${Date.now() - start}ms`)).catch(logger.error);
2489
- });
2490
- }
2491
- });
2492
- await withLogs(() => buildClient(nuxt, ctx), "Vite client built", nuxt.options.dev);
2493
- await withLogs(() => buildServer(nuxt, ctx), "Vite server built", nuxt.options.dev);
2108
+ nuxt.hook("vite:serverCreated", (server, env) => {
2109
+ if (nuxt.options.vite.warmupEntry !== false) useNitro().hooks.hookOnce("compiled", () => {
2110
+ const start = Date.now();
2111
+ warmupViteServer(server, [ctx.entry], env.isServer).then(() => logger.info(`Vite ${env.isClient ? "client" : "server"} warmed up in ${Date.now() - start}ms`)).catch(logger.error);
2112
+ });
2113
+ });
2114
+ await withLogs(() => buildClient(nuxt, ctx), "Vite client built", nuxt.options.dev);
2115
+ await withLogs(() => buildServer(nuxt, ctx), "Vite server built", nuxt.options.dev);
2494
2116
  }
2495
2117
  async function withLogs(fn, message, enabled = true) {
2496
- if (!enabled) {
2497
- return fn();
2498
- }
2499
- const start = performance.now();
2500
- await fn();
2501
- const duration = performance.now() - start;
2502
- logger.success(`${message} in ${Math.round(duration)}ms`);
2118
+ if (!enabled) return fn();
2119
+ const start = performance.now();
2120
+ await fn();
2121
+ const duration = performance.now() - start;
2122
+ logger.success(`${message} in ${Math.round(duration)}ms`);
2503
2123
  }
2504
2124
 
2505
- export { bundle };
2125
+ //#endregion
2126
+ export { bundle };