@depup/nuxt__kit 4.4.2-depup.0 → 4.5.0-depup.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
@@ -4,6 +4,10 @@ import { applyDefaults } from "untyped";
4
4
  import { consola } from "consola";
5
5
  import { AsyncLocalStorage } from "node:async_hooks";
6
6
  import { getContext } from "unctx";
7
+ import { createConsoleReporter, defineDiagnostics } from "nostics";
8
+ import process from "node:process";
9
+ import { ansiFormatter } from "nostics/formatters/ansi";
10
+ import { colors } from "consola/utils";
7
11
  import satisfies from "semver/functions/satisfies.js";
8
12
  import { readPackageJSON, resolvePackageJSON } from "pkg-types";
9
13
  import { existsSync, lstatSync, promises, readFileSync } from "node:fs";
@@ -16,11 +20,10 @@ import { isRelative, withTrailingSlash, withoutTrailingSlash } from "ufo";
16
20
  import { read, update } from "rc9";
17
21
  import semver, { gte } from "semver";
18
22
  import { captureStackTrace } from "errx";
19
- import process from "node:process";
20
23
  import { glob } from "tinyglobby";
21
24
  import { resolveAlias as resolveAlias$1, reverseResolveAlias } from "pathe/utils";
22
25
  import ignore from "ignore";
23
- import { loadConfig } from "c12";
26
+ import { loadConfig, setupDotenv } from "c12";
24
27
  import destr from "destr";
25
28
  import { kebabCase, pascalCase, snakeCase } from "scule";
26
29
  import { klona } from "klona";
@@ -32,6 +35,123 @@ function useLogger(tag, options = {}) {
32
35
  return tag ? logger.create(options).withTag(tag) : logger;
33
36
  }
34
37
  //#endregion
38
+ //#region src/diagnostics/_shared.ts
39
+ /**
40
+ * Resolve the docs URL for a stable `NUXT_B<NNNN>` code.
41
+ *
42
+ * Codes with a dedicated docs page pass this as their `see:` URL; codes whose
43
+ * inline why+fix is self-sufficient opt out with `docs: false`.
44
+ */
45
+ const docsBase = (code) => `https://nuxt.com/docs/4.x/errors/${code.replace("NUXT_", "").toLowerCase()}`;
46
+ const reporters = [/* @__PURE__ */ createConsoleReporter(process.env.NODE_ENV === "test" ? void 0 : { formatter: ansiFormatter(colors) })];
47
+ //#endregion
48
+ //#region src/diagnostics/kit-api.ts
49
+ /**
50
+ * B8xxx
51
+ * Kit API diagnostics.
52
+ */
53
+ const kitDiagnostics = /* #__PURE__ */ defineDiagnostics({
54
+ docsBase,
55
+ reporters,
56
+ codes: {
57
+ NUXT_B8001: {
58
+ why: "The active Nuxt instance is unavailable in the current context.",
59
+ fix: "Call this within a Nuxt module `setup()` function, or inside a `nuxt.hook()` callback.",
60
+ docs: false
61
+ },
62
+ NUXT_B8002: {
63
+ why: "The `base` argument to `createResolver(base)` is missing.",
64
+ fix: "Pass `import.meta.url` or a directory path as the `base` argument to `createResolver()`.",
65
+ docs: false
66
+ },
67
+ NUXT_B8003: {
68
+ why: "Nitro is not initialized yet: `useNitro()` was called before the `ready` hook ran.",
69
+ fix: "Move the `useNitro()` call inside a hook that runs after initialization, such as `nuxt.hook('ready', () => { ... })`.",
70
+ docs: false
71
+ },
72
+ NUXT_B8004: {
73
+ why: (p) => `Nuxt compatibility issues were found:\n${p.issues}`,
74
+ fix: "Update the module to support the current Nuxt version, or check if a newer version of the module is available.",
75
+ docs: false
76
+ },
77
+ NUXT_B8005: {
78
+ why: "The Nuxt version cannot be determined: no current instance was passed.",
79
+ fix: "Pass a valid Nuxt instance to `getNuxtVersion()`, or ensure `useNuxt()` is available in the current context.",
80
+ docs: false
81
+ },
82
+ NUXT_B8006: {
83
+ why: (p) => `No Nuxt version could be found from \`${p.cwd}\`.`,
84
+ fix: "Run `npm install nuxt` in your project directory to install Nuxt.",
85
+ docs: false
86
+ },
87
+ NUXT_B8007: {
88
+ why: (p) => `The type template filename \`${p.template}\` is invalid.`,
89
+ fix: "Rename the template filename to end with `.d.ts`.",
90
+ docs: false
91
+ },
92
+ NUXT_B8008: {
93
+ why: (p) => `The template value is invalid: ${p.template}.`,
94
+ fix: "Pass a valid template object or a string path to `addTemplate()`.",
95
+ docs: false
96
+ },
97
+ NUXT_B8009: {
98
+ why: (p) => `The template was not found at \`${p.template}\`.`,
99
+ fix: "Check that the `src` path exists and is an absolute path or resolvable from the module directory.",
100
+ docs: false
101
+ },
102
+ NUXT_B8010: {
103
+ why: (p) => `The template \`${p.template}\` provides neither \`getContents\` nor \`src\`.`,
104
+ fix: "Add a `getContents` function or a `src` path to the template object.",
105
+ docs: false
106
+ },
107
+ NUXT_B8011: {
108
+ why: (p) => `The template is missing a \`filename\`: ${p.template}.`,
109
+ fix: "Add a `filename` property to the template object, or provide a `src` path so the filename can be derived from it.",
110
+ docs: false
111
+ },
112
+ NUXT_B8012: {
113
+ why: (p) => `\`${p.name}\` was used outside of a Nuxt context.`,
114
+ fix: "Register this module in the `modules` array of `nuxt.config` rather than calling it directly.",
115
+ docs: false
116
+ },
117
+ NUXT_B8013: {
118
+ why: (p) => p.message,
119
+ fix: "Update the module to a version that supports the current Nuxt version, or set `experimental.enforceModuleCompatibility` to `true` to make this a fatal error.",
120
+ docs: false
121
+ },
122
+ NUXT_B8014: {
123
+ why: (p) => `Module \`${p.name}\` was slow to set up, taking \`${p.time}ms\`.`,
124
+ fix: "Defer expensive operations to a later hook (e.g. `build:before`) to reduce startup time.",
125
+ docs: false
126
+ },
127
+ NUXT_B8015: {
128
+ why: (p) => `A Nuxt module must be a function or a string to import. Received: \`${p.received}\`.`,
129
+ fix: "Pass a module function or a string package name to the `modules` array in `nuxt.config`.",
130
+ docs: false
131
+ },
132
+ NUXT_B8016: {
133
+ why: (p) => `The Nuxt module \`${p.module}\` is not a function.`,
134
+ fix: "Ensure the module has a default export that is a function, using `defineNuxtModule()` to create a valid module.",
135
+ docs: false
136
+ },
137
+ NUXT_B8017: {
138
+ why: (p) => `The module \`${p.module}\` could not be loaded. It may not be installed.`,
139
+ fix: (p) => `Run \`npm install ${p.module}\` to install it.`,
140
+ docs: false
141
+ },
142
+ NUXT_B8018: {
143
+ why: (p) => `An error occurred while importing the module \`${p.module}\`: ${p.error}.`,
144
+ fix: "A sub-dependency of this module is missing. Install it, or check that the module is compatible with the current environment.",
145
+ docs: false
146
+ },
147
+ NUXT_B8019: {
148
+ why: (p) => `An error occurred while executing the ${p.phase} hook for module \`${p.name}\`: ${p.error}.`,
149
+ fix: "Check the module's install/upgrade hook implementation, or report this issue to the module author.",
150
+ docs: false
151
+ }
152
+ }
153
+ });
154
+ //#endregion
35
155
  //#region src/context.ts
36
156
  /**
37
157
  * Direct access to the Nuxt global context - see https://github.com/unjs/unctx.
@@ -56,7 +176,7 @@ const getNuxtCtx = () => asyncNuxtStorage.tryUse();
56
176
  */
57
177
  function useNuxt() {
58
178
  const instance = asyncNuxtStorage.tryUse() || nuxtCtx.tryUse();
59
- if (!instance) throw new Error("Nuxt instance is unavailable!");
179
+ if (!instance) throw kitDiagnostics.NUXT_B8001();
60
180
  return instance;
61
181
  }
62
182
  /**
@@ -136,7 +256,7 @@ async function checkNuxtCompatibility(constraints, nuxt = useNuxt()) {
136
256
  */
137
257
  async function assertNuxtCompatibility(constraints, nuxt = useNuxt()) {
138
258
  const issues = await checkNuxtCompatibility(constraints, nuxt);
139
- if (issues.length) throw new Error("Nuxt compatibility issues found:\n" + issues.toString());
259
+ if (issues.length) throw kitDiagnostics.NUXT_B8004({ issues: issues.toString() });
140
260
  return true;
141
261
  }
142
262
  /**
@@ -170,7 +290,7 @@ const NUXT_VERSION_RE = /^v/g;
170
290
  */
171
291
  function getNuxtVersion(nuxt = useNuxt()) {
172
292
  const rawVersion = nuxt?._version || nuxt?.version || nuxt?.constructor?.version;
173
- if (typeof rawVersion !== "string") throw new TypeError("Cannot determine nuxt version! Is current instance passed?");
293
+ if (typeof rawVersion !== "string") throw kitDiagnostics.NUXT_B8005();
174
294
  return rawVersion.replace(NUXT_VERSION_RE, "");
175
295
  }
176
296
  //#endregion
@@ -194,7 +314,7 @@ function _defineNuxtModule(definition) {
194
314
  return module.moduleDependencies;
195
315
  }
196
316
  async function normalizedModule(inlineOptions, nuxt = tryUseNuxt()) {
197
- if (!nuxt) throw new TypeError(`Cannot use ${module.meta.name || "module"} outside of Nuxt context`);
317
+ if (!nuxt) throw kitDiagnostics.NUXT_B8012({ name: module.meta.name || "module" });
198
318
  const uniqueKey = module.meta.name || module.meta.configKey;
199
319
  if (uniqueKey) {
200
320
  nuxt.options._requiredModules ||= {};
@@ -210,7 +330,7 @@ function _defineNuxtModule(definition) {
210
330
  error.name = "ModuleCompatibilityError";
211
331
  throw error;
212
332
  }
213
- logger.warn(errorMessage);
333
+ kitDiagnostics.NUXT_B8013({ message: errorMessage });
214
334
  return;
215
335
  }
216
336
  }
@@ -219,7 +339,7 @@ function _defineNuxtModule(definition) {
219
339
  const moduleName = uniqueKey || module.meta.name || "<no name>";
220
340
  nuxt._perf?.startPhase(`module:${moduleName}`);
221
341
  const start = performance.now();
222
- let res = {};
342
+ let res;
223
343
  try {
224
344
  res = await module.setup?.call(null, _options, nuxt) ?? {};
225
345
  } finally {
@@ -227,7 +347,10 @@ function _defineNuxtModule(definition) {
227
347
  }
228
348
  const perf = performance.now() - start;
229
349
  const setupTime = Math.round(perf * 100) / 100;
230
- if (setupTime > 5e3 && uniqueKey !== "@nuxt/telemetry") logger.warn(`Slow module \`${moduleName}\` took \`${setupTime}ms\` to setup.`);
350
+ if (setupTime > 5e3 && uniqueKey !== "@nuxt/telemetry") kitDiagnostics.NUXT_B8014({
351
+ name: moduleName,
352
+ time: setupTime
353
+ });
231
354
  else if (nuxt.options.debug && nuxt.options.debug.modules) logger.info(`Module \`${moduleName}\` took \`${setupTime}ms\` to setup.`);
232
355
  if (res === false) return false;
233
356
  return defu(res, { timings: { setup: setupTime } });
@@ -303,6 +426,7 @@ function withTrailingSlash$2(dir) {
303
426
  function createIsIgnored(nuxt = tryUseNuxt()) {
304
427
  return (pathname, stats) => isIgnored(pathname, stats, nuxt);
305
428
  }
429
+ const layerRootsCache = /* @__PURE__ */ new WeakMap();
306
430
  /**
307
431
  * Return a filter function to filter an array of paths
308
432
  */
@@ -312,7 +436,16 @@ function isIgnored(pathname, _stats, nuxt = tryUseNuxt()) {
312
436
  nuxt._ignore = ignore(nuxt.options.ignoreOptions);
313
437
  nuxt._ignore.add(resolveIgnorePatterns());
314
438
  }
315
- const relativePath = relative(getLayerDirectories(nuxt).map((dirs) => dirs.root).sort((a, b) => b.length - a.length).find((cwd) => pathname.startsWith(cwd)) ?? nuxt.options.rootDir, pathname);
439
+ let cwds = layerRootsCache.get(nuxt);
440
+ if (!cwds) {
441
+ cwds = getLayerDirectories(nuxt).map((dirs) => dirs.root).sort((a, b) => b.length - a.length);
442
+ layerRootsCache.set(nuxt, cwds);
443
+ }
444
+ for (const cwd of cwds) if (pathname.startsWith(cwd)) {
445
+ const relativePath = pathname.slice(cwd.length);
446
+ return !!(relativePath && nuxt._ignore.ignores(relativePath));
447
+ }
448
+ const relativePath = relative(nuxt.options.rootDir, pathname);
316
449
  if (relativePath[0] === "." && relativePath[1] === ".") return false;
317
450
  return !!(relativePath && nuxt._ignore.ignores(relativePath));
318
451
  }
@@ -392,11 +525,12 @@ async function resolvePath(path, opts = {}) {
392
525
  */
393
526
  async function findPath(paths, opts, pathType = "file") {
394
527
  for (const path of toArray(paths)) {
528
+ const type = opts?.type || pathType;
395
529
  const res = await _resolvePathGranularly(path, {
396
530
  ...opts,
397
- type: opts?.type || pathType
531
+ type
398
532
  });
399
- if (!res.type || pathType && res.type !== pathType) continue;
533
+ if (!res.type || res.type !== type) continue;
400
534
  if (res.virtual || await existsSensitive(res.path)) return res.path;
401
535
  }
402
536
  return null;
@@ -412,7 +546,7 @@ function resolveAlias(path, alias) {
412
546
  * Create a relative resolver
413
547
  */
414
548
  function createResolver(base) {
415
- if (!base) throw new Error("`base` argument is missing for createResolver(base)!");
549
+ if (!base) throw kitDiagnostics.NUXT_B8002();
416
550
  base = base.toString();
417
551
  if (base.startsWith("file://")) base = dirname(fileURLToPath(base));
418
552
  return {
@@ -449,17 +583,12 @@ async function _resolvePathType(path, opts = {}, skipFs = false) {
449
583
  virtual: true
450
584
  };
451
585
  if (skipFs) return;
452
- const fd = await promises.open(path, "r").catch(() => null);
453
- try {
454
- const stats = await fd?.stat();
455
- if (stats) return {
456
- path,
457
- type: stats.isFile() ? "file" : "dir",
458
- virtual: false
459
- };
460
- } finally {
461
- fd?.close();
462
- }
586
+ const stats = await promises.stat(path).catch(() => null);
587
+ if (stats) return {
588
+ path,
589
+ type: stats.isFile() ? "file" : "dir",
590
+ virtual: false
591
+ };
463
592
  }
464
593
  function normalizeExtension(ext) {
465
594
  return ext.startsWith(".") ? ext : `.${ext}`;
@@ -585,7 +714,7 @@ function tryRequireModule(id, opts) {
585
714
  //#endregion
586
715
  //#region src/module/install.ts
587
716
  const NODE_MODULES_RE = /[/\\]node_modules[/\\]/;
588
- const ignoredConfigKeys = new Set([
717
+ const ignoredConfigKeys = /* @__PURE__ */ new Set([
589
718
  "components",
590
719
  "imports",
591
720
  "pages",
@@ -605,6 +734,8 @@ async function installModules(modulesToInstall, resolvedModulePaths, nuxt = useN
605
734
  nuxt._moduleOptionsFunctions ||= /* @__PURE__ */ new Map();
606
735
  const resolvedModules = [];
607
736
  const modulesByMetaName = /* @__PURE__ */ new Map();
737
+ const moduleLoadCache = /* @__PURE__ */ new Map();
738
+ for (const [key] of modulesToInstall) moduleLoadCache.set(key, loadNuxtModuleInstance(key, nuxt));
608
739
  const inlineConfigKeys = new Set(await Promise.all([...modulesToInstall].map(async ([mod]) => {
609
740
  if (typeof mod === "string") return;
610
741
  const meta = await Promise.resolve(mod.getMeta?.());
@@ -617,7 +748,7 @@ async function installModules(modulesToInstall, resolvedModulePaths, nuxt = useN
617
748
  let error;
618
749
  const dependencyMap = /* @__PURE__ */ new Map();
619
750
  for (const [key, options] of modulesToInstall) {
620
- const res = await loadNuxtModuleInstance(key, nuxt).catch((err) => {
751
+ const res = await (moduleLoadCache.get(key) || loadNuxtModuleInstance(key, nuxt)).catch((err) => {
621
752
  if (dependencyMap.has(key) && typeof key === "string") err.cause = `Could not resolve \`${key}\` (specified as a dependency of ${dependencyMap.get(key)}).`;
622
753
  throw err;
623
754
  });
@@ -667,7 +798,7 @@ async function installModules(modulesToInstall, resolvedModulePaths, nuxt = useN
667
798
  if (error) throw error;
668
799
  for (const { nuxtModule, meta = {}, moduleToInstall, buildTimeModuleMeta, resolvedModulePath, inlineOptions } of resolvedModules) {
669
800
  const configKey = meta.configKey;
670
- const optionsFns = new Set([
801
+ const optionsFns = /* @__PURE__ */ new Set([
671
802
  ...nuxt._moduleOptionsFunctions.get(moduleToInstall) || [],
672
803
  ...meta?.name ? nuxt._moduleOptionsFunctions.get(meta.name) || [] : [],
673
804
  ...configKey ? nuxt._moduleOptionsFunctions.get(configKey) || [] : []
@@ -762,14 +893,24 @@ function resolveModuleWithOptions(definition, nuxt) {
762
893
  options
763
894
  };
764
895
  }
896
+ let _jitiCache;
897
+ function getSharedJiti(nuxt) {
898
+ _jitiCache ||= /* @__PURE__ */ new WeakMap();
899
+ let jiti = _jitiCache.get(nuxt);
900
+ if (!jiti) {
901
+ jiti = createJiti(nuxt.options.rootDir, { alias: nuxt.options.alias });
902
+ _jitiCache.set(nuxt, jiti);
903
+ }
904
+ return jiti;
905
+ }
765
906
  async function loadNuxtModuleInstance(nuxtModule, nuxt = useNuxt()) {
766
907
  let buildTimeModuleMeta = {};
767
908
  if (typeof nuxtModule === "function") return {
768
909
  nuxtModule,
769
910
  buildTimeModuleMeta
770
911
  };
771
- if (typeof nuxtModule !== "string") throw new TypeError(`Nuxt module should be a function or a string to import. Received: ${nuxtModule}.`);
772
- const jiti = createJiti(nuxt.options.rootDir, { alias: nuxt.options.alias });
912
+ if (typeof nuxtModule !== "string") throw kitDiagnostics.NUXT_B8015({ received: `${typeof nuxtModule} (${JSON.stringify(nuxtModule)})` });
913
+ const jiti = getSharedJiti(nuxt);
773
914
  nuxtModule = resolveAlias(nuxtModule, nuxt.options.alias);
774
915
  if (isRelative(nuxtModule)) nuxtModule = resolve(nuxt.options.rootDir, nuxtModule);
775
916
  try {
@@ -794,7 +935,7 @@ async function loadNuxtModuleInstance(nuxtModule, nuxt = useNuxt()) {
794
935
  });
795
936
  const resolvedModulePath = fileURLToPath(src);
796
937
  const resolvedNuxtModule = await jiti.import(src, { default: true });
797
- if (typeof resolvedNuxtModule !== "function") throw new TypeError(`Nuxt module should be a function: ${nuxtModule}.`);
938
+ if (typeof resolvedNuxtModule !== "function") throw kitDiagnostics.NUXT_B8016({ module: nuxtModule });
798
939
  const moduleMetadataPath = new URL("module.json", src);
799
940
  if (existsSync(moduleMetadataPath)) buildTimeModuleMeta = JSON.parse(await promises.readFile(moduleMetadataPath, "utf-8"));
800
941
  return {
@@ -804,13 +945,20 @@ async function loadNuxtModuleInstance(nuxtModule, nuxt = useNuxt()) {
804
945
  };
805
946
  } catch (error) {
806
947
  const code = error.code;
807
- if (code === "ERR_PACKAGE_PATH_NOT_EXPORTED" || code === "ERR_UNSUPPORTED_DIR_IMPORT" || code === "ENOTDIR") throw new TypeError(`Could not load \`${nuxtModule}\`. Is it installed?`);
948
+ if (code === "ERR_PACKAGE_PATH_NOT_EXPORTED" || code === "ERR_UNSUPPORTED_DIR_IMPORT" || code === "ENOTDIR") throw kitDiagnostics.NUXT_B8017({
949
+ module: nuxtModule,
950
+ cause: error
951
+ });
808
952
  if (code === "MODULE_NOT_FOUND" || code === "ERR_MODULE_NOT_FOUND") {
809
953
  const module = MissingModuleMatcher.exec(error.message)?.[1];
810
- if (module && !module.includes(nuxtModule)) throw new TypeError(`Error while importing module \`${nuxtModule}\`: ${error}`);
954
+ if (module && !module.includes(nuxtModule)) throw kitDiagnostics.NUXT_B8018({
955
+ module: nuxtModule,
956
+ error: String(error),
957
+ cause: error
958
+ });
811
959
  }
812
960
  }
813
- throw new TypeError(`Could not load \`${nuxtModule}\`. Is it installed?`);
961
+ throw kitDiagnostics.NUXT_B8017({ module: nuxtModule });
814
962
  }
815
963
  function getDirectory(p) {
816
964
  try {
@@ -837,7 +985,11 @@ async function callLifecycleHooks(nuxtModule, meta = {}, inlineOptions, nuxt = u
837
985
  name: ".nuxtrc"
838
986
  });
839
987
  } catch (e) {
840
- logger.error(`Error while executing ${!previousVersion ? "install" : "upgrade"} hook for module \`${meta.name}\`: ${e}`);
988
+ kitDiagnostics.NUXT_B8019({
989
+ phase: !previousVersion ? "install" : "upgrade",
990
+ name: meta.name,
991
+ error: String(e)
992
+ });
841
993
  }
842
994
  }
843
995
  async function callModule(nuxt, nuxtModule, moduleOptions = {}, options) {
@@ -926,6 +1078,11 @@ async function loadNuxtConfig(opts) {
926
1078
  cwd: opts.cwd || process.cwd()
927
1079
  })).map((d) => withTrailingSlash(d)).sort((a, b) => b.localeCompare(a));
928
1080
  opts.overrides = defu(opts.overrides, { _extends: localLayers });
1081
+ if (opts.dotenv !== false) await setupDotenv({
1082
+ cwd: opts.cwd || process.cwd(),
1083
+ ...typeof opts.dotenv === "object" ? opts.dotenv : {}
1084
+ });
1085
+ const schemaPromise = loadNuxtSchema(opts.cwd || process.cwd());
929
1086
  const { configFile, layers = [], cwd, config: nuxtConfig, meta } = await withDefineNuxtConfig(() => loadConfig({
930
1087
  name: "nuxt",
931
1088
  configFile: "nuxt.config",
@@ -935,15 +1092,16 @@ async function loadNuxtConfig(opts) {
935
1092
  "_extends",
936
1093
  "extends"
937
1094
  ] },
938
- dotenv: true,
939
1095
  globalRc: true,
940
1096
  merger,
941
- ...opts
1097
+ ...opts,
1098
+ dotenv: false
942
1099
  }));
943
1100
  nuxtConfig.rootDir ||= cwd;
944
1101
  nuxtConfig._nuxtConfigFile = configFile;
945
1102
  nuxtConfig._nuxtConfigFiles = [configFile];
946
1103
  nuxtConfig._loadOptions = opts;
1104
+ if (typeof opts.envName === "string") nuxtConfig.envName = opts.envName;
947
1105
  nuxtConfig.alias ||= {};
948
1106
  if (meta?.name) {
949
1107
  const alias = `#layers/${meta.name}`;
@@ -951,7 +1109,7 @@ async function loadNuxtConfig(opts) {
951
1109
  }
952
1110
  const defaultBuildDir = join(nuxtConfig.rootDir, ".nuxt");
953
1111
  if (!opts.overrides?._prepare && !nuxtConfig.dev && !nuxtConfig.buildDir && existsSync(defaultBuildDir)) nuxtConfig.buildDir = join(nuxtConfig.rootDir, "node_modules/.cache/nuxt/.nuxt");
954
- const NuxtConfigSchema = await loadNuxtSchema(nuxtConfig.rootDir || cwd || process.cwd());
1112
+ const NuxtConfigSchema = await schemaPromise;
955
1113
  const layerSchemaKeys = [
956
1114
  "future",
957
1115
  "srcDir",
@@ -1045,7 +1203,7 @@ async function loadNuxt(opts) {
1045
1203
  });
1046
1204
  return path && path.length > resolvedPath.length ? path : resolvedPath;
1047
1205
  }, "");
1048
- if (!resolvedPath) throw new Error(`Cannot find any nuxt version from ${opts.cwd}`);
1206
+ if (!resolvedPath) throw kitDiagnostics.NUXT_B8006({ cwd: opts.cwd });
1049
1207
  const { loadNuxt } = await import(pathToFileURL(resolvedPath).href).then((r) => interopDefault(r));
1050
1208
  return await loadNuxt(opts);
1051
1209
  }
@@ -1078,6 +1236,16 @@ function addImportsSources(presets) {
1078
1236
  });
1079
1237
  }
1080
1238
  //#endregion
1239
+ //#region src/app-config.ts
1240
+ /**
1241
+ * Update Nuxt app configuration.
1242
+ * @since 4.5.0
1243
+ */
1244
+ function updateAppConfig(appConfig) {
1245
+ const nuxt = useNuxt();
1246
+ Object.assign(nuxt.options.appConfig, defu(appConfig, nuxt.options.appConfig));
1247
+ }
1248
+ //#endregion
1081
1249
  //#region src/nitro.ts
1082
1250
  const HANDLER_METHOD_RE = /\.(get|head|patch|post|put|delete|connect|options|trace)(\.\w+)*$/;
1083
1251
  /**
@@ -1141,7 +1309,7 @@ function addPrerenderRoutes(routes) {
1141
1309
  */
1142
1310
  function useNitro() {
1143
1311
  const nuxt = useNuxt();
1144
- if (!nuxt._nitro) throw new Error("Nitro is not initialized yet. You can call `useNitro()` only after `ready` hook.");
1312
+ if (!nuxt._nitro) throw kitDiagnostics.NUXT_B8003();
1145
1313
  return nuxt._nitro;
1146
1314
  }
1147
1315
  /**
@@ -1342,6 +1510,91 @@ function addBuildPlugin(pluginFactory, options) {
1342
1510
  if (pluginFactory.webpack) addWebpackPlugin(pluginFactory.webpack, options);
1343
1511
  if (pluginFactory.rspack) addRspackPlugin(pluginFactory.rspack, options);
1344
1512
  }
1513
+ /**
1514
+ * Set the build output for the given key. See {@link NuxtBuildOutputs}.
1515
+ */
1516
+ function setBuildOutput(key, provider, nuxt = useNuxt()) {
1517
+ nuxt.buildOutputs[key] = provider;
1518
+ }
1519
+ //#endregion
1520
+ //#region src/diagnostics/components.ts
1521
+ /**
1522
+ * B3xxx
1523
+ * Component diagnostics.
1524
+ *
1525
+ * @internal
1526
+ */
1527
+ const componentDiagnostics = /* #__PURE__ */ defineDiagnostics({
1528
+ docsBase,
1529
+ reporters,
1530
+ codes: {
1531
+ NUXT_B3001: {
1532
+ why: (p) => `Components directory not found: \`${p.dirPath}\`.`,
1533
+ fix: "If this is intentional, remove it from `components.dirs` in your `nuxt.config`.",
1534
+ docs: false
1535
+ },
1536
+ NUXT_B3002: {
1537
+ why: (p) => `Using server component \`${p.component}\` with \`ssr: false\` is not supported with auto-detected component islands.`,
1538
+ fix: "Set `experimental.componentIslands` to `true` in your `nuxt.config`, or convert the component to a client component.",
1539
+ docs: false
1540
+ },
1541
+ NUXT_B3003: {
1542
+ why: (p) => `Standalone server components (\`${p.component}\`) are not yet supported without enabling \`experimental.componentIslands\`.`,
1543
+ fix: "Set `experimental.componentIslands` to `true` in your `nuxt.config`.",
1544
+ docs: false
1545
+ },
1546
+ NUXT_B3004: {
1547
+ why: (p) => `\`${p.file}\` is using \`${p.component}\` which requires \`${p.requiredModule}\`.`,
1548
+ fix: (p) => `Run \`npx nuxt add ${p.requiredModule}\` to install it.`,
1549
+ docs: false
1550
+ },
1551
+ NUXT_B3005: {
1552
+ why: (p) => `Multiple hydration strategies are not supported in the same component \`<${p.component}>\` in \`${p.file}\`.`,
1553
+ fix: "Use only one hydration strategy attribute (e.g. `hydrate-on-visible` or `hydrate-on-idle`) per component.",
1554
+ docs: false
1555
+ },
1556
+ NUXT_B3006: {
1557
+ why: (p) => `Component \`<${p.component}>\` (used in \`${p.file}\`) has lazy-hydration props but is not declared as a lazy component.`,
1558
+ fix: (p) => `Rename it to \`<${p.lazyName} />\` or remove the lazy-hydration props.`,
1559
+ docs: false
1560
+ },
1561
+ NUXT_B3007: {
1562
+ why: (p) => `Using the \`nuxt-client\` attribute (in \`${p.file}\`) to render client components within islands requires \`experimental.componentIslands.selectiveClient\` to be enabled.`,
1563
+ fix: "Set `experimental.componentIslands.selectiveClient` to `true` in your `nuxt.config`.",
1564
+ docs: false
1565
+ },
1566
+ NUXT_B3008: {
1567
+ why: (p) => `Components not scanned from \`${p.scannedPath}\`, likely due to a directory casing mismatch.`,
1568
+ fix: (p) => `Rename the directory from \`${p.scannedPath}\` to \`${p.expectedPath}\` to match the expected casing.`,
1569
+ docs: false
1570
+ },
1571
+ NUXT_B3009: {
1572
+ why: (p) => `The component \`${p.component}\` (in \`${p.filePath}\`) is using the reserved "Lazy" prefix used for dynamic imports, which may cause it to break at runtime.`,
1573
+ fix: "Rename the component to avoid the `Lazy` prefix.",
1574
+ docs: false
1575
+ },
1576
+ NUXT_B3010: {
1577
+ why: (p) => `Component did not resolve to a file name in \`${p.filePath}\`.`,
1578
+ fix: "Rename the component file to something other than `index` (e.g. `MyComponent.vue`).",
1579
+ docs: false
1580
+ },
1581
+ NUXT_B3011: {
1582
+ why: (p) => `Two component files resolving to the same name \`${p.component}\`:\n\n - ${p.filePath}\n - ${p.duplicatePath}`,
1583
+ fix: "Rename one of the files or adjust the `components.dirs` prefix settings in your `nuxt.config`.",
1584
+ docs: false
1585
+ },
1586
+ NUXT_B3012: {
1587
+ why: (p) => `Overriding ${p.name} component.`,
1588
+ fix: "Specify a `priority` option when calling `addComponent` to avoid this warning.",
1589
+ docs: false
1590
+ },
1591
+ NUXT_B3013: {
1592
+ why: (p) => `Rendering client components within islands via the \`nuxt-client\` attribute (in \`${p.file}\`) is only supported with the Vite builder.`,
1593
+ fix: "Switch to the Vite builder with `builder: 'vite'` in your `nuxt.config`.",
1594
+ docs: false
1595
+ }
1596
+ }
1597
+ });
1345
1598
  //#endregion
1346
1599
  //#region src/components.ts
1347
1600
  /**
@@ -1391,7 +1644,7 @@ function addComponents(addedComponents) {
1391
1644
  if (newPriority < existingPriority) continue;
1392
1645
  if (newPriority === existingPriority) {
1393
1646
  const name = existingComponent.pascalName || existingComponent.kebabName;
1394
- logger.warn(`Overriding ${name} component. You can specify a \`priority\` option when calling \`addComponent\` to avoid this warning.`);
1647
+ componentDiagnostics.NUXT_B3012({ name });
1395
1648
  }
1396
1649
  components.splice(existingComponentIndex, 1, component);
1397
1650
  } else components.push(component);
@@ -1419,6 +1672,174 @@ function normalizeComponent(opts) {
1419
1672
  };
1420
1673
  }
1421
1674
  //#endregion
1675
+ //#region src/diagnostics/pages.ts
1676
+ /**
1677
+ * B4xxx
1678
+ * Pages / routing diagnostics.
1679
+ *
1680
+ * @internal
1681
+ */
1682
+ const pageDiagnostics = /* #__PURE__ */ defineDiagnostics({
1683
+ docsBase,
1684
+ reporters,
1685
+ codes: {
1686
+ NUXT_B4001: {
1687
+ why: (p) => `The file \`${p.pathname}\` is empty, so it cannot be a valid page.`,
1688
+ fix: "Add a `<template>` block to the page file, or remove the empty file from the `pages/` directory.",
1689
+ docs: false
1690
+ },
1691
+ NUXT_B4002: {
1692
+ why: "An `await` expression is used in a variable referenced by `definePageMeta`, which runs synchronously.",
1693
+ fix: (p) => `Move the \`await\` outside of variables referenced in \`definePageMeta\`, or use a static value instead (near offset ${p.offset}): ${p.codeSnippet}`,
1694
+ docs: false
1695
+ },
1696
+ NUXT_B4003: {
1697
+ why: (p) => `\`definePageMeta()\` is called ${p.callCount} times in \`${p.file}\`, but only one call is allowed.`,
1698
+ fix: "Merge all `definePageMeta()` calls into a single call.",
1699
+ docs: false
1700
+ },
1701
+ NUXT_B4004: {
1702
+ why: (p) => `The route name generated for \`${p.file}\` collides with the one already generated for \`${p.existingFile}\`.`,
1703
+ fix: "Set a custom name using `definePageMeta` within one of the page files.",
1704
+ docs: false
1705
+ },
1706
+ NUXT_B4005: {
1707
+ why: (p) => `\`${p.fnName}\` was called with a \`${p.receivedType}\` instead of an object literal (reading \`${p.file}\`).`,
1708
+ fix: (p) => `Pass a plain object literal to \`${p.fnName}()\`, e.g. \`${p.fnName}({ ... })\`. Variables and function calls are not supported.`,
1709
+ docs: false
1710
+ },
1711
+ NUXT_B4006: {
1712
+ why: (p) => `\`${p.fnName}\` was called with a non-serializable object literal (reading \`${p.file}\`).`,
1713
+ fix: "Use only JSON-serializable values (strings, numbers, booleans, arrays, plain objects) in `defineRouteRules()`.",
1714
+ docs: false
1715
+ },
1716
+ NUXT_B4008: {
1717
+ why: "Server pages with `ssr: false` are not supported while component islands are auto-detected.",
1718
+ fix: "Set `experimental.componentIslands` to `true`.",
1719
+ docs: false
1720
+ },
1721
+ NUXT_B4009: {
1722
+ why: (p) => `No layout name could be resolved for \`${p.file}\` (\`index\` is ignored for the purpose of creating a layout name).`,
1723
+ fix: "Rename the layout file to something other than `index` (e.g. `layouts/default.vue`).",
1724
+ docs: false
1725
+ },
1726
+ NUXT_B4010: {
1727
+ why: (p) => `No middleware name could be resolved for \`${p.file}\` (\`index\` is ignored for the purpose of creating a middleware name).`,
1728
+ fix: "Rename the middleware file to something other than `index` (e.g. `middleware/auth.ts`).",
1729
+ docs: false
1730
+ },
1731
+ NUXT_B4011: {
1732
+ why: (p) => `While building the page tree: ${p.message}`,
1733
+ fix: "Check the page file naming and directory structure for issues.",
1734
+ docs: false
1735
+ },
1736
+ NUXT_B4012: {
1737
+ why: (p) => `The incremental route update for \`${p.event}\` on \`${p.path}\` failed, so a full rebuild was performed.`,
1738
+ fix: "This is usually harmless: the full rebuild will recover. If it happens repeatedly, check for unusual file naming in `pages/`.",
1739
+ docs: false
1740
+ },
1741
+ NUXT_B4013: {
1742
+ why: (p) => `A \`${p.name}\` middleware already exists at \`${p.foundPath}\`.`,
1743
+ fix: "Set `override: true` to replace it.",
1744
+ docs: false
1745
+ },
1746
+ NUXT_B4014: {
1747
+ why: (p) => `Layout \`${p.layoutName}\` is already provided by \`${p.existingPath}\` and was not overridden with \`${p.newPath}\`.`,
1748
+ fix: "Rename one of the layouts, or remove the duplicate layout registration.",
1749
+ docs: false
1750
+ }
1751
+ }
1752
+ });
1753
+ //#endregion
1754
+ //#region src/types.ts
1755
+ const TYPE_RESOLVE_OPTIONS = {
1756
+ conditions: [
1757
+ "types",
1758
+ "import",
1759
+ "require"
1760
+ ],
1761
+ extensions: [
1762
+ ".js",
1763
+ ".mjs",
1764
+ ".cjs",
1765
+ ".ts",
1766
+ ".mts",
1767
+ ".cts"
1768
+ ]
1769
+ };
1770
+ const STRIPPABLE_EXT_RE = /\b\.(?:d\.ts|tsx?|jsx?)$/;
1771
+ const RUNTIME_EXT_RE = /(?<!\.d)\.([cm])(?:ts|js)$/;
1772
+ function isFile(path) {
1773
+ return promises.stat(path).then((s) => s.isFile(), () => false);
1774
+ }
1775
+ /**
1776
+ * Rewrite a resolved module path to the declaration file TypeScript will load for it.
1777
+ *
1778
+ * A `.d.ts` / `.d.mts` / `.d.cts` or `.ts` / `.tsx` path is returned unchanged (or with
1779
+ * the extension stripped, where TypeScript's extensionless `paths` retry will find it).
1780
+ * A `.mjs` / `.cjs` / `.mts` / `.cts` runtime path is rewritten to an adjacent declaration
1781
+ * sibling when one exists; otherwise it is returned as-is for the caller to handle.
1782
+ */
1783
+ async function resolveDeclarationPath(absolutePath) {
1784
+ const stripped = absolutePath.replace(STRIPPABLE_EXT_RE, "");
1785
+ if (stripped !== absolutePath) return stripped;
1786
+ const runtimeMatch = absolutePath.match(RUNTIME_EXT_RE);
1787
+ if (runtimeMatch) {
1788
+ const base = absolutePath.slice(0, -runtimeMatch[0].length);
1789
+ if (await isFile(`${base}.d.ts`)) return base;
1790
+ const declaration = `${base}.d.${runtimeMatch[1]}ts`;
1791
+ if (await isFile(declaration)) return declaration;
1792
+ }
1793
+ return absolutePath;
1794
+ }
1795
+ /** Extract the package name (including scope) from a (possibly subpath) module specifier. */
1796
+ function packageName(specifier) {
1797
+ const segments = specifier.split("/");
1798
+ return specifier[0] === "@" ? segments.slice(0, 2).join("/") : segments[0];
1799
+ }
1800
+ const rootCache = /* @__PURE__ */ new Map();
1801
+ function resolveRoot(basePkg, from) {
1802
+ const cacheKey = `${basePkg}\0${from.map(String).join("\0")}`;
1803
+ if (rootCache.has(cacheKey)) return rootCache.get(cacheKey);
1804
+ const promise = (async () => {
1805
+ try {
1806
+ return dirname(await resolvePackageJSON(resolveModulePath(basePkg, {
1807
+ from,
1808
+ ...TYPE_RESOLVE_OPTIONS
1809
+ })));
1810
+ } catch {
1811
+ return;
1812
+ }
1813
+ })();
1814
+ rootCache.set(cacheKey, promise);
1815
+ return promise;
1816
+ }
1817
+ /**
1818
+ * Resolve auto-import / `tsConfig.paths` entries to the path TypeScript should load types from.
1819
+ *
1820
+ * A bare package resolves to its package root, so TypeScript follows the package's own
1821
+ * `exports` / `types` (which may differ from the file its `.` export condition points at).
1822
+ * A subpath export resolves to its entry's declaration sibling when one exists, otherwise to
1823
+ * the resolved file itself.
1824
+ *
1825
+ * Returns `[specifier, absolutePath]` pairs, omitting any specifier that cannot be resolved.
1826
+ */
1827
+ async function resolveTypePaths(packages, searchPaths) {
1828
+ const from = searchPaths.map((d) => directoryToURL(d));
1829
+ return (await Promise.allSettled(packages.map(async (pkg) => {
1830
+ if (pkg === packageName(pkg)) {
1831
+ const root = await resolveRoot(pkg, from);
1832
+ return root ? [pkg, root] : void 0;
1833
+ }
1834
+ const resolved = resolveModulePath(pkg, {
1835
+ from,
1836
+ try: true,
1837
+ ...TYPE_RESOLVE_OPTIONS
1838
+ });
1839
+ return resolved ? [pkg, await resolveDeclarationPath(resolved)] : void 0;
1840
+ }))).flatMap((result) => result.status === "fulfilled" && result.value ? [result.value] : []);
1841
+ }
1842
+ //#endregion
1422
1843
  //#region src/template.ts
1423
1844
  /**
1424
1845
  * Renders given template during build into the virtual file system (and optionally to disk in the project `buildDir`)
@@ -1458,7 +1879,7 @@ function addServerTemplate(template) {
1458
1879
  function addTypeTemplate(_template, context) {
1459
1880
  const nuxt = useNuxt();
1460
1881
  const template = addTemplate(_template);
1461
- if (!template.filename.endsWith(".d.ts")) throw new Error(`Invalid type template. Filename must end with .d.ts : "${template.filename}"`);
1882
+ if (!template.filename.endsWith(".d.ts")) throw kitDiagnostics.NUXT_B8007({ template: template.filename });
1462
1883
  if (!context || context.nuxt) nuxt.hook("prepare:types", (payload) => {
1463
1884
  payload.references ||= [];
1464
1885
  payload.references.push({ path: template.dst });
@@ -1482,19 +1903,19 @@ function addTypeTemplate(_template, context) {
1482
1903
  * Normalize a nuxt template object
1483
1904
  */
1484
1905
  function normalizeTemplate(template, buildDir) {
1485
- if (!template) throw new Error("Invalid template: " + JSON.stringify(template));
1906
+ if (!template) throw kitDiagnostics.NUXT_B8008({ template: JSON.stringify(template) });
1486
1907
  if (typeof template === "string") template = { src: template };
1487
1908
  else template = { ...template };
1488
1909
  if (template.src) {
1489
- if (!existsSync(template.src)) throw new Error("Template not found: " + template.src);
1910
+ if (!existsSync(template.src)) throw kitDiagnostics.NUXT_B8009({ template: template.src });
1490
1911
  if (!template.filename) {
1491
1912
  const srcPath = parse(template.src);
1492
1913
  template.filename = template.fileName || `${basename(srcPath.dir)}.${srcPath.name}.${hash(template.src).replace(/-/g, "_")}${srcPath.ext}`;
1493
1914
  }
1494
1915
  }
1495
- if (!template.src && !template.getContents) throw new Error("Invalid template. Either `getContents` or `src` should be provided: " + JSON.stringify(template));
1496
- if (!template.filename) throw new Error("Invalid template. `filename` must be provided: " + JSON.stringify(template));
1497
- if (template.filename.endsWith(".d.ts")) template.write = true;
1916
+ if (!template.src && !template.getContents) throw kitDiagnostics.NUXT_B8010({ template: template.filename || template.src || JSON.stringify(template) });
1917
+ if (!template.filename) throw kitDiagnostics.NUXT_B8011({ template: JSON.stringify(template) });
1918
+ if (template.filename.endsWith(".d.ts") || template.filename.endsWith(".d.mts") || template.filename.endsWith(".d.cts")) template.write = true;
1498
1919
  template.dst ||= resolve(buildDir ?? useNuxt().options.buildDir, template.filename);
1499
1920
  return template;
1500
1921
  }
@@ -1531,7 +1952,8 @@ function resolveLayerPaths(dirs, projectBuildDir) {
1531
1952
  join(relativeRootDir, `.config/nuxt.*`),
1532
1953
  join(relativeRootDir, `layers/*/nuxt.config.*`),
1533
1954
  join(relativeRootDir, `layers/*/.config/nuxt.*`),
1534
- join(relativeRootDir, `layers/*/modules/**/*`)
1955
+ join(relativeRootDir, `layers/*/modules/*.*`),
1956
+ join(relativeRootDir, `layers/*/modules/*/*.*`)
1535
1957
  ],
1536
1958
  shared: [
1537
1959
  join(relativeSharedDir, `**/*`),
@@ -1546,13 +1968,15 @@ function resolveLayerPaths(dirs, projectBuildDir) {
1546
1968
  globalDeclarations: [join(relativeRootDir, `*.d.ts`), join(relativeRootDir, `layers/*/*.d.ts`)]
1547
1969
  };
1548
1970
  }
1549
- const EXTENSION_RE = /\b(?:\.d\.[cm]?ts|\.\w+)$/g;
1971
+ async function getPathSubstitution(absolutePath, buildDir) {
1972
+ return relativeWithDot(buildDir, await resolveDeclarationPath(absolutePath));
1973
+ }
1550
1974
  const excludedAlias = [/^@vue\/.*$/, /^#internal\/nuxt/];
1551
1975
  async function _generateTypes(nuxt) {
1552
- const include = new Set(["./nuxt.d.ts"]);
1553
- const nodeInclude = new Set(["./nuxt.node.d.ts"]);
1554
- const sharedInclude = new Set(["./nuxt.shared.d.ts"]);
1555
- const legacyInclude = new Set([...include, ...nodeInclude]);
1976
+ const include = /* @__PURE__ */ new Set(["./nuxt.d.ts"]);
1977
+ const nodeInclude = /* @__PURE__ */ new Set(["./nuxt.node.d.ts"]);
1978
+ const sharedInclude = /* @__PURE__ */ new Set(["./nuxt.shared.d.ts"]);
1979
+ const legacyInclude = /* @__PURE__ */ new Set([...include, ...nodeInclude]);
1556
1980
  const exclude = /* @__PURE__ */ new Set();
1557
1981
  const nodeExclude = /* @__PURE__ */ new Set();
1558
1982
  const sharedExclude = /* @__PURE__ */ new Set();
@@ -1628,7 +2052,7 @@ async function _generateTypes(nuxt) {
1628
2052
  legacyExclude.add(join(relative, "dist/runtime/server"));
1629
2053
  }
1630
2054
  const nestedModulesDirs = [];
1631
- for (const dir of [...nuxt.options.modulesDir].sort()) {
2055
+ for (const dir of nuxt.options.modulesDir.toSorted()) {
1632
2056
  const withSlash = withTrailingSlash$1(dir);
1633
2057
  if (nestedModulesDirs.every((d) => !d.startsWith(withSlash))) nestedModulesDirs.push(withSlash);
1634
2058
  }
@@ -1636,12 +2060,15 @@ async function _generateTypes(nuxt) {
1636
2060
  for (const parent of nestedModulesDirs) hasTypescriptVersionWithModulePreserve ??= await readPackageJSON("typescript", { parent }).then((r) => r?.version && gte(r.version, "5.4.0")).catch(() => void 0);
1637
2061
  hasTypescriptVersionWithModulePreserve ??= true;
1638
2062
  const useDecorators = Boolean(nuxt.options.experimental?.decorators);
2063
+ const isV5OrHigher = (nuxt.options.future?.compatibilityVersion ?? 4) >= 5;
2064
+ const userExclude = nuxt.options.typescript?.tsConfig?.exclude ?? [];
1639
2065
  const tsConfig = defu(nuxt.options.typescript?.tsConfig, {
1640
2066
  compilerOptions: {
1641
2067
  esModuleInterop: true,
1642
2068
  skipLibCheck: true,
1643
2069
  target: "ESNext",
1644
2070
  allowJs: true,
2071
+ allowImportingTsExtensions: true,
1645
2072
  resolveJsonModule: true,
1646
2073
  moduleDetection: "force",
1647
2074
  isolatedModules: true,
@@ -1651,6 +2078,7 @@ async function _generateTypes(nuxt) {
1651
2078
  noUncheckedIndexedAccess: true,
1652
2079
  forceConsistentCasingInFileNames: true,
1653
2080
  noImplicitOverride: true,
2081
+ ...isV5OrHigher ? { noUncheckedSideEffectImports: true } : {},
1654
2082
  ...useDecorators ? { experimentalDecorators: false } : {},
1655
2083
  module: hasTypescriptVersionWithModulePreserve ? "preserve" : "ESNext",
1656
2084
  noEmit: true,
@@ -1661,6 +2089,7 @@ async function _generateTypes(nuxt) {
1661
2089
  "dom.iterable",
1662
2090
  "webworker"
1663
2091
  ],
2092
+ libReplacement: false,
1664
2093
  jsx: "preserve",
1665
2094
  jsxImportSource: "vue",
1666
2095
  types: [],
@@ -1679,6 +2108,7 @@ async function _generateTypes(nuxt) {
1679
2108
  skipLibCheck: tsConfig.compilerOptions?.skipLibCheck,
1680
2109
  target: tsConfig.compilerOptions?.target,
1681
2110
  allowJs: tsConfig.compilerOptions?.allowJs,
2111
+ allowImportingTsExtensions: tsConfig.compilerOptions?.allowImportingTsExtensions,
1682
2112
  resolveJsonModule: tsConfig.compilerOptions?.resolveJsonModule,
1683
2113
  moduleDetection: tsConfig.compilerOptions?.moduleDetection,
1684
2114
  isolatedModules: tsConfig.compilerOptions?.isolatedModules,
@@ -1706,6 +2136,7 @@ async function _generateTypes(nuxt) {
1706
2136
  skipLibCheck: tsConfig.compilerOptions?.skipLibCheck,
1707
2137
  target: tsConfig.compilerOptions?.target,
1708
2138
  allowJs: tsConfig.compilerOptions?.allowJs,
2139
+ allowImportingTsExtensions: tsConfig.compilerOptions?.allowImportingTsExtensions,
1709
2140
  resolveJsonModule: tsConfig.compilerOptions?.resolveJsonModule,
1710
2141
  moduleDetection: tsConfig.compilerOptions?.moduleDetection,
1711
2142
  isolatedModules: tsConfig.compilerOptions?.isolatedModules,
@@ -1732,6 +2163,7 @@ async function _generateTypes(nuxt) {
1732
2163
  tsConfig.compilerOptions ||= {};
1733
2164
  tsConfig.compilerOptions.paths ||= {};
1734
2165
  tsConfig.include ||= [];
2166
+ tsConfig.exclude ||= [];
1735
2167
  const importPaths = nuxt.options.modulesDir.map((d) => directoryToURL(d));
1736
2168
  for (const alias in aliases) {
1737
2169
  if (excludedAlias.some((re) => re.test(alias))) continue;
@@ -1758,7 +2190,7 @@ async function _generateTypes(nuxt) {
1758
2190
  tsConfig.compilerOptions.paths[alias] = [relativePath];
1759
2191
  tsConfig.compilerOptions.paths[`${alias}/*`] = [`${relativePath}/*`];
1760
2192
  } else {
1761
- const path = stats?.isFile() ? relativePath.replace(EXTENSION_RE, "") : aliases[alias];
2193
+ const path = stats?.isFile() ? await getPathSubstitution(absolutePath, nuxt.options.buildDir) : aliases[alias];
1762
2194
  tsConfig.compilerOptions.paths[alias] = [path];
1763
2195
  }
1764
2196
  }
@@ -1791,18 +2223,18 @@ async function _generateTypes(nuxt) {
1791
2223
  const legacyTsConfig = defu({}, {
1792
2224
  ...tsConfig,
1793
2225
  include: [...tsConfig.include, ...legacyInclude],
1794
- exclude: [...legacyExclude]
2226
+ exclude: [...userExclude, ...legacyExclude]
1795
2227
  });
2228
+ const nonRootLayerDirs = layerDirs.map((dirs) => dirs.root).filter((root) => !rootDirWithSlash.startsWith(root));
1796
2229
  async function resolveConfig(tsConfig) {
1797
2230
  for (const alias in tsConfig.compilerOptions.paths) {
1798
2231
  const paths = tsConfig.compilerOptions.paths[alias];
1799
2232
  tsConfig.compilerOptions.paths[alias] = [...new Set(await Promise.all(paths.map(async (path) => {
1800
2233
  if (!isAbsolute(path)) return path;
1801
- const stats = await promises.stat(path).catch(() => null);
1802
- return relativeWithDot(nuxt.options.buildDir, stats?.isFile() ? path.replace(EXTENSION_RE, "") : path);
2234
+ return (await promises.stat(path).catch(() => null))?.isFile() ? getPathSubstitution(path, nuxt.options.buildDir) : relativeWithDot(nuxt.options.buildDir, path);
1803
2235
  })))];
1804
2236
  }
1805
- sortTsPaths(tsConfig.compilerOptions.paths);
2237
+ tsConfig.compilerOptions.paths = sortTsPaths(tsConfig.compilerOptions.paths, nonRootLayerDirs, nuxt.options.buildDir, nuxt.options.typescript?.hoist ?? []);
1806
2238
  tsConfig.include = [...new Set(tsConfig.include.map((p) => isAbsolute(p) ? relativeWithDot(nuxt.options.buildDir, p) : p))];
1807
2239
  tsConfig.exclude = [...new Set(tsConfig.exclude.map((p) => isAbsolute(p) ? relativeWithDot(nuxt.options.buildDir, p) : p))];
1808
2240
  }
@@ -1860,12 +2292,48 @@ async function writeTypes(nuxt) {
1860
2292
  promises.writeFile(sharedDeclarationPath, sharedDeclaration)
1861
2293
  ]);
1862
2294
  }
1863
- function sortTsPaths(paths) {
1864
- for (const pathKey in paths) if (pathKey.startsWith("#build")) {
1865
- const pathValue = paths[pathKey];
1866
- delete paths[pathKey];
1867
- paths[pathKey] = pathValue;
2295
+ /**
2296
+ * Sort the paths in the tsconfig.json file, so
2297
+ * - Hoisted package paths stay at the top (`typescript.hoist`)
2298
+ * - Custom layer aliases follow, then generic `#layers/*` aliases
2299
+ * - Generic `~`/`@` aliases come after layer aliases
2300
+ * - `#build` alias is at the bottom (https://github.com/nuxt/nuxt/issues/30325)
2301
+ */
2302
+ function sortTsPaths(paths, layerDirs, buildDir, hoist) {
2303
+ const hoistKeys = new Set(hoist);
2304
+ const hoistPaths = {};
2305
+ const customLayerPaths = {};
2306
+ const genericLayerPaths = {};
2307
+ const otherPaths = {};
2308
+ const buildPaths = {};
2309
+ for (const pathKey in paths) {
2310
+ if (pathKey.startsWith("#build")) {
2311
+ buildPaths[pathKey] = paths[pathKey];
2312
+ continue;
2313
+ }
2314
+ if (isHoistPathKey(pathKey, hoistKeys)) {
2315
+ hoistPaths[pathKey] = paths[pathKey];
2316
+ continue;
2317
+ }
2318
+ if (layerDirs.length && paths[pathKey].some((target) => isPathUnderLayerDirs(target, buildDir, layerDirs))) if (pathKey.startsWith("#layers")) genericLayerPaths[pathKey] = paths[pathKey];
2319
+ else customLayerPaths[pathKey] = paths[pathKey];
2320
+ else otherPaths[pathKey] = paths[pathKey];
1868
2321
  }
2322
+ return {
2323
+ ...hoistPaths,
2324
+ ...customLayerPaths,
2325
+ ...genericLayerPaths,
2326
+ ...otherPaths,
2327
+ ...buildPaths
2328
+ };
2329
+ }
2330
+ const PATH_WILDCARD_RE = /\/?\*$/;
2331
+ function isHoistPathKey(pathKey, hoistKeys) {
2332
+ return hoistKeys.has(pathKey.replace(PATH_WILDCARD_RE, ""));
2333
+ }
2334
+ function isPathUnderLayerDirs(target, buildDir, layerDirs) {
2335
+ const absolute = withTrailingSlash$1(resolve(buildDir, target.replace(PATH_WILDCARD_RE, "")));
2336
+ return layerDirs.some((dir) => absolute.startsWith(dir));
1869
2337
  }
1870
2338
  function renderReference(ref, baseDir) {
1871
2339
  return `/// <reference ${"path" in ref ? `path="${isAbsolute(ref.path) ? relative(baseDir, ref.path) : ref.path}"` : `types="${ref.types}"`} />`;
@@ -1890,7 +2358,12 @@ function addLayout(template, name) {
1890
2358
  ...nuxt?.options.alias || {},
1891
2359
  ...strippedAtAliases
1892
2360
  }).pop() || app.layouts[layoutName].file;
1893
- return logger.warn(`Not overriding \`${layoutName}\` (provided by \`${relativePath}\`) with \`${src || filename}\`.`);
2361
+ pageDiagnostics.NUXT_B4014({
2362
+ layoutName,
2363
+ existingPath: relativePath,
2364
+ newPath: src || filename
2365
+ });
2366
+ return;
1894
2367
  }
1895
2368
  app.layouts[layoutName] = {
1896
2369
  file: join("#build", filename),
@@ -1924,13 +2397,85 @@ function addRouteMiddleware(input, options = {}) {
1924
2397
  const foundPath = app.middleware[find].path;
1925
2398
  if (foundPath === middleware.path) continue;
1926
2399
  if (options.override === true) app.middleware[find] = { ...middleware };
1927
- else logger.warn(`'${middleware.name}' middleware already exists at '${foundPath}'. You can set \`override: true\` to replace it.`);
2400
+ else pageDiagnostics.NUXT_B4013({
2401
+ name: middleware.name,
2402
+ foundPath
2403
+ });
1928
2404
  } else if (options.prepend === true) app.middleware.unshift({ ...middleware });
1929
2405
  else app.middleware.push({ ...middleware });
1930
2406
  }
1931
2407
  });
1932
2408
  }
1933
2409
  //#endregion
2410
+ //#region src/diagnostics/plugins.ts
2411
+ /**
2412
+ * B2xxx
2413
+ * Plugin diagnostics (`addPlugin`, plugin metadata, plugin ordering).
2414
+ *
2415
+ * @internal
2416
+ */
2417
+ const pluginDiagnostics = /* #__PURE__ */ defineDiagnostics({
2418
+ docsBase,
2419
+ reporters,
2420
+ codes: {
2421
+ NUXT_B2001: {
2422
+ why: (p) => `The second argument to \`${p.name}\` is a \`${p.type}\`, not an object literal.`,
2423
+ fix: "Pass an object literal as the second argument, e.g. `defineNuxtPlugin(() => {}, { name: 'my-plugin' })`.",
2424
+ docs: false
2425
+ },
2426
+ NUXT_B2002: {
2427
+ why: "Plugin options contain spread elements or computed keys, which are not supported.",
2428
+ fix: "Use static properties instead.",
2429
+ docs: false
2430
+ },
2431
+ NUXT_B2003: {
2432
+ why: "`dependsOn` is not an array of string literals.",
2433
+ fix: "Use string literals in the `dependsOn` array, e.g. `dependsOn: ['my-plugin']`.",
2434
+ docs: false
2435
+ },
2436
+ NUXT_B2004: {
2437
+ why: (p) => `Plugin \`${p.src}\` has no content.`,
2438
+ fix: "Add content to the plugin file, or remove it from the `plugins/` directory.",
2439
+ docs: false
2440
+ },
2441
+ NUXT_B2005: {
2442
+ why: (p) => `Plugin \`${p.src}\` has no default export and will be ignored at build time.`,
2443
+ fix: "Add `export default defineNuxtPlugin(() => {})` to your plugin.",
2444
+ docs: false
2445
+ },
2446
+ NUXT_B2006: {
2447
+ why: (p) => `Error parsing plugin \`${p.src}\`.`,
2448
+ fix: "Check the plugin file for syntax errors.",
2449
+ docs: false
2450
+ },
2451
+ NUXT_B2007: {
2452
+ why: (p) => `Plugin \`${p.src}\` is not wrapped in \`defineNuxtPlugin\`.`,
2453
+ fix: "Wrap your plugin with `defineNuxtPlugin`. This may enable enhancements in future.",
2454
+ docs: false
2455
+ },
2456
+ NUXT_B2008: {
2457
+ why: (p) => `Plugin \`${p.name}\` depends on \`${p.missing}\` but they are not registered.`,
2458
+ fix: "Register the missing dependency plugins, or remove them from the `dependsOn` array.",
2459
+ docs: false
2460
+ },
2461
+ NUXT_B2009: {
2462
+ why: (p) => `Circular dependency detected in plugins: ${p.cycle}.`,
2463
+ fix: "Restructure the plugin `dependsOn` declarations to break the cycle.",
2464
+ docs: false
2465
+ },
2466
+ NUXT_B2010: {
2467
+ why: (p) => `Failed to parse static properties from plugin \`${p.src}\`, falling back to non-optimized runtime meta.`,
2468
+ fix: "Use an object literal with static values as the second argument to `defineNuxtPlugin()`, and check the plugin file for syntax errors or unsupported constructs in the metadata.",
2469
+ docs: false
2470
+ },
2471
+ NUXT_B2011: {
2472
+ why: (p) => `Invalid plugin \`${p.src}\`. The \`src\` option is required.`,
2473
+ fix: "Pass a string path, or an object with a `src` property, to `addPlugin()`.",
2474
+ docs: false
2475
+ }
2476
+ }
2477
+ });
2478
+ //#endregion
1934
2479
  //#region src/plugin.ts
1935
2480
  /**
1936
2481
  * Normalize a nuxt plugin object
@@ -1940,7 +2485,7 @@ function normalizePlugin(plugin) {
1940
2485
  if (typeof plugin === "string") plugin = { src: plugin };
1941
2486
  else plugin = { ...plugin };
1942
2487
  if (pluginSymbol in plugin) return plugin;
1943
- if (!plugin.src) throw new Error("Invalid plugin. src option is required: " + JSON.stringify(plugin));
2488
+ if (!plugin.src) throw pluginDiagnostics.NUXT_B2011({ src: JSON.stringify(plugin) });
1944
2489
  plugin.src = normalize(resolveAlias(plugin.src));
1945
2490
  if (!existsSync(plugin.src) && isAbsolute$1(plugin.src)) try {
1946
2491
  plugin.src = resolveModulePath(plugin.src, { extensions: tryUseNuxt()?.options.extensions ?? [
@@ -1978,4 +2523,317 @@ function addPluginTemplate(plugin, opts = {}) {
1978
2523
  }, opts);
1979
2524
  }
1980
2525
  //#endregion
1981
- export { addBuildPlugin, addComponent, addComponentExports, addComponentsDir, addDevServerHandler, addImports, addImportsDir, addImportsSources, addLayout, addPlugin, addPluginTemplate, addPrerenderRoutes, addRouteMiddleware, addRspackPlugin, addServerHandler, addServerImports, addServerImportsDir, addServerPlugin, addServerScanDir, addServerTemplate, addTemplate, addTypeTemplate, addVitePlugin, addWebpackPlugin, assertNuxtCompatibility, buildNuxt, checkNuxtCompatibility, createIsIgnored, createResolver, defineNuxtModule, directoryToURL, extendNuxtSchema, extendPages, extendRouteRules, extendRspackConfig, extendViteConfig, extendWebpackConfig, findPath, getDirectory, getLayerDirectories, getNuxtCtx, getNuxtModuleVersion, getNuxtVersion, hasNuxtCompatibility, hasNuxtModule, hasNuxtModuleCompatibility, importModule, installModule, installModules, isIgnored, isNuxt2, isNuxt3, isNuxtMajorVersion, loadNuxt, loadNuxtConfig, loadNuxtModuleInstance, logger, normalizeModuleTranspilePath, normalizePlugin, normalizeSemanticVersion, normalizeTemplate, nuxtCtx, requireModule, resolveAlias, resolveFiles, resolveIgnorePatterns, resolveModule, resolveModuleWithOptions, resolveNuxtModule, resolvePath, runWithNuxtContext, setGlobalHead, tryImportModule, tryRequireModule, tryResolveModule, tryUseNuxt, updateRuntimeConfig, updateTemplates, useLogger, useNitro, useNuxt, useRuntimeConfig, writeTypes };
2526
+ //#region src/diagnostics/build.ts
2527
+ /**
2528
+ * B1xxx
2529
+ * Build / compilation diagnostics.
2530
+ *
2531
+ * @internal
2532
+ */
2533
+ const buildDiagnostics = /* #__PURE__ */ defineDiagnostics({
2534
+ docsBase,
2535
+ reporters,
2536
+ codes: {
2537
+ NUXT_B1001: {
2538
+ why: (p) => `Could not compile template \`${p.filename}\`.`,
2539
+ fix: (p) => p.src ? `Check the template source file at \`${p.src}\` for syntax errors.` : "Check the `getContents` function of this template for errors.",
2540
+ docs: false
2541
+ },
2542
+ NUXT_B1002: {
2543
+ why: (p) => `Error reading template from \`${p.src}\`.`,
2544
+ fix: "Check that the template `src` path exists and is readable.",
2545
+ docs: false
2546
+ },
2547
+ NUXT_B1003: {
2548
+ why: "Invalid template. Templates must have either `src` or `getContents`.",
2549
+ fix: "Add a `getContents` function or a `src` path to the `addTemplate()` call.",
2550
+ docs: false
2551
+ },
2552
+ NUXT_B1004: {
2553
+ why: "Failed to install dependencies.",
2554
+ fix: (p) => `Try installing manually with \`npm install ${p.packages}\`.`,
2555
+ docs: false
2556
+ },
2557
+ NUXT_B1005: {
2558
+ why: (p) => `Plugin \`${p.plugin}\` failed to scan file \`${p.file}\`.`,
2559
+ fix: "Check the file for syntax errors, or report this issue to the plugin author.",
2560
+ docs: false
2561
+ },
2562
+ NUXT_B1006: {
2563
+ why: (p) => `Cannot read file \`${p.file}\`.`,
2564
+ fix: "Check that the file exists and has correct permissions.",
2565
+ docs: false
2566
+ },
2567
+ NUXT_B1007: {
2568
+ why: (p) => `Error in \`afterScan\` hook of plugin \`${p.plugin}\`.`,
2569
+ fix: "Check the plugin implementation or report this issue to the plugin author.",
2570
+ docs: false
2571
+ },
2572
+ NUXT_B1008: {
2573
+ why: (p) => `No factory function found for \`${p.function}\` in file \`${p.file}\`. This is a Nuxt bug.`,
2574
+ fix: "Please report this issue at https://github.com/nuxt/nuxt/issues with the file contents.",
2575
+ docs: false
2576
+ },
2577
+ NUXT_B1009: {
2578
+ why: (p) => `Duplicate keyed function name \`${p.functionName}\`${p.name && p.functionName !== p.name ? ` defined as \`${p.name}\`` : ""} with ${p.source ? `the same source \`${p.source}\`` : "no source"} found. Overwriting the existing entry.`,
2579
+ fix: "Ensure each keyed function has a unique name, or use a different source to distinguish them.",
2580
+ docs: false
2581
+ },
2582
+ NUXT_B1010: {
2583
+ why: (p) => `Failed to read file \`${p.file}\` as it changed during read.`,
2584
+ fix: "The file was modified while being read, usually by a concurrent process writing to it. Try restarting the build.",
2585
+ docs: false
2586
+ },
2587
+ NUXT_B1011: {
2588
+ why: (p) => `Failed to read file \`${p.file}\`.`,
2589
+ fix: "Check that the file exists and is readable, or try clearing the build cache with `nuxi clean`.",
2590
+ docs: false
2591
+ },
2592
+ NUXT_B1012: {
2593
+ why: (p) => `Skipping unsafe cache path: ${p.path}. This cache file has a path that escapes the project directory (possible path traversal).`,
2594
+ fix: "Delete the cache with `nuxi clean` and rebuild.",
2595
+ docs: false
2596
+ },
2597
+ NUXT_B1013: {
2598
+ why: (p) => `Failed to restore cached file \`${p.file}\`.`,
2599
+ fix: "Try clearing the build cache with `nuxi clean` and rebuilding from scratch.",
2600
+ docs: false
2601
+ },
2602
+ NUXT_B1014: {
2603
+ why: "Problem checking for external configuration files.",
2604
+ fix: "This is likely a transient file system error. If it persists, check file permissions in your project root.",
2605
+ docs: false
2606
+ },
2607
+ NUXT_B1015: {
2608
+ why: "Falling back to `chokidar-granular` as `@parcel/watcher` cannot be resolved in your project.",
2609
+ fix: "Install `@parcel/watcher` for better performance: `npm install -D @parcel/watcher`.",
2610
+ docs: false
2611
+ },
2612
+ NUXT_B1016: {
2613
+ why: "Failed to set up the `@parcel/watcher` file watcher.",
2614
+ fix: "This is likely an environment or file system issue. Watching for file changes may not work; restart the dev server and, if the problem persists, report it.",
2615
+ docs: false
2616
+ },
2617
+ NUXT_B1017: {
2618
+ why: (p) => `Loading \`${p.builder}\` builder failed.`,
2619
+ fix: (p) => `Run \`npm install ${p.builder}\` to install it.`,
2620
+ docs: false
2621
+ },
2622
+ NUXT_B1018: {
2623
+ why: (p) => `Loading \`${p.builder}\` server builder failed.`,
2624
+ fix: (p) => `Run \`npm install ${p.builder}\` to install it.`,
2625
+ docs: false
2626
+ },
2627
+ NUXT_B1019: {
2628
+ why: (p) => `Unknown component mode \`${p.mode}\`. This might be an internal Nuxt bug.`,
2629
+ fix: "If you are a module author, ensure the component `mode` is set to `client`, `server`, or `all`. Otherwise, please report this issue.",
2630
+ docs: false
2631
+ },
2632
+ NUXT_B1020: {
2633
+ why: "`experimental.watcher: \"builder\"` is set but the active builder does not implement `setupWatcher`. Falling back to the default file watcher.",
2634
+ fix: "Remove `experimental.watcher` from your `nuxt.config`, or use a builder that supports its own watcher.",
2635
+ docs: false
2636
+ }
2637
+ }
2638
+ });
2639
+ //#endregion
2640
+ //#region src/diagnostics/config.ts
2641
+ /**
2642
+ * B5xxx
2643
+ * Configuration diagnostics.
2644
+ *
2645
+ * @internal
2646
+ */
2647
+ const configDiagnostics = /* #__PURE__ */ defineDiagnostics({
2648
+ docsBase,
2649
+ reporters,
2650
+ codes: {
2651
+ NUXT_B5001: {
2652
+ why: (p) => `No \`compatibilityDate\` is set in \`nuxt.config\`, so the \`${p.fallback}\` fallback is being used.`,
2653
+ fix: (p) => `Add \`compatibilityDate: '${p.latest}'\` to your \`nuxt.config.ts\`.`
2654
+ },
2655
+ NUXT_B5002: {
2656
+ why: (p) => `\`@nuxt/webpack-builder\` could not be installed in \`${p.rootDir}\`.`,
2657
+ fix: "Install it manually with `npm install -D @nuxt/webpack-builder`, or change the `builder` option to `vite` in `nuxt.config`.",
2658
+ docs: false
2659
+ },
2660
+ NUXT_B5003: {
2661
+ why: (p) => `The \`app\` namespace is reserved for Nuxt and exposed to the browser, but \`runtimeConfig.app.${p.key}\` is set.`,
2662
+ fix: "Move the key to `runtimeConfig.public` or a custom namespace."
2663
+ },
2664
+ NUXT_B5004: {
2665
+ why: (p) => `External configuration files are not supported: ${p.files}.`,
2666
+ fix: "Move these configurations into `nuxt.config.ts` and delete the external config files."
2667
+ },
2668
+ NUXT_B5005: {
2669
+ why: (p) => `Nuxt schema could not be loaded from \`${p.filePath}\`.`,
2670
+ fix: "Ensure the file exports a valid object with `defineNuxtSchema()` or as a plain object.",
2671
+ docs: false
2672
+ },
2673
+ NUXT_B5006: {
2674
+ why: (p) => `\`${p.option}\` is used in dev mode, which causes a memory leak.`,
2675
+ fix: "Remove the hash option from your webpack config.",
2676
+ docs: false
2677
+ },
2678
+ NUXT_B5007: {
2679
+ why: "The webpack server config `target` is not set to \"node\".",
2680
+ fix: "Set `target: \"node\"` in your webpack server configuration.",
2681
+ docs: false
2682
+ },
2683
+ NUXT_B5009: {
2684
+ why: "`@parcel/watcher` cannot be resolved in your project, so `chokidar` is being used instead.",
2685
+ fix: "Install `@parcel/watcher` for better file watching: `npm install -D @parcel/watcher`.",
2686
+ docs: false
2687
+ },
2688
+ NUXT_B5010: {
2689
+ why: (p) => `Required packages are not installed: ${p.names}.`,
2690
+ fix: (p) => `Run \`npm install ${p.install}\` to install them.`,
2691
+ docs: false
2692
+ },
2693
+ NUXT_B5011: {
2694
+ why: (p) => `Package \`${p.name}\` is missing.`,
2695
+ fix: (p) => `Run \`npx nuxt add ${p.name}\` to install it.`,
2696
+ docs: false
2697
+ }
2698
+ }
2699
+ });
2700
+ //#endregion
2701
+ //#region src/diagnostics/head.ts
2702
+ /**
2703
+ * B6xxx
2704
+ * Head / auto-import diagnostics.
2705
+ *
2706
+ * @internal
2707
+ */
2708
+ const headDiagnostics = /* #__PURE__ */ defineDiagnostics({
2709
+ docsBase,
2710
+ reporters,
2711
+ codes: {
2712
+ NUXT_B6001: {
2713
+ why: (p) => `\`${p.file}\` imports head composables directly from \`${p.module}\`, which loses Nuxt's type safety.`,
2714
+ fix: "Import from `#imports` instead.",
2715
+ docs: false
2716
+ },
2717
+ NUXT_B6002: {
2718
+ why: (p) => `\`${p.name}\` is already auto-imported by Nuxt as a built-in, and overriding it will likely cause issues.`,
2719
+ fix: (p) => `Rename \`${p.name}\` in \`${p.file}\` so it no longer collides with the built-in auto-import.`,
2720
+ docs: false
2721
+ },
2722
+ NUXT_B6003: {
2723
+ why: "`unhead.legacy` is deprecated and will be removed.",
2724
+ fix: "Remove deprecated head patterns (`hid`, `vmid`, `children`, `body: true`) and resolve promise values before passing them to `useHead`.",
2725
+ docs: false
2726
+ },
2727
+ NUXT_B6004: {
2728
+ why: "`experimental.headNext` is deprecated. CAPO sorting is now the default.",
2729
+ fix: "Remove `experimental.headNext` from your `nuxt.config`, or set `unhead.legacy: true` to opt out temporarily.",
2730
+ docs: false
2731
+ }
2732
+ }
2733
+ });
2734
+ //#endregion
2735
+ //#region src/diagnostics/bundler.ts
2736
+ /**
2737
+ * B7xxx
2738
+ * Bundler (Vite / webpack / Nitro) diagnostics.
2739
+ *
2740
+ * @internal
2741
+ */
2742
+ const bundlerDiagnostics = /* #__PURE__ */ defineDiagnostics({
2743
+ docsBase,
2744
+ reporters,
2745
+ codes: {
2746
+ NUXT_B7001: {
2747
+ why: "`rollup-plugin-visualizer` is not installed, so bundle analysis cannot run.",
2748
+ fix: "Run `npm install -D rollup-plugin-visualizer` to enable bundle analysis.",
2749
+ docs: false
2750
+ },
2751
+ NUXT_B7002: {
2752
+ why: (p) => `Some \`vite.optimizeDeps.include\` entries could not be resolved: ${p.deps}.`,
2753
+ fix: "Remove or correct these entries in the `vite.optimizeDeps.include` array of your `nuxt.config.ts`. Report entries added by a Nuxt module to the module author.",
2754
+ docs: false
2755
+ },
2756
+ NUXT_B7003: {
2757
+ why: "The server-side bundle produced more than one JS entry file.",
2758
+ fix: "Avoid using `optimization.splitChunks` in the server config.",
2759
+ docs: false
2760
+ },
2761
+ NUXT_B7004: {
2762
+ why: (p) => `Webpack entry \`${p.entryName}\` was not found.`,
2763
+ fix: (p) => `Check that the \`entry\` option in your webpack configuration points to an existing file. Expected entry name: \`${p.entryName}\`.`,
2764
+ docs: false
2765
+ },
2766
+ NUXT_B7005: {
2767
+ why: (p) => `No client entry was found in \`rollupOptions.input\`; expected an \`entry\` key or a string input but received ${p.input}.`,
2768
+ fix: "Set `vite.build.rollupOptions.input` to a string or an object with an `entry` key in your `nuxt.config`.",
2769
+ docs: false
2770
+ },
2771
+ NUXT_B7006: {
2772
+ why: (p) => `No server entry was found in \`rollupOptions.input\`; expected a \`server\` key or a string input but received ${p.input}.`,
2773
+ fix: "Set `vite.build.rollupOptions.input` to a string or an object with a `server` key in your `nuxt.config`.",
2774
+ docs: false
2775
+ },
2776
+ NUXT_B7007: {
2777
+ why: (p) => `The PostCSS plugin \`${p.pluginName}\` could not be loaded.`,
2778
+ fix: (p) => `Run \`npm install -D ${p.pluginName}\` to install the PostCSS plugin.`,
2779
+ docs: false
2780
+ },
2781
+ NUXT_B7008: {
2782
+ why: "`@vitejs/plugin-vue-jsx` is not installed, so JSX support is unavailable.",
2783
+ fix: "Run `npm install -D @vitejs/plugin-vue-jsx` to install it.",
2784
+ docs: false
2785
+ },
2786
+ NUXT_B7009: {
2787
+ why: (p) => `The Babel dependencies required for decorator support are missing: ${p.deps}.`,
2788
+ fix: (p) => `Run \`npm install -D ${p.install}\` to install the required Babel decorator dependencies.`,
2789
+ docs: false
2790
+ },
2791
+ NUXT_B7011: {
2792
+ why: (p) => `The PostCSS plugin \`${p.pluginName}\` could not be imported, which is unexpected.`,
2793
+ fix: (p) => `Run \`npm install -D ${p.pluginName}\` to install it, or report this issue at https://github.com/nuxt/nuxt/issues.`,
2794
+ docs: false
2795
+ },
2796
+ NUXT_B7012: {
2797
+ why: (p) => `A ViteNode socket payload of ${p.requiredSize} bytes exceeds the internal buffer limit of ${p.maxSize} bytes.`,
2798
+ fix: "Reduce the payload size sent through the ViteNode socket.",
2799
+ docs: false
2800
+ },
2801
+ NUXT_B7013: {
2802
+ why: "The ViteNode socket server was started without a configured socket path.",
2803
+ fix: "This is likely an internal Nuxt bug. Please report it at https://github.com/nuxt/nuxt/issues.",
2804
+ docs: false
2805
+ },
2806
+ NUXT_B7014: {
2807
+ why: (p) => `The webpack \`${p.name}\` build failed with errors.`,
2808
+ fix: "Fix the build errors listed above. If the errors are unclear, try running `nuxi clean` and rebuilding.",
2809
+ docs: false
2810
+ },
2811
+ NUXT_B7015: {
2812
+ why: "Payload extraction is disabled, which is suboptimal for full-static output.",
2813
+ fix: "Set `experimental.payloadExtraction` to `true` or `'client'`.",
2814
+ docs: false
2815
+ },
2816
+ NUXT_B7016: {
2817
+ why: (p) => `The configured \`spaLoadingTemplate\` path does not exist: \`${p.path}\`.`,
2818
+ fix: "Point `spaLoadingTemplate` in `nuxt.config` at an existing HTML file, or set it to `true` to use the default template.",
2819
+ docs: false
2820
+ },
2821
+ NUXT_B7017: {
2822
+ why: "Could not find the Nuxt dev server to attach Rspack HMR to; hot module replacement will be disabled.",
2823
+ fix: "This is likely an internal Nuxt bug. Please report it with a reproduction.",
2824
+ docs: false
2825
+ },
2826
+ NUXT_B7018: {
2827
+ why: "Failed to restrict vite-node socket permissions; closing the socket.",
2828
+ fix: "Check that the temporary directory used for the vite-node socket is writable and supports `chmod`.",
2829
+ docs: false
2830
+ },
2831
+ NUXT_B7019: {
2832
+ why: "The server webpack build does not externalize dependencies.",
2833
+ fix: "Externalize dependencies in the server build (`externals`) for better build performance.",
2834
+ docs: false
2835
+ }
2836
+ }
2837
+ });
2838
+ //#endregion
2839
+ export { addBuildPlugin, addComponent, addComponentExports, addComponentsDir, addDevServerHandler, addImports, addImportsDir, addImportsSources, addLayout, addPlugin, addPluginTemplate, addPrerenderRoutes, addRouteMiddleware, addRspackPlugin, addServerHandler, addServerImports, addServerImportsDir, addServerPlugin, addServerScanDir, addServerTemplate, addTemplate, addTypeTemplate, addVitePlugin, addWebpackPlugin, assertNuxtCompatibility, buildDiagnostics, buildNuxt, bundlerDiagnostics, checkNuxtCompatibility, componentDiagnostics, configDiagnostics, createIsIgnored, createResolver, defineNuxtModule, directoryToURL, extendNuxtSchema, extendPages, extendRouteRules, extendRspackConfig, extendViteConfig, extendWebpackConfig, findPath, getDirectory, getLayerDirectories, getNuxtCtx, getNuxtModuleVersion, getNuxtVersion, hasNuxtCompatibility, hasNuxtModule, hasNuxtModuleCompatibility, headDiagnostics, importModule, installModule, installModules, isIgnored, isNuxt2, isNuxt3, isNuxtMajorVersion, loadNuxt, loadNuxtConfig, loadNuxtModuleInstance, logger, normalizeModuleTranspilePath, normalizePlugin, normalizeSemanticVersion, normalizeTemplate, nuxtCtx, packageName, pageDiagnostics, pluginDiagnostics, requireModule, resolveAlias, resolveDeclarationPath, resolveFiles, resolveIgnorePatterns, resolveModule, resolveModuleWithOptions, resolveNuxtModule, resolvePath, resolveTypePaths, runWithNuxtContext, setBuildOutput, setGlobalHead, tryImportModule, tryRequireModule, tryResolveModule, tryUseNuxt, updateAppConfig, updateRuntimeConfig, updateTemplates, useLogger, useNitro, useNuxt, useRuntimeConfig, writeTypes };