@nuxt/rspack-builder 3.20.2 → 3.21.0

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