@nuxt/rspack-builder 4.2.2 → 4.3.1

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,193 +1,496 @@
1
- import pify from 'pify';
2
- import { fromNodeMiddleware, defineEventHandler, handleCors, getRequestHeader, createError, setHeader } from 'h3';
3
- import webpackDevMiddleware from 'webpack-dev-middleware';
4
- import webpackHotMiddleware from 'webpack-hot-middleware';
5
- import { defu } from 'defu';
6
- import { joinURL } from 'ufo';
7
- import { logger, useNitro, useNuxt } from '@nuxt/kit';
8
- import { createUnplugin } from 'unplugin';
9
- import MagicString from 'magic-string';
10
- import { webpack, WebpackBarPlugin, builder, MiniCssExtractPlugin, TsCheckerPlugin } from '#builder';
11
- import { join, resolve, basename, normalize, isAbsolute } from 'pathe';
12
- import { createFsFromVolume, Volume } from 'memfs';
13
- import querystring from 'node:querystring';
14
- import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer';
15
- import { defineEnv } from 'unenv';
16
- import TimeFixPlugin from 'time-fix-plugin';
17
- import FriendlyErrorsWebpackPlugin from '@nuxt/friendly-errors-webpack-plugin';
18
- import escapeRegExp from 'escape-string-regexp';
19
- import { isTest } from 'std-env';
20
- import { genObjectFromRawEntries, genString } from 'knitwork';
21
- import { EsbuildPlugin } from 'esbuild-loader';
22
- import CssMinimizerPlugin from 'css-minimizer-webpack-plugin';
23
- import createResolver from 'postcss-import-resolver';
24
- import { createJiti } from 'jiti';
25
- import VueLoaderPlugin from 'vue-loader/dist/pluginWebpack5.js';
26
- import { mkdir, writeFile } from 'node:fs/promises';
27
- import { normalizeWebpackManifest, precomputeDependencies } from 'vue-bundle-renderer';
28
- import { hash } from 'ohash';
29
- import { serialize } from 'seroval';
30
-
1
+ import { createRequire } from "node:module";
2
+ import pify from "pify";
3
+ import webpackDevMiddleware from "webpack-dev-middleware";
4
+ import webpackHotMiddleware from "webpack-hot-middleware";
5
+ import { defu } from "defu";
6
+ import { joinURL, parseURL, withTrailingSlash } from "ufo";
7
+ import { directoryToURL, logger, resolveAlias, useNitro, useNuxt } from "@nuxt/kit";
8
+ import { createUnplugin } from "unplugin";
9
+ import MagicString from "magic-string";
10
+ import { MiniCssExtractPlugin, TsCheckerPlugin, WebpackBarPlugin, builder, webpack } from "#builder";
11
+ import { existsSync, readFileSync } from "node:fs";
12
+ import { pathToFileURL } from "node:url";
13
+ import { basename, isAbsolute, join, normalize, relative, resolve } from "pathe";
14
+ import { genArrayFromRaw, genObjectFromRawEntries, genString } from "knitwork";
15
+ import { compileStyle, parse } from "@vue/compiler-sfc";
16
+ import { createHash } from "node:crypto";
17
+ import { Volume, createFsFromVolume } from "memfs";
18
+ import querystring from "node:querystring";
19
+ import { BundleAnalyzerPlugin } from "webpack-bundle-analyzer";
20
+ import { defineEnv } from "unenv";
21
+ import TimeFixPlugin from "time-fix-plugin";
22
+ import FriendlyErrorsWebpackPlugin from "@nuxt/friendly-errors-webpack-plugin";
23
+ import escapeRegExp from "escape-string-regexp";
24
+ import { isTest } from "std-env";
25
+ import { EsbuildPlugin } from "esbuild-loader";
26
+ import CssMinimizerPlugin from "css-minimizer-webpack-plugin";
27
+ import createResolver from "postcss-import-resolver";
28
+ import { createJiti } from "jiti";
29
+ import VueLoaderPlugin from "vue-loader/dist/pluginWebpack5.js";
30
+ import { resolveModulePath } from "exsolve";
31
+ import { mkdir, writeFile } from "node:fs/promises";
32
+ import { normalizeWebpackManifest, precomputeDependencies } from "vue-bundle-renderer";
33
+ import { hash } from "ohash";
34
+ import { serialize } from "seroval";
35
+ import { parseNodeModulePath } from "mlly";
31
36
  const defaults = {
32
- globalPublicPath: "__webpack_public_path__",
33
- sourcemap: true
37
+ globalPublicPath: "__webpack_public_path__",
38
+ sourcemap: true
34
39
  };
35
40
  const ENTRY_RE = /import ["']#build\/css["'];/;
36
41
  const DynamicBasePlugin = createUnplugin((options = {}) => {
37
- options = { ...defaults, ...options };
38
- return {
39
- name: "nuxt:dynamic-base-path",
40
- enforce: "post",
41
- transform: {
42
- filter: {
43
- id: { include: /entry/ },
44
- code: { include: ENTRY_RE }
45
- },
46
- handler(code) {
47
- const s = new MagicString(code);
48
- s.prepend(`import { buildAssetsURL } from '#internal/nuxt/paths';
49
- ${options.globalPublicPath} = buildAssetsURL();
50
- `);
51
- return {
52
- code: s.toString(),
53
- map: options.sourcemap ? s.generateMap({ hires: true }) : void 0
54
- };
55
- }
56
- }
57
- };
42
+ options = {
43
+ ...defaults,
44
+ ...options
45
+ };
46
+ return {
47
+ name: "nuxt:dynamic-base-path",
48
+ enforce: "post",
49
+ transform: {
50
+ filter: {
51
+ id: { include: /entry/ },
52
+ code: { include: ENTRY_RE }
53
+ },
54
+ handler(code) {
55
+ const s = new MagicString(code);
56
+ s.prepend(`import { buildAssetsURL } from '#internal/nuxt/paths';\n${options.globalPublicPath} = buildAssetsURL();\n`);
57
+ return {
58
+ code: s.toString(),
59
+ map: options.sourcemap ? s.generateMap({ hires: true }) : void 0
60
+ };
61
+ }
62
+ }
63
+ };
58
64
  });
59
-
60
65
  const pluginName = "ChunkErrorPlugin";
61
- class ChunkErrorPlugin {
62
- script = `
63
- if (typeof ${webpack.RuntimeGlobals.require} !== "undefined") {
64
- var _ensureChunk = ${webpack.RuntimeGlobals.ensureChunk};
65
- ${webpack.RuntimeGlobals.ensureChunk} = function (chunkId) {
66
- return Promise.resolve(_ensureChunk(chunkId)).catch(error => {
67
- const e = new Event('nuxt:preloadError', { cancelable: true })
68
- e.payload = error
69
- window.dispatchEvent(e)
70
- throw error
66
+ var ChunkErrorPlugin = class {
67
+ apply(compiler) {
68
+ compiler.hooks.thisCompilation.tap(pluginName, (compilation) => {
69
+ compilation.hooks.runtimeRequirementInTree.for(webpack.RuntimeGlobals.ensureChunk).tap(pluginName, (chunk) => {
70
+ compilation.addRuntimeModule(chunk, new ChunkErrorRuntimeModule());
71
+ });
72
+ });
73
+ }
74
+ };
75
+ var ChunkErrorRuntimeModule = class extends webpack.RuntimeModule {
76
+ constructor() {
77
+ super("chunk preload error handler", webpack.RuntimeModule.STAGE_ATTACH);
78
+ }
79
+ generate() {
80
+ const { ensureChunk } = webpack.RuntimeGlobals;
81
+ return `
82
+ if (typeof ${ensureChunk} !== "undefined") {
83
+ var _ensureChunk = ${ensureChunk};
84
+ ${ensureChunk} = function (chunkId) {
85
+ return Promise.resolve(_ensureChunk(chunkId)).catch(function(error) {
86
+ var e = new Event('nuxt:preloadError', { cancelable: true });
87
+ e.payload = error;
88
+ window.dispatchEvent(e);
89
+ throw error;
71
90
  });
72
91
  };
73
- };`;
74
- apply(compiler) {
75
- compiler.hooks.thisCompilation.tap(
76
- pluginName,
77
- (compilation) => compilation.mainTemplate.hooks.localVars.tap(
78
- { name: pluginName, stage: 1 },
79
- (source) => source + this.script
80
- )
81
- );
82
- }
83
92
  }
84
-
93
+ `;
94
+ }
95
+ };
96
+ const CSS_URL_RE = /url\((['"]?)(\/[^)]+?)\1\)/g;
97
+ const isVueFile = (id) => /\.vue(?:\?|$)/.test(id);
98
+ const isCSSLike = (name) => /\.(?:css|scss|sass|less|styl(?:us)?|postcss|pcss)(?:\?|$)/.test(name);
99
+ function normalizePath(nuxt, id) {
100
+ if (!id) return null;
101
+ const { pathname } = parseURL(decodeURIComponent(pathToFileURL(id).href));
102
+ const rel = relative(nuxt.options.srcDir, pathname);
103
+ if (rel.startsWith("..")) return null;
104
+ return rel;
105
+ }
106
+ function resolveFilePath(id) {
107
+ if (!id) return null;
108
+ return parseURL(decodeURIComponent(pathToFileURL(id).href)).pathname || null;
109
+ }
110
+ function sanitizeStyleAssetName(rel) {
111
+ return rel.replace(/[\\/]/g, "_").replace(/\.{2,}/g, "_");
112
+ }
113
+ function normalizeCSSContent(css) {
114
+ return css.trim().replace(/(--[^:]+):\s*'([^']*)'/g, "$1:\"$2\"").replace(/:\s+/g, ":").replace(/\s*\{\s*/g, "{").replace(/;\s*\}/g, "}").replace(/\s*\}\s*/g, "}");
115
+ }
116
+ function extractVueStyles(filePath) {
117
+ try {
118
+ const { descriptor } = parse(readFileSync(filePath, "utf8"), { filename: filePath });
119
+ const styles = [];
120
+ const scopeId = createHash("sha256").update(filePath).digest("hex").slice(0, 8);
121
+ for (let i = 0; i < descriptor.styles.length; i++) {
122
+ const style = descriptor.styles[i];
123
+ const result = compileStyle({
124
+ source: style.content,
125
+ filename: filePath,
126
+ id: `data-v-${scopeId}`,
127
+ scoped: style.scoped
128
+ });
129
+ if (!result.errors.length && result.code) styles.push(normalizeCSSContent(result.code));
130
+ }
131
+ return styles;
132
+ } catch {
133
+ return [];
134
+ }
135
+ }
136
+ var SSRStylesPlugin = class {
137
+ nuxt;
138
+ clientCSSByIssuer = /* @__PURE__ */ new Map();
139
+ chunksWithInlinedCSS = /* @__PURE__ */ new Set();
140
+ globalCSSPaths = /* @__PURE__ */ new Set();
141
+ constructor(nuxt) {
142
+ this.nuxt = nuxt;
143
+ this.globalCSSPaths = this.resolveGlobalCSS();
144
+ nuxt.hook("build:manifest", (manifest) => {
145
+ for (const [id, chunk] of Object.entries(manifest)) {
146
+ if (chunk.isEntry && chunk.src) this.chunksWithInlinedCSS.add(chunk.src);
147
+ else if (this.chunksWithInlinedCSS.has(id)) chunk.css &&= [];
148
+ if (chunk.css?.length) chunk.css = chunk.css.filter((cssPath) => {
149
+ for (const globalPath of this.globalCSSPaths) if (cssPath.includes(globalPath.split("/").pop() || "")) return false;
150
+ return true;
151
+ });
152
+ }
153
+ });
154
+ }
155
+ shouldInline(mod) {
156
+ const shouldInline = this.nuxt.options.features.inlineStyles;
157
+ if (typeof shouldInline === "boolean") return shouldInline;
158
+ return shouldInline(mod.identifier());
159
+ }
160
+ escapeTemplateLiteral(str) {
161
+ return str.replace(/[`\\$]/g, (m) => m === "$" ? "\\$" : `\\${m}`);
162
+ }
163
+ isBuildAsset(url) {
164
+ const buildDir = withTrailingSlash(this.nuxt.options.app.buildAssetsDir || "/_nuxt/");
165
+ return url.startsWith(buildDir);
166
+ }
167
+ isPublicAsset(url, nitro) {
168
+ const cleaned = url.replace(/[?#].*$/, "");
169
+ for (const dir of nitro.options.publicAssets) {
170
+ const base = withTrailingSlash(dir.baseURL || "/");
171
+ if (!url.startsWith(base)) continue;
172
+ if (existsSync(cleaned.replace(base, withTrailingSlash(dir.dir)))) return true;
173
+ }
174
+ return false;
175
+ }
176
+ rewriteStyle(css, nitro) {
177
+ let changed = false;
178
+ let needsPublicAsset = false;
179
+ let needsBuildAsset = false;
180
+ let lastIndex = 0;
181
+ let out = "`";
182
+ for (const match of css.matchAll(CSS_URL_RE)) {
183
+ const index = match.index ?? 0;
184
+ const before = css.slice(lastIndex, index);
185
+ if (before) out += this.escapeTemplateLiteral(before);
186
+ const full = match[0];
187
+ const rawUrl = match[2] || "";
188
+ const stripped = rawUrl.replace(/[?#].*$/, "");
189
+ if (this.isPublicAsset(stripped, nitro)) {
190
+ needsPublicAsset = true;
191
+ changed = true;
192
+ out += "${publicAssetsURL(" + JSON.stringify(rawUrl) + ")}";
193
+ } else if (this.isBuildAsset(stripped)) {
194
+ needsBuildAsset = true;
195
+ changed = true;
196
+ out += "${buildAssetsURL(" + JSON.stringify(rawUrl) + ")}";
197
+ } else out += this.escapeTemplateLiteral(full);
198
+ lastIndex = index + full.length;
199
+ }
200
+ const tail = css.slice(lastIndex);
201
+ if (tail) out += this.escapeTemplateLiteral(tail);
202
+ out += "`";
203
+ return {
204
+ code: changed ? out : JSON.stringify(css),
205
+ needsPublicAsset,
206
+ needsBuildAsset
207
+ };
208
+ }
209
+ resolveGlobalCSS() {
210
+ const req = createRequire(this.nuxt.options.rootDir);
211
+ const resolved = /* @__PURE__ */ new Set();
212
+ const entries = this.nuxt.options.css || [];
213
+ for (const entry of entries) {
214
+ const src = typeof entry === "string" ? entry : entry?.src;
215
+ if (!src) continue;
216
+ const path = this.resolveCSSRequest(src, req);
217
+ if (path) resolved.add(path);
218
+ }
219
+ return resolved;
220
+ }
221
+ resolveCSSRequest(request, req) {
222
+ const candidates = /* @__PURE__ */ new Set();
223
+ const resolved = resolveAlias(request, this.nuxt.options.alias);
224
+ if (isAbsolute(resolved)) candidates.add(resolved);
225
+ else candidates.add(resolve(this.nuxt.options.srcDir, resolved));
226
+ try {
227
+ candidates.add(req.resolve(request));
228
+ } catch {}
229
+ for (const candidate of candidates) {
230
+ const path = resolveFilePath(candidate);
231
+ if (path) return path;
232
+ }
233
+ return null;
234
+ }
235
+ normalizeResourcePath(resource) {
236
+ if (!resource) return null;
237
+ const withoutQuery = resource.split("?")[0];
238
+ return resolveFilePath(withoutQuery);
239
+ }
240
+ apply(compiler) {
241
+ if (this.nuxt.options.dev) return;
242
+ const isClient = compiler.options.name === "client";
243
+ const isServer = compiler.options.name === "server";
244
+ if (!isClient && !isServer) return;
245
+ compiler.hooks.thisCompilation.tap("SSRStylesPlugin", (compilation) => {
246
+ this.collectCSS(compilation);
247
+ if (isClient) this.removeGlobalCSSFromClient(compilation);
248
+ if (isServer) this.emitServerStyles(compilation);
249
+ });
250
+ }
251
+ emitServerStyles(compilation) {
252
+ const { webpack } = compilation.compiler;
253
+ const stage = webpack.Compilation.PROCESS_ASSETS_STAGE_SUMMARIZE;
254
+ compilation.hooks.processAssets.tap({
255
+ name: "SSRStylesPlugin",
256
+ stage
257
+ }, () => {
258
+ const nitro = useNitro();
259
+ const collected = new Map(this.clientCSSByIssuer);
260
+ const entryModules = /* @__PURE__ */ new Set();
261
+ for (const entrypoint of compilation.entrypoints.values()) {
262
+ const primaryChunk = typeof entrypoint.getEntrypointChunk === "function" ? entrypoint.getEntrypointChunk() : void 0;
263
+ const chunks = primaryChunk ? [primaryChunk] : entrypoint.chunks;
264
+ for (const chunk of chunks) for (const mod of compilation.chunkGraph.getChunkModulesIterable(chunk)) if ("resource" in mod && typeof mod.resource === "string") {
265
+ const resolved = resolveFilePath(mod.resource);
266
+ if (resolved) {
267
+ const rel = normalizePath(this.nuxt, resolved);
268
+ if (rel) entryModules.add(rel);
269
+ else entryModules.add(resolved);
270
+ }
271
+ }
272
+ }
273
+ for (const module of compilation.modules) {
274
+ const resource = module.resource;
275
+ if (!resource || !isVueFile(resource)) continue;
276
+ const rel = normalizePath(this.nuxt, resource);
277
+ if (!rel) continue;
278
+ if (collected.has(rel)) continue;
279
+ const vueStyles = extractVueStyles(resolveFilePath(resource) || resource);
280
+ if (vueStyles.length) collected.set(rel, new Set(vueStyles));
281
+ }
282
+ const emitted = {};
283
+ const rawSource = webpack.sources.RawSource;
284
+ for (const [rel, cssSet] of collected.entries()) {
285
+ if (!cssSet.size) continue;
286
+ const transformed = Array.from(cssSet).map((style) => this.rewriteStyle(style, nitro));
287
+ const needsPublicAssets = transformed.some((t) => t.needsPublicAsset);
288
+ const needsBuildAssets = transformed.some((t) => t.needsBuildAsset);
289
+ const imports = [];
290
+ if (needsPublicAssets || needsBuildAssets) {
291
+ const names = [];
292
+ if (needsBuildAssets) names.push("buildAssetsURL");
293
+ if (needsPublicAssets) names.push("publicAssetsURL");
294
+ imports.push(`import { ${names.join(", ")} } from '#internal/nuxt/paths'`);
295
+ }
296
+ const moduleSource = [...imports, `export default ${genArrayFromRaw(transformed.map((t) => t.code))}`].filter(Boolean).join("\n");
297
+ const styleModuleName = `${sanitizeStyleAssetName(rel)}-styles.mjs`;
298
+ compilation.emitAsset(styleModuleName, new rawSource(moduleSource));
299
+ emitted[rel] = styleModuleName;
300
+ this.chunksWithInlinedCSS.add(rel);
301
+ }
302
+ const stylesSource = ["const interopDefault = r => r.default || r || []", `export default ${genObjectFromRawEntries(Object.entries(emitted).map(([key, value]) => [key, `() => import('./${value}').then(interopDefault)`]))}`].join("\n");
303
+ compilation.emitAsset("styles.mjs", new rawSource(stylesSource));
304
+ const entryIds = Array.from(this.chunksWithInlinedCSS).filter((id) => entryModules.has(id));
305
+ nitro.options.virtual["#internal/nuxt/entry-ids.mjs"] = () => `export default ${JSON.stringify(entryIds)}`;
306
+ nitro.options._config.virtual ||= {};
307
+ nitro.options._config.virtual["#internal/nuxt/entry-ids.mjs"] = nitro.options.virtual["#internal/nuxt/entry-ids.mjs"];
308
+ });
309
+ }
310
+ findIssuerPath(compilation, mod) {
311
+ let issuer = compilation.moduleGraph.getIssuer(mod);
312
+ while (issuer) {
313
+ if ("resource" in issuer && typeof issuer.resource === "string") return issuer.resource;
314
+ issuer = compilation.moduleGraph.getIssuer(issuer);
315
+ }
316
+ return null;
317
+ }
318
+ removeGlobalCSSFromClient(compilation) {
319
+ compilation.hooks.processAssets.tap({
320
+ name: "SSRStylesPlugin:RemoveGlobalCSS",
321
+ stage: 650
322
+ }, () => {
323
+ for (const chunk of compilation.chunks) if (chunk.name === "nuxt-global-css") {
324
+ const cssAssets = [];
325
+ for (const file of Array.from(chunk.files)) {
326
+ const filename = String(file);
327
+ if (isCSSLike(filename)) {
328
+ const source = compilation.getAsset(filename)?.source;
329
+ const content = source && typeof source.source === "function" ? source.source() : null;
330
+ const text = typeof content === "string" ? content : content instanceof Buffer ? content.toString("utf8") : "";
331
+ if (text) cssAssets.push(text);
332
+ }
333
+ }
334
+ if (cssAssets.length > 0) for (const mod of compilation.chunkGraph.getChunkModulesIterable(chunk)) {
335
+ const issuerPath = this.findIssuerPath(compilation, mod) || ("resource" in mod && typeof mod.resource === "string" ? mod.resource : null);
336
+ const normalized = normalizePath(this.nuxt, issuerPath);
337
+ if (!normalized) continue;
338
+ const set = this.clientCSSByIssuer.get(normalized) || /* @__PURE__ */ new Set();
339
+ for (const css of cssAssets) set.add(normalizeCSSContent(css));
340
+ this.clientCSSByIssuer.set(normalized, set);
341
+ }
342
+ for (const file of Array.from(chunk.files)) {
343
+ const filename = String(file);
344
+ if (isCSSLike(filename)) {
345
+ compilation.deleteAsset(filename);
346
+ chunk.files.delete(file);
347
+ }
348
+ }
349
+ }
350
+ });
351
+ }
352
+ collectCSS(compilation) {
353
+ const { webpack } = compilation.compiler;
354
+ const stage = compilation.compiler.options.name === "server" ? webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS : webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_TRANSFER;
355
+ const chunkCSSMeta = /* @__PURE__ */ new Map();
356
+ compilation.hooks.processAssets.tap({
357
+ name: "SSRStylesPlugin",
358
+ stage
359
+ }, () => {
360
+ const cssAssetsByChunk = /* @__PURE__ */ new Map();
361
+ for (const chunk of compilation.chunks) {
362
+ const cssAssets = [];
363
+ const chunkCSSFiles = [];
364
+ for (const file of chunk.files) {
365
+ if (!isCSSLike(file)) continue;
366
+ chunkCSSFiles.push(file);
367
+ const source = compilation.getAsset(file)?.source;
368
+ const content = source && typeof source.source === "function" ? source.source() : null;
369
+ const text = typeof content === "string" ? content : content instanceof Buffer ? content.toString("utf8") : "";
370
+ if (text) cssAssets.push(text);
371
+ }
372
+ if (chunkCSSFiles.length) {
373
+ const chunkCSSModules = Array.from(compilation.chunkGraph.getChunkModulesIterable(chunk));
374
+ chunkCSSMeta.set(chunk, {
375
+ files: chunkCSSFiles,
376
+ modules: chunkCSSModules
377
+ });
378
+ }
379
+ if (cssAssets.length) cssAssetsByChunk.set(chunk, cssAssets);
380
+ }
381
+ for (const [chunk, cssAssets] of cssAssetsByChunk) for (const mod of compilation.chunkGraph.getChunkModulesIterable(chunk)) {
382
+ if (!this.shouldInline(mod)) continue;
383
+ const issuerPath = this.findIssuerPath(compilation, mod) || ("resource" in mod && typeof mod.resource === "string" ? mod.resource : null);
384
+ const normalized = normalizePath(this.nuxt, issuerPath);
385
+ if (!normalized) continue;
386
+ const set = this.clientCSSByIssuer.get(normalized) || /* @__PURE__ */ new Set();
387
+ for (const css of cssAssets) set.add(normalizeCSSContent(css));
388
+ this.clientCSSByIssuer.set(normalized, set);
389
+ }
390
+ for (const mod of compilation.modules) {
391
+ if (!this.shouldInline(mod)) continue;
392
+ const issuerPath = this.findIssuerPath(compilation, mod);
393
+ const normalized = normalizePath(this.nuxt, issuerPath);
394
+ if (!normalized) continue;
395
+ const cssChunks = this.getModuleCSS(mod, compilation);
396
+ if (!cssChunks.length) continue;
397
+ const set = this.clientCSSByIssuer.get(normalized) || /* @__PURE__ */ new Set();
398
+ set.add(cssChunks.join("\n"));
399
+ this.clientCSSByIssuer.set(normalized, set);
400
+ }
401
+ });
402
+ }
403
+ getModuleCSS(mod, _compilation) {
404
+ const cssModule = mod;
405
+ const cssChunks = [];
406
+ if (mod.type === "css/mini-extract" && Array.isArray(cssModule.content)) for (const part of cssModule.content) {
407
+ const css = part?.[1];
408
+ if (css && typeof css === "string") cssChunks.push(normalizeCSSContent(css));
409
+ }
410
+ return cssChunks;
411
+ }
412
+ };
85
413
  function createMFS() {
86
- const fs = createFsFromVolume(new Volume());
87
- const _fs = { ...fs };
88
- _fs.join = join;
89
- _fs.exists = (p) => Promise.resolve(_fs.existsSync(p));
90
- _fs.readFile = pify(_fs.readFile);
91
- return _fs;
414
+ const _fs = { ...createFsFromVolume(new Volume()) };
415
+ _fs.join = join;
416
+ _fs.exists = (p) => Promise.resolve(_fs.existsSync(p));
417
+ _fs.readFile = pify(_fs.readFile);
418
+ return _fs;
92
419
  }
93
-
94
420
  function toArray(value) {
95
- return Array.isArray(value) ? value : [value];
421
+ return Array.isArray(value) ? value : [value];
96
422
  }
97
-
98
423
  function createWebpackConfigContext(nuxt) {
99
- return {
100
- nuxt,
101
- options: nuxt.options,
102
- userConfig: nuxt.options.webpack,
103
- config: {},
104
- name: "base",
105
- isDev: nuxt.options.dev,
106
- isServer: false,
107
- isClient: false,
108
- alias: {},
109
- transpile: []
110
- };
424
+ return {
425
+ nuxt,
426
+ options: nuxt.options,
427
+ userConfig: nuxt.options.webpack,
428
+ config: {},
429
+ name: "base",
430
+ isDev: nuxt.options.dev,
431
+ isServer: false,
432
+ isClient: false,
433
+ alias: {},
434
+ transpile: []
435
+ };
111
436
  }
112
437
  async function applyPresets(ctx, presets) {
113
- for (const preset of toArray(presets)) {
114
- if (Array.isArray(preset)) {
115
- await preset[0](ctx, preset[1]);
116
- } else {
117
- await preset(ctx);
118
- }
119
- }
438
+ for (const preset of toArray(presets)) if (Array.isArray(preset)) await preset[0](ctx, preset[1]);
439
+ else await preset(ctx);
120
440
  }
121
441
  function fileName(ctx, key) {
122
- let fileName2 = ctx.userConfig.filenames[key];
123
- if (typeof fileName2 === "function") {
124
- fileName2 = fileName2(ctx);
125
- }
126
- if (typeof fileName2 === "string" && ctx.options.dev) {
127
- const hash = /\[(chunkhash|contenthash|hash)(?::\d+)?\]/.exec(fileName2);
128
- if (hash) {
129
- logger.warn(`Notice: Please do not use ${hash[1]} in dev mode to prevent memory leak`);
130
- }
131
- }
132
- return fileName2;
442
+ let fileName = ctx.userConfig.filenames[key];
443
+ if (typeof fileName === "function") fileName = fileName(ctx);
444
+ if (typeof fileName === "string" && ctx.options.dev) {
445
+ const hash = /\[(chunkhash|contenthash|hash)(?::\d+)?\]/.exec(fileName);
446
+ if (hash) logger.warn(`Notice: Please do not use ${hash[1]} in dev mode to prevent memory leak`);
447
+ }
448
+ return fileName;
133
449
  }
134
-
135
450
  function assets(ctx) {
136
- ctx.config.module.rules.push(
137
- {
138
- test: /\.(png|jpe?g|gif|svg|webp)$/i,
139
- use: [{
140
- loader: "url-loader",
141
- options: {
142
- ...ctx.userConfig.loaders.imgUrl,
143
- name: fileName(ctx, "img")
144
- }
145
- }]
146
- },
147
- {
148
- test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/i,
149
- use: [{
150
- loader: "url-loader",
151
- options: {
152
- ...ctx.userConfig.loaders.fontUrl,
153
- name: fileName(ctx, "font")
154
- }
155
- }]
156
- },
157
- {
158
- test: /\.(webm|mp4|ogv)$/i,
159
- use: [{
160
- loader: "file-loader",
161
- options: {
162
- ...ctx.userConfig.loaders.file,
163
- name: fileName(ctx, "video")
164
- }
165
- }]
166
- }
167
- );
451
+ ctx.config.module.rules.push({
452
+ test: /\.(png|jpe?g|gif|svg|webp)$/i,
453
+ use: [{
454
+ loader: "url-loader",
455
+ options: {
456
+ ...ctx.userConfig.loaders.imgUrl,
457
+ name: fileName(ctx, "img")
458
+ }
459
+ }]
460
+ }, {
461
+ test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/i,
462
+ use: [{
463
+ loader: "url-loader",
464
+ options: {
465
+ ...ctx.userConfig.loaders.fontUrl,
466
+ name: fileName(ctx, "font")
467
+ }
468
+ }]
469
+ }, {
470
+ test: /\.(webm|mp4|ogv)$/i,
471
+ use: [{
472
+ loader: "file-loader",
473
+ options: {
474
+ ...ctx.userConfig.loaders.file,
475
+ name: fileName(ctx, "video")
476
+ }
477
+ }]
478
+ });
168
479
  }
169
-
170
- class WarningIgnorePlugin {
171
- filter;
172
- constructor(filter) {
173
- this.filter = filter;
174
- }
175
- apply(compiler) {
176
- compiler.hooks.done.tap("warnfix-plugin", (stats) => {
177
- stats.compilation.warnings = stats.compilation.warnings.filter(this.filter);
178
- });
179
- }
180
- }
181
-
480
+ var WarningIgnorePlugin = class {
481
+ filter;
482
+ constructor(filter) {
483
+ this.filter = filter;
484
+ }
485
+ apply(compiler) {
486
+ compiler.hooks.done.tap("warnfix-plugin", (stats) => {
487
+ stats.compilation.warnings = stats.compilation.warnings.filter(this.filter);
488
+ });
489
+ }
490
+ };
182
491
  const validate = (compiler) => {
183
- if (compiler.options.target !== "node") {
184
- logger.warn('webpack config `target` should be "node".');
185
- }
186
- if (!compiler.options.externals) {
187
- logger.info(
188
- "It is recommended to externalize dependencies in the server build for better build performance."
189
- );
190
- }
492
+ if (compiler.options.target !== "node") logger.warn("webpack config `target` should be \"node\".");
493
+ if (!compiler.options.externals) logger.info("It is recommended to externalize dependencies in the server build for better build performance.");
191
494
  };
192
495
  const isJSRegExp = /\.[cm]?js(\?[^.]+)?$/;
193
496
  const isJS = (file) => isJSRegExp.test(file);
@@ -195,88 +498,59 @@ const extractQueryPartJS = (file) => isJSRegExp.exec(file)?.[1];
195
498
  const isCSSRegExp = /\.css(?:\?[^.]+)?$/;
196
499
  const isCSS = (file) => isCSSRegExp.test(file);
197
500
  const isHotUpdate = (file) => file.includes("hot-update");
198
-
199
501
  const DYNAMIC_IMPORT_RE = /import\([^)]*\+\s*__webpack_require__[^+]*\)\.then/;
200
502
  const DYNAMIC_IMPORT_REPLACE_RE = /import\([^)]*\+\s*(__webpack_require__[^+]*)\)\.then/g;
201
503
  const HELPER_FILENAME = "_dynamic-import-helper.mjs";
202
- const HELPER_IMPORT = `import { _rollupDynamicImport } from "./${HELPER_FILENAME}";
203
- `;
204
- class RollupCompatDynamicImportPlugin {
205
- apply(compiler) {
206
- compiler.hooks.compilation.tap("RollupCompatDynamicImportPlugin", (compilation) => {
207
- compilation.hooks.processAssets.tapAsync(
208
- {
209
- name: "RollupCompatDynamicImportPlugin",
210
- stage: compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_INLINE
211
- },
212
- (assets, callback) => {
213
- try {
214
- const targetFiles = /* @__PURE__ */ new Set();
215
- for (const chunk of compilation.chunks) {
216
- if (chunk.canBeInitial() || chunk.hasRuntime()) {
217
- for (const file of chunk.files || []) {
218
- targetFiles.add(file);
219
- }
220
- }
221
- }
222
- for (const [filename, asset] of Object.entries(assets)) {
223
- if (!isJS(filename)) {
224
- continue;
225
- }
226
- if (!targetFiles.has(filename)) {
227
- continue;
228
- }
229
- const source = asset.source();
230
- const originalCode = typeof source === "string" ? source : source.toString();
231
- if (!DYNAMIC_IMPORT_RE.test(originalCode)) {
232
- continue;
233
- }
234
- const transformedCode = this.transformDynamicImports(originalCode);
235
- if (transformedCode !== originalCode) {
236
- assets[filename] = new compiler.webpack.sources.RawSource(transformedCode);
237
- }
238
- }
239
- this.generateDynamicImportHelper(compilation);
240
- callback();
241
- } catch (error) {
242
- callback(error);
243
- }
244
- }
245
- );
246
- });
247
- }
248
- transformDynamicImports(source) {
249
- let transformed = source;
250
- let needsHelperImport = false;
251
- transformed = transformed.replace(DYNAMIC_IMPORT_REPLACE_RE, (match, filename) => {
252
- needsHelperImport = true;
253
- return `_rollupDynamicImport(${filename}).then`;
254
- });
255
- if (needsHelperImport && !transformed.includes(HELPER_IMPORT)) {
256
- transformed = HELPER_IMPORT + transformed;
257
- }
258
- return transformed;
259
- }
260
- generateDynamicImportHelper(compilation) {
261
- const chunkFiles = [];
262
- for (const chunk of compilation.chunks) {
263
- if (chunk.hasRuntime()) {
264
- continue;
265
- }
266
- for (const filename of chunk.files) {
267
- if (filename && isJS(filename)) {
268
- chunkFiles.push(filename);
269
- }
270
- }
271
- }
272
- if (chunkFiles.length === 0) {
273
- return;
274
- }
275
- const helperContent = this.generateHelperContent(chunkFiles);
276
- compilation.emitAsset(HELPER_FILENAME, new compilation.compiler.webpack.sources.RawSource(helperContent));
277
- }
278
- generateHelperContent(chunkFiles) {
279
- return `
504
+ const HELPER_IMPORT = `import { _rollupDynamicImport } from "./${HELPER_FILENAME}";\n`;
505
+ var RollupCompatDynamicImportPlugin = class {
506
+ apply(compiler) {
507
+ compiler.hooks.compilation.tap("RollupCompatDynamicImportPlugin", (compilation) => {
508
+ compilation.hooks.processAssets.tapAsync({
509
+ name: "RollupCompatDynamicImportPlugin",
510
+ stage: compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_INLINE
511
+ }, (assets, callback) => {
512
+ try {
513
+ const targetFiles = /* @__PURE__ */ new Set();
514
+ for (const chunk of compilation.chunks) if (chunk.canBeInitial() || chunk.hasRuntime()) for (const file of chunk.files || []) targetFiles.add(file);
515
+ for (const [filename, asset] of Object.entries(assets)) {
516
+ if (!isJS(filename)) continue;
517
+ if (!targetFiles.has(filename)) continue;
518
+ const source = asset.source();
519
+ const originalCode = typeof source === "string" ? source : source.toString();
520
+ if (!DYNAMIC_IMPORT_RE.test(originalCode)) continue;
521
+ const transformedCode = this.transformDynamicImports(originalCode);
522
+ if (transformedCode !== originalCode) assets[filename] = new compiler.webpack.sources.RawSource(transformedCode);
523
+ }
524
+ this.generateDynamicImportHelper(compilation);
525
+ callback();
526
+ } catch (error) {
527
+ callback(error);
528
+ }
529
+ });
530
+ });
531
+ }
532
+ transformDynamicImports(source) {
533
+ let transformed = source;
534
+ let needsHelperImport = false;
535
+ transformed = transformed.replace(DYNAMIC_IMPORT_REPLACE_RE, (match, filename) => {
536
+ needsHelperImport = true;
537
+ return `_rollupDynamicImport(${filename}).then`;
538
+ });
539
+ if (needsHelperImport && !transformed.includes(HELPER_IMPORT)) transformed = HELPER_IMPORT + transformed;
540
+ return transformed;
541
+ }
542
+ generateDynamicImportHelper(compilation) {
543
+ const chunkFiles = [];
544
+ for (const chunk of compilation.chunks) {
545
+ if (chunk.hasRuntime()) continue;
546
+ for (const filename of chunk.files) if (filename && isJS(filename)) chunkFiles.push(filename);
547
+ }
548
+ if (chunkFiles.length === 0) return;
549
+ const helperContent = this.generateHelperContent(chunkFiles);
550
+ compilation.emitAsset(HELPER_FILENAME, new compilation.compiler.webpack.sources.RawSource(helperContent));
551
+ }
552
+ generateHelperContent(chunkFiles) {
553
+ return `
280
554
  // Rollup-compatible dynamic import helper generated by webpack
281
555
  // This helper enables rollup to consume webpack chunks directly
282
556
 
@@ -293,1000 +567,878 @@ export function _rollupDynamicImport(chunkId) {
293
567
  return chunk()
294
568
  }
295
569
  `;
296
- }
297
- }
298
-
570
+ }
571
+ };
299
572
  async function base(ctx) {
300
- await applyPresets(ctx, [
301
- baseAlias,
302
- baseConfig,
303
- basePlugins,
304
- baseResolve,
305
- baseTranspile
306
- ]);
573
+ await applyPresets(ctx, [
574
+ baseAlias,
575
+ baseConfig,
576
+ basePlugins,
577
+ baseResolve,
578
+ baseTranspile
579
+ ]);
307
580
  }
308
581
  function baseConfig(ctx) {
309
- ctx.config = defu({}, {
310
- name: ctx.name,
311
- entry: { app: [resolve(ctx.options.appDir, ctx.options.experimental.asyncEntry ? "entry.async" : "entry")] },
312
- module: { rules: [] },
313
- plugins: [],
314
- externals: [],
315
- optimization: {
316
- ...ctx.userConfig.optimization,
317
- minimizer: []
318
- },
319
- experiments: {
320
- ...ctx.userConfig.experiments
321
- },
322
- mode: ctx.isDev ? "development" : "production",
323
- cache: getCache(ctx),
324
- output: getOutput(ctx),
325
- stats: statsMap[ctx.nuxt.options.logLevel] ?? statsMap.info,
326
- ...ctx.config
327
- });
582
+ ctx.config = defu({}, {
583
+ name: ctx.name,
584
+ entry: { app: [resolve(ctx.options.appDir, ctx.options.experimental.asyncEntry ? "entry.async" : "entry")] },
585
+ module: { rules: [] },
586
+ plugins: [],
587
+ externals: [],
588
+ optimization: {
589
+ ...ctx.userConfig.optimization,
590
+ minimizer: []
591
+ },
592
+ experiments: { ...ctx.userConfig.experiments },
593
+ mode: ctx.isDev ? "development" : "production",
594
+ cache: getCache(ctx),
595
+ output: getOutput(ctx),
596
+ stats: statsMap[ctx.nuxt.options.logLevel] ?? statsMap.info,
597
+ ...ctx.config
598
+ });
328
599
  }
329
600
  function basePlugins(ctx) {
330
- ctx.config.plugins ||= [];
331
- if (ctx.options.dev) {
332
- if (ctx.nuxt.options.builder !== "@nuxt/rspack-builder") {
333
- ctx.config.plugins.push(new TimeFixPlugin());
334
- }
335
- }
336
- ctx.config.plugins.push(...ctx.userConfig.plugins || []);
337
- if (ctx.nuxt.options.builder !== "@nuxt/rspack-builder") {
338
- ctx.config.plugins.push(new WarningIgnorePlugin(getWarningIgnoreFilter(ctx)));
339
- }
340
- ctx.config.plugins.push(new webpack.DefinePlugin(getEnv(ctx)));
341
- if (ctx.isServer || ctx.isDev && ctx.userConfig.friendlyErrors) {
342
- ctx.config.plugins.push(
343
- new FriendlyErrorsWebpackPlugin({
344
- clearConsole: false,
345
- reporter: "consola",
346
- logLevel: "ERROR"
347
- // TODO
348
- })
349
- );
350
- }
351
- if (ctx.nuxt.options.webpack.profile) {
352
- const colors = {
353
- client: "green",
354
- server: "orange",
355
- modern: "blue"
356
- };
357
- ctx.config.plugins.push(new WebpackBarPlugin({
358
- name: ctx.name,
359
- color: colors[ctx.name],
360
- reporters: ["stats"],
361
- // @ts-expect-error TODO: this is a valid option for Webpack.ProgressPlugin and needs to be declared for WebpackBar
362
- stats: !ctx.isDev,
363
- reporter: {
364
- reporter: {
365
- change: (_, { shortPath }) => {
366
- if (!ctx.isServer) {
367
- ctx.nuxt.callHook(`${builder}:change`, shortPath);
368
- }
369
- },
370
- done: (_, { stats }) => {
371
- if (stats.hasErrors()) {
372
- ctx.nuxt.callHook(`${builder}:error`);
373
- } else {
374
- logger.success(`Finished building ${stats.compilation.name ?? "Nuxt app"}`);
375
- }
376
- },
377
- allDone: () => {
378
- ctx.nuxt.callHook(`${builder}:done`);
379
- },
380
- progress: ({ webpackbar }) => {
381
- ctx.nuxt.callHook(`${builder}:progress`, webpackbar.statesArray);
382
- }
383
- }
384
- }
385
- }));
386
- }
387
- if (ctx.isServer && !ctx.isDev) {
388
- ctx.config.plugins.push(new RollupCompatDynamicImportPlugin());
389
- }
601
+ ctx.config.plugins ||= [];
602
+ if (ctx.options.dev) {
603
+ if (ctx.nuxt.options.builder !== "@nuxt/rspack-builder") ctx.config.plugins.push(new TimeFixPlugin());
604
+ }
605
+ ctx.config.plugins.push(...ctx.userConfig.plugins || []);
606
+ if (ctx.nuxt.options.builder !== "@nuxt/rspack-builder") ctx.config.plugins.push(new WarningIgnorePlugin(getWarningIgnoreFilter(ctx)));
607
+ ctx.config.plugins.push(new webpack.DefinePlugin(getEnv(ctx)));
608
+ if (ctx.isServer || ctx.isDev && ctx.userConfig.friendlyErrors) ctx.config.plugins.push(new FriendlyErrorsWebpackPlugin({
609
+ clearConsole: false,
610
+ reporter: "consola",
611
+ logLevel: "ERROR"
612
+ }));
613
+ if (ctx.nuxt.options.webpack.profile) ctx.config.plugins.push(new WebpackBarPlugin({
614
+ name: ctx.name,
615
+ color: {
616
+ client: "green",
617
+ server: "orange",
618
+ modern: "blue"
619
+ }[ctx.name],
620
+ reporters: ["stats"],
621
+ stats: !ctx.isDev,
622
+ reporter: { reporter: {
623
+ change: (_, { shortPath }) => {
624
+ if (!ctx.isServer) ctx.nuxt.callHook(`${builder}:change`, shortPath);
625
+ },
626
+ done: (_, { stats }) => {
627
+ if (stats.hasErrors()) ctx.nuxt.callHook(`${builder}:error`);
628
+ else logger.success(`Finished building ${stats.compilation.name ?? "Nuxt app"}`);
629
+ },
630
+ allDone: () => {
631
+ ctx.nuxt.callHook(`${builder}:done`);
632
+ },
633
+ progress: ({ webpackbar }) => {
634
+ ctx.nuxt.callHook(`${builder}:progress`, webpackbar.statesArray);
635
+ }
636
+ } }
637
+ }));
638
+ if (ctx.isServer && !ctx.isDev) ctx.config.plugins.push(new RollupCompatDynamicImportPlugin());
390
639
  }
391
640
  function baseAlias(ctx) {
392
- ctx.alias = {
393
- "#app": ctx.options.appDir,
394
- [basename(ctx.nuxt.options.dir.assets)]: resolve(ctx.nuxt.options.srcDir, ctx.nuxt.options.dir.assets),
395
- ...ctx.options.alias,
396
- ...ctx.alias
397
- };
398
- if (ctx.isClient) {
399
- ctx.alias["nitro/runtime"] = resolve(ctx.nuxt.options.buildDir, "nitro.client.mjs");
400
- ctx.alias["#internal/nitro"] = resolve(ctx.nuxt.options.buildDir, "nitro.client.mjs");
401
- ctx.alias["nitropack/runtime"] = resolve(ctx.nuxt.options.buildDir, "nitro.client.mjs");
402
- }
641
+ ctx.alias = {
642
+ "#app": ctx.options.appDir,
643
+ [basename(ctx.nuxt.options.dir.assets)]: resolve(ctx.nuxt.options.srcDir, ctx.nuxt.options.dir.assets),
644
+ ...ctx.options.alias,
645
+ ...ctx.alias
646
+ };
647
+ if (ctx.isClient) {
648
+ ctx.alias["nitro/runtime"] = resolve(ctx.nuxt.options.buildDir, "nitro.client.mjs");
649
+ ctx.alias["#internal/nitro"] = resolve(ctx.nuxt.options.buildDir, "nitro.client.mjs");
650
+ ctx.alias["nitropack/runtime"] = resolve(ctx.nuxt.options.buildDir, "nitro.client.mjs");
651
+ }
403
652
  }
404
653
  function baseResolve(ctx) {
405
- const webpackModulesDir = ["node_modules"].concat(ctx.options.modulesDir);
406
- ctx.config.resolve = {
407
- extensions: [".wasm", ".mjs", ".js", ".ts", ".json", ".vue", ".jsx", ".tsx"],
408
- alias: ctx.alias,
409
- modules: webpackModulesDir,
410
- fullySpecified: false,
411
- ...ctx.config.resolve
412
- };
413
- ctx.config.resolveLoader = {
414
- modules: webpackModulesDir,
415
- ...ctx.config.resolveLoader
416
- };
654
+ const webpackModulesDir = ["node_modules"].concat(ctx.options.modulesDir);
655
+ ctx.config.resolve = {
656
+ extensions: [
657
+ ".wasm",
658
+ ".mjs",
659
+ ".js",
660
+ ".ts",
661
+ ".json",
662
+ ".vue",
663
+ ".jsx",
664
+ ".tsx"
665
+ ],
666
+ alias: ctx.alias,
667
+ modules: webpackModulesDir,
668
+ fullySpecified: false,
669
+ ...ctx.config.resolve
670
+ };
671
+ ctx.config.resolveLoader = {
672
+ modules: webpackModulesDir,
673
+ ...ctx.config.resolveLoader
674
+ };
417
675
  }
418
676
  function baseTranspile(ctx) {
419
- const transpile = [
420
- /\.vue\.js/i,
421
- // include SFCs in node_modules
422
- /consola\/src/,
423
- /vue-demi/,
424
- /(^|\/)nuxt\/(src\/|dist\/)?(app|[^/]+\/runtime)($|\/)/
425
- ];
426
- for (let pattern of ctx.options.build.transpile) {
427
- if (typeof pattern === "function") {
428
- const result = pattern(ctx);
429
- if (result) {
430
- pattern = result;
431
- }
432
- }
433
- if (typeof pattern === "string") {
434
- transpile.push(new RegExp(escapeRegExp(normalize(pattern))));
435
- } else if (pattern instanceof RegExp) {
436
- transpile.push(pattern);
437
- }
438
- }
439
- ctx.transpile = [...transpile, ...ctx.transpile];
677
+ const transpile = [
678
+ /\.vue\.js/i,
679
+ /consola\/src/,
680
+ /vue-demi/,
681
+ /(^|\/)nuxt\/(src\/|dist\/)?(app|[^/]+\/runtime)($|\/)/
682
+ ];
683
+ for (let pattern of ctx.options.build.transpile) {
684
+ if (typeof pattern === "function") {
685
+ const result = pattern(ctx);
686
+ if (result) pattern = result;
687
+ }
688
+ if (typeof pattern === "string") transpile.push(new RegExp(escapeRegExp(normalize(pattern))));
689
+ else if (pattern instanceof RegExp) transpile.push(pattern);
690
+ }
691
+ ctx.transpile = [...transpile, ...ctx.transpile];
440
692
  }
441
693
  function getCache(ctx) {
442
- if (!ctx.options.dev) {
443
- return false;
444
- }
694
+ if (!ctx.options.dev) return false;
445
695
  }
446
696
  function getOutput(ctx) {
447
- return {
448
- path: resolve(ctx.options.buildDir, "dist", ctx.isServer ? "server" : joinURL("client", ctx.options.app.buildAssetsDir)),
449
- filename: fileName(ctx, "app"),
450
- chunkFilename: fileName(ctx, "chunk"),
451
- publicPath: joinURL(ctx.options.app.baseURL, ctx.options.app.buildAssetsDir)
452
- };
697
+ return {
698
+ path: resolve(ctx.options.buildDir, "dist", ctx.isServer ? "server" : joinURL("client", ctx.options.app.buildAssetsDir)),
699
+ filename: fileName(ctx, "app"),
700
+ chunkFilename: fileName(ctx, "chunk"),
701
+ publicPath: joinURL(ctx.options.app.baseURL, ctx.options.app.buildAssetsDir)
702
+ };
453
703
  }
454
704
  function getWarningIgnoreFilter(ctx) {
455
- const filters = [
456
- // Hide warnings about plugins without a default export (#1179)
457
- (warn) => warn.name === "ModuleDependencyWarning" && warn.message.includes("export 'default'") && warn.message.includes("nuxt_plugin_"),
458
- ...ctx.userConfig.warningIgnoreFilters || []
459
- ];
460
- return (warn) => !filters.some((ignoreFilter) => ignoreFilter(warn));
705
+ const filters = [(warn) => warn.name === "ModuleDependencyWarning" && warn.message.includes("export 'default'") && warn.message.includes("nuxt_plugin_"), ...ctx.userConfig.warningIgnoreFilters || []];
706
+ return (warn) => !filters.some((ignoreFilter) => ignoreFilter(warn));
461
707
  }
462
708
  function getEnv(ctx) {
463
- const _env = {
464
- "process.env.NODE_ENV": JSON.stringify(ctx.config.mode),
465
- "__NUXT_VERSION__": JSON.stringify(ctx.nuxt._version),
466
- "__NUXT_ASYNC_CONTEXT__": ctx.options.experimental.asyncContext,
467
- "process.env.VUE_ENV": JSON.stringify(ctx.name),
468
- "process.dev": ctx.options.dev,
469
- "process.test": isTest,
470
- "process.browser": ctx.isClient,
471
- "process.client": ctx.isClient,
472
- "process.server": ctx.isServer,
473
- "import.meta.dev": ctx.options.dev,
474
- "import.meta.test": isTest,
475
- "import.meta.browser": ctx.isClient,
476
- "import.meta.client": ctx.isClient,
477
- "import.meta.server": ctx.isServer
478
- };
479
- if (ctx.isClient) {
480
- _env["process.prerender"] = false;
481
- _env["process.nitro"] = false;
482
- _env["import.meta.prerender"] = false;
483
- _env["import.meta.nitro"] = false;
484
- } else {
485
- _env["process.prerender"] = "(()=>process.prerender)()";
486
- _env["process.nitro"] = "(()=>process.nitro)()";
487
- _env["import.meta.prerender"] = "(()=>import.meta.prerender)()";
488
- _env["import.meta.nitro"] = "(()=>import.meta.nitro)()";
489
- }
490
- if (ctx.userConfig.aggressiveCodeRemoval) {
491
- _env["typeof process"] = JSON.stringify(ctx.isServer ? "object" : "undefined");
492
- _env["typeof window"] = _env["typeof document"] = JSON.stringify(!ctx.isServer ? "object" : "undefined");
493
- }
494
- return _env;
709
+ const _env = {
710
+ "process.env.NODE_ENV": JSON.stringify(ctx.config.mode),
711
+ "__NUXT_VERSION__": JSON.stringify(ctx.nuxt._version),
712
+ "__NUXT_ASYNC_CONTEXT__": ctx.options.experimental.asyncContext,
713
+ "process.env.VUE_ENV": JSON.stringify(ctx.name),
714
+ "process.dev": ctx.options.dev,
715
+ "process.test": isTest,
716
+ "process.browser": ctx.isClient,
717
+ "process.client": ctx.isClient,
718
+ "process.server": ctx.isServer,
719
+ "import.meta.dev": ctx.options.dev,
720
+ "import.meta.test": isTest,
721
+ "import.meta.browser": ctx.isClient,
722
+ "import.meta.client": ctx.isClient,
723
+ "import.meta.server": ctx.isServer
724
+ };
725
+ if (ctx.isClient) {
726
+ _env["process.prerender"] = false;
727
+ _env["process.nitro"] = false;
728
+ _env["import.meta.prerender"] = false;
729
+ _env["import.meta.nitro"] = false;
730
+ } else {
731
+ _env["process.prerender"] = "(()=>process.prerender)()";
732
+ _env["process.nitro"] = "(()=>process.nitro)()";
733
+ _env["import.meta.prerender"] = "(()=>import.meta.prerender)()";
734
+ _env["import.meta.nitro"] = "(()=>import.meta.nitro)()";
735
+ }
736
+ if (ctx.userConfig.aggressiveCodeRemoval) {
737
+ _env["typeof process"] = JSON.stringify(ctx.isServer ? "object" : "undefined");
738
+ _env["typeof window"] = _env["typeof document"] = JSON.stringify(!ctx.isServer ? "object" : "undefined");
739
+ }
740
+ return _env;
495
741
  }
496
742
  const statsMap = {
497
- silent: "none",
498
- info: "normal",
499
- verbose: "verbose"
743
+ silent: "none",
744
+ info: "normal",
745
+ verbose: "verbose"
500
746
  };
501
-
502
747
  function esbuild(ctx) {
503
- const target = ctx.isServer ? "es2020" : "chrome85";
504
- ctx.config.optimization.minimizer.push(new EsbuildPlugin());
505
- ctx.config.module.rules.push(
506
- {
507
- test: /\.m?[jt]s$/i,
508
- loader: "esbuild-loader",
509
- exclude: (file) => {
510
- const lastSegment = file.split("node_modules", 2)[1];
511
- if (!lastSegment) {
512
- return false;
513
- }
514
- return !ctx.transpile.some((module) => module.test(lastSegment));
515
- },
516
- resolve: {
517
- fullySpecified: false
518
- },
519
- options: {
520
- target,
521
- ...ctx.nuxt.options.webpack.loaders.esbuild,
522
- loader: "ts"
523
- }
524
- },
525
- {
526
- test: /\.m?[jt]sx$/,
527
- loader: "esbuild-loader",
528
- options: {
529
- target,
530
- ...ctx.nuxt.options.webpack.loaders.esbuild,
531
- loader: "tsx"
532
- }
533
- }
534
- );
748
+ const target = ctx.isServer ? "es2020" : "chrome85";
749
+ ctx.config.optimization.minimizer.push(new EsbuildPlugin());
750
+ ctx.config.module.rules.push({
751
+ test: /\.m?[jt]s$/i,
752
+ loader: "esbuild-loader",
753
+ exclude: (file) => {
754
+ const lastSegment = file.split("node_modules", 2)[1];
755
+ if (!lastSegment) return false;
756
+ return !ctx.transpile.some((module) => module.test(lastSegment));
757
+ },
758
+ resolve: { fullySpecified: false },
759
+ options: {
760
+ target,
761
+ ...ctx.nuxt.options.webpack.loaders.esbuild,
762
+ loader: "ts"
763
+ }
764
+ }, {
765
+ test: /\.m?[jt]sx$/,
766
+ loader: "esbuild-loader",
767
+ options: {
768
+ target,
769
+ ...ctx.nuxt.options.webpack.loaders.esbuild,
770
+ loader: "tsx"
771
+ }
772
+ });
535
773
  }
536
-
537
774
  function pug(ctx) {
538
- ctx.config.module.rules.push({
539
- test: /\.pug$/i,
540
- oneOf: [
541
- {
542
- resourceQuery: /^\?vue/i,
543
- use: [{
544
- loader: "pug-plain-loader",
545
- options: ctx.userConfig.loaders.pugPlain
546
- }]
547
- },
548
- {
549
- use: [
550
- "raw-loader",
551
- {
552
- loader: "pug-plain-loader",
553
- options: ctx.userConfig.loaders.pugPlain
554
- }
555
- ]
556
- }
557
- ]
558
- });
775
+ ctx.config.module.rules.push({
776
+ test: /\.pug$/i,
777
+ oneOf: [{
778
+ resourceQuery: /^\?vue/i,
779
+ use: [{
780
+ loader: "pug-plain-loader",
781
+ options: ctx.userConfig.loaders.pugPlain
782
+ }]
783
+ }, { use: ["raw-loader", {
784
+ loader: "pug-plain-loader",
785
+ options: ctx.userConfig.loaders.pugPlain
786
+ }] }]
787
+ });
559
788
  }
560
-
561
789
  const isPureObject = (obj) => obj !== null && !Array.isArray(obj) && typeof obj === "object";
562
790
  function sortPlugins({ plugins, order }) {
563
- const names = Object.keys(plugins);
564
- return typeof order === "function" ? order(names) : order || names;
791
+ const names = Object.keys(plugins);
792
+ return typeof order === "function" ? order(names) : order || names;
565
793
  }
566
794
  async function getPostcssConfig(nuxt) {
567
- if (!nuxt.options.webpack.postcss || !nuxt.options.postcss) {
568
- return false;
569
- }
570
- const postcssOptions = defu({}, nuxt.options.postcss, {
571
- plugins: {
572
- /**
573
- * https://github.com/postcss/postcss-import
574
- */
575
- "postcss-import": {
576
- resolve: createResolver({
577
- alias: { ...nuxt.options.alias },
578
- modules: nuxt.options.modulesDir
579
- })
580
- },
581
- /**
582
- * https://github.com/postcss/postcss-url
583
- */
584
- "postcss-url": {}
585
- },
586
- sourceMap: nuxt.options.webpack.cssSourceMap
587
- });
588
- const jiti = createJiti(nuxt.options.rootDir, { alias: nuxt.options.alias });
589
- if (!Array.isArray(postcssOptions.plugins) && isPureObject(postcssOptions.plugins)) {
590
- const plugins = [];
591
- for (const pluginName of sortPlugins(postcssOptions)) {
592
- const pluginOptions = postcssOptions.plugins[pluginName];
593
- if (!pluginOptions) {
594
- continue;
595
- }
596
- let pluginFn;
597
- for (const parentURL of nuxt.options.modulesDir) {
598
- pluginFn = await jiti.import(pluginName, { parentURL: parentURL.replace(/\/node_modules\/?$/, ""), try: true, default: true });
599
- if (typeof pluginFn === "function") {
600
- plugins.push(pluginFn(pluginOptions));
601
- break;
602
- }
603
- }
604
- if (typeof pluginFn !== "function") {
605
- console.warn(`[nuxt] could not import postcss plugin \`${pluginName}\`. Please report this as a bug.`);
606
- }
607
- }
608
- postcssOptions.plugins = plugins;
609
- }
610
- return {
611
- sourceMap: nuxt.options.webpack.cssSourceMap,
612
- ...nuxt.options.webpack.postcss,
613
- postcssOptions
614
- };
795
+ if (!nuxt.options.webpack.postcss || !nuxt.options.postcss) return false;
796
+ const postcssOptions = defu({}, nuxt.options.postcss, {
797
+ plugins: {
798
+ "postcss-import": { resolve: createResolver({
799
+ alias: { ...nuxt.options.alias },
800
+ modules: nuxt.options.modulesDir
801
+ }) },
802
+ "postcss-url": {}
803
+ },
804
+ sourceMap: nuxt.options.webpack.cssSourceMap
805
+ });
806
+ const jiti = createJiti(nuxt.options.rootDir, { alias: nuxt.options.alias });
807
+ if (!Array.isArray(postcssOptions.plugins) && isPureObject(postcssOptions.plugins)) {
808
+ const plugins = [];
809
+ for (const pluginName of sortPlugins(postcssOptions)) {
810
+ const pluginOptions = postcssOptions.plugins[pluginName];
811
+ if (!pluginOptions) continue;
812
+ let pluginFn;
813
+ for (const parentURL of nuxt.options.modulesDir) {
814
+ pluginFn = await jiti.import(pluginName, {
815
+ parentURL: parentURL.replace(/\/node_modules\/?$/, ""),
816
+ try: true,
817
+ default: true
818
+ });
819
+ if (typeof pluginFn === "function") {
820
+ plugins.push(pluginFn(pluginOptions));
821
+ break;
822
+ }
823
+ }
824
+ if (typeof pluginFn !== "function") console.warn(`[nuxt] could not import postcss plugin \`${pluginName}\`. Please report this as a bug.`);
825
+ }
826
+ postcssOptions.plugins = plugins;
827
+ }
828
+ return {
829
+ sourceMap: nuxt.options.webpack.cssSourceMap,
830
+ ...nuxt.options.webpack.postcss,
831
+ postcssOptions
832
+ };
615
833
  }
616
-
617
834
  async function style(ctx) {
618
- await applyPresets(ctx, [
619
- loaders,
620
- extractCSS,
621
- minimizer
622
- ]);
835
+ await applyPresets(ctx, [
836
+ loaders,
837
+ extractCSS,
838
+ minimizer
839
+ ]);
623
840
  }
624
841
  function minimizer(ctx) {
625
- if (ctx.userConfig.optimizeCSS && Array.isArray(ctx.config.optimization.minimizer)) {
626
- ctx.config.optimization.minimizer.push(new CssMinimizerPlugin({
627
- ...ctx.userConfig.optimizeCSS
628
- }));
629
- }
842
+ if (ctx.userConfig.optimizeCSS && Array.isArray(ctx.config.optimization.minimizer)) ctx.config.optimization.minimizer.push(new CssMinimizerPlugin({ ...ctx.userConfig.optimizeCSS }));
630
843
  }
631
844
  function extractCSS(ctx) {
632
- const config = ctx.userConfig.extractCSS;
633
- if (!config) {
634
- return;
635
- }
636
- const filename = fileName(ctx, "css");
637
- ctx.config.plugins.push(new MiniCssExtractPlugin({
638
- filename,
639
- chunkFilename: filename,
640
- ...config === true ? {} : config
641
- }));
845
+ const config = ctx.userConfig.extractCSS;
846
+ if (!config) return;
847
+ const filename = fileName(ctx, "css");
848
+ ctx.config.plugins.push(new MiniCssExtractPlugin({
849
+ filename,
850
+ chunkFilename: filename,
851
+ ...config === true ? {} : config
852
+ }));
642
853
  }
643
854
  async function loaders(ctx) {
644
- ctx.config.module.rules.push(await createdStyleRule("css", /\.css$/i, null, ctx));
645
- ctx.config.module.rules.push(await createdStyleRule("postcss", /\.p(ost)?css$/i, null, ctx));
646
- const lessLoader = { loader: "less-loader", options: ctx.userConfig.loaders.less };
647
- ctx.config.module.rules.push(await createdStyleRule("less", /\.less$/i, lessLoader, ctx));
648
- const sassLoader = { loader: "sass-loader", options: ctx.userConfig.loaders.sass };
649
- ctx.config.module.rules.push(await createdStyleRule("sass", /\.sass$/i, sassLoader, ctx));
650
- const scssLoader = { loader: "sass-loader", options: ctx.userConfig.loaders.scss };
651
- ctx.config.module.rules.push(await createdStyleRule("scss", /\.scss$/i, scssLoader, ctx));
652
- const stylusLoader = { loader: "stylus-loader", options: ctx.userConfig.loaders.stylus };
653
- ctx.config.module.rules.push(await createdStyleRule("stylus", /\.styl(us)?$/i, stylusLoader, ctx));
855
+ ctx.config.module.rules.push(await createdStyleRule("css", /\.css$/i, null, ctx));
856
+ ctx.config.module.rules.push(await createdStyleRule("postcss", /\.p(ost)?css$/i, null, ctx));
857
+ const lessLoader = {
858
+ loader: "less-loader",
859
+ options: ctx.userConfig.loaders.less
860
+ };
861
+ ctx.config.module.rules.push(await createdStyleRule("less", /\.less$/i, lessLoader, ctx));
862
+ const sassLoader = {
863
+ loader: "sass-loader",
864
+ options: ctx.userConfig.loaders.sass
865
+ };
866
+ ctx.config.module.rules.push(await createdStyleRule("sass", /\.sass$/i, sassLoader, ctx));
867
+ const scssLoader = {
868
+ loader: "sass-loader",
869
+ options: ctx.userConfig.loaders.scss
870
+ };
871
+ ctx.config.module.rules.push(await createdStyleRule("scss", /\.scss$/i, scssLoader, ctx));
872
+ const stylusLoader = {
873
+ loader: "stylus-loader",
874
+ options: ctx.userConfig.loaders.stylus
875
+ };
876
+ ctx.config.module.rules.push(await createdStyleRule("stylus", /\.styl(us)?$/i, stylusLoader, ctx));
654
877
  }
655
878
  async function createdStyleRule(lang, test, processorLoader, ctx) {
656
- const styleLoaders = [
657
- await createPostcssLoadersRule(ctx),
658
- processorLoader
659
- ].filter(Boolean);
660
- ctx.userConfig.loaders.css.importLoaders = ctx.userConfig.loaders.cssModules.importLoaders = styleLoaders.length;
661
- const cssLoaders = createCssLoadersRule(ctx, ctx.userConfig.loaders.css);
662
- const cssModuleLoaders = createCssLoadersRule(ctx, ctx.userConfig.loaders.cssModules);
663
- return {
664
- test,
665
- oneOf: [
666
- // This matches <style module>
667
- {
668
- resourceQuery: /module/,
669
- use: cssModuleLoaders.concat(styleLoaders)
670
- },
671
- // This matches plain <style> or <style scoped>
672
- {
673
- use: cssLoaders.concat(styleLoaders)
674
- }
675
- ]
676
- };
879
+ const styleLoaders = [await createPostcssLoadersRule(ctx), processorLoader].filter(Boolean);
880
+ ctx.userConfig.loaders.css.importLoaders = ctx.userConfig.loaders.cssModules.importLoaders = styleLoaders.length;
881
+ const cssLoaders = createCssLoadersRule(ctx, ctx.userConfig.loaders.css);
882
+ return {
883
+ test,
884
+ oneOf: [{
885
+ resourceQuery: /module/,
886
+ use: createCssLoadersRule(ctx, ctx.userConfig.loaders.cssModules).concat(styleLoaders)
887
+ }, { use: cssLoaders.concat(styleLoaders) }]
888
+ };
677
889
  }
678
890
  function createCssLoadersRule(ctx, cssLoaderOptions) {
679
- const cssLoader = { loader: "css-loader", options: cssLoaderOptions };
680
- if (ctx.userConfig.extractCSS) {
681
- if (ctx.isServer) {
682
- if (cssLoader.options.modules) {
683
- cssLoader.options.modules.exportOnlyLocals ??= true;
684
- }
685
- return [cssLoader];
686
- }
687
- return [
688
- {
689
- loader: MiniCssExtractPlugin.loader
690
- },
691
- cssLoader
692
- ];
693
- }
694
- return [
695
- // https://github.com/vuejs/vue-style-loader/issues/56
696
- // {
697
- // loader: 'vue-style-loader',
698
- // options: options.webpack.loaders.vueStyle
699
- // },
700
- cssLoader
701
- ];
891
+ const cssLoader = {
892
+ loader: "css-loader",
893
+ options: cssLoaderOptions
894
+ };
895
+ if (ctx.userConfig.extractCSS) {
896
+ if (ctx.isServer) {
897
+ if (cssLoader.options.modules) cssLoader.options.modules.exportOnlyLocals ??= true;
898
+ return [cssLoader];
899
+ }
900
+ return [{ loader: MiniCssExtractPlugin.loader }, cssLoader];
901
+ }
902
+ return [cssLoader];
702
903
  }
703
904
  async function createPostcssLoadersRule(ctx) {
704
- if (!ctx.options.postcss) {
705
- return;
706
- }
707
- const config = await getPostcssConfig(ctx.nuxt);
708
- if (!config) {
709
- return;
710
- }
711
- return {
712
- loader: "postcss-loader",
713
- options: config
714
- };
715
- }
716
-
717
- class VueSSRClientPlugin {
718
- serverDist;
719
- nuxt;
720
- constructor(options) {
721
- this.serverDist = resolve(options.nuxt.options.buildDir, "dist/server");
722
- this.nuxt = options.nuxt;
723
- }
724
- apply(compiler) {
725
- compiler.hooks.afterEmit.tap("VueSSRClientPlugin", async (compilation) => {
726
- const stats = compilation.getStats().toJson();
727
- const initialFiles = /* @__PURE__ */ new Set();
728
- for (const { assets } of Object.values(stats.entrypoints)) {
729
- if (!assets) {
730
- continue;
731
- }
732
- for (const asset of assets) {
733
- const file = asset.name;
734
- if ((isJS(file) || isCSS(file)) && !isHotUpdate(file)) {
735
- initialFiles.add(file);
736
- }
737
- }
738
- }
739
- const allFiles = /* @__PURE__ */ new Set();
740
- const asyncFiles = /* @__PURE__ */ new Set();
741
- const assetsMapping = {};
742
- for (const { name: file, chunkNames = [] } of stats.assets) {
743
- if (isHotUpdate(file)) {
744
- continue;
745
- }
746
- allFiles.add(file);
747
- const isFileJS = isJS(file);
748
- if (!initialFiles.has(file) && (isFileJS || isCSS(file))) {
749
- asyncFiles.add(file);
750
- }
751
- if (isFileJS) {
752
- const componentHash = hash(chunkNames.join("|"));
753
- const map = assetsMapping[componentHash] ||= [];
754
- map.push(file);
755
- }
756
- }
757
- const webpackManifest = {
758
- publicPath: stats.publicPath,
759
- all: [...allFiles],
760
- initial: [...initialFiles],
761
- async: [...asyncFiles],
762
- modules: {
763
- /* [identifier: string]: Array<index: number> */
764
- },
765
- assetsMapping
766
- };
767
- const { entrypoints = {}, namedChunkGroups = {} } = stats;
768
- const fileToIndex = (file) => webpackManifest.all.indexOf(String(file));
769
- for (const m of stats.modules) {
770
- if (m.chunks?.length !== 1) {
771
- continue;
772
- }
773
- const [cid] = m.chunks;
774
- const chunk = stats.chunks.find((c) => c.id === cid);
775
- if (!chunk || !chunk.files || !cid) {
776
- continue;
777
- }
778
- const id = m.identifier.replace(/\s\w+$/, "");
779
- const filesSet = /* @__PURE__ */ new Set();
780
- for (const file of chunk.files) {
781
- const index = fileToIndex(file);
782
- if (index !== -1) {
783
- filesSet.add(index);
784
- }
785
- }
786
- for (const chunkName of chunk.names) {
787
- if (!entrypoints[chunkName]) {
788
- const chunkGroup = namedChunkGroups[chunkName];
789
- if (chunkGroup) {
790
- for (const asset of chunkGroup.assets) {
791
- filesSet.add(fileToIndex(asset.name));
792
- }
793
- }
794
- }
795
- }
796
- const files = Array.from(filesSet);
797
- webpackManifest.modules[hash(id)] = files;
798
- if (Array.isArray(m.modules)) {
799
- for (const concatenatedModule of m.modules) {
800
- const id2 = hash(concatenatedModule.identifier.replace(/\s\w+$/, ""));
801
- webpackManifest.modules[id2] ||= files;
802
- }
803
- }
804
- if (stats.modules) {
805
- for (const m2 of stats.modules) {
806
- if (m2.assets?.length && m2.chunks?.includes(cid)) {
807
- files.push(...m2.assets.map(fileToIndex));
808
- }
809
- }
810
- }
811
- }
812
- const manifest = normalizeWebpackManifest(webpackManifest);
813
- await this.nuxt.callHook("build:manifest", manifest);
814
- await mkdir(this.serverDist, { recursive: true });
815
- const precomputed = precomputeDependencies(manifest);
816
- await writeFile(join(this.serverDist, `client.manifest.json`), JSON.stringify(manifest, null, 2));
817
- await writeFile(join(this.serverDist, "client.manifest.mjs"), "export default " + serialize(manifest), "utf8");
818
- await writeFile(join(this.serverDist, "client.precomputed.mjs"), "export default " + serialize(precomputed), "utf8");
819
- });
820
- }
905
+ if (!ctx.options.postcss) return;
906
+ const config = await getPostcssConfig(ctx.nuxt);
907
+ if (!config) return;
908
+ return {
909
+ loader: "postcss-loader",
910
+ options: config
911
+ };
821
912
  }
822
-
913
+ var VueSSRClientPlugin = class {
914
+ serverDist;
915
+ nuxt;
916
+ constructor(options) {
917
+ this.serverDist = resolve(options.nuxt.options.buildDir, "dist/server");
918
+ this.nuxt = options.nuxt;
919
+ }
920
+ getRelativeModuleId(identifier, context) {
921
+ const id = identifier.replace(/\s\w+$/, "");
922
+ const resourceMatch = id.match(/([^!]*\.vue)(?:\?|$)/);
923
+ return resourceMatch && resourceMatch[1] ? normalize(relative(context, resourceMatch[1])).replace(/^\.\//, "").replace(/\\/g, "/") : id;
924
+ }
925
+ apply(compiler) {
926
+ compiler.hooks.afterEmit.tap("VueSSRClientPlugin", async (compilation) => {
927
+ const stats = compilation.getStats().toJson();
928
+ const context = this.nuxt.options.srcDir;
929
+ const initialFiles = /* @__PURE__ */ new Set();
930
+ for (const { assets } of Object.values(stats.entrypoints)) {
931
+ if (!assets) continue;
932
+ for (const asset of assets) {
933
+ const file = asset.name;
934
+ if ((isJS(file) || isCSS(file)) && !isHotUpdate(file)) initialFiles.add(file);
935
+ }
936
+ }
937
+ const allFiles = /* @__PURE__ */ new Set();
938
+ const asyncFiles = /* @__PURE__ */ new Set();
939
+ const assetsMapping = {};
940
+ for (const { name: file, chunkNames = [] } of stats.assets) {
941
+ if (isHotUpdate(file)) continue;
942
+ allFiles.add(file);
943
+ const isFileJS = isJS(file);
944
+ if (!initialFiles.has(file) && (isFileJS || isCSS(file))) asyncFiles.add(file);
945
+ if (isFileJS) {
946
+ const componentHash = hash(chunkNames.join("|"));
947
+ (assetsMapping[componentHash] ||= []).push(file);
948
+ }
949
+ }
950
+ const webpackManifest = {
951
+ publicPath: stats.publicPath,
952
+ all: [...allFiles],
953
+ initial: [...initialFiles],
954
+ async: [...asyncFiles],
955
+ modules: {},
956
+ assetsMapping
957
+ };
958
+ const { entrypoints = {}, namedChunkGroups = {} } = stats;
959
+ const fileToIndex = (file) => webpackManifest.all.indexOf(String(file));
960
+ for (const m of stats.modules) {
961
+ if (m.chunks?.length !== 1) continue;
962
+ const [cid] = m.chunks;
963
+ const chunk = stats.chunks.find((c) => c.id === cid);
964
+ if (!chunk || !chunk.files || !cid) continue;
965
+ const relativeId = this.getRelativeModuleId(m.identifier, context);
966
+ const filesSet = /* @__PURE__ */ new Set();
967
+ for (const file of chunk.files) {
968
+ const index = fileToIndex(file);
969
+ if (index !== -1) filesSet.add(index);
970
+ }
971
+ for (const chunkName of chunk.names) if (!entrypoints[chunkName]) {
972
+ const chunkGroup = namedChunkGroups[chunkName];
973
+ if (chunkGroup) for (const asset of chunkGroup.assets) filesSet.add(fileToIndex(asset.name));
974
+ }
975
+ const files = Array.from(filesSet);
976
+ webpackManifest.modules[relativeId] = files;
977
+ if (Array.isArray(m.modules)) for (const concatenatedModule of m.modules) {
978
+ const relativeId = this.getRelativeModuleId(concatenatedModule.identifier, context);
979
+ webpackManifest.modules[relativeId] ||= files;
980
+ }
981
+ if (stats.modules) {
982
+ for (const m of stats.modules) if (m.assets?.length && m.chunks?.includes(cid)) files.push(...m.assets.map(fileToIndex));
983
+ }
984
+ }
985
+ const manifest = normalizeWebpackManifest(webpackManifest);
986
+ await this.nuxt.callHook("build:manifest", manifest);
987
+ await mkdir(this.serverDist, { recursive: true });
988
+ const precomputed = precomputeDependencies(manifest);
989
+ await writeFile(join(this.serverDist, `client.manifest.json`), JSON.stringify(manifest, null, 2));
990
+ await writeFile(join(this.serverDist, "client.manifest.mjs"), "export default " + serialize(manifest), "utf8");
991
+ await writeFile(join(this.serverDist, "client.precomputed.mjs"), "export default " + serialize(precomputed), "utf8");
992
+ });
993
+ }
994
+ };
823
995
  const JS_MAP_RE = /\.js\.map$/;
824
- class VueSSRServerPlugin {
825
- options;
826
- constructor(options = {}) {
827
- this.options = Object.assign({
828
- filename: null
829
- }, options);
830
- }
831
- apply(compiler) {
832
- validate(compiler);
833
- compiler.hooks.make.tap("VueSSRServerPlugin", (compilation) => {
834
- compilation.hooks.processAssets.tapAsync({
835
- name: "VueSSRServerPlugin",
836
- stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL
837
- }, (assets, cb) => {
838
- const stats = compilation.getStats().toJson();
839
- const [entryName] = Object.keys(stats.entrypoints);
840
- const entryInfo = stats.entrypoints[entryName];
841
- if (!entryInfo) {
842
- return cb();
843
- }
844
- const entryAssets = entryInfo.assets.filter((asset) => isJS(asset.name));
845
- if (entryAssets.length > 1) {
846
- throw new Error(
847
- "Server-side bundle should have one single entry file. Avoid using CommonsChunkPlugin in the server config."
848
- );
849
- }
850
- const [entry] = entryAssets;
851
- if (!entry || typeof entry.name !== "string") {
852
- throw new Error(
853
- `Entry "${entryName}" not found. Did you specify the correct entry option?`
854
- );
855
- }
856
- const bundle = {
857
- entry: entry.name,
858
- files: {},
859
- maps: {}
860
- };
861
- for (const asset of stats.assets) {
862
- if (isJS(asset.name)) {
863
- const queryPart = extractQueryPartJS(asset.name);
864
- if (queryPart !== void 0) {
865
- bundle.files[asset.name] = asset.name.replace(queryPart, "");
866
- } else {
867
- bundle.files[asset.name] = asset.name;
868
- }
869
- } else if (JS_MAP_RE.test(asset.name)) {
870
- bundle.maps[asset.name.replace(/\.map$/, "")] = asset.name;
871
- } else {
872
- delete assets[asset.name];
873
- }
874
- }
875
- const src = JSON.stringify(bundle, null, 2);
876
- assets[this.options.filename] = {
877
- source: () => src,
878
- size: () => src.length
879
- };
880
- const mjsSrc = "export default " + src;
881
- assets[this.options.filename.replace(".json", ".mjs")] = {
882
- source: () => mjsSrc,
883
- map: () => null,
884
- size: () => mjsSrc.length
885
- };
886
- cb();
887
- });
888
- });
889
- }
890
- }
891
-
996
+ var VueSSRServerPlugin = class {
997
+ options;
998
+ constructor(options = {}) {
999
+ this.options = Object.assign({ filename: null }, options);
1000
+ }
1001
+ apply(compiler) {
1002
+ validate(compiler);
1003
+ compiler.hooks.make.tap("VueSSRServerPlugin", (compilation) => {
1004
+ compilation.hooks.processAssets.tapAsync({
1005
+ name: "VueSSRServerPlugin",
1006
+ stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL
1007
+ }, (assets, cb) => {
1008
+ const stats = compilation.getStats().toJson();
1009
+ const [entryName] = Object.keys(stats.entrypoints);
1010
+ const entryInfo = stats.entrypoints[entryName];
1011
+ if (!entryInfo) return cb();
1012
+ const entryAssets = entryInfo.assets.filter((asset) => isJS(asset.name));
1013
+ if (entryAssets.length > 1) throw new Error("Server-side bundle should have one single entry file. Avoid using CommonsChunkPlugin in the server config.");
1014
+ const [entry] = entryAssets;
1015
+ if (!entry || typeof entry.name !== "string") throw new Error(`Entry "${entryName}" not found. Did you specify the correct entry option?`);
1016
+ const bundle = {
1017
+ entry: entry.name,
1018
+ files: {},
1019
+ maps: {}
1020
+ };
1021
+ for (const asset of stats.assets) if (isJS(asset.name)) {
1022
+ const queryPart = extractQueryPartJS(asset.name);
1023
+ if (queryPart !== void 0) bundle.files[asset.name] = asset.name.replace(queryPart, "");
1024
+ else bundle.files[asset.name] = asset.name;
1025
+ } else if (JS_MAP_RE.test(asset.name)) bundle.maps[asset.name.replace(/\.map$/, "")] = asset.name;
1026
+ else delete assets[asset.name];
1027
+ const src = JSON.stringify(bundle, null, 2);
1028
+ assets[this.options.filename] = {
1029
+ source: () => src,
1030
+ size: () => src.length
1031
+ };
1032
+ const mjsSrc = "export default " + src;
1033
+ assets[this.options.filename.replace(".json", ".mjs")] = {
1034
+ source: () => mjsSrc,
1035
+ map: () => null,
1036
+ size: () => mjsSrc.length
1037
+ };
1038
+ cb();
1039
+ });
1040
+ });
1041
+ }
1042
+ };
892
1043
  function vue(ctx) {
893
- ctx.config.plugins.push(new (VueLoaderPlugin.default || VueLoaderPlugin)());
894
- ctx.config.module.rules.push({
895
- test: /\.vue$/i,
896
- loader: "vue-loader",
897
- options: ctx.userConfig.loaders.vue
898
- });
899
- if (ctx.isClient) {
900
- ctx.config.plugins.push(new VueSSRClientPlugin({ nuxt: ctx.nuxt }));
901
- } else {
902
- ctx.config.plugins.push(new VueSSRServerPlugin({
903
- filename: `${ctx.name}.manifest.json`
904
- }));
905
- }
906
- ctx.config.plugins.push(new webpack.DefinePlugin({
907
- "__VUE_OPTIONS_API__": "true",
908
- "__VUE_PROD_DEVTOOLS__": "false",
909
- "__VUE_PROD_HYDRATION_MISMATCH_DETAILS__": ctx.nuxt.options.debug && ctx.nuxt.options.debug.hydration
910
- }));
1044
+ ctx.config.plugins.push(new (VueLoaderPlugin.default || VueLoaderPlugin)());
1045
+ ctx.config.module.rules.push({
1046
+ test: /\.vue$/i,
1047
+ loader: "vue-loader",
1048
+ options: {
1049
+ ...ctx.userConfig.loaders.vue,
1050
+ isServerBuild: ctx.isServer
1051
+ }
1052
+ });
1053
+ if (ctx.isClient) ctx.config.plugins.push(new VueSSRClientPlugin({ nuxt: ctx.nuxt }));
1054
+ else {
1055
+ ctx.config.plugins.push(new VueSSRServerPlugin({ filename: `${ctx.name}.manifest.json` }));
1056
+ const loaderPath = resolveModulePath("#vue-module-identifier", { from: import.meta.url });
1057
+ ctx.config.module.rules.push({
1058
+ test: /\.vue$/i,
1059
+ enforce: "post",
1060
+ use: [{
1061
+ loader: loaderPath,
1062
+ options: { srcDir: ctx.nuxt.options.srcDir }
1063
+ }]
1064
+ });
1065
+ }
1066
+ ctx.config.plugins.push(new webpack.DefinePlugin({
1067
+ "__VUE_OPTIONS_API__": "true",
1068
+ "__VUE_PROD_DEVTOOLS__": "false",
1069
+ "__VUE_PROD_HYDRATION_MISMATCH_DETAILS__": ctx.nuxt.options.debug && ctx.nuxt.options.debug.hydration
1070
+ }));
911
1071
  }
912
-
913
1072
  async function nuxt(ctx) {
914
- await applyPresets(ctx, [
915
- base,
916
- assets,
917
- esbuild,
918
- pug,
919
- style,
920
- vue
921
- ]);
1073
+ await applyPresets(ctx, [
1074
+ base,
1075
+ assets,
1076
+ esbuild,
1077
+ pug,
1078
+ style,
1079
+ vue
1080
+ ]);
922
1081
  }
923
-
924
1082
  async function client(ctx) {
925
- ctx.name = "client";
926
- ctx.isClient = true;
927
- await applyPresets(ctx, [
928
- nuxt,
929
- clientPlugins,
930
- clientOptimization,
931
- clientDevtool,
932
- clientPerformance,
933
- clientHMR,
934
- clientNodeCompat
935
- ]);
1083
+ ctx.name = "client";
1084
+ ctx.isClient = true;
1085
+ await applyPresets(ctx, [
1086
+ nuxt,
1087
+ clientPlugins,
1088
+ clientOptimization,
1089
+ clientDevtool,
1090
+ clientPerformance,
1091
+ clientHMR,
1092
+ clientNodeCompat
1093
+ ]);
936
1094
  }
937
1095
  function clientDevtool(ctx) {
938
- if (!ctx.nuxt.options.sourcemap.client) {
939
- ctx.config.devtool = false;
940
- return;
941
- }
942
- const prefix = ctx.nuxt.options.sourcemap.client === "hidden" ? "hidden-" : "";
943
- if (!ctx.isDev) {
944
- ctx.config.devtool = prefix + "source-map";
945
- return;
946
- }
947
- ctx.config.devtool = prefix + "eval-cheap-module-source-map";
1096
+ if (!ctx.nuxt.options.sourcemap.client) {
1097
+ ctx.config.devtool = false;
1098
+ return;
1099
+ }
1100
+ const prefix = ctx.nuxt.options.sourcemap.client === "hidden" ? "hidden-" : "";
1101
+ if (!ctx.isDev) {
1102
+ ctx.config.devtool = prefix + "source-map";
1103
+ return;
1104
+ }
1105
+ ctx.config.devtool = prefix + "eval-cheap-module-source-map";
948
1106
  }
949
1107
  function clientPerformance(ctx) {
950
- ctx.config.performance = {
951
- maxEntrypointSize: 1e3 * 1024,
952
- hints: ctx.isDev ? false : "warning",
953
- ...ctx.config.performance
954
- };
1108
+ ctx.config.performance = {
1109
+ maxEntrypointSize: 1e3 * 1024,
1110
+ hints: ctx.isDev ? false : "warning",
1111
+ ...ctx.config.performance
1112
+ };
955
1113
  }
956
1114
  function clientNodeCompat(ctx) {
957
- if (!ctx.nuxt.options.experimental.clientNodeCompat) {
958
- return;
959
- }
960
- ctx.config.plugins.push(new webpack.DefinePlugin({ global: "globalThis" }));
961
- ctx.config.resolve ||= {};
962
- ctx.config.resolve.fallback = {
963
- ...defineEnv({
964
- nodeCompat: true,
965
- resolve: true
966
- }).env.alias,
967
- ...ctx.config.resolve.fallback
968
- };
969
- ctx.config.plugins.unshift(new webpack.NormalModuleReplacementPlugin(/node:/, (resource) => {
970
- resource.request = resource.request.replace(/^node:/, "");
971
- }));
1115
+ if (!ctx.nuxt.options.experimental.clientNodeCompat) return;
1116
+ ctx.config.plugins.push(new webpack.DefinePlugin({ global: "globalThis" }));
1117
+ ctx.config.resolve ||= {};
1118
+ ctx.config.resolve.fallback = {
1119
+ ...defineEnv({
1120
+ nodeCompat: true,
1121
+ resolve: true
1122
+ }).env.alias,
1123
+ ...ctx.config.resolve.fallback
1124
+ };
1125
+ ctx.config.plugins.unshift(new webpack.NormalModuleReplacementPlugin(/node:/, (resource) => {
1126
+ resource.request = resource.request.replace(/^node:/, "");
1127
+ }));
972
1128
  }
973
1129
  function clientHMR(ctx) {
974
- if (!ctx.isDev) {
975
- return;
976
- }
977
- const clientOptions = ctx.userConfig.hotMiddleware?.client || {};
978
- const hotMiddlewareClientOptions = {
979
- reload: true,
980
- timeout: 3e4,
981
- path: joinURL(ctx.options.app.baseURL, "__webpack_hmr", ctx.name),
982
- ...clientOptions,
983
- ansiColors: JSON.stringify(clientOptions.ansiColors || {}),
984
- overlayStyles: JSON.stringify(clientOptions.overlayStyles || {}),
985
- name: ctx.name
986
- };
987
- const hotMiddlewareClientOptionsStr = querystring.stringify(hotMiddlewareClientOptions);
988
- const app = ctx.config.entry.app;
989
- app.unshift(
990
- // https://github.com/webpack/webpack-hot-middleware#config
991
- `webpack-hot-middleware/client?${hotMiddlewareClientOptionsStr}`
992
- );
993
- ctx.config.plugins ||= [];
994
- ctx.config.plugins.push(new webpack.HotModuleReplacementPlugin());
1130
+ if (!ctx.isDev) return;
1131
+ const clientOptions = ctx.userConfig.hotMiddleware?.client || {};
1132
+ const hotMiddlewareClientOptions = {
1133
+ reload: true,
1134
+ timeout: 3e4,
1135
+ path: joinURL(ctx.options.app.baseURL, "__webpack_hmr", ctx.name),
1136
+ ...clientOptions,
1137
+ ansiColors: JSON.stringify(clientOptions.ansiColors || {}),
1138
+ overlayStyles: JSON.stringify(clientOptions.overlayStyles || {}),
1139
+ name: ctx.name
1140
+ };
1141
+ const hotMiddlewareClientOptionsStr = querystring.stringify(hotMiddlewareClientOptions);
1142
+ ctx.config.entry.app.unshift(`webpack-hot-middleware/client?${hotMiddlewareClientOptionsStr}`);
1143
+ ctx.config.plugins ||= [];
1144
+ ctx.config.plugins.push(new webpack.HotModuleReplacementPlugin());
995
1145
  }
996
- function clientOptimization(_ctx) {
1146
+ function clientOptimization(ctx) {
1147
+ if (!ctx.nuxt.options.features.inlineStyles) return;
1148
+ const globalCSSPaths = /* @__PURE__ */ new Set();
1149
+ for (const css of ctx.options.css) if (typeof css === "string") {
1150
+ const resolved = resolveAlias(css, ctx.options.alias);
1151
+ globalCSSPaths.add(normalize(resolved));
1152
+ }
1153
+ if (globalCSSPaths.size > 0) {
1154
+ ctx.config.optimization ||= {};
1155
+ ctx.config.optimization.splitChunks ||= {};
1156
+ ctx.config.optimization.splitChunks.cacheGroups ||= {};
1157
+ ctx.config.optimization.splitChunks.cacheGroups.nuxtGlobalCSS = {
1158
+ name: "nuxt-global-css",
1159
+ chunks: "all",
1160
+ enforce: true,
1161
+ test: (module) => {
1162
+ if (module.type !== "css/mini-extract") return false;
1163
+ const identifier = normalize(module.identifier());
1164
+ for (const globalPath of globalCSSPaths) if (identifier.includes(globalPath)) return true;
1165
+ return false;
1166
+ }
1167
+ };
1168
+ }
997
1169
  }
998
1170
  function clientPlugins(ctx) {
999
- if (!ctx.isDev && !ctx.nuxt.options.test && ctx.name === "client" && ctx.userConfig.analyze && (ctx.userConfig.analyze === true || ctx.userConfig.analyze.enabled)) {
1000
- const statsDir = resolve(ctx.options.analyzeDir);
1001
- ctx.config.plugins.push(new BundleAnalyzerPlugin({
1002
- analyzerMode: "static",
1003
- defaultSizes: "gzip",
1004
- generateStatsFile: true,
1005
- openAnalyzer: true,
1006
- reportFilename: resolve(statsDir, `${ctx.name}.html`),
1007
- statsFilename: resolve(statsDir, `${ctx.name}.json`),
1008
- ...ctx.userConfig.analyze === true ? {} : ctx.userConfig.analyze
1009
- }));
1010
- }
1011
- if (!ctx.nuxt.options.ssr) {
1012
- if (!ctx.nuxt.options.test && (ctx.nuxt.options.typescript.typeCheck === true || ctx.nuxt.options.typescript.typeCheck === "build" && !ctx.nuxt.options.dev)) {
1013
- ctx.config.plugins.push(new TsCheckerPlugin({
1014
- logger
1015
- }));
1016
- }
1017
- }
1171
+ if (!ctx.isDev && !ctx.nuxt.options.test && ctx.name === "client" && ctx.userConfig.analyze && (ctx.userConfig.analyze === true || ctx.userConfig.analyze.enabled)) {
1172
+ const statsDir = resolve(ctx.options.analyzeDir);
1173
+ ctx.config.plugins.push(new BundleAnalyzerPlugin({
1174
+ analyzerMode: "static",
1175
+ defaultSizes: "gzip",
1176
+ generateStatsFile: true,
1177
+ openAnalyzer: true,
1178
+ reportFilename: resolve(statsDir, `${ctx.name}.html`),
1179
+ statsFilename: resolve(statsDir, `${ctx.name}.json`),
1180
+ ...ctx.userConfig.analyze === true ? {} : ctx.userConfig.analyze
1181
+ }));
1182
+ }
1183
+ if (!ctx.nuxt.options.ssr) {
1184
+ if (!ctx.nuxt.options.test && (ctx.nuxt.options.typescript.typeCheck === true || ctx.nuxt.options.typescript.typeCheck === "build" && !ctx.nuxt.options.dev)) ctx.config.plugins.push(new TsCheckerPlugin({ logger }));
1185
+ }
1018
1186
  }
1019
-
1020
1187
  function node(ctx) {
1021
- ctx.config.target = "node";
1022
- ctx.config.node = false;
1023
- ctx.config.experiments.outputModule = true;
1024
- ctx.config.output = {
1025
- ...ctx.config.output,
1026
- chunkFilename: "[name].mjs",
1027
- chunkFormat: "module",
1028
- chunkLoading: "import",
1029
- module: true,
1030
- environment: {
1031
- module: true,
1032
- arrowFunction: true,
1033
- bigIntLiteral: true,
1034
- const: true,
1035
- destructuring: true,
1036
- dynamicImport: true,
1037
- forOf: true
1038
- },
1039
- library: {
1040
- type: "module"
1041
- }
1042
- };
1043
- ctx.config.performance = {
1044
- ...ctx.config.performance,
1045
- hints: false,
1046
- maxEntrypointSize: Number.POSITIVE_INFINITY,
1047
- maxAssetSize: Number.POSITIVE_INFINITY
1048
- };
1188
+ ctx.config.target = "node";
1189
+ ctx.config.node = false;
1190
+ ctx.config.experiments.outputModule = true;
1191
+ ctx.config.output = {
1192
+ ...ctx.config.output,
1193
+ chunkFilename: "[name].mjs",
1194
+ chunkFormat: "module",
1195
+ chunkLoading: "import",
1196
+ module: true,
1197
+ environment: {
1198
+ module: true,
1199
+ arrowFunction: true,
1200
+ bigIntLiteral: true,
1201
+ const: true,
1202
+ destructuring: true,
1203
+ dynamicImport: true,
1204
+ forOf: true
1205
+ },
1206
+ library: { type: "module" }
1207
+ };
1208
+ ctx.config.performance = {
1209
+ ...ctx.config.performance,
1210
+ hints: false,
1211
+ maxEntrypointSize: Number.POSITIVE_INFINITY,
1212
+ maxAssetSize: Number.POSITIVE_INFINITY
1213
+ };
1049
1214
  }
1050
-
1051
1215
  const assetPattern = /\.(?:css|s[ca]ss|png|jpe?g|gif|svg|woff2?|eot|ttf|otf|webp|webm|mp4|ogv)(?:\?.*)?$/i;
1216
+ const VIRTUAL_RE = /^\0?virtual:(?:nuxt:)?/;
1052
1217
  async function server(ctx) {
1053
- ctx.name = "server";
1054
- ctx.isServer = true;
1055
- await applyPresets(ctx, [
1056
- nuxt,
1057
- node,
1058
- serverStandalone,
1059
- serverPreset,
1060
- serverPlugins
1061
- ]);
1218
+ ctx.name = "server";
1219
+ ctx.isServer = true;
1220
+ await applyPresets(ctx, [
1221
+ nuxt,
1222
+ node,
1223
+ serverStandalone,
1224
+ serverPreset,
1225
+ serverPlugins
1226
+ ]);
1062
1227
  }
1063
1228
  function serverPreset(ctx) {
1064
- ctx.config.output.filename = "server.mjs";
1065
- if (ctx.nuxt.options.sourcemap.server) {
1066
- const prefix = ctx.nuxt.options.sourcemap.server === "hidden" ? "hidden-" : "";
1067
- ctx.config.devtool = prefix + ctx.isDev ? "cheap-module-source-map" : "source-map";
1068
- } else {
1069
- ctx.config.devtool = false;
1070
- }
1071
- ctx.config.optimization = {
1072
- splitChunks: false,
1073
- minimize: false
1074
- };
1229
+ ctx.config.output.filename = "server.mjs";
1230
+ if (ctx.nuxt.options.sourcemap.server) {
1231
+ const prefix = ctx.nuxt.options.sourcemap.server === "hidden" ? "hidden-" : "";
1232
+ ctx.config.devtool = prefix + (ctx.isDev ? "cheap-module-source-map" : "source-map");
1233
+ } else ctx.config.devtool = false;
1234
+ ctx.config.optimization = {
1235
+ splitChunks: false,
1236
+ minimize: false
1237
+ };
1238
+ if (ctx.isDev) ctx.config.output.asyncChunks = false;
1075
1239
  }
1076
1240
  function serverStandalone(ctx) {
1077
- const inline = [
1078
- "src/",
1079
- "#app",
1080
- "nuxt",
1081
- "nuxt3",
1082
- "nuxt-nightly",
1083
- "!",
1084
- "-!",
1085
- "~",
1086
- "@/",
1087
- "#",
1088
- ...ctx.options.build.transpile
1089
- ];
1090
- const external = /* @__PURE__ */ new Set([
1091
- "nitro/runtime",
1092
- // TODO: remove in v5
1093
- "#internal/nitro",
1094
- "nitropack/runtime",
1095
- "#shared",
1096
- resolve(ctx.nuxt.options.rootDir, ctx.nuxt.options.dir.shared)
1097
- ]);
1098
- if (!ctx.nuxt.options.dev) {
1099
- external.add("#internal/nuxt/paths");
1100
- external.add("#internal/nuxt/app-config");
1101
- external.add("#app-manifest");
1102
- }
1103
- if (!Array.isArray(ctx.config.externals)) {
1104
- return;
1105
- }
1106
- ctx.config.externals.push(({ request }, cb) => {
1107
- if (!request) {
1108
- return cb(void 0, false);
1109
- }
1110
- if (external.has(request)) {
1111
- return cb(void 0, true);
1112
- }
1113
- if (request[0] === "." || isAbsolute(request) || inline.find((prefix) => typeof prefix === "string" && request.startsWith(prefix)) || assetPattern.test(request)) {
1114
- return cb(void 0, false);
1115
- }
1116
- return cb(void 0, true);
1117
- });
1241
+ const inline = [
1242
+ "src/",
1243
+ "#app",
1244
+ "nuxt",
1245
+ "nuxt3",
1246
+ "nuxt-nightly",
1247
+ "!",
1248
+ "-!",
1249
+ "~",
1250
+ "@/",
1251
+ "#",
1252
+ ...ctx.options.build.transpile
1253
+ ];
1254
+ const external = new Set([
1255
+ "nitro/runtime",
1256
+ "#internal/nitro",
1257
+ "nitropack/runtime",
1258
+ "#shared",
1259
+ resolve(ctx.nuxt.options.rootDir, ctx.nuxt.options.dir.shared),
1260
+ ...ctx.nuxt["~runtimeDependencies"] || []
1261
+ ]);
1262
+ if (!ctx.nuxt.options.dev) {
1263
+ external.add("#internal/nuxt/paths");
1264
+ external.add("#internal/nuxt/app-config");
1265
+ external.add("#app-manifest");
1266
+ }
1267
+ if (!Array.isArray(ctx.config.externals)) return;
1268
+ const conditions = [
1269
+ ctx.nuxt.options.dev ? "development" : "production",
1270
+ "node",
1271
+ "import",
1272
+ "require"
1273
+ ];
1274
+ ctx.config.externals.push(({ request, context }, cb) => {
1275
+ if (!request) return cb(void 0, false);
1276
+ if (external.has(request)) {
1277
+ const resolved = resolveModulePath(request, {
1278
+ from: context ? [context, ...ctx.nuxt.options.modulesDir].map((d) => directoryToURL(d)) : ctx.nuxt.options.modulesDir.map((d) => directoryToURL(d)),
1279
+ suffixes: ["", "index"],
1280
+ conditions,
1281
+ try: true
1282
+ });
1283
+ if (resolved && isAbsolute(resolved)) return cb(void 0, resolved);
1284
+ return cb(void 0, true);
1285
+ }
1286
+ if (request[0] === "." || isAbsolute(request) || inline.find((prefix) => typeof prefix === "string" && request.startsWith(prefix)) || assetPattern.test(request)) return cb(void 0, false);
1287
+ if (context && request && !request.startsWith("node:") && (isAbsolute(context) || VIRTUAL_RE.test(context))) try {
1288
+ const resolved = resolveModulePath(resolveAlias(normalize(request), ctx.nuxt.options.alias), {
1289
+ from: [parseNodeModulePath(context).dir || ctx.nuxt.options.rootDir, ...ctx.nuxt.options.modulesDir].map((d) => directoryToURL(d)),
1290
+ suffixes: ["", "index"],
1291
+ conditions,
1292
+ try: true
1293
+ });
1294
+ if (resolved && isAbsolute(resolved)) return cb(void 0, false);
1295
+ } catch {}
1296
+ return cb(void 0, true);
1297
+ });
1118
1298
  }
1119
1299
  function serverPlugins(ctx) {
1120
- ctx.config.plugins ||= [];
1121
- if (ctx.userConfig.serverURLPolyfill) {
1122
- ctx.config.plugins.push(new webpack.ProvidePlugin({
1123
- URL: [ctx.userConfig.serverURLPolyfill, "URL"],
1124
- URLSearchParams: [ctx.userConfig.serverURLPolyfill, "URLSearchParams"]
1125
- }));
1126
- }
1127
- if (!ctx.nuxt.options.test && (ctx.nuxt.options.typescript.typeCheck === true || ctx.nuxt.options.typescript.typeCheck === "build" && !ctx.nuxt.options.dev)) {
1128
- ctx.config.plugins.push(new TsCheckerPlugin({
1129
- logger
1130
- }));
1131
- }
1300
+ ctx.config.plugins ||= [];
1301
+ if (ctx.userConfig.serverURLPolyfill) ctx.config.plugins.push(new webpack.ProvidePlugin({
1302
+ URL: [ctx.userConfig.serverURLPolyfill, "URL"],
1303
+ URLSearchParams: [ctx.userConfig.serverURLPolyfill, "URLSearchParams"]
1304
+ }));
1305
+ if (!ctx.nuxt.options.test && (ctx.nuxt.options.typescript.typeCheck === true || ctx.nuxt.options.typescript.typeCheck === "build" && !ctx.nuxt.options.dev)) ctx.config.plugins.push(new TsCheckerPlugin({ logger }));
1132
1306
  }
1133
-
1134
1307
  const bundle = async (nuxt) => {
1135
- const webpackConfigs = await Promise.all([client, ...nuxt.options.ssr ? [server] : []].map(async (preset) => {
1136
- const ctx = createWebpackConfigContext(nuxt);
1137
- ctx.userConfig = defu(nuxt.options.webpack[`$${preset.name}`], ctx.userConfig);
1138
- await applyPresets(ctx, preset);
1139
- return ctx.config;
1140
- }));
1141
- if (!nuxt.options.dev) {
1142
- const nitro = useNitro();
1143
- nitro.hooks.hook("rollup:before", (_nitro, config) => {
1144
- const plugins = config.plugins;
1145
- const existingPlugin = plugins.findIndex((i) => i && "name" in i && i.name === "dynamic-require");
1146
- if (existingPlugin >= 0) {
1147
- plugins.splice(existingPlugin, 1);
1148
- }
1149
- });
1150
- }
1151
- await nuxt.callHook(`${builder}:config`, webpackConfigs);
1152
- const mfs = nuxt.options.dev ? createMFS() : null;
1153
- for (const config of webpackConfigs) {
1154
- config.plugins.push(DynamicBasePlugin.webpack({
1155
- sourcemap: !!nuxt.options.sourcemap[config.name]
1156
- }));
1157
- if (config.name === "client" && nuxt.options.experimental.emitRouteChunkError && nuxt.options.builder !== "@nuxt/rspack-builder") {
1158
- config.plugins.push(new ChunkErrorPlugin());
1159
- }
1160
- }
1161
- await nuxt.callHook(`${builder}:configResolved`, webpackConfigs);
1162
- const compilers = webpackConfigs.map((config) => {
1163
- const compiler = webpack(config);
1164
- if (nuxt.options.dev && compiler) {
1165
- compiler.outputFileSystem = mfs;
1166
- }
1167
- return compiler;
1168
- });
1169
- nuxt.hook("close", async () => {
1170
- for (const compiler of compilers) {
1171
- await new Promise((resolve) => compiler?.close(resolve));
1172
- }
1173
- });
1174
- if (nuxt.options.dev) {
1175
- await Promise.all(compilers.map((c) => c && compile(c)));
1176
- return;
1177
- }
1178
- for (const c of compilers) {
1179
- if (c) {
1180
- await compile(c);
1181
- }
1182
- }
1308
+ const webpackConfigs = await Promise.all([client, ...nuxt.options.ssr ? [server] : []].map(async (preset) => {
1309
+ const ctx = createWebpackConfigContext(nuxt);
1310
+ ctx.userConfig = defu(nuxt.options.webpack[`$${preset.name}`], ctx.userConfig);
1311
+ await applyPresets(ctx, preset);
1312
+ return ctx.config;
1313
+ }));
1314
+ if (!nuxt.options.dev) useNitro().hooks.hook("rollup:before", (_nitro, config) => {
1315
+ const plugins = config.plugins;
1316
+ const existingPlugin = plugins.findIndex((i) => i && "name" in i && i.name === "dynamic-require");
1317
+ if (existingPlugin >= 0) plugins.splice(existingPlugin, 1);
1318
+ });
1319
+ await nuxt.callHook(`${builder}:config`, webpackConfigs);
1320
+ const mfs = nuxt.options.dev ? createMFS() : null;
1321
+ const ssrStylesPlugin = nuxt.options.ssr && !nuxt.options.dev && nuxt.options.features.inlineStyles ? new SSRStylesPlugin(nuxt) : null;
1322
+ for (const config of webpackConfigs) {
1323
+ config.plugins.push(DynamicBasePlugin.webpack({ sourcemap: !!nuxt.options.sourcemap[config.name] }));
1324
+ if (config.name === "client" && nuxt.options.experimental.emitRouteChunkError && nuxt.options.builder !== "@nuxt/rspack-builder") config.plugins.push(new ChunkErrorPlugin());
1325
+ if (ssrStylesPlugin) config.plugins.push(ssrStylesPlugin);
1326
+ }
1327
+ await nuxt.callHook(`${builder}:configResolved`, webpackConfigs);
1328
+ const compilers = webpackConfigs.map((config) => {
1329
+ const compiler = webpack(config);
1330
+ if (nuxt.options.dev && compiler) compiler.outputFileSystem = mfs;
1331
+ return compiler;
1332
+ });
1333
+ nuxt.hook("close", async () => {
1334
+ for (const compiler of compilers) await new Promise((resolve) => compiler.close(resolve));
1335
+ });
1336
+ if (nuxt.options.dev) {
1337
+ await Promise.all(compilers.map((c) => compile(c)));
1338
+ return;
1339
+ }
1340
+ for (const c of compilers) await compile(c);
1183
1341
  };
1184
1342
  async function createDevMiddleware(compiler) {
1185
- const nuxt = useNuxt();
1186
- logger.debug("Creating webpack middleware...");
1187
- const devMiddleware = webpackDevMiddleware(compiler, {
1188
- publicPath: joinURL(nuxt.options.app.baseURL, nuxt.options.app.buildAssetsDir),
1189
- outputFileSystem: compiler.outputFileSystem,
1190
- stats: "none",
1191
- ...nuxt.options.webpack.devMiddleware
1192
- });
1193
- nuxt.hook("close", () => pify(devMiddleware.close.bind(devMiddleware))());
1194
- const { client: _client, ...hotMiddlewareOptions } = nuxt.options.webpack.hotMiddleware || {};
1195
- const hotMiddleware = webpackHotMiddleware(compiler, {
1196
- log: false,
1197
- heartbeat: 1e4,
1198
- path: joinURL(nuxt.options.app.baseURL, "__webpack_hmr", compiler.options.name),
1199
- ...hotMiddlewareOptions
1200
- });
1201
- const devHandler = wdmToH3Handler(devMiddleware, nuxt.options.devServer.cors);
1202
- const hotHandler = fromNodeMiddleware(hotMiddleware);
1203
- await nuxt.callHook("server:devHandler", defineEventHandler(async (event) => {
1204
- const body = await devHandler(event);
1205
- if (body !== void 0) {
1206
- return body;
1207
- }
1208
- await hotHandler(event);
1209
- }));
1210
- return devMiddleware;
1343
+ const nuxt = useNuxt();
1344
+ logger.debug("Creating webpack middleware...");
1345
+ const devMiddleware = webpackDevMiddleware(compiler, {
1346
+ publicPath: joinURL(nuxt.options.app.baseURL, nuxt.options.app.buildAssetsDir),
1347
+ outputFileSystem: compiler.outputFileSystem,
1348
+ stats: "none",
1349
+ ...nuxt.options.webpack.devMiddleware
1350
+ });
1351
+ nuxt.hook("close", () => pify(devMiddleware.close.bind(devMiddleware))());
1352
+ const { client: _client, ...hotMiddlewareOptions } = nuxt.options.webpack.hotMiddleware || {};
1353
+ const hotMiddleware = webpackHotMiddleware(compiler, {
1354
+ log: false,
1355
+ heartbeat: 1e4,
1356
+ path: joinURL(nuxt.options.app.baseURL, "__webpack_hmr", compiler.options.name),
1357
+ ...hotMiddlewareOptions
1358
+ });
1359
+ const devHandler = wdmToH3Handler(devMiddleware);
1360
+ await nuxt.callHook("server:devHandler", defineEventHandler(async (event) => {
1361
+ const body = await devHandler(event);
1362
+ if (body !== void 0) return body;
1363
+ const { req, res } = "runtime" in event ? event.runtime.node : event.node;
1364
+ await new Promise((resolve, reject) => hotMiddleware(req, res, (err) => err ? reject(err) : resolve()));
1365
+ }), { cors: () => true });
1366
+ return devMiddleware;
1211
1367
  }
1212
- function wdmToH3Handler(devMiddleware, corsOptions) {
1213
- return defineEventHandler(async (event) => {
1214
- const isPreflight = handleCors(event, corsOptions);
1215
- if (isPreflight) {
1216
- return null;
1217
- }
1218
- if (getRequestHeader(event, "sec-fetch-mode") === "no-cors" && getRequestHeader(event, "sec-fetch-site") === "cross-site") {
1219
- throw createError({ statusCode: 403 });
1220
- }
1221
- setHeader(event, "Vary", "Origin");
1222
- event.context.webpack = {
1223
- ...event.context.webpack,
1224
- devMiddleware: devMiddleware.context
1225
- };
1226
- const { req, res } = event.node;
1227
- const body = await new Promise((resolve, reject) => {
1228
- res.stream = (stream) => {
1229
- resolve(stream);
1230
- };
1231
- res.send = (data) => {
1232
- resolve(data);
1233
- };
1234
- res.finish = (data) => {
1235
- resolve(data);
1236
- };
1237
- devMiddleware(req, res, (err) => {
1238
- if (err) {
1239
- reject(err);
1240
- } else {
1241
- resolve(void 0);
1242
- }
1243
- });
1244
- });
1245
- return body;
1246
- });
1368
+ function wdmToH3Handler(devMiddleware) {
1369
+ return defineEventHandler(async (event) => {
1370
+ const { req, res } = "runtime" in event ? event.runtime.node : event.node;
1371
+ if (req.headers["sec-fetch-mode"] === "no-cors" && req.headers["sec-fetch-site"] === "cross-site") {
1372
+ res.statusCode = 403;
1373
+ res.end("Forbidden");
1374
+ return;
1375
+ }
1376
+ event.context.webpack = {
1377
+ ...event.context.webpack,
1378
+ devMiddleware: devMiddleware.context
1379
+ };
1380
+ return await new Promise((resolve, reject) => {
1381
+ res.stream = (stream) => {
1382
+ resolve(stream);
1383
+ };
1384
+ res.send = (data) => {
1385
+ resolve(data);
1386
+ };
1387
+ res.finish = (data) => {
1388
+ resolve(data);
1389
+ };
1390
+ devMiddleware(req, res, (err) => {
1391
+ if (err) reject(err);
1392
+ else resolve(void 0);
1393
+ });
1394
+ });
1395
+ });
1247
1396
  }
1248
1397
  async function compile(compiler) {
1249
- const nuxt = useNuxt();
1250
- await nuxt.callHook(`${builder}:compile`, { name: compiler.options.name, compiler });
1251
- compiler.hooks.done.tap("load-resources", async (stats2) => {
1252
- await nuxt.callHook(`${builder}:compiled`, { name: compiler.options.name, compiler, stats: stats2 });
1253
- });
1254
- if (nuxt.options.dev) {
1255
- const compilersWatching = [];
1256
- nuxt.hook("close", async () => {
1257
- await Promise.all(compilersWatching.map((watching) => watching && pify(watching.close.bind(watching))()));
1258
- });
1259
- if (compiler.options.name === "client") {
1260
- return new Promise((resolve, reject) => {
1261
- compiler.hooks.done.tap("nuxt-dev", () => {
1262
- resolve(null);
1263
- });
1264
- compiler.hooks.failed.tap("nuxt-errorlog", (err) => {
1265
- reject(err);
1266
- });
1267
- createDevMiddleware(compiler).then((devMiddleware) => {
1268
- if (devMiddleware.context.watching) {
1269
- compilersWatching.push(devMiddleware.context.watching);
1270
- }
1271
- });
1272
- });
1273
- }
1274
- return new Promise((resolve, reject) => {
1275
- const watching = compiler.watch(nuxt.options.watchers.webpack, (err) => {
1276
- if (err) {
1277
- return reject(err);
1278
- }
1279
- resolve(null);
1280
- });
1281
- compilersWatching.push(watching);
1282
- });
1283
- }
1284
- const stats = await new Promise((resolve, reject) => compiler.run((err, stats2) => err ? reject(err) : resolve(stats2)));
1285
- if (stats.hasErrors()) {
1286
- const error = new Error("Nuxt build error");
1287
- error.stack = stats.toString("errors-only");
1288
- throw error;
1289
- }
1398
+ const nuxt = useNuxt();
1399
+ await nuxt.callHook(`${builder}:compile`, {
1400
+ name: compiler.options.name,
1401
+ compiler
1402
+ });
1403
+ compiler.hooks.done.tap("load-resources", async (stats) => {
1404
+ await nuxt.callHook(`${builder}:compiled`, {
1405
+ name: compiler.options.name,
1406
+ compiler,
1407
+ stats
1408
+ });
1409
+ });
1410
+ if (nuxt.options.dev) {
1411
+ const compilersWatching = [];
1412
+ nuxt.hook("close", async () => {
1413
+ await Promise.all(compilersWatching.map((watching) => watching && pify(watching.close.bind(watching))()));
1414
+ });
1415
+ if (compiler.options.name === "client") return new Promise((resolve, reject) => {
1416
+ compiler.hooks.done.tap("nuxt-dev", () => {
1417
+ resolve(null);
1418
+ });
1419
+ compiler.hooks.failed.tap("nuxt-errorlog", (err) => {
1420
+ reject(err);
1421
+ });
1422
+ createDevMiddleware(compiler).then((devMiddleware) => {
1423
+ if (devMiddleware.context.watching) compilersWatching.push(devMiddleware.context.watching);
1424
+ });
1425
+ });
1426
+ return new Promise((resolve, reject) => {
1427
+ const watching = compiler.watch(nuxt.options.watchers.webpack, (err) => {
1428
+ if (err) return reject(err);
1429
+ resolve(null);
1430
+ });
1431
+ compilersWatching.push(watching);
1432
+ });
1433
+ }
1434
+ const stats = await new Promise((resolve, reject) => compiler.run((err, stats) => err ? reject(err) : resolve(stats)));
1435
+ if (stats.hasErrors()) {
1436
+ const error = /* @__PURE__ */ new Error("Nuxt build error");
1437
+ error.stack = stats.toString("errors-only");
1438
+ throw error;
1439
+ }
1440
+ }
1441
+ function defineEventHandler(handler) {
1442
+ return Object.assign(handler, { __is_handler__: true });
1290
1443
  }
1291
-
1292
1444
  export { bundle };