@nuxt/kit 4.2.2 → 4.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,1988 +1,1685 @@
1
- import { performance } from 'node:perf_hooks';
2
- import defu$1, { defu, createDefu } from 'defu';
3
- import { applyDefaults } from 'untyped';
4
- import { consola } from 'consola';
5
- import { AsyncLocalStorage } from 'node:async_hooks';
6
- import { getContext, createContext } from 'unctx';
7
- import satisfies from 'semver/functions/satisfies.js';
8
- import { readPackageJSON, resolvePackageJSON } from 'pkg-types';
9
- import { existsSync, readFileSync, promises, lstatSync } from 'node:fs';
10
- import { fileURLToPath, pathToFileURL } from 'node:url';
11
- import { resolve, relative, join, dirname, normalize, isAbsolute, basename, parse } from 'pathe';
12
- import { createJiti } from 'jiti';
13
- import { parseNodeModulePath, interopDefault, lookupNodeModuleSubpath, resolveModuleExportNames } from 'mlly';
14
- import { resolveModulePath, resolveModuleURL } from 'exsolve';
15
- import { isRelative, withTrailingSlash as withTrailingSlash$2 } from 'ufo';
16
- import { read, update } from 'rc9';
17
- import semver, { gte } from 'semver';
18
- import { captureStackTrace } from 'errx';
19
- import process from 'node:process';
20
- import { glob } from 'tinyglobby';
21
- import { resolveAlias as resolveAlias$1, reverseResolveAlias } from 'pathe/utils';
22
- import ignore from 'ignore';
23
- import { loadConfig } from 'c12';
24
- import destr from 'destr';
25
- import { snakeCase, pascalCase, kebabCase } from 'scule';
26
- import { klona } from 'klona';
27
- import { hash } from 'ohash';
28
- import { isAbsolute as isAbsolute$1 } from 'node:path';
29
-
1
+ import { performance } from "node:perf_hooks";
2
+ import { createDefu, defu } from "defu";
3
+ import { applyDefaults } from "untyped";
4
+ import { consola } from "consola";
5
+ import { AsyncLocalStorage } from "node:async_hooks";
6
+ import { createContext, getContext } from "unctx";
7
+ import satisfies from "semver/functions/satisfies.js";
8
+ import { readPackageJSON, resolvePackageJSON } from "pkg-types";
9
+ import { existsSync, lstatSync, promises, readFileSync } from "node:fs";
10
+ import { fileURLToPath, pathToFileURL } from "node:url";
11
+ import { basename, dirname, isAbsolute, join, normalize, parse, relative, resolve } from "pathe";
12
+ import { createJiti } from "jiti";
13
+ import { interopDefault, lookupNodeModuleSubpath, parseNodeModulePath, resolveModuleExportNames } from "mlly";
14
+ import { resolveModulePath, resolveModuleURL } from "exsolve";
15
+ import { isRelative, withTrailingSlash, withoutTrailingSlash } from "ufo";
16
+ import { read, update } from "rc9";
17
+ import semver, { gte } from "semver";
18
+ import { captureStackTrace } from "errx";
19
+ import process from "node:process";
20
+ import { glob } from "tinyglobby";
21
+ import { resolveAlias as resolveAlias$1, reverseResolveAlias } from "pathe/utils";
22
+ import ignore from "ignore";
23
+ import { loadConfig } from "c12";
24
+ import destr from "destr";
25
+ import { kebabCase, pascalCase, snakeCase } from "scule";
26
+ import { klona } from "klona";
27
+ import { hash } from "ohash";
28
+ import { isAbsolute as isAbsolute$1 } from "node:path";
30
29
  const logger = consola;
31
30
  function useLogger(tag, options = {}) {
32
- return tag ? logger.create(options).withTag(tag) : logger;
31
+ return tag ? logger.create(options).withTag(tag) : logger;
33
32
  }
34
-
35
33
  const nuxtCtx = getContext("nuxt");
36
34
  const asyncNuxtStorage = createContext({
37
- asyncContext: true,
38
- AsyncLocalStorage
35
+ asyncContext: true,
36
+ AsyncLocalStorage
39
37
  });
40
38
  const getNuxtCtx = () => asyncNuxtStorage.tryUse();
41
39
  function useNuxt() {
42
- const instance = asyncNuxtStorage.tryUse() || nuxtCtx.tryUse();
43
- if (!instance) {
44
- throw new Error("Nuxt instance is unavailable!");
45
- }
46
- return instance;
40
+ const instance = asyncNuxtStorage.tryUse() || nuxtCtx.tryUse();
41
+ if (!instance) throw new Error("Nuxt instance is unavailable!");
42
+ return instance;
47
43
  }
48
44
  function tryUseNuxt() {
49
- return asyncNuxtStorage.tryUse() || nuxtCtx.tryUse();
45
+ return asyncNuxtStorage.tryUse() || nuxtCtx.tryUse();
50
46
  }
51
47
  function runWithNuxtContext(nuxt, fn) {
52
- return asyncNuxtStorage.call(nuxt, fn);
48
+ return asyncNuxtStorage.call(nuxt, fn);
53
49
  }
54
-
55
50
  const SEMANTIC_VERSION_RE = /-\d+\.[0-9a-f]+/;
56
51
  function normalizeSemanticVersion(version) {
57
- return version.replace(SEMANTIC_VERSION_RE, "");
52
+ return version.replace(SEMANTIC_VERSION_RE, "");
58
53
  }
59
54
  const builderMap = {
60
- "@nuxt/rspack-builder": "rspack",
61
- "@nuxt/vite-builder": "vite",
62
- "@nuxt/webpack-builder": "webpack"
55
+ "@nuxt/rspack-builder": "rspack",
56
+ "@nuxt/vite-builder": "vite",
57
+ "@nuxt/webpack-builder": "webpack"
63
58
  };
64
59
  function checkNuxtVersion(version, nuxt = useNuxt()) {
65
- const nuxtVersion = getNuxtVersion(nuxt);
66
- return satisfies(normalizeSemanticVersion(nuxtVersion), version, { includePrerelease: true });
60
+ return satisfies(normalizeSemanticVersion(getNuxtVersion(nuxt)), version, { includePrerelease: true });
67
61
  }
68
62
  async function checkNuxtCompatibility(constraints, nuxt = useNuxt()) {
69
- const issues = [];
70
- if (constraints.nuxt) {
71
- const nuxtVersion = getNuxtVersion(nuxt);
72
- if (!checkNuxtVersion(constraints.nuxt, nuxt)) {
73
- issues.push({
74
- name: "nuxt",
75
- message: `Nuxt version \`${constraints.nuxt}\` is required but currently using \`${nuxtVersion}\``
76
- });
77
- }
78
- }
79
- if (constraints.builder && typeof nuxt.options.builder === "string") {
80
- const currentBuilder = builderMap[nuxt.options.builder] || nuxt.options.builder;
81
- if (currentBuilder in constraints.builder) {
82
- const constraint = constraints.builder[currentBuilder];
83
- if (constraint === false) {
84
- issues.push({
85
- name: "builder",
86
- message: `Not compatible with \`${nuxt.options.builder}\`.`
87
- });
88
- } else {
89
- for (const parent of [nuxt.options.rootDir, nuxt.options.workspaceDir, import.meta.url]) {
90
- const builderVersion = await readPackageJSON(nuxt.options.builder, { parent }).then((r) => r.version).catch(() => void 0);
91
- if (builderVersion) {
92
- if (!satisfies(normalizeSemanticVersion(builderVersion), constraint, { includePrerelease: true })) {
93
- issues.push({
94
- name: "builder",
95
- message: `Not compatible with \`${builderVersion}\` of \`${currentBuilder}\`. This module requires \`${constraint}\`.`
96
- });
97
- }
98
- break;
99
- }
100
- }
101
- }
102
- }
103
- }
104
- await nuxt.callHook("kit:compatibility", constraints, issues);
105
- issues.toString = () => issues.map((issue) => ` - [${issue.name}] ${issue.message}`).join("\n");
106
- return issues;
63
+ const issues = [];
64
+ if (constraints.nuxt) {
65
+ const nuxtVersion = getNuxtVersion(nuxt);
66
+ if (!checkNuxtVersion(constraints.nuxt, nuxt)) issues.push({
67
+ name: "nuxt",
68
+ message: `Nuxt version \`${constraints.nuxt}\` is required but currently using \`${nuxtVersion}\``
69
+ });
70
+ }
71
+ if (constraints.builder && typeof nuxt.options.builder === "string") {
72
+ const currentBuilder = builderMap[nuxt.options.builder] || nuxt.options.builder;
73
+ if (currentBuilder in constraints.builder) {
74
+ const constraint = constraints.builder[currentBuilder];
75
+ if (constraint === false) issues.push({
76
+ name: "builder",
77
+ message: `Not compatible with \`${nuxt.options.builder}\`.`
78
+ });
79
+ else for (const parent of [
80
+ nuxt.options.rootDir,
81
+ nuxt.options.workspaceDir,
82
+ import.meta.url
83
+ ]) {
84
+ const builderVersion = await readPackageJSON(nuxt.options.builder, { parent }).then((r) => r.version).catch(() => void 0);
85
+ if (builderVersion) {
86
+ if (!satisfies(normalizeSemanticVersion(builderVersion), constraint, { includePrerelease: true })) issues.push({
87
+ name: "builder",
88
+ message: `Not compatible with \`${builderVersion}\` of \`${currentBuilder}\`. This module requires \`${constraint}\`.`
89
+ });
90
+ break;
91
+ }
92
+ }
93
+ }
94
+ }
95
+ await nuxt.callHook("kit:compatibility", constraints, issues);
96
+ issues.toString = () => issues.map((issue) => ` - [${issue.name}] ${issue.message}`).join("\n");
97
+ return issues;
107
98
  }
108
99
  async function assertNuxtCompatibility(constraints, nuxt = useNuxt()) {
109
- const issues = await checkNuxtCompatibility(constraints, nuxt);
110
- if (issues.length) {
111
- throw new Error("Nuxt compatibility issues found:\n" + issues.toString());
112
- }
113
- return true;
100
+ const issues = await checkNuxtCompatibility(constraints, nuxt);
101
+ if (issues.length) throw new Error("Nuxt compatibility issues found:\n" + issues.toString());
102
+ return true;
114
103
  }
115
104
  async function hasNuxtCompatibility(constraints, nuxt = useNuxt()) {
116
- const issues = await checkNuxtCompatibility(constraints, nuxt);
117
- return !issues.length;
105
+ return !(await checkNuxtCompatibility(constraints, nuxt)).length;
118
106
  }
119
107
  function isNuxtMajorVersion(majorVersion, nuxt = useNuxt()) {
120
- const version = getNuxtVersion(nuxt);
121
- return version[0] === majorVersion.toString() && version[1] === ".";
108
+ const version = getNuxtVersion(nuxt);
109
+ return version[0] === majorVersion.toString() && version[1] === ".";
122
110
  }
123
111
  function isNuxt2(nuxt = useNuxt()) {
124
- return isNuxtMajorVersion(2, nuxt);
112
+ return isNuxtMajorVersion(2, nuxt);
125
113
  }
126
114
  function isNuxt3(nuxt = useNuxt()) {
127
- return isNuxtMajorVersion(3, nuxt);
115
+ return isNuxtMajorVersion(3, nuxt);
128
116
  }
129
117
  const NUXT_VERSION_RE = /^v/g;
130
118
  function getNuxtVersion(nuxt = useNuxt()) {
131
- const rawVersion = nuxt?._version || nuxt?.version || nuxt?.constructor?.version;
132
- if (typeof rawVersion !== "string") {
133
- throw new TypeError("Cannot determine nuxt version! Is current instance passed?");
134
- }
135
- return rawVersion.replace(NUXT_VERSION_RE, "");
119
+ const rawVersion = nuxt?._version || nuxt?.version || nuxt?.constructor?.version;
120
+ if (typeof rawVersion !== "string") throw new TypeError("Cannot determine nuxt version! Is current instance passed?");
121
+ return rawVersion.replace(NUXT_VERSION_RE, "");
136
122
  }
137
-
138
123
  function defineNuxtModule(definition) {
139
- if (definition) {
140
- return _defineNuxtModule(definition);
141
- }
142
- return {
143
- with: (definition2) => _defineNuxtModule(definition2)
144
- };
124
+ if (definition) return _defineNuxtModule(definition);
125
+ return { with: (definition) => _defineNuxtModule(definition) };
145
126
  }
146
127
  function _defineNuxtModule(definition) {
147
- if (typeof definition === "function") {
148
- return _defineNuxtModule({ setup: definition });
149
- }
150
- const module = defu(definition, { meta: {} });
151
- module.meta.configKey ||= module.meta.name;
152
- async function getOptions(inlineOptions, nuxt = useNuxt()) {
153
- const nuxtConfigOptionsKey = module.meta.configKey || module.meta.name;
154
- const nuxtConfigOptions = nuxtConfigOptionsKey && nuxtConfigOptionsKey in nuxt.options ? nuxt.options[nuxtConfigOptionsKey] : {};
155
- const optionsDefaults = module.defaults instanceof Function ? await module.defaults(nuxt) : module.defaults ?? {};
156
- let options = defu(inlineOptions, nuxtConfigOptions, optionsDefaults);
157
- if (module.schema) {
158
- options = await applyDefaults(module.schema, options);
159
- }
160
- return Promise.resolve(options);
161
- }
162
- function getModuleDependencies(nuxt = useNuxt()) {
163
- if (typeof module.moduleDependencies === "function") {
164
- return module.moduleDependencies(nuxt);
165
- }
166
- return module.moduleDependencies;
167
- }
168
- async function normalizedModule(inlineOptions, nuxt = tryUseNuxt()) {
169
- if (!nuxt) {
170
- throw new TypeError(`Cannot use ${module.meta.name || "module"} outside of Nuxt context`);
171
- }
172
- const uniqueKey = module.meta.name || module.meta.configKey;
173
- if (uniqueKey) {
174
- nuxt.options._requiredModules ||= {};
175
- if (nuxt.options._requiredModules[uniqueKey]) {
176
- return false;
177
- }
178
- nuxt.options._requiredModules[uniqueKey] = true;
179
- }
180
- if (module.meta.compatibility) {
181
- const issues = await checkNuxtCompatibility(module.meta.compatibility, nuxt);
182
- if (issues.length) {
183
- const errorMessage = `Module \`${module.meta.name}\` is disabled due to incompatibility issues:
184
- ${issues.toString()}`;
185
- if (nuxt.options.experimental.enforceModuleCompatibility) {
186
- const error = new Error(errorMessage);
187
- error.name = "ModuleCompatibilityError";
188
- throw error;
189
- }
190
- logger.warn(errorMessage);
191
- return;
192
- }
193
- }
194
- const _options = await getOptions(inlineOptions, nuxt);
195
- if (module.hooks) {
196
- nuxt.hooks.addHooks(module.hooks);
197
- }
198
- const start = performance.now();
199
- const res = await module.setup?.call(null, _options, nuxt) ?? {};
200
- const perf = performance.now() - start;
201
- const setupTime = Math.round(perf * 100) / 100;
202
- if (setupTime > 5e3 && uniqueKey !== "@nuxt/telemetry") {
203
- logger.warn(`Slow module \`${uniqueKey || "<no name>"}\` took \`${setupTime}ms\` to setup.`);
204
- } else if (nuxt.options.debug && nuxt.options.debug.modules) {
205
- logger.info(`Module \`${uniqueKey || "<no name>"}\` took \`${setupTime}ms\` to setup.`);
206
- }
207
- if (res === false) {
208
- return false;
209
- }
210
- return defu(res, {
211
- timings: {
212
- setup: setupTime
213
- }
214
- });
215
- }
216
- normalizedModule.getMeta = () => Promise.resolve(module.meta);
217
- normalizedModule.getOptions = getOptions;
218
- normalizedModule.getModuleDependencies = getModuleDependencies;
219
- normalizedModule.onInstall = module.onInstall;
220
- normalizedModule.onUpgrade = module.onUpgrade;
221
- return normalizedModule;
222
- }
223
-
128
+ if (typeof definition === "function") return _defineNuxtModule({ setup: definition });
129
+ const module = defu(definition, { meta: {} });
130
+ module.meta.configKey ||= module.meta.name;
131
+ async function getOptions(inlineOptions, nuxt = useNuxt()) {
132
+ const nuxtConfigOptionsKey = module.meta.configKey || module.meta.name;
133
+ let options = defu(inlineOptions, nuxtConfigOptionsKey && nuxtConfigOptionsKey in nuxt.options ? nuxt.options[nuxtConfigOptionsKey] : {}, module.defaults instanceof Function ? await module.defaults(nuxt) : module.defaults ?? {});
134
+ if (module.schema) options = await applyDefaults(module.schema, options);
135
+ return Promise.resolve(options);
136
+ }
137
+ function getModuleDependencies(nuxt = useNuxt()) {
138
+ if (typeof module.moduleDependencies === "function") return module.moduleDependencies(nuxt);
139
+ return module.moduleDependencies;
140
+ }
141
+ async function normalizedModule(inlineOptions, nuxt = tryUseNuxt()) {
142
+ if (!nuxt) throw new TypeError(`Cannot use ${module.meta.name || "module"} outside of Nuxt context`);
143
+ const uniqueKey = module.meta.name || module.meta.configKey;
144
+ if (uniqueKey) {
145
+ nuxt.options._requiredModules ||= {};
146
+ if (nuxt.options._requiredModules[uniqueKey]) return false;
147
+ nuxt.options._requiredModules[uniqueKey] = true;
148
+ }
149
+ if (module.meta.compatibility) {
150
+ const issues = await checkNuxtCompatibility(module.meta.compatibility, nuxt);
151
+ if (issues.length) {
152
+ const errorMessage = `Module \`${module.meta.name}\` is disabled due to incompatibility issues:\n${issues.toString()}`;
153
+ if (nuxt.options.experimental.enforceModuleCompatibility) {
154
+ const error = new Error(errorMessage);
155
+ error.name = "ModuleCompatibilityError";
156
+ throw error;
157
+ }
158
+ logger.warn(errorMessage);
159
+ return;
160
+ }
161
+ }
162
+ const _options = await getOptions(inlineOptions, nuxt);
163
+ if (module.hooks) nuxt.hooks.addHooks(module.hooks);
164
+ const start = performance.now();
165
+ const res = await module.setup?.call(null, _options, nuxt) ?? {};
166
+ const perf = performance.now() - start;
167
+ const setupTime = Math.round(perf * 100) / 100;
168
+ if (setupTime > 5e3 && uniqueKey !== "@nuxt/telemetry") logger.warn(`Slow module \`${uniqueKey || "<no name>"}\` took \`${setupTime}ms\` to setup.`);
169
+ else if (nuxt.options.debug && nuxt.options.debug.modules) logger.info(`Module \`${uniqueKey || "<no name>"}\` took \`${setupTime}ms\` to setup.`);
170
+ if (res === false) return false;
171
+ return defu(res, { timings: { setup: setupTime } });
172
+ }
173
+ normalizedModule.getMeta = () => Promise.resolve(module.meta);
174
+ normalizedModule.getOptions = getOptions;
175
+ normalizedModule.getModuleDependencies = getModuleDependencies;
176
+ normalizedModule.onInstall = module.onInstall;
177
+ normalizedModule.onUpgrade = module.onUpgrade;
178
+ return normalizedModule;
179
+ }
224
180
  const distURL = import.meta.url.replace(/\/dist\/.*$/, "/");
225
181
  function getUserCaller() {
226
- if (!import.meta.dev) {
227
- return null;
228
- }
229
- const { source, line, column } = captureStackTrace().find((entry) => !entry.source.startsWith(distURL)) ?? {};
230
- if (!source) {
231
- return null;
232
- }
233
- return {
234
- source: source.replace(/^file:\/\//, ""),
235
- line,
236
- column
237
- };
182
+ if (!import.meta.dev) return null;
183
+ const { source, line, column } = captureStackTrace().find((entry) => !entry.source.startsWith(distURL)) ?? {};
184
+ if (!source) return null;
185
+ return {
186
+ source: source.replace(/^file:\/\//, ""),
187
+ line,
188
+ column
189
+ };
238
190
  }
239
191
  const warnings = /* @__PURE__ */ new Set();
240
192
  function warn(warning) {
241
- if (!warnings.has(warning)) {
242
- console.warn(warning);
243
- warnings.add(warning);
244
- }
193
+ if (!warnings.has(warning)) {
194
+ console.warn(warning);
195
+ warnings.add(warning);
196
+ }
245
197
  }
246
-
247
198
  const layerMap = /* @__PURE__ */ new WeakMap();
248
199
  function getLayerDirectories(nuxt = useNuxt()) {
249
- return nuxt.options._layers.map((layer) => {
250
- if (layerMap.has(layer)) {
251
- return layerMap.get(layer);
252
- }
253
- const isRoot = withTrailingSlash$1(layer.config.rootDir) === withTrailingSlash$1(nuxt.options.rootDir);
254
- const config = isRoot ? nuxt.options : layer.config;
255
- const src = withTrailingSlash$1(config.srcDir || layer.cwd);
256
- const root = withTrailingSlash$1(config.rootDir || layer.cwd);
257
- const directories = {
258
- root,
259
- shared: withTrailingSlash$1(resolve(root, resolveAlias(config.dir?.shared || "shared", nuxt.options.alias))),
260
- // these are resolved relative to root in `@nuxt/schema` for v4+
261
- // so resolving relative to `src` covers backward compatibility for v3
262
- server: withTrailingSlash$1(resolve(src, resolveAlias(config.serverDir || "server", nuxt.options.alias))),
263
- modules: withTrailingSlash$1(resolve(src, resolveAlias(config.dir?.modules || "modules", nuxt.options.alias))),
264
- public: withTrailingSlash$1(resolve(src, resolveAlias(config.dir?.public || "public", nuxt.options.alias))),
265
- // nuxt app
266
- app: src,
267
- appLayouts: withTrailingSlash$1(resolve(src, resolveAlias(config.dir?.layouts || "layouts", nuxt.options.alias))),
268
- appMiddleware: withTrailingSlash$1(resolve(src, resolveAlias(config.dir?.middleware || "middleware", nuxt.options.alias))),
269
- appPages: withTrailingSlash$1(resolve(src, resolveAlias(config.dir?.pages || "pages", nuxt.options.alias))),
270
- appPlugins: withTrailingSlash$1(resolve(src, resolveAlias(config.dir?.plugins || "plugins", nuxt.options.alias)))
271
- };
272
- layerMap.set(layer, directories);
273
- return directories;
274
- });
275
- }
276
- function withTrailingSlash$1(dir) {
277
- return dir.replace(/[^/]$/, "$&/");
200
+ return nuxt.options._layers.map((layer) => {
201
+ if (layerMap.has(layer)) return layerMap.get(layer);
202
+ const config = withTrailingSlash$2(layer.config.rootDir) === withTrailingSlash$2(nuxt.options.rootDir) ? nuxt.options : layer.config;
203
+ const src = withTrailingSlash$2(config.srcDir || layer.cwd);
204
+ const root = withTrailingSlash$2(config.rootDir || layer.cwd);
205
+ const directories = {
206
+ root,
207
+ shared: withTrailingSlash$2(resolve(root, resolveAlias(config.dir?.shared || "shared", nuxt.options.alias))),
208
+ server: withTrailingSlash$2(resolve(src, resolveAlias(config.serverDir || "server", nuxt.options.alias))),
209
+ modules: withTrailingSlash$2(resolve(src, resolveAlias(config.dir?.modules || "modules", nuxt.options.alias))),
210
+ public: withTrailingSlash$2(resolve(src, resolveAlias(config.dir?.public || "public", nuxt.options.alias))),
211
+ app: src,
212
+ appLayouts: withTrailingSlash$2(resolve(src, resolveAlias(config.dir?.layouts || "layouts", nuxt.options.alias))),
213
+ appMiddleware: withTrailingSlash$2(resolve(src, resolveAlias(config.dir?.middleware || "middleware", nuxt.options.alias))),
214
+ appPages: withTrailingSlash$2(resolve(src, resolveAlias(config.dir?.pages || "pages", nuxt.options.alias))),
215
+ appPlugins: withTrailingSlash$2(resolve(src, resolveAlias(config.dir?.plugins || "plugins", nuxt.options.alias)))
216
+ };
217
+ layerMap.set(layer, directories);
218
+ return directories;
219
+ });
220
+ }
221
+ function withTrailingSlash$2(dir) {
222
+ return dir.replace(/[^/]$/, "$&/");
278
223
  }
279
-
280
224
  function createIsIgnored(nuxt = tryUseNuxt()) {
281
- return (pathname, stats) => isIgnored(pathname, stats, nuxt);
225
+ return (pathname, stats) => isIgnored(pathname, stats, nuxt);
282
226
  }
283
227
  function isIgnored(pathname, _stats, nuxt = tryUseNuxt()) {
284
- if (!nuxt) {
285
- return false;
286
- }
287
- if (!nuxt._ignore) {
288
- nuxt._ignore = ignore(nuxt.options.ignoreOptions);
289
- nuxt._ignore.add(resolveIgnorePatterns());
290
- }
291
- const cwds = getLayerDirectories(nuxt).map((dirs) => dirs.root).sort((a, b) => b.length - a.length);
292
- const layer = cwds.find((cwd) => pathname.startsWith(cwd));
293
- const relativePath = relative(layer ?? nuxt.options.rootDir, pathname);
294
- if (relativePath[0] === "." && relativePath[1] === ".") {
295
- return false;
296
- }
297
- return !!(relativePath && nuxt._ignore.ignores(relativePath));
228
+ if (!nuxt) return false;
229
+ if (!nuxt._ignore) {
230
+ nuxt._ignore = ignore(nuxt.options.ignoreOptions);
231
+ nuxt._ignore.add(resolveIgnorePatterns());
232
+ }
233
+ 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);
234
+ if (relativePath[0] === "." && relativePath[1] === ".") return false;
235
+ return !!(relativePath && nuxt._ignore.ignores(relativePath));
298
236
  }
299
237
  const NEGATION_RE = /^(!?)(.*)$/;
300
238
  function resolveIgnorePatterns(relativePath) {
301
- const nuxt = tryUseNuxt();
302
- if (!nuxt) {
303
- return [];
304
- }
305
- const ignorePatterns = nuxt.options.ignore.flatMap((s) => resolveGroupSyntax(s));
306
- const nuxtignoreFile = join(nuxt.options.rootDir, ".nuxtignore");
307
- if (existsSync(nuxtignoreFile)) {
308
- const contents = readFileSync(nuxtignoreFile, "utf-8");
309
- ignorePatterns.push(...contents.trim().split(/\r?\n/));
310
- }
311
- if (relativePath) {
312
- return ignorePatterns.map((p) => {
313
- const [_, negation = "", pattern] = p.match(NEGATION_RE) || [];
314
- if (pattern && pattern[0] === "*") {
315
- return p;
316
- }
317
- return negation + relative(relativePath, resolve(nuxt.options.rootDir, pattern || p));
318
- });
319
- }
320
- return ignorePatterns;
239
+ const nuxt = tryUseNuxt();
240
+ if (!nuxt) return [];
241
+ const ignorePatterns = nuxt.options.ignore.flatMap((s) => resolveGroupSyntax(s));
242
+ const nuxtignoreFile = join(nuxt.options.rootDir, ".nuxtignore");
243
+ if (existsSync(nuxtignoreFile)) {
244
+ const contents = readFileSync(nuxtignoreFile, "utf-8");
245
+ ignorePatterns.push(...contents.trim().split(/\r?\n/));
246
+ }
247
+ if (relativePath) return ignorePatterns.map((p) => {
248
+ const [_, negation = "", pattern] = p.match(NEGATION_RE) || [];
249
+ if (pattern && pattern[0] === "*") return p;
250
+ return negation + relative(relativePath, resolve(nuxt.options.rootDir, pattern || p));
251
+ });
252
+ return ignorePatterns;
321
253
  }
322
254
  function resolveGroupSyntax(group) {
323
- let groups = [group];
324
- while (groups.some((group2) => group2.includes("{"))) {
325
- groups = groups.flatMap((group2) => {
326
- const [head, ...tail] = group2.split("{");
327
- if (tail.length) {
328
- const [body = "", ...rest] = tail.join("{").split("}");
329
- return body.split(",").map((part) => `${head}${part}${rest.join("")}`);
330
- }
331
- return group2;
332
- });
333
- }
334
- return groups;
335
- }
336
-
255
+ let groups = [group];
256
+ while (groups.some((group) => group.includes("{"))) groups = groups.flatMap((group) => {
257
+ const [head, ...tail] = group.split("{");
258
+ if (tail.length) {
259
+ const [body = "", ...rest] = tail.join("{").split("}");
260
+ return body.split(",").map((part) => `${head}${part}${rest.join("")}`);
261
+ }
262
+ return group;
263
+ });
264
+ return groups;
265
+ }
337
266
  function toArray(value) {
338
- return Array.isArray(value) ? value : [value];
267
+ return Array.isArray(value) ? value : [value];
339
268
  }
340
269
  function filterInPlace(array, predicate) {
341
- for (let i = array.length; i--; i >= 0) {
342
- if (!predicate(array[i], i, array)) {
343
- array.splice(i, 1);
344
- }
345
- }
346
- return array;
270
+ for (let i = array.length; i--;) if (!predicate(array[i], i, array)) array.splice(i, 1);
271
+ return array;
347
272
  }
348
273
  const MODE_RE = /\.(server|client)(\.\w+)*$/;
349
274
  const distDirURL = new URL(".", import.meta.url);
350
-
351
275
  async function resolvePath(path, opts = {}) {
352
- const { type = "file" } = opts;
353
- const res = await _resolvePathGranularly(path, { ...opts, type });
354
- if (res.type === type) {
355
- return res.path;
356
- }
357
- return opts.fallbackToOriginal ? path : res.path;
276
+ const { type = "file" } = opts;
277
+ const res = await _resolvePathGranularly(path, {
278
+ ...opts,
279
+ type
280
+ });
281
+ if (res.type === type) return res.path;
282
+ return opts.fallbackToOriginal ? path : res.path;
358
283
  }
359
284
  async function findPath(paths, opts, pathType = "file") {
360
- for (const path of toArray(paths)) {
361
- const res = await _resolvePathGranularly(path, {
362
- ...opts,
363
- // TODO: this is for backwards compatibility, remove the `pathType` argument in Nuxt 5
364
- type: opts?.type || pathType
365
- });
366
- if (!res.type || pathType && res.type !== pathType) {
367
- continue;
368
- }
369
- if (res.virtual || await existsSensitive(res.path)) {
370
- return res.path;
371
- }
372
- }
373
- return null;
285
+ for (const path of toArray(paths)) {
286
+ const res = await _resolvePathGranularly(path, {
287
+ ...opts,
288
+ type: opts?.type || pathType
289
+ });
290
+ if (!res.type || pathType && res.type !== pathType) continue;
291
+ if (res.virtual || await existsSensitive(res.path)) return res.path;
292
+ }
293
+ return null;
374
294
  }
375
295
  function resolveAlias(path, alias) {
376
- alias ||= tryUseNuxt()?.options.alias || {};
377
- return resolveAlias$1(path, alias);
296
+ alias ||= tryUseNuxt()?.options.alias || {};
297
+ return resolveAlias$1(path, alias);
378
298
  }
379
299
  function createResolver(base) {
380
- if (!base) {
381
- throw new Error("`base` argument is missing for createResolver(base)!");
382
- }
383
- base = base.toString();
384
- if (base.startsWith("file://")) {
385
- base = dirname(fileURLToPath(base));
386
- }
387
- return {
388
- resolve: (...path) => resolve(base, ...path),
389
- resolvePath: (path, opts) => resolvePath(path, { cwd: base, ...opts })
390
- };
300
+ if (!base) throw new Error("`base` argument is missing for createResolver(base)!");
301
+ base = base.toString();
302
+ if (base.startsWith("file://")) base = dirname(fileURLToPath(base));
303
+ return {
304
+ resolve: (...path) => resolve(base, ...path),
305
+ resolvePath: (path, opts) => resolvePath(path, {
306
+ cwd: base,
307
+ ...opts
308
+ })
309
+ };
391
310
  }
392
311
  async function resolveNuxtModule(base, paths) {
393
- const resolved = [];
394
- const resolver = createResolver(base);
395
- for (const path of paths) {
396
- if (path.startsWith(base)) {
397
- resolved.push(path.split("/index.ts")[0]);
398
- continue;
399
- }
400
- const resolvedPath = await resolver.resolvePath(path);
401
- const dir = parseNodeModulePath(resolvedPath).dir;
402
- if (dir) {
403
- resolved.push(dir);
404
- continue;
405
- }
406
- const index = resolvedPath.lastIndexOf(path);
407
- resolved.push(index === -1 ? dirname(resolvedPath) : resolvedPath.slice(0, index + path.length));
408
- }
409
- return resolved;
312
+ const resolved = [];
313
+ const resolver = createResolver(base);
314
+ for (const path of paths) {
315
+ if (path.startsWith(base)) {
316
+ resolved.push(path.split("/index.ts")[0]);
317
+ continue;
318
+ }
319
+ const resolvedPath = await resolver.resolvePath(path);
320
+ const dir = parseNodeModulePath(resolvedPath).dir;
321
+ if (dir) {
322
+ resolved.push(dir);
323
+ continue;
324
+ }
325
+ const index = resolvedPath.lastIndexOf(path);
326
+ resolved.push(index === -1 ? dirname(resolvedPath) : resolvedPath.slice(0, index + path.length));
327
+ }
328
+ return resolved;
410
329
  }
411
330
  async function _resolvePathType(path, opts = {}, skipFs = false) {
412
- if (opts?.virtual && existsInVFS(path)) {
413
- return {
414
- path,
415
- type: "file",
416
- virtual: true
417
- };
418
- }
419
- if (skipFs) {
420
- return;
421
- }
422
- const fd = await promises.open(path, "r").catch(() => null);
423
- try {
424
- const stats = await fd?.stat();
425
- if (stats) {
426
- return {
427
- path,
428
- type: stats.isFile() ? "file" : "dir",
429
- virtual: false
430
- };
431
- }
432
- } finally {
433
- fd?.close();
434
- }
331
+ if (opts?.virtual && existsInVFS(path)) return {
332
+ path,
333
+ type: "file",
334
+ virtual: true
335
+ };
336
+ if (skipFs) return;
337
+ const fd = await promises.open(path, "r").catch(() => null);
338
+ try {
339
+ const stats = await fd?.stat();
340
+ if (stats) return {
341
+ path,
342
+ type: stats.isFile() ? "file" : "dir",
343
+ virtual: false
344
+ };
345
+ } finally {
346
+ fd?.close();
347
+ }
435
348
  }
436
349
  function normalizeExtension(ext) {
437
- return ext.startsWith(".") ? ext : `.${ext}`;
350
+ return ext.startsWith(".") ? ext : `.${ext}`;
438
351
  }
439
352
  async function _resolvePathGranularly(path, opts = { type: "file" }) {
440
- const _path = path;
441
- path = normalize(path);
442
- if (isAbsolute(path)) {
443
- const res2 = await _resolvePathType(path, opts);
444
- if (res2 && res2.type === opts.type) {
445
- return res2;
446
- }
447
- }
448
- const nuxt = tryUseNuxt();
449
- const cwd = opts.cwd || (nuxt ? nuxt.options.rootDir : process.cwd());
450
- const extensions = opts.extensions || (nuxt ? nuxt.options.extensions : [".ts", ".mjs", ".cjs", ".json"]);
451
- const modulesDir = nuxt ? nuxt.options.modulesDir : [];
452
- path = resolveAlias$1(path, opts.alias ?? nuxt?.options.alias ?? {});
453
- if (!isAbsolute(path)) {
454
- path = resolve(cwd, path);
455
- }
456
- const res = await _resolvePathType(path, opts);
457
- if (res && res.type === opts.type) {
458
- return res;
459
- }
460
- if (opts.type === "file") {
461
- for (const ext of extensions) {
462
- const normalizedExt = normalizeExtension(ext);
463
- const extPath = await _resolvePathType(path + normalizedExt, opts);
464
- if (extPath && extPath.type === "file") {
465
- return extPath;
466
- }
467
- const indexPath = await _resolvePathType(
468
- join(path, "index" + normalizedExt),
469
- opts,
470
- res?.type !== "dir"
471
- /* skip checking if parent is not a directory */
472
- );
473
- if (indexPath && indexPath.type === "file") {
474
- return indexPath;
475
- }
476
- }
477
- const resolvedModulePath = resolveModulePath(_path, {
478
- try: true,
479
- suffixes: ["", "index"],
480
- from: [cwd, ...modulesDir].map((d) => directoryToURL(d))
481
- });
482
- if (resolvedModulePath) {
483
- return {
484
- path: resolvedModulePath,
485
- type: "file",
486
- virtual: false
487
- };
488
- }
489
- }
490
- return {
491
- path
492
- };
353
+ const _path = path;
354
+ path = normalize(path);
355
+ if (isAbsolute(path)) {
356
+ const res = await _resolvePathType(path, opts);
357
+ if (res && res.type === opts.type) return res;
358
+ }
359
+ const nuxt = tryUseNuxt();
360
+ const cwd = opts.cwd || (nuxt ? nuxt.options.rootDir : process.cwd());
361
+ const extensions = opts.extensions || (nuxt ? nuxt.options.extensions : [
362
+ ".ts",
363
+ ".mjs",
364
+ ".cjs",
365
+ ".json"
366
+ ]);
367
+ const modulesDir = nuxt ? nuxt.options.modulesDir : [];
368
+ path = resolveAlias$1(path, opts.alias ?? nuxt?.options.alias ?? {});
369
+ if (!isAbsolute(path)) path = resolve(cwd, path);
370
+ const res = await _resolvePathType(path, opts);
371
+ if (res && res.type === opts.type) return res;
372
+ if (opts.type === "file") {
373
+ for (const ext of extensions) {
374
+ const normalizedExt = normalizeExtension(ext);
375
+ const extPath = await _resolvePathType(path + normalizedExt, opts);
376
+ if (extPath && extPath.type === "file") return extPath;
377
+ const indexPath = await _resolvePathType(join(path, "index" + normalizedExt), opts, res?.type !== "dir");
378
+ if (indexPath && indexPath.type === "file") return indexPath;
379
+ }
380
+ const resolvedModulePath = resolveModulePath(_path, {
381
+ try: true,
382
+ suffixes: ["", "index"],
383
+ from: [cwd, ...modulesDir].map((d) => directoryToURL(d))
384
+ });
385
+ if (resolvedModulePath) return {
386
+ path: resolvedModulePath,
387
+ type: "file",
388
+ virtual: false
389
+ };
390
+ }
391
+ return { path };
493
392
  }
494
393
  async function existsSensitive(path) {
495
- const dirFiles = new Set(await promises.readdir(dirname(path)).catch(() => []));
496
- return dirFiles.has(basename(path));
394
+ return new Set(await promises.readdir(dirname(path)).catch(() => [])).has(basename(path));
497
395
  }
498
396
  function existsInVFS(path, nuxt = tryUseNuxt()) {
499
- if (!nuxt) {
500
- return false;
501
- }
502
- if (path in nuxt.vfs) {
503
- return true;
504
- }
505
- const templates = nuxt.apps.default?.templates ?? nuxt.options.build.templates;
506
- return templates.some((template) => template.dst === path);
397
+ if (!nuxt) return false;
398
+ if (path in nuxt.vfs) return true;
399
+ return (nuxt.apps.default?.templates ?? nuxt.options.build.templates).some((template) => template.dst === path);
507
400
  }
508
401
  async function resolveFiles(path, pattern, opts = {}) {
509
- const files = [];
510
- for (const p of await glob(pattern, { cwd: path, followSymbolicLinks: opts.followSymbolicLinks ?? true, absolute: true, ignore: opts.ignore })) {
511
- if (!isIgnored(p)) {
512
- files.push(p);
513
- }
514
- }
515
- return files.sort();
516
- }
517
-
402
+ const files = [];
403
+ for (const p of await glob(pattern, {
404
+ cwd: path,
405
+ followSymbolicLinks: opts.followSymbolicLinks ?? true,
406
+ absolute: true,
407
+ ignore: opts.ignore
408
+ })) if (!isIgnored(p)) files.push(p);
409
+ return files.sort();
410
+ }
518
411
  function directoryToURL(dir) {
519
- return pathToFileURL(dir + "/");
412
+ return pathToFileURL(dir + "/");
520
413
  }
521
414
  function tryResolveModule(id, url = import.meta.url) {
522
- return Promise.resolve(resolveModulePath(id, {
523
- from: url,
524
- suffixes: ["", "index"],
525
- try: true
526
- }));
415
+ return Promise.resolve(resolveModulePath(id, {
416
+ from: url,
417
+ suffixes: ["", "index"],
418
+ try: true
419
+ }));
527
420
  }
528
421
  function resolveModule(id, options) {
529
- return resolveModulePath(id, {
530
- // eslint-disable-next-line @typescript-eslint/no-deprecated
531
- from: options?.url ?? options?.paths ?? [import.meta.url],
532
- extensions: options?.extensions ?? [".js", ".mjs", ".cjs", ".ts", ".mts", ".cts"]
533
- });
422
+ return resolveModulePath(id, {
423
+ from: options?.url ?? options?.paths ?? [import.meta.url],
424
+ extensions: options?.extensions ?? [
425
+ ".js",
426
+ ".mjs",
427
+ ".cjs",
428
+ ".ts",
429
+ ".mts",
430
+ ".cts"
431
+ ]
432
+ });
534
433
  }
535
434
  async function importModule(id, opts) {
536
- const resolvedPath = resolveModule(id, opts);
537
- return await import(pathToFileURL(resolvedPath).href).then((r) => opts?.interopDefault !== false ? interopDefault(r) : r);
435
+ return await import(pathToFileURL(resolveModule(id, opts)).href).then((r) => opts?.interopDefault !== false ? interopDefault(r) : r);
538
436
  }
539
437
  function tryImportModule(id, opts) {
540
- try {
541
- return importModule(id, opts).catch(() => void 0);
542
- } catch {
543
- }
438
+ try {
439
+ return importModule(id, opts).catch(() => void 0);
440
+ } catch {}
544
441
  }
545
442
  function requireModule(id, opts) {
546
- const caller = getUserCaller();
547
- const explanation = caller ? ` (used at \`${resolveAlias(caller.source)}:${caller.line}:${caller.column}\`)` : "";
548
- const warning = `[@nuxt/kit] \`requireModule\` is deprecated${explanation}. Please use \`importModule\` instead.`;
549
- warn(warning);
550
- const resolvedPath = resolveModule(id, opts);
551
- const jiti = createJiti(import.meta.url, {
552
- interopDefault: opts?.interopDefault !== false
553
- });
554
- return jiti(pathToFileURL(resolvedPath).href);
443
+ const caller = getUserCaller();
444
+ warn(`[@nuxt/kit] \`requireModule\` is deprecated${caller ? ` (used at \`${resolveAlias(caller.source)}:${caller.line}:${caller.column}\`)` : ""}. Please use \`importModule\` instead.`);
445
+ const resolvedPath = resolveModule(id, opts);
446
+ return createJiti(import.meta.url, { interopDefault: opts?.interopDefault !== false })(pathToFileURL(resolvedPath).href);
555
447
  }
556
448
  function tryRequireModule(id, opts) {
557
- try {
558
- return requireModule(id, opts);
559
- } catch {
560
- }
449
+ try {
450
+ return requireModule(id, opts);
451
+ } catch {}
561
452
  }
562
-
563
453
  const NODE_MODULES_RE = /[/\\]node_modules[/\\]/;
454
+ const ignoredConfigKeys = new Set([
455
+ "components",
456
+ "imports",
457
+ "pages",
458
+ "devtools",
459
+ "telemetry"
460
+ ]);
564
461
  async function installModules(modulesToInstall, resolvedModulePaths, nuxt = useNuxt()) {
565
- const localLayerModuleDirs = [];
566
- for (const l of nuxt.options._layers) {
567
- const srcDir = l.config.srcDir || l.cwd;
568
- if (!NODE_MODULES_RE.test(srcDir)) {
569
- localLayerModuleDirs.push(resolve(srcDir, l.config?.dir?.modules || "modules").replace(/\/?$/, "/"));
570
- }
571
- }
572
- nuxt._moduleOptionsFunctions ||= /* @__PURE__ */ new Map();
573
- const resolvedModules = [];
574
- const inlineConfigKeys = new Set(
575
- await Promise.all([...modulesToInstall].map(([mod]) => typeof mod !== "string" && Promise.resolve(mod.getMeta?.())?.then((r) => r?.configKey)))
576
- );
577
- let error;
578
- const dependencyMap = /* @__PURE__ */ new Map();
579
- for (const [key, options] of modulesToInstall) {
580
- const res = await loadNuxtModuleInstance(key, nuxt).catch((err) => {
581
- if (dependencyMap.has(key) && typeof key === "string") {
582
- err.cause = `Could not resolve \`${key}\` (specified as a dependency of ${dependencyMap.get(key)}).`;
583
- }
584
- throw err;
585
- });
586
- const dependencyMeta = res.nuxtModule.getModuleDependencies?.(nuxt) || {};
587
- for (const [name, value] of Object.entries(dependencyMeta)) {
588
- if (!value.overrides && !value.defaults && !value.version && value.optional) {
589
- continue;
590
- }
591
- const resolvedModule = resolveModuleWithOptions(name, nuxt);
592
- const moduleToAttribute = typeof key === "string" ? `\`${key}\`` : "a module in `nuxt.options`";
593
- if (!resolvedModule?.module) {
594
- const message = `Could not resolve \`${name}\` (specified as a dependency of ${moduleToAttribute}).`;
595
- error = new TypeError(message);
596
- continue;
597
- }
598
- if (value.version) {
599
- const resolvePaths = [res.resolvedModulePath, ...nuxt.options.modulesDir].filter(Boolean);
600
- const pkg = await readPackageJSON(name, { from: resolvePaths }).catch(() => null);
601
- if (pkg?.version && !semver.satisfies(pkg.version, value.version)) {
602
- const message = `Module \`${name}\` version (\`${pkg.version}\`) does not satisfy \`${value.version}\` (requested by ${moduleToAttribute}).`;
603
- error = new TypeError(message);
604
- }
605
- }
606
- if (value.overrides || value.defaults) {
607
- const currentFns = nuxt._moduleOptionsFunctions.get(resolvedModule.module) || [];
608
- nuxt._moduleOptionsFunctions.set(resolvedModule.module, [
609
- ...currentFns,
610
- () => ({ defaults: value.defaults, overrides: value.overrides })
611
- ]);
612
- }
613
- if (value.optional === true) {
614
- continue;
615
- }
616
- nuxt.options.typescript.hoist.push(name);
617
- if (resolvedModule && !modulesToInstall.has(resolvedModule.module) && (!resolvedModule.resolvedPath || !resolvedModulePaths.has(resolvedModule.resolvedPath))) {
618
- if (typeof resolvedModule.module === "string" && inlineConfigKeys.has(resolvedModule.module)) {
619
- continue;
620
- }
621
- modulesToInstall.set(resolvedModule.module, resolvedModule.options);
622
- dependencyMap.set(resolvedModule.module, moduleToAttribute);
623
- const path = resolvedModule.resolvedPath || resolvedModule.module;
624
- if (typeof path === "string") {
625
- resolvedModulePaths.add(path);
626
- }
627
- }
628
- }
629
- resolvedModules.push({
630
- moduleToInstall: key,
631
- meta: await res.nuxtModule.getMeta?.(),
632
- nuxtModule: res.nuxtModule,
633
- buildTimeModuleMeta: res.buildTimeModuleMeta,
634
- resolvedModulePath: res.resolvedModulePath,
635
- inlineOptions: options
636
- });
637
- }
638
- if (error) {
639
- throw error;
640
- }
641
- for (const { nuxtModule, meta, moduleToInstall, buildTimeModuleMeta, resolvedModulePath, inlineOptions } of resolvedModules) {
642
- const configKey = meta?.configKey;
643
- const optionsFns = [
644
- ...nuxt._moduleOptionsFunctions.get(moduleToInstall) || [],
645
- ...meta?.name ? nuxt._moduleOptionsFunctions.get(meta.name) || [] : [],
646
- // TODO: consider dropping options functions keyed by config key
647
- ...configKey ? nuxt._moduleOptionsFunctions.get(configKey) || [] : []
648
- ];
649
- if (optionsFns.length > 0) {
650
- const overrides = [];
651
- const defaults = [];
652
- for (const fn of optionsFns) {
653
- const options = fn();
654
- overrides.push(options.overrides);
655
- defaults.push(options.defaults);
656
- }
657
- if (configKey) {
658
- nuxt.options[configKey] = defu(...overrides, nuxt.options[configKey], ...defaults);
659
- }
660
- }
661
- await callLifecycleHooks(nuxtModule, meta, inlineOptions, nuxt);
662
- await callModule(nuxtModule, meta, inlineOptions, resolvedModulePath, moduleToInstall, localLayerModuleDirs, buildTimeModuleMeta, nuxt);
663
- }
664
- delete nuxt._moduleOptionsFunctions;
462
+ const localLayerModuleDirs = [];
463
+ for (const l of nuxt.options._layers) {
464
+ const srcDir = l.config.srcDir || l.cwd;
465
+ if (!NODE_MODULES_RE.test(srcDir)) localLayerModuleDirs.push(resolve(srcDir, l.config?.dir?.modules || "modules").replace(/\/?$/, "/"));
466
+ }
467
+ nuxt._moduleOptionsFunctions ||= /* @__PURE__ */ new Map();
468
+ const resolvedModules = [];
469
+ const modulesByMetaName = /* @__PURE__ */ new Map();
470
+ const inlineConfigKeys = new Set(await Promise.all([...modulesToInstall].map(async ([mod]) => {
471
+ if (typeof mod === "string") return;
472
+ const meta = await Promise.resolve(mod.getMeta?.());
473
+ if (meta?.name) modulesByMetaName.set(meta.name, mod);
474
+ if (meta?.configKey) {
475
+ if (meta.configKey !== meta.name) modulesByMetaName.set(meta.configKey, mod);
476
+ return meta.configKey;
477
+ }
478
+ })));
479
+ let error;
480
+ const dependencyMap = /* @__PURE__ */ new Map();
481
+ for (const [key, options] of modulesToInstall) {
482
+ const res = await loadNuxtModuleInstance(key, nuxt).catch((err) => {
483
+ if (dependencyMap.has(key) && typeof key === "string") err.cause = `Could not resolve \`${key}\` (specified as a dependency of ${dependencyMap.get(key)}).`;
484
+ throw err;
485
+ });
486
+ const dependencyMeta = await res.nuxtModule.getModuleDependencies?.(nuxt) || {};
487
+ for (const [name, value] of Object.entries(dependencyMeta)) {
488
+ if (!value.overrides && !value.defaults && !value.version && value.optional) continue;
489
+ const resolvedModule = modulesByMetaName.has(name) ? resolveModuleWithOptions(modulesByMetaName.get(name), nuxt) : resolveModuleWithOptions(name, nuxt);
490
+ const moduleToAttribute = typeof key === "string" ? `\`${key}\`` : "a module in `nuxt.options`";
491
+ if (!resolvedModule?.module) {
492
+ const message = `Could not resolve \`${name}\` (specified as a dependency of ${moduleToAttribute}).`;
493
+ error = new TypeError(message);
494
+ continue;
495
+ }
496
+ if (value.version) {
497
+ const pkg = await readPackageJSON(name, { from: [res.resolvedModulePath, ...nuxt.options.modulesDir].filter(Boolean) }).catch(() => null);
498
+ if (pkg?.version && !semver.satisfies(pkg.version, value.version, { includePrerelease: true })) {
499
+ const message = `Module \`${name}\` version (\`${pkg.version}\`) does not satisfy \`${value.version}\` (requested by ${moduleToAttribute}).`;
500
+ error = new TypeError(message);
501
+ }
502
+ }
503
+ if (value.overrides || value.defaults) {
504
+ const currentFns = nuxt._moduleOptionsFunctions.get(resolvedModule.module) || [];
505
+ nuxt._moduleOptionsFunctions.set(resolvedModule.module, [...currentFns, () => ({
506
+ defaults: value.defaults,
507
+ overrides: value.overrides
508
+ })]);
509
+ }
510
+ if (value.optional === true) continue;
511
+ nuxt.options.typescript.hoist.push(name);
512
+ if (resolvedModule && !modulesToInstall.has(resolvedModule.module) && (!resolvedModule.resolvedPath || !resolvedModulePaths.has(resolvedModule.resolvedPath))) {
513
+ if (typeof resolvedModule.module === "string" && inlineConfigKeys.has(resolvedModule.module)) continue;
514
+ modulesToInstall.set(resolvedModule.module, resolvedModule.options);
515
+ dependencyMap.set(resolvedModule.module, moduleToAttribute);
516
+ const path = resolvedModule.resolvedPath || resolvedModule.module;
517
+ if (typeof path === "string") resolvedModulePaths.add(path);
518
+ }
519
+ }
520
+ resolvedModules.push({
521
+ moduleToInstall: key,
522
+ meta: await res.nuxtModule.getMeta?.(),
523
+ nuxtModule: res.nuxtModule,
524
+ buildTimeModuleMeta: res.buildTimeModuleMeta,
525
+ resolvedModulePath: res.resolvedModulePath,
526
+ inlineOptions: options
527
+ });
528
+ }
529
+ if (error) throw error;
530
+ for (const { nuxtModule, meta = {}, moduleToInstall, buildTimeModuleMeta, resolvedModulePath, inlineOptions } of resolvedModules) {
531
+ const configKey = meta.configKey;
532
+ const optionsFns = [
533
+ ...nuxt._moduleOptionsFunctions.get(moduleToInstall) || [],
534
+ ...meta?.name ? nuxt._moduleOptionsFunctions.get(meta.name) || [] : [],
535
+ ...configKey ? nuxt._moduleOptionsFunctions.get(configKey) || [] : []
536
+ ];
537
+ if (optionsFns.length > 0) {
538
+ const overrides = [];
539
+ const defaults = [];
540
+ for (const fn of optionsFns) {
541
+ const options = fn();
542
+ overrides.push(options.overrides);
543
+ defaults.push(options.defaults);
544
+ }
545
+ if (configKey) nuxt.options[configKey] = defu(...overrides, nuxt.options[configKey], ...defaults);
546
+ }
547
+ const isDisabled = configKey && !ignoredConfigKeys.has(configKey) && nuxt.options[configKey] === false;
548
+ if (!isDisabled) await callLifecycleHooks(nuxtModule, meta, inlineOptions, nuxt);
549
+ const path = typeof moduleToInstall === "string" ? moduleToInstall : void 0;
550
+ await callModule(nuxt, nuxtModule, inlineOptions, {
551
+ meta: defu({ disabled: isDisabled }, meta, buildTimeModuleMeta),
552
+ nameOrPath: path,
553
+ modulePath: resolvedModulePath || path,
554
+ localLayerModuleDirs
555
+ });
556
+ }
557
+ delete nuxt._moduleOptionsFunctions;
665
558
  }
666
559
  async function installModule(moduleToInstall, inlineOptions, nuxt = useNuxt()) {
667
- const { nuxtModule, buildTimeModuleMeta, resolvedModulePath } = await loadNuxtModuleInstance(moduleToInstall, nuxt);
668
- const localLayerModuleDirs = [];
669
- for (const dirs of getLayerDirectories(nuxt)) {
670
- if (!NODE_MODULES_RE.test(dirs.app)) {
671
- localLayerModuleDirs.push(dirs.modules);
672
- }
673
- }
674
- const meta = await nuxtModule.getMeta?.();
675
- let mergedOptions = inlineOptions;
676
- const configKey = meta?.configKey;
677
- if (configKey && nuxt._moduleOptionsFunctions) {
678
- const optionsFns = [
679
- ...nuxt._moduleOptionsFunctions.get(moduleToInstall) || [],
680
- ...nuxt._moduleOptionsFunctions.get(configKey) || []
681
- ];
682
- if (optionsFns.length > 0) {
683
- const overrides = [];
684
- const defaults = [];
685
- for (const fn of optionsFns) {
686
- const options = fn();
687
- overrides.push(options.overrides);
688
- defaults.push(options.defaults);
689
- }
690
- mergedOptions = defu(inlineOptions, ...overrides, nuxt.options[configKey], ...defaults);
691
- nuxt.options[configKey] = mergedOptions;
692
- }
693
- }
694
- await callLifecycleHooks(nuxtModule, meta, mergedOptions, nuxt);
695
- await callModule(nuxtModule, meta, mergedOptions, resolvedModulePath, moduleToInstall, localLayerModuleDirs, buildTimeModuleMeta, nuxt);
560
+ const { nuxtModule, buildTimeModuleMeta, resolvedModulePath } = await loadNuxtModuleInstance(moduleToInstall, nuxt);
561
+ const localLayerModuleDirs = [];
562
+ for (const dirs of getLayerDirectories(nuxt)) if (!NODE_MODULES_RE.test(dirs.app)) localLayerModuleDirs.push(dirs.modules);
563
+ const meta = await nuxtModule.getMeta?.();
564
+ let mergedOptions = inlineOptions;
565
+ const configKey = meta?.configKey;
566
+ if (configKey && nuxt._moduleOptionsFunctions) {
567
+ const optionsFns = [...nuxt._moduleOptionsFunctions.get(moduleToInstall) || [], ...nuxt._moduleOptionsFunctions.get(configKey) || []];
568
+ if (optionsFns.length > 0) {
569
+ const overrides = [];
570
+ const defaults = [];
571
+ for (const fn of optionsFns) {
572
+ const options = fn();
573
+ overrides.push(options.overrides);
574
+ defaults.push(options.defaults);
575
+ }
576
+ mergedOptions = defu(inlineOptions, ...overrides, nuxt.options[configKey], ...defaults);
577
+ nuxt.options[configKey] = mergedOptions;
578
+ }
579
+ }
580
+ const isDisabled = configKey && !ignoredConfigKeys.has(configKey) && nuxt.options[configKey] === false;
581
+ if (!isDisabled) await callLifecycleHooks(nuxtModule, meta, mergedOptions, nuxt);
582
+ const path = typeof moduleToInstall === "string" ? moduleToInstall : void 0;
583
+ await callModule(nuxt, nuxtModule, mergedOptions, {
584
+ meta: defu({ disabled: isDisabled }, meta, buildTimeModuleMeta),
585
+ nameOrPath: path,
586
+ modulePath: resolvedModulePath || path,
587
+ localLayerModuleDirs
588
+ });
696
589
  }
697
590
  function resolveModuleWithOptions(definition, nuxt) {
698
- const [module, options = {}] = Array.isArray(definition) ? definition : [definition, {}];
699
- if (!module) {
700
- return;
701
- }
702
- if (typeof module !== "string") {
703
- return {
704
- module,
705
- options
706
- };
707
- }
708
- const modAlias = resolveAlias(module, nuxt.options.alias);
709
- const modPath = resolveModulePath(modAlias, {
710
- try: true,
711
- from: nuxt.options.modulesDir.map((m) => directoryToURL(m.replace(/\/node_modules\/?$/, "/"))),
712
- suffixes: ["nuxt", "nuxt/index", "module", "module/index", "", "index"],
713
- extensions: [".js", ".mjs", ".cjs", ".ts", ".mts", ".cts"]
714
- });
715
- return {
716
- module,
717
- resolvedPath: modPath || modAlias,
718
- options
719
- };
591
+ const [module, options = {}] = Array.isArray(definition) ? definition : [definition, {}];
592
+ if (!module) return;
593
+ if (typeof module !== "string") return {
594
+ module,
595
+ options
596
+ };
597
+ const modAlias = resolveAlias(module, nuxt.options.alias);
598
+ return {
599
+ module,
600
+ resolvedPath: resolveModulePath(modAlias, {
601
+ try: true,
602
+ from: nuxt.options.modulesDir.map((m) => directoryToURL(m.replace(/\/node_modules\/?$/, "/"))),
603
+ suffixes: [
604
+ "nuxt",
605
+ "nuxt/index",
606
+ "module",
607
+ "module/index",
608
+ "",
609
+ "index"
610
+ ],
611
+ extensions: [
612
+ ".js",
613
+ ".mjs",
614
+ ".cjs",
615
+ ".ts",
616
+ ".mts",
617
+ ".cts"
618
+ ]
619
+ }) || modAlias,
620
+ options
621
+ };
720
622
  }
721
623
  async function loadNuxtModuleInstance(nuxtModule, nuxt = useNuxt()) {
722
- let buildTimeModuleMeta = {};
723
- if (typeof nuxtModule === "function") {
724
- return {
725
- nuxtModule,
726
- buildTimeModuleMeta
727
- };
728
- }
729
- if (typeof nuxtModule !== "string") {
730
- throw new TypeError(`Nuxt module should be a function or a string to import. Received: ${nuxtModule}.`);
731
- }
732
- const jiti = createJiti(nuxt.options.rootDir, { alias: nuxt.options.alias });
733
- nuxtModule = resolveAlias(nuxtModule, nuxt.options.alias);
734
- if (isRelative(nuxtModule)) {
735
- nuxtModule = resolve(nuxt.options.rootDir, nuxtModule);
736
- }
737
- try {
738
- const src = resolveModuleURL(nuxtModule, {
739
- from: nuxt.options.modulesDir.map((m) => directoryToURL(m.replace(/\/node_modules\/?$/, "/"))),
740
- suffixes: ["nuxt", "nuxt/index", "module", "module/index", "", "index"],
741
- extensions: [".js", ".mjs", ".cjs", ".ts", ".mts", ".cts"]
742
- });
743
- const resolvedModulePath = fileURLToPath(src);
744
- const resolvedNuxtModule = await jiti.import(src, { default: true });
745
- if (typeof resolvedNuxtModule !== "function") {
746
- throw new TypeError(`Nuxt module should be a function: ${nuxtModule}.`);
747
- }
748
- const moduleMetadataPath = new URL("module.json", src);
749
- if (existsSync(moduleMetadataPath)) {
750
- buildTimeModuleMeta = JSON.parse(await promises.readFile(moduleMetadataPath, "utf-8"));
751
- }
752
- return { nuxtModule: resolvedNuxtModule, buildTimeModuleMeta, resolvedModulePath };
753
- } catch (error) {
754
- const code = error.code;
755
- if (code === "ERR_PACKAGE_PATH_NOT_EXPORTED" || code === "ERR_UNSUPPORTED_DIR_IMPORT" || code === "ENOTDIR") {
756
- throw new TypeError(`Could not load \`${nuxtModule}\`. Is it installed?`);
757
- }
758
- if (code === "MODULE_NOT_FOUND" || code === "ERR_MODULE_NOT_FOUND") {
759
- const module = MissingModuleMatcher.exec(error.message)?.[1];
760
- if (module && !module.includes(nuxtModule)) {
761
- throw new TypeError(`Error while importing module \`${nuxtModule}\`: ${error}`);
762
- }
763
- }
764
- }
765
- throw new TypeError(`Could not load \`${nuxtModule}\`. Is it installed?`);
624
+ let buildTimeModuleMeta = {};
625
+ if (typeof nuxtModule === "function") return {
626
+ nuxtModule,
627
+ buildTimeModuleMeta
628
+ };
629
+ if (typeof nuxtModule !== "string") throw new TypeError(`Nuxt module should be a function or a string to import. Received: ${nuxtModule}.`);
630
+ const jiti = createJiti(nuxt.options.rootDir, { alias: nuxt.options.alias });
631
+ nuxtModule = resolveAlias(nuxtModule, nuxt.options.alias);
632
+ if (isRelative(nuxtModule)) nuxtModule = resolve(nuxt.options.rootDir, nuxtModule);
633
+ try {
634
+ const src = resolveModuleURL(nuxtModule, {
635
+ from: nuxt.options.modulesDir.map((m) => directoryToURL(m.replace(/\/node_modules\/?$/, "/"))),
636
+ suffixes: [
637
+ "nuxt",
638
+ "nuxt/index",
639
+ "module",
640
+ "module/index",
641
+ "",
642
+ "index"
643
+ ],
644
+ extensions: [
645
+ ".js",
646
+ ".mjs",
647
+ ".cjs",
648
+ ".ts",
649
+ ".mts",
650
+ ".cts"
651
+ ]
652
+ });
653
+ const resolvedModulePath = fileURLToPath(src);
654
+ const resolvedNuxtModule = await jiti.import(src, { default: true });
655
+ if (typeof resolvedNuxtModule !== "function") throw new TypeError(`Nuxt module should be a function: ${nuxtModule}.`);
656
+ const moduleMetadataPath = new URL("module.json", src);
657
+ if (existsSync(moduleMetadataPath)) buildTimeModuleMeta = JSON.parse(await promises.readFile(moduleMetadataPath, "utf-8"));
658
+ return {
659
+ nuxtModule: resolvedNuxtModule,
660
+ buildTimeModuleMeta,
661
+ resolvedModulePath
662
+ };
663
+ } catch (error) {
664
+ const code = error.code;
665
+ if (code === "ERR_PACKAGE_PATH_NOT_EXPORTED" || code === "ERR_UNSUPPORTED_DIR_IMPORT" || code === "ENOTDIR") throw new TypeError(`Could not load \`${nuxtModule}\`. Is it installed?`);
666
+ if (code === "MODULE_NOT_FOUND" || code === "ERR_MODULE_NOT_FOUND") {
667
+ const module = MissingModuleMatcher.exec(error.message)?.[1];
668
+ if (module && !module.includes(nuxtModule)) throw new TypeError(`Error while importing module \`${nuxtModule}\`: ${error}`);
669
+ }
670
+ }
671
+ throw new TypeError(`Could not load \`${nuxtModule}\`. Is it installed?`);
766
672
  }
767
673
  function getDirectory(p) {
768
- try {
769
- return isAbsolute(p) && lstatSync(p).isFile() ? dirname(p) : p;
770
- } catch {
771
- }
772
- return p;
674
+ try {
675
+ return isAbsolute(p) && lstatSync(p).isFile() ? dirname(p) : p;
676
+ } catch {}
677
+ return p;
773
678
  }
774
679
  const normalizeModuleTranspilePath = (p) => {
775
- return getDirectory(p).split("node_modules/").pop();
680
+ return getDirectory(p).split("node_modules/").pop();
776
681
  };
777
682
  const MissingModuleMatcher = /Cannot find module\s+['"]?([^'")\s]+)['"]?/i;
778
683
  async function callLifecycleHooks(nuxtModule, meta = {}, inlineOptions, nuxt = useNuxt()) {
779
- if (!meta.name || !meta.version) {
780
- return;
781
- }
782
- if (!nuxtModule.onInstall && !nuxtModule.onUpgrade) {
783
- return;
784
- }
785
- const rc = read({ dir: nuxt.options.rootDir, name: ".nuxtrc" });
786
- const previousVersion = rc?.setups?.[meta.name];
787
- try {
788
- if (!previousVersion) {
789
- await nuxtModule.onInstall?.(nuxt);
790
- } else if (semver.gt(meta.version, previousVersion)) {
791
- await nuxtModule.onUpgrade?.(inlineOptions, nuxt, previousVersion);
792
- }
793
- if (previousVersion !== meta.version) {
794
- update(
795
- { setups: { [meta.name]: meta?.version } },
796
- { dir: nuxt.options.rootDir, name: ".nuxtrc" }
797
- );
798
- }
799
- } catch (e) {
800
- logger.error(
801
- `Error while executing ${!previousVersion ? "install" : "upgrade"} hook for module \`${meta.name}\`: ${e}`
802
- );
803
- }
804
- }
805
- async function callModule(nuxtModule, meta = {}, inlineOptions, resolvedModulePath, moduleToInstall, localLayerModuleDirs, buildTimeModuleMeta, nuxt = useNuxt()) {
806
- const res = nuxt.options.experimental?.debugModuleMutation && nuxt._asyncLocalStorageModule ? await nuxt._asyncLocalStorageModule.run(nuxtModule, () => nuxtModule(inlineOptions || {}, nuxt)) ?? {} : await nuxtModule(inlineOptions || {}, nuxt) ?? {};
807
- if (res === false) {
808
- return;
809
- }
810
- const modulePath = resolvedModulePath || moduleToInstall;
811
- let entryPath;
812
- if (typeof modulePath === "string") {
813
- const parsed = parseNodeModulePath(modulePath);
814
- if (parsed.name) {
815
- const subpath = await lookupNodeModuleSubpath(modulePath) || ".";
816
- entryPath = join(parsed.name, subpath === "./" ? "." : subpath);
817
- }
818
- const moduleRoot = parsed.dir ? parsed.dir + parsed.name : await resolvePackageJSON(modulePath, { try: true }).then((r) => r ? dirname(r) : modulePath);
819
- nuxt.options.build.transpile.push(normalizeModuleTranspilePath(moduleRoot));
820
- const directory = moduleRoot.replace(/\/?$/, "/");
821
- if (moduleRoot !== moduleToInstall && !localLayerModuleDirs.some((dir) => directory.startsWith(dir))) {
822
- nuxt.options.modulesDir.push(join(moduleRoot, "node_modules"));
823
- }
824
- }
825
- nuxt.options._installedModules ||= [];
826
- entryPath ||= typeof moduleToInstall === "string" ? resolveAlias(moduleToInstall, nuxt.options.alias) : void 0;
827
- if (typeof moduleToInstall === "string" && entryPath !== moduleToInstall) {
828
- buildTimeModuleMeta.rawPath = moduleToInstall;
829
- }
830
- nuxt.options._installedModules.push({
831
- meta: defu(meta, buildTimeModuleMeta),
832
- module: nuxtModule,
833
- timings: res.timings,
834
- entryPath
835
- });
836
- }
837
-
684
+ if (!meta.name || !meta.version) return;
685
+ if (!nuxtModule.onInstall && !nuxtModule.onUpgrade) return;
686
+ const previousVersion = read({
687
+ dir: nuxt.options.rootDir,
688
+ name: ".nuxtrc"
689
+ })?.setups?.[meta.name];
690
+ try {
691
+ if (!previousVersion) await nuxtModule.onInstall?.(nuxt);
692
+ else if (semver.gt(meta.version, previousVersion)) await nuxtModule.onUpgrade?.(nuxt, inlineOptions, previousVersion);
693
+ if (previousVersion !== meta.version) update({ setups: { [meta.name]: meta?.version } }, {
694
+ dir: nuxt.options.rootDir,
695
+ name: ".nuxtrc"
696
+ });
697
+ } catch (e) {
698
+ logger.error(`Error while executing ${!previousVersion ? "install" : "upgrade"} hook for module \`${meta.name}\`: ${e}`);
699
+ }
700
+ }
701
+ async function callModule(nuxt, nuxtModule, moduleOptions = {}, options) {
702
+ const modulePath = options.modulePath;
703
+ const nameOrPath = options.nameOrPath;
704
+ const localLayerModuleDirs = options.localLayerModuleDirs;
705
+ const fn = () => nuxt.options.experimental?.debugModuleMutation && nuxt._asyncLocalStorageModule ? nuxt._asyncLocalStorageModule.run(nuxtModule, () => nuxtModule(moduleOptions, nuxt)) : nuxtModule(moduleOptions, nuxt);
706
+ const res = options.meta.disabled ? false : await fn();
707
+ let entryPath;
708
+ if (typeof modulePath === "string") {
709
+ const parsed = parseNodeModulePath(modulePath);
710
+ if (parsed.name) {
711
+ const subpath = await lookupNodeModuleSubpath(modulePath) || ".";
712
+ entryPath = join(parsed.name, subpath === "./" ? "." : subpath);
713
+ }
714
+ if (res !== false) {
715
+ const moduleRoot = parsed.dir ? parsed.dir + parsed.name : await resolvePackageJSON(modulePath, { try: true }).then((r) => r ? dirname(r) : modulePath);
716
+ nuxt.options.build.transpile.push(normalizeModuleTranspilePath(moduleRoot));
717
+ const directory = moduleRoot.replace(/\/?$/, "/");
718
+ if (moduleRoot !== nameOrPath && !localLayerModuleDirs.some((dir) => directory.startsWith(dir))) nuxt.options.modulesDir.push(join(moduleRoot, "node_modules"));
719
+ }
720
+ }
721
+ if (nameOrPath) {
722
+ entryPath ||= resolveAlias(nameOrPath, nuxt.options.alias);
723
+ if (entryPath !== nameOrPath) options.meta.rawPath = nameOrPath;
724
+ }
725
+ nuxt.options._installedModules ||= [];
726
+ nuxt.options._installedModules.push({
727
+ meta: options.meta,
728
+ module: nuxtModule,
729
+ timings: (res || {}).timings,
730
+ entryPath
731
+ });
732
+ }
838
733
  function resolveNuxtModuleEntryName(m) {
839
- if (typeof m === "object" && !Array.isArray(m)) {
840
- return m.name;
841
- }
842
- if (Array.isArray(m)) {
843
- return resolveNuxtModuleEntryName(m[0]);
844
- }
845
- return m || false;
734
+ if (typeof m === "object" && !Array.isArray(m)) return m.name;
735
+ if (Array.isArray(m)) return resolveNuxtModuleEntryName(m[0]);
736
+ return m || false;
846
737
  }
847
738
  function hasNuxtModule(moduleName, nuxt = useNuxt()) {
848
- return nuxt.options._installedModules.some(({ meta }) => meta.name === moduleName) || // check modules to be installed
849
- nuxt.options.modules.some((m) => moduleName === resolveNuxtModuleEntryName(m));
739
+ return nuxt.options._installedModules.some(({ meta }) => meta.name === moduleName) || nuxt.options.modules.some((m) => moduleName === resolveNuxtModuleEntryName(m));
850
740
  }
851
741
  async function hasNuxtModuleCompatibility(module, semverVersion, nuxt = useNuxt()) {
852
- const version = await getNuxtModuleVersion(module, nuxt);
853
- if (!version) {
854
- return false;
855
- }
856
- return satisfies(normalizeSemanticVersion(version), semverVersion, {
857
- includePrerelease: true
858
- });
742
+ const version = await getNuxtModuleVersion(module, nuxt);
743
+ if (!version) return false;
744
+ return satisfies(normalizeSemanticVersion(version), semverVersion, { includePrerelease: true });
859
745
  }
860
746
  async function getNuxtModuleVersion(module, nuxt = useNuxt()) {
861
- const moduleMeta = (typeof module === "string" ? { name: module } : await module.getMeta?.()) || {};
862
- if (moduleMeta.version) {
863
- return moduleMeta.version;
864
- }
865
- if (!moduleMeta.name) {
866
- return false;
867
- }
868
- for (const m of nuxt.options._installedModules) {
869
- if (m.meta.name === moduleMeta.name && m.meta.version) {
870
- return m.meta.version;
871
- }
872
- }
873
- if (hasNuxtModule(moduleMeta.name)) {
874
- const { nuxtModule, buildTimeModuleMeta } = await loadNuxtModuleInstance(moduleMeta.name, nuxt);
875
- return buildTimeModuleMeta.version || await nuxtModule.getMeta?.().then((r) => r.version) || false;
876
- }
877
- return false;
878
- }
879
-
747
+ const moduleMeta = (typeof module === "string" ? { name: module } : await module.getMeta?.()) || {};
748
+ if (moduleMeta.version) return moduleMeta.version;
749
+ if (!moduleMeta.name) return false;
750
+ for (const m of nuxt.options._installedModules) if (m.meta.name === moduleMeta.name && m.meta.version) return m.meta.version;
751
+ if (hasNuxtModule(moduleMeta.name)) {
752
+ const { nuxtModule, buildTimeModuleMeta } = await loadNuxtModuleInstance(moduleMeta.name, nuxt);
753
+ return buildTimeModuleMeta.version || await nuxtModule.getMeta?.().then((r) => r.version) || false;
754
+ }
755
+ return false;
756
+ }
880
757
  const merger = createDefu((obj, key, value) => {
881
- if (Array.isArray(obj[key]) && Array.isArray(value)) {
882
- obj[key] = obj[key].concat(value);
883
- return true;
884
- }
758
+ if (Array.isArray(obj[key]) && Array.isArray(value)) {
759
+ obj[key] = obj[key].concat(value);
760
+ return true;
761
+ }
885
762
  });
886
763
  async function loadNuxtConfig(opts) {
887
- const localLayers = (await glob("layers/*", {
888
- onlyDirectories: true,
889
- cwd: opts.cwd || process.cwd()
890
- })).map((d) => d.endsWith("/") ? d.substring(0, d.length - 1) : d).sort((a, b) => b.localeCompare(a));
891
- opts.overrides = defu$1(opts.overrides, { _extends: localLayers });
892
- const { configFile, layers = [], cwd, config: nuxtConfig, meta } = await withDefineNuxtConfig(
893
- () => loadConfig({
894
- name: "nuxt",
895
- configFile: "nuxt.config",
896
- rcFile: ".nuxtrc",
897
- extend: { extendKey: ["theme", "_extends", "extends"] },
898
- dotenv: true,
899
- globalRc: true,
900
- // @ts-expect-error TODO: fix type in c12, it should accept createDefu directly
901
- merger,
902
- ...opts
903
- })
904
- );
905
- nuxtConfig.rootDir ||= cwd;
906
- nuxtConfig._nuxtConfigFile = configFile;
907
- nuxtConfig._nuxtConfigFiles = [configFile];
908
- nuxtConfig._loadOptions = opts;
909
- nuxtConfig.alias ||= {};
910
- if (meta?.name) {
911
- const alias = `#layers/${meta.name}`;
912
- nuxtConfig.alias[alias] ||= withTrailingSlash$2(nuxtConfig.rootDir);
913
- }
914
- const defaultBuildDir = join(nuxtConfig.rootDir, ".nuxt");
915
- if (!opts.overrides?._prepare && !nuxtConfig.dev && !nuxtConfig.buildDir && existsSync(defaultBuildDir)) {
916
- nuxtConfig.buildDir = join(nuxtConfig.rootDir, "node_modules/.cache/nuxt/.nuxt");
917
- }
918
- const NuxtConfigSchema = await loadNuxtSchema(nuxtConfig.rootDir || cwd || process.cwd());
919
- const layerSchemaKeys = ["future", "srcDir", "rootDir", "serverDir", "dir"];
920
- const layerSchema = /* @__PURE__ */ Object.create(null);
921
- for (const key of layerSchemaKeys) {
922
- if (key in NuxtConfigSchema) {
923
- layerSchema[key] = NuxtConfigSchema[key];
924
- }
925
- }
926
- const _layers = [];
927
- const processedLayers = /* @__PURE__ */ new Set();
928
- const localRelativePaths = new Set(localLayers);
929
- for (const layer of layers) {
930
- const resolvedRootDir = layer.config?.rootDir ?? layer.cwd;
931
- layer.config = {
932
- ...layer.config || {},
933
- rootDir: resolvedRootDir
934
- };
935
- if (processedLayers.has(resolvedRootDir)) {
936
- continue;
937
- }
938
- processedLayers.add(resolvedRootDir);
939
- layer.config = await applyDefaults(layerSchema, layer.config);
940
- if (!layer.configFile || layer.configFile.endsWith(".nuxtrc")) {
941
- continue;
942
- }
943
- if (layer.cwd && cwd && localRelativePaths.has(relative(cwd, layer.cwd))) {
944
- layer.meta ||= {};
945
- layer.meta.name ||= basename(layer.cwd);
946
- }
947
- if (layer.meta?.name) {
948
- const alias = `#layers/${layer.meta.name}`;
949
- nuxtConfig.alias[alias] ||= withTrailingSlash$2(layer.config.rootDir || layer.cwd);
950
- }
951
- _layers.push(layer);
952
- }
953
- nuxtConfig._layers = _layers;
954
- if (!_layers.length) {
955
- _layers.push({
956
- cwd,
957
- config: {
958
- rootDir: cwd,
959
- srcDir: cwd
960
- }
961
- });
962
- }
963
- return await applyDefaults(NuxtConfigSchema, nuxtConfig);
764
+ const localLayers = (await glob("layers/*", {
765
+ onlyDirectories: true,
766
+ cwd: opts.cwd || process.cwd()
767
+ })).map((d) => withTrailingSlash(d)).sort((a, b) => b.localeCompare(a));
768
+ opts.overrides = defu(opts.overrides, { _extends: localLayers });
769
+ const { configFile, layers = [], cwd, config: nuxtConfig, meta } = await withDefineNuxtConfig(() => loadConfig({
770
+ name: "nuxt",
771
+ configFile: "nuxt.config",
772
+ rcFile: ".nuxtrc",
773
+ extend: { extendKey: [
774
+ "theme",
775
+ "_extends",
776
+ "extends"
777
+ ] },
778
+ dotenv: true,
779
+ globalRc: true,
780
+ merger,
781
+ ...opts
782
+ }));
783
+ nuxtConfig.rootDir ||= cwd;
784
+ nuxtConfig._nuxtConfigFile = configFile;
785
+ nuxtConfig._nuxtConfigFiles = [configFile];
786
+ nuxtConfig._loadOptions = opts;
787
+ nuxtConfig.alias ||= {};
788
+ if (meta?.name) {
789
+ const alias = `#layers/${meta.name}`;
790
+ nuxtConfig.alias[alias] ||= withTrailingSlash(nuxtConfig.rootDir);
791
+ }
792
+ const defaultBuildDir = join(nuxtConfig.rootDir, ".nuxt");
793
+ if (!opts.overrides?._prepare && !nuxtConfig.dev && !nuxtConfig.buildDir && existsSync(defaultBuildDir)) nuxtConfig.buildDir = join(nuxtConfig.rootDir, "node_modules/.cache/nuxt/.nuxt");
794
+ const NuxtConfigSchema = await loadNuxtSchema(nuxtConfig.rootDir || cwd || process.cwd());
795
+ const layerSchemaKeys = [
796
+ "future",
797
+ "srcDir",
798
+ "rootDir",
799
+ "serverDir",
800
+ "dir"
801
+ ];
802
+ const layerSchema = Object.create(null);
803
+ for (const key of layerSchemaKeys) if (key in NuxtConfigSchema) layerSchema[key] = NuxtConfigSchema[key];
804
+ const _layers = [];
805
+ const processedLayers = /* @__PURE__ */ new Set();
806
+ const localRelativePaths = new Set(localLayers.map((layer) => withoutTrailingSlash(layer)));
807
+ for (const layer of layers) {
808
+ const resolvedRootDir = layer.config?.rootDir ?? layer.cwd;
809
+ layer.config = {
810
+ ...layer.config || {},
811
+ rootDir: resolvedRootDir
812
+ };
813
+ if (processedLayers.has(resolvedRootDir)) continue;
814
+ processedLayers.add(resolvedRootDir);
815
+ layer.config = await applyDefaults(layerSchema, layer.config);
816
+ if (!layer.configFile || layer.configFile.endsWith(".nuxtrc")) continue;
817
+ if (layer.cwd && cwd && localRelativePaths.has(relative(cwd, layer.cwd))) {
818
+ layer.meta ||= {};
819
+ layer.meta.name ||= basename(layer.cwd);
820
+ }
821
+ if (layer.meta?.name) {
822
+ const alias = `#layers/${layer.meta.name}`;
823
+ nuxtConfig.alias[alias] ||= withTrailingSlash(layer.config.rootDir || layer.cwd);
824
+ }
825
+ _layers.push(layer);
826
+ }
827
+ nuxtConfig._layers = _layers;
828
+ if (!_layers.length) _layers.push({
829
+ cwd,
830
+ config: {
831
+ rootDir: cwd,
832
+ srcDir: cwd
833
+ }
834
+ });
835
+ return await applyDefaults(NuxtConfigSchema, nuxtConfig);
964
836
  }
965
837
  async function loadNuxtSchema(cwd) {
966
- const url = directoryToURL(cwd);
967
- const urls = [url];
968
- const nuxtPath = resolveModuleURL("nuxt", { try: true, from: url }) ?? resolveModuleURL("nuxt-nightly", { try: true, from: url });
969
- if (nuxtPath) {
970
- urls.unshift(nuxtPath);
971
- }
972
- const schemaPath = resolveModuleURL("@nuxt/schema", { try: true, from: urls }) ?? "@nuxt/schema";
973
- return await import(schemaPath).then((r) => r.NuxtConfigSchema);
838
+ const url = directoryToURL(cwd);
839
+ const urls = [url];
840
+ const nuxtPath = resolveModuleURL("nuxt", {
841
+ try: true,
842
+ from: url
843
+ }) ?? resolveModuleURL("nuxt-nightly", {
844
+ try: true,
845
+ from: url
846
+ });
847
+ if (nuxtPath) urls.unshift(nuxtPath);
848
+ return await import(resolveModuleURL("@nuxt/schema", {
849
+ try: true,
850
+ from: urls
851
+ }) ?? "@nuxt/schema").then((r) => r.NuxtConfigSchema);
974
852
  }
975
853
  async function withDefineNuxtConfig(fn) {
976
- const key = "defineNuxtConfig";
977
- const globalSelf = globalThis;
978
- if (!globalSelf[key]) {
979
- globalSelf[key] = (c) => c;
980
- globalSelf[key].count = 0;
981
- }
982
- globalSelf[key].count++;
983
- try {
984
- return await fn();
985
- } finally {
986
- globalSelf[key].count--;
987
- if (!globalSelf[key].count) {
988
- delete globalSelf[key];
989
- }
990
- }
991
- }
992
-
854
+ const key = "defineNuxtConfig";
855
+ const globalSelf = globalThis;
856
+ if (!globalSelf[key]) {
857
+ globalSelf[key] = (c) => c;
858
+ globalSelf[key].count = 0;
859
+ }
860
+ globalSelf[key].count++;
861
+ try {
862
+ return await fn();
863
+ } finally {
864
+ globalSelf[key].count--;
865
+ if (!globalSelf[key].count) delete globalSelf[key];
866
+ }
867
+ }
993
868
  function extendNuxtSchema(def) {
994
- const nuxt = useNuxt();
995
- nuxt.hook("schema:extend", (schemas) => {
996
- schemas.push(typeof def === "function" ? def() : def);
997
- });
869
+ useNuxt().hook("schema:extend", (schemas) => {
870
+ schemas.push(typeof def === "function" ? def() : def);
871
+ });
998
872
  }
999
-
1000
873
  async function loadNuxt(opts) {
1001
- opts.cwd = resolve(opts.cwd || opts.rootDir || ".");
1002
- opts.overrides ||= opts.config || {};
1003
- opts.overrides.dev = !!opts.dev;
1004
- const resolvedPath = ["nuxt-nightly", "nuxt"].reduce((resolvedPath2, pkg) => {
1005
- const path = resolveModulePath(pkg, { try: true, from: [directoryToURL(opts.cwd)] });
1006
- return path && path.length > resolvedPath2.length ? path : resolvedPath2;
1007
- }, "");
1008
- if (!resolvedPath) {
1009
- throw new Error(`Cannot find any nuxt version from ${opts.cwd}`);
1010
- }
1011
- const { loadNuxt: loadNuxt2 } = await import(pathToFileURL(resolvedPath).href).then((r) => interopDefault(r));
1012
- const nuxt = await loadNuxt2(opts);
1013
- return nuxt;
874
+ opts.cwd = resolve(opts.cwd || opts.rootDir || ".");
875
+ opts.overrides ||= opts.config || {};
876
+ opts.overrides.dev = !!opts.dev;
877
+ const resolvedPath = ["nuxt-nightly", "nuxt"].reduce((resolvedPath, pkg) => {
878
+ const path = resolveModulePath(pkg, {
879
+ try: true,
880
+ from: [directoryToURL(opts.cwd)]
881
+ });
882
+ return path && path.length > resolvedPath.length ? path : resolvedPath;
883
+ }, "");
884
+ if (!resolvedPath) throw new Error(`Cannot find any nuxt version from ${opts.cwd}`);
885
+ const { loadNuxt } = await import(pathToFileURL(resolvedPath).href).then((r) => interopDefault(r));
886
+ return await loadNuxt(opts);
1014
887
  }
1015
888
  async function buildNuxt(nuxt) {
1016
- const rootURL = directoryToURL(nuxt.options.rootDir);
1017
- const { build } = await tryImportModule("nuxt-nightly", { url: rootURL }) || await importModule("nuxt", { url: rootURL });
1018
- return runWithNuxtContext(nuxt, () => build(nuxt));
889
+ const rootURL = directoryToURL(nuxt.options.rootDir);
890
+ const { build } = await tryImportModule("nuxt-nightly", { url: rootURL }) || await importModule("nuxt", { url: rootURL });
891
+ return runWithNuxtContext(nuxt, () => build(nuxt));
1019
892
  }
1020
-
1021
893
  function setGlobalHead(head) {
1022
- const nuxt = useNuxt();
1023
- nuxt.options.app.head = defu(head, nuxt.options.app.head);
894
+ const nuxt = useNuxt();
895
+ nuxt.options.app.head = defu(head, nuxt.options.app.head);
1024
896
  }
1025
-
1026
897
  function addImports(imports) {
1027
- useNuxt().hook("imports:extend", (_imports) => {
1028
- _imports.push(...toArray(imports));
1029
- });
898
+ useNuxt().hook("imports:extend", (_imports) => {
899
+ _imports.push(...toArray(imports));
900
+ });
1030
901
  }
1031
902
  function addImportsDir(dirs, opts = {}) {
1032
- useNuxt().hook("imports:dirs", (_dirs) => {
1033
- for (const dir of toArray(dirs)) {
1034
- _dirs[opts.prepend ? "unshift" : "push"](dir);
1035
- }
1036
- });
903
+ useNuxt().hook("imports:dirs", (_dirs) => {
904
+ for (const dir of toArray(dirs)) _dirs[opts.prepend ? "unshift" : "push"](dir);
905
+ });
1037
906
  }
1038
907
  function addImportsSources(presets) {
1039
- useNuxt().hook("imports:sources", (_presets) => {
1040
- for (const preset of toArray(presets)) {
1041
- _presets.push(preset);
1042
- }
1043
- });
908
+ useNuxt().hook("imports:sources", (_presets) => {
909
+ for (const preset of toArray(presets)) _presets.push(preset);
910
+ });
1044
911
  }
1045
-
1046
912
  const HANDLER_METHOD_RE = /\.(get|head|patch|post|put|delete|connect|options|trace)(\.\w+)*$/;
1047
913
  function normalizeHandlerMethod(handler) {
1048
- const [, method = void 0] = handler.handler.match(HANDLER_METHOD_RE) || [];
1049
- return {
1050
- method,
1051
- ...handler,
1052
- handler: normalize(handler.handler)
1053
- };
914
+ const [, method = void 0] = handler.handler.match(HANDLER_METHOD_RE) || [];
915
+ return {
916
+ method: method?.toUpperCase(),
917
+ ...handler,
918
+ handler: normalize(handler.handler)
919
+ };
1054
920
  }
1055
921
  function addServerHandler(handler) {
1056
- useNuxt().options.serverHandlers.push(normalizeHandlerMethod(handler));
922
+ useNuxt().options.serverHandlers.push(normalizeHandlerMethod(handler));
1057
923
  }
1058
924
  function addDevServerHandler(handler) {
1059
- useNuxt().options.devServerHandlers.push(handler);
925
+ useNuxt().options.devServerHandlers.push(handler);
1060
926
  }
1061
927
  function addServerPlugin(plugin) {
1062
- const nuxt = useNuxt();
1063
- nuxt.options.nitro.plugins ||= [];
1064
- nuxt.options.nitro.plugins.push(normalize(plugin));
928
+ const nuxt = useNuxt();
929
+ nuxt.options.nitro.plugins ||= [];
930
+ nuxt.options.nitro.plugins.push(normalize(plugin));
1065
931
  }
1066
932
  function addPrerenderRoutes(routes) {
1067
- const nuxt = useNuxt();
1068
- routes = toArray(routes).filter(Boolean);
1069
- if (!routes.length) {
1070
- return;
1071
- }
1072
- nuxt.hook("prerender:routes", (ctx) => {
1073
- for (const route of routes) {
1074
- ctx.routes.add(route);
1075
- }
1076
- });
933
+ const nuxt = useNuxt();
934
+ routes = toArray(routes).filter(Boolean);
935
+ if (!routes.length) return;
936
+ nuxt.hook("prerender:routes", (ctx) => {
937
+ for (const route of routes) ctx.routes.add(route);
938
+ });
1077
939
  }
1078
940
  function useNitro() {
1079
- const nuxt = useNuxt();
1080
- if (!nuxt._nitro) {
1081
- throw new Error("Nitro is not initialized yet. You can call `useNitro()` only after `ready` hook.");
1082
- }
1083
- return nuxt._nitro;
941
+ const nuxt = useNuxt();
942
+ if (!nuxt._nitro) throw new Error("Nitro is not initialized yet. You can call `useNitro()` only after `ready` hook.");
943
+ return nuxt._nitro;
1084
944
  }
1085
945
  function addServerImports(imports) {
1086
- const nuxt = useNuxt();
1087
- const _imports = toArray(imports);
1088
- nuxt.hook("nitro:config", (config) => {
1089
- config.imports ||= {};
1090
- config.imports.imports ||= [];
1091
- config.imports.imports.push(..._imports);
1092
- });
946
+ const nuxt = useNuxt();
947
+ const _imports = toArray(imports);
948
+ nuxt.hook("nitro:config", (config) => {
949
+ config.imports ||= {};
950
+ config.imports.imports ||= [];
951
+ config.imports.imports.push(..._imports);
952
+ });
1093
953
  }
1094
954
  function addServerImportsDir(dirs, opts = {}) {
1095
- const nuxt = useNuxt();
1096
- const _dirs = toArray(dirs);
1097
- nuxt.hook("nitro:config", (config) => {
1098
- config.imports ||= {};
1099
- config.imports.dirs ||= [];
1100
- config.imports.dirs[opts.prepend ? "unshift" : "push"](..._dirs);
1101
- });
955
+ const nuxt = useNuxt();
956
+ const _dirs = toArray(dirs);
957
+ nuxt.hook("nitro:config", (config) => {
958
+ config.imports ||= {};
959
+ config.imports.dirs ||= [];
960
+ config.imports.dirs[opts.prepend ? "unshift" : "push"](..._dirs);
961
+ });
1102
962
  }
1103
963
  function addServerScanDir(dirs, opts = {}) {
1104
- const nuxt = useNuxt();
1105
- nuxt.hook("nitro:config", (config) => {
1106
- config.scanDirs ||= [];
1107
- for (const dir of toArray(dirs)) {
1108
- config.scanDirs[opts.prepend ? "unshift" : "push"](dir);
1109
- }
1110
- });
1111
- }
1112
-
964
+ useNuxt().hook("nitro:config", (config) => {
965
+ config.scanDirs ||= [];
966
+ for (const dir of toArray(dirs)) config.scanDirs[opts.prepend ? "unshift" : "push"](dir);
967
+ });
968
+ }
1113
969
  function useRuntimeConfig() {
1114
- const nuxt = useNuxt();
1115
- return applyEnv(klona(nuxt.options.nitro.runtimeConfig), {
1116
- prefix: "NITRO_",
1117
- altPrefix: "NUXT_",
1118
- envExpansion: nuxt.options.nitro.experimental?.envExpansion ?? !!process.env.NITRO_ENV_EXPANSION
1119
- });
970
+ const nuxt = useNuxt();
971
+ return applyEnv(klona(nuxt.options.nitro.runtimeConfig), {
972
+ prefix: "NITRO_",
973
+ altPrefix: "NUXT_",
974
+ envExpansion: nuxt.options.nitro.experimental?.envExpansion ?? !!process.env.NITRO_ENV_EXPANSION
975
+ });
1120
976
  }
1121
977
  function updateRuntimeConfig(runtimeConfig) {
1122
- const nuxt = useNuxt();
1123
- Object.assign(nuxt.options.nitro.runtimeConfig, defu$1(runtimeConfig, nuxt.options.nitro.runtimeConfig));
1124
- try {
1125
- return useNitro().updateConfig({ runtimeConfig });
1126
- } catch {
1127
- }
978
+ const nuxt = useNuxt();
979
+ Object.assign(nuxt.options.nitro.runtimeConfig, defu(runtimeConfig, nuxt.options.nitro.runtimeConfig));
980
+ try {
981
+ return useNitro().updateConfig({ runtimeConfig });
982
+ } catch {}
1128
983
  }
1129
984
  function getEnv(key, opts, env = process.env) {
1130
- const envKey = snakeCase(key).toUpperCase();
1131
- return destr(
1132
- env[opts.prefix + envKey] ?? env[opts.altPrefix + envKey]
1133
- );
985
+ const envKey = snakeCase(key).toUpperCase();
986
+ return destr(env[opts.prefix + envKey] ?? env[opts.altPrefix + envKey]);
1134
987
  }
1135
988
  function _isObject(input) {
1136
- return typeof input === "object" && !Array.isArray(input);
989
+ return typeof input === "object" && !Array.isArray(input);
1137
990
  }
1138
991
  function applyEnv(obj, opts, parentKey = "") {
1139
- for (const key in obj) {
1140
- const subKey = parentKey ? `${parentKey}_${key}` : key;
1141
- const envValue = getEnv(subKey, opts);
1142
- if (_isObject(obj[key])) {
1143
- if (_isObject(envValue)) {
1144
- obj[key] = { ...obj[key], ...envValue };
1145
- applyEnv(obj[key], opts, subKey);
1146
- } else if (envValue === void 0) {
1147
- applyEnv(obj[key], opts, subKey);
1148
- } else {
1149
- obj[key] = envValue ?? obj[key];
1150
- }
1151
- } else {
1152
- obj[key] = envValue ?? obj[key];
1153
- }
1154
- if (opts.envExpansion && typeof obj[key] === "string") {
1155
- obj[key] = _expandFromEnv(obj[key]);
1156
- }
1157
- }
1158
- return obj;
992
+ for (const key in obj) {
993
+ const subKey = parentKey ? `${parentKey}_${key}` : key;
994
+ const envValue = getEnv(subKey, opts);
995
+ if (_isObject(obj[key])) if (_isObject(envValue)) {
996
+ obj[key] = {
997
+ ...obj[key],
998
+ ...envValue
999
+ };
1000
+ applyEnv(obj[key], opts, subKey);
1001
+ } else if (envValue === void 0) applyEnv(obj[key], opts, subKey);
1002
+ else obj[key] = envValue ?? obj[key];
1003
+ else obj[key] = envValue ?? obj[key];
1004
+ if (opts.envExpansion && typeof obj[key] === "string") obj[key] = _expandFromEnv(obj[key]);
1005
+ }
1006
+ return obj;
1159
1007
  }
1160
1008
  const envExpandRx = /\{\{([^{}]*)\}\}/g;
1161
1009
  function _expandFromEnv(value, env = process.env) {
1162
- return value.replace(envExpandRx, (match, key) => {
1163
- return env[key] || match;
1164
- });
1010
+ return value.replace(envExpandRx, (match, key) => {
1011
+ return env[key] || match;
1012
+ });
1165
1013
  }
1166
-
1167
1014
  const extendWebpackCompatibleConfig = (builder) => (fn, options = {}) => {
1168
- const nuxt = useNuxt();
1169
- if (options.dev === false && nuxt.options.dev) {
1170
- return;
1171
- }
1172
- if (options.build === false && nuxt.options.build) {
1173
- return;
1174
- }
1175
- nuxt.hook(`${builder}:config`, (configs) => {
1176
- if (options.server !== false) {
1177
- const config = configs.find((i) => i.name === "server");
1178
- if (config) {
1179
- fn(config);
1180
- }
1181
- }
1182
- if (options.client !== false) {
1183
- const config = configs.find((i) => i.name === "client");
1184
- if (config) {
1185
- fn(config);
1186
- }
1187
- }
1188
- });
1015
+ const nuxt = useNuxt();
1016
+ if (options.dev === false && nuxt.options.dev) return;
1017
+ if (options.build === false && nuxt.options.build) return;
1018
+ nuxt.hook(`${builder}:config`, async (configs) => {
1019
+ if (options.server !== false) {
1020
+ const config = configs.find((i) => i.name === "server");
1021
+ if (config) await fn(config);
1022
+ }
1023
+ if (options.client !== false) {
1024
+ const config = configs.find((i) => i.name === "client");
1025
+ if (config) await fn(config);
1026
+ }
1027
+ });
1189
1028
  };
1190
1029
  const extendWebpackConfig = extendWebpackCompatibleConfig("webpack");
1191
1030
  const extendRspackConfig = extendWebpackCompatibleConfig("rspack");
1192
1031
  function extendViteConfig(fn, options = {}) {
1193
- const nuxt = useNuxt();
1194
- if (options.dev === false && nuxt.options.dev) {
1195
- return;
1196
- }
1197
- if (options.build === false && nuxt.options.build) {
1198
- return;
1199
- }
1200
- if (options.server === false || options.client === false) {
1201
- const caller = getUserCaller();
1202
- const explanation = caller ? ` (used at \`${resolveAlias(caller.source)}:${caller.line}:${caller.column}\`)` : "";
1203
- const warning = `[@nuxt/kit] calling \`extendViteConfig\` with only server/client environment is deprecated${explanation}. Nuxt 5+ will use the Vite Environment API which shares a configuration between environments. You can likely use a Vite plugin to achieve the same result.`;
1204
- warn(warning);
1205
- }
1206
- return nuxt.hook("vite:extend", ({ config }) => fn(config));
1032
+ const nuxt = useNuxt();
1033
+ if (options.dev === false && nuxt.options.dev) return;
1034
+ if (options.build === false && nuxt.options.build) return;
1035
+ if (options.server === false || options.client === false) {
1036
+ const caller = getUserCaller();
1037
+ warn(`[@nuxt/kit] calling \`extendViteConfig\` with only server/client environment is deprecated${caller ? ` (used at \`${resolveAlias(caller.source)}:${caller.line}:${caller.column}\`)` : ""}. Nuxt 5+ will use the Vite Environment API which shares a configuration between environments. You can likely use a Vite plugin to achieve the same result.`);
1038
+ }
1039
+ return nuxt.hook("vite:extend", ({ config }) => fn(config));
1207
1040
  }
1208
1041
  function addWebpackPlugin(pluginOrGetter, options) {
1209
- extendWebpackConfig((config) => {
1210
- const method = options?.prepend ? "unshift" : "push";
1211
- const plugin = typeof pluginOrGetter === "function" ? pluginOrGetter() : pluginOrGetter;
1212
- config.plugins ||= [];
1213
- config.plugins[method](...toArray(plugin));
1214
- }, options);
1042
+ extendWebpackConfig(async (config) => {
1043
+ const method = options?.prepend ? "unshift" : "push";
1044
+ const plugin = typeof pluginOrGetter === "function" ? await pluginOrGetter() : pluginOrGetter;
1045
+ config.plugins ||= [];
1046
+ config.plugins[method](...toArray(plugin));
1047
+ }, options);
1215
1048
  }
1216
1049
  function addRspackPlugin(pluginOrGetter, options) {
1217
- extendRspackConfig((config) => {
1218
- const method = options?.prepend ? "unshift" : "push";
1219
- const plugin = typeof pluginOrGetter === "function" ? pluginOrGetter() : pluginOrGetter;
1220
- config.plugins ||= [];
1221
- config.plugins[method](...toArray(plugin));
1222
- }, options);
1050
+ extendRspackConfig(async (config) => {
1051
+ const method = options?.prepend ? "unshift" : "push";
1052
+ const plugin = typeof pluginOrGetter === "function" ? await pluginOrGetter() : pluginOrGetter;
1053
+ config.plugins ||= [];
1054
+ config.plugins[method](...toArray(plugin));
1055
+ }, options);
1223
1056
  }
1224
1057
  function addVitePlugin(pluginOrGetter, options = {}) {
1225
- const nuxt = useNuxt();
1226
- if (options.dev === false && nuxt.options.dev) {
1227
- return;
1228
- }
1229
- if (options.build === false && nuxt.options.build) {
1230
- return;
1231
- }
1232
- let needsEnvInjection = false;
1233
- nuxt.hook("vite:extend", ({ config }) => {
1234
- config.plugins ||= [];
1235
- const plugin = toArray(typeof pluginOrGetter === "function" ? pluginOrGetter() : pluginOrGetter);
1236
- if (options.server !== false && options.client !== false) {
1237
- const method = options?.prepend ? "unshift" : "push";
1238
- config.plugins[method](...plugin);
1239
- return;
1240
- }
1241
- if (!config.environments?.ssr || !config.environments.client) {
1242
- needsEnvInjection = true;
1243
- return;
1244
- }
1245
- const environmentName = options.server === false ? "client" : "ssr";
1246
- const pluginName = plugin.map((p) => p.name).join("|");
1247
- config.plugins.push({
1248
- name: `${pluginName}:wrapper`,
1249
- enforce: options?.prepend ? "pre" : "post",
1250
- applyToEnvironment(environment) {
1251
- if (environment.name === environmentName) {
1252
- return plugin;
1253
- }
1254
- }
1255
- });
1256
- });
1257
- nuxt.hook("vite:extendConfig", (config, env) => {
1258
- if (!needsEnvInjection) {
1259
- return;
1260
- }
1261
- const plugin = toArray(typeof pluginOrGetter === "function" ? pluginOrGetter() : pluginOrGetter);
1262
- const method = options?.prepend ? "unshift" : "push";
1263
- if (env.isClient && options.server === false) {
1264
- config.plugins[method](...plugin);
1265
- }
1266
- if (env.isServer && options.client === false) {
1267
- config.plugins[method](...plugin);
1268
- }
1269
- });
1058
+ const nuxt = useNuxt();
1059
+ if (options.dev === false && nuxt.options.dev) return;
1060
+ if (options.build === false && nuxt.options.build) return;
1061
+ let needsEnvInjection = false;
1062
+ nuxt.hook("vite:extend", async ({ config }) => {
1063
+ config.plugins ||= [];
1064
+ const plugin = toArray(typeof pluginOrGetter === "function" ? await pluginOrGetter() : pluginOrGetter);
1065
+ if (options.server !== false && options.client !== false) {
1066
+ const method = options?.prepend ? "unshift" : "push";
1067
+ config.plugins[method](...plugin);
1068
+ return;
1069
+ }
1070
+ if (!config.environments?.ssr || !config.environments.client) {
1071
+ needsEnvInjection = true;
1072
+ return;
1073
+ }
1074
+ const environmentName = options.server === false ? "client" : "ssr";
1075
+ const pluginName = plugin.map((p) => p.name).join("|");
1076
+ config.plugins.push({
1077
+ name: `${pluginName}:wrapper`,
1078
+ enforce: options?.prepend ? "pre" : "post",
1079
+ applyToEnvironment(environment) {
1080
+ if (environment.name === environmentName) return plugin;
1081
+ }
1082
+ });
1083
+ });
1084
+ nuxt.hook("vite:extendConfig", async (config, env) => {
1085
+ if (!needsEnvInjection) return;
1086
+ const plugin = toArray(typeof pluginOrGetter === "function" ? await pluginOrGetter() : pluginOrGetter);
1087
+ const method = options?.prepend ? "unshift" : "push";
1088
+ if (env.isClient && options.server === false) config.plugins[method](...plugin);
1089
+ if (env.isServer && options.client === false) config.plugins[method](...plugin);
1090
+ });
1270
1091
  }
1271
1092
  function addBuildPlugin(pluginFactory, options) {
1272
- if (pluginFactory.vite) {
1273
- addVitePlugin(pluginFactory.vite, options);
1274
- }
1275
- if (pluginFactory.webpack) {
1276
- addWebpackPlugin(pluginFactory.webpack, options);
1277
- }
1278
- if (pluginFactory.rspack) {
1279
- addRspackPlugin(pluginFactory.rspack, options);
1280
- }
1281
- }
1282
-
1093
+ if (pluginFactory.vite) addVitePlugin(pluginFactory.vite, options);
1094
+ if (pluginFactory.webpack) addWebpackPlugin(pluginFactory.webpack, options);
1095
+ if (pluginFactory.rspack) addRspackPlugin(pluginFactory.rspack, options);
1096
+ }
1283
1097
  function addComponentsDir(dir, opts = {}) {
1284
- const nuxt = useNuxt();
1285
- nuxt.options.components ||= [];
1286
- dir.priority ||= 0;
1287
- nuxt.hook("components:dirs", (dirs) => {
1288
- dirs[opts.prepend ? "unshift" : "push"](dir);
1289
- });
1098
+ const nuxt = useNuxt();
1099
+ nuxt.options.components ||= [];
1100
+ dir.priority ||= 0;
1101
+ nuxt.hook("components:dirs", (dirs) => {
1102
+ dirs[opts.prepend ? "unshift" : "push"](dir);
1103
+ });
1290
1104
  }
1291
1105
  function addComponentExports(opts) {
1292
- const nuxt = useNuxt();
1293
- const components = [];
1294
- nuxt.hook("components:dirs", async () => {
1295
- const filePath = await resolvePath(opts.filePath);
1296
- const names = await resolveModuleExportNames(filePath, { extensions: nuxt.options.extensions });
1297
- components.length = 0;
1298
- for (const name of names) {
1299
- components.push(normalizeComponent({ name: pascalCase([opts.prefix || "", name === "default" ? "" : name]), export: name, ...opts }));
1300
- }
1301
- });
1302
- addComponents(components);
1106
+ const nuxt = useNuxt();
1107
+ const components = [];
1108
+ nuxt.hook("components:dirs", async () => {
1109
+ const names = await resolveModuleExportNames(await resolvePath(opts.filePath), { extensions: nuxt.options.extensions });
1110
+ components.length = 0;
1111
+ for (const name of names) components.push(normalizeComponent({
1112
+ name: pascalCase([opts.prefix || "", name === "default" ? "" : name]),
1113
+ export: name,
1114
+ ...opts
1115
+ }));
1116
+ });
1117
+ addComponents(components);
1303
1118
  }
1304
1119
  function addComponent(opts) {
1305
- const component = normalizeComponent(opts);
1306
- addComponents([component]);
1120
+ addComponents([normalizeComponent(opts)]);
1307
1121
  }
1308
1122
  function addComponents(addedComponents) {
1309
- const nuxt = useNuxt();
1310
- nuxt.options.components ||= [];
1311
- nuxt.hook("components:extend", (components) => {
1312
- for (const component of addedComponents) {
1313
- const existingComponentIndex = components.findIndex((c) => (c.pascalName === component.pascalName || c.kebabName === component.kebabName) && c.mode === component.mode);
1314
- if (existingComponentIndex !== -1) {
1315
- const existingComponent = components[existingComponentIndex];
1316
- const existingPriority = existingComponent.priority ?? 0;
1317
- const newPriority = component.priority ?? 0;
1318
- if (newPriority < existingPriority) {
1319
- return;
1320
- }
1321
- if (newPriority === existingPriority) {
1322
- const name = existingComponent.pascalName || existingComponent.kebabName;
1323
- logger.warn(`Overriding ${name} component. You can specify a \`priority\` option when calling \`addComponent\` to avoid this warning.`);
1324
- }
1325
- components.splice(existingComponentIndex, 1, component);
1326
- } else {
1327
- components.push(component);
1328
- }
1329
- }
1330
- });
1123
+ const nuxt = useNuxt();
1124
+ nuxt.options.components ||= [];
1125
+ nuxt.hook("components:extend", (components) => {
1126
+ for (const component of addedComponents) {
1127
+ const existingComponentIndex = components.findIndex((c) => (c.pascalName === component.pascalName || c.kebabName === component.kebabName) && c.mode === component.mode);
1128
+ if (existingComponentIndex !== -1) {
1129
+ const existingComponent = components[existingComponentIndex];
1130
+ const existingPriority = existingComponent.priority ?? 0;
1131
+ const newPriority = component.priority ?? 0;
1132
+ if (newPriority < existingPriority) continue;
1133
+ if (newPriority === existingPriority) {
1134
+ const name = existingComponent.pascalName || existingComponent.kebabName;
1135
+ logger.warn(`Overriding ${name} component. You can specify a \`priority\` option when calling \`addComponent\` to avoid this warning.`);
1136
+ }
1137
+ components.splice(existingComponentIndex, 1, component);
1138
+ } else components.push(component);
1139
+ }
1140
+ });
1331
1141
  }
1332
1142
  function normalizeComponent(opts) {
1333
- if (!opts.mode) {
1334
- const [, mode = "all"] = opts.filePath.match(MODE_RE) || [];
1335
- opts.mode = mode;
1336
- }
1337
- const component = {
1338
- export: opts.export || "default",
1339
- chunkName: "components/" + kebabCase(opts.name),
1340
- global: opts.global ?? false,
1341
- kebabName: kebabCase(opts.name || ""),
1342
- pascalName: pascalCase(opts.name || ""),
1343
- prefetch: false,
1344
- preload: false,
1345
- mode: "all",
1346
- shortPath: opts.filePath,
1347
- priority: 0,
1348
- meta: {},
1349
- ...opts
1350
- };
1351
- return component;
1352
- }
1353
-
1143
+ if (!opts.mode) {
1144
+ const [, mode = "all"] = opts.filePath.match(MODE_RE) || [];
1145
+ opts.mode = mode;
1146
+ }
1147
+ return {
1148
+ export: opts.export || "default",
1149
+ chunkName: "components/" + kebabCase(opts.name),
1150
+ global: opts.global ?? false,
1151
+ kebabName: kebabCase(opts.name || ""),
1152
+ pascalName: pascalCase(opts.name || ""),
1153
+ prefetch: false,
1154
+ preload: false,
1155
+ mode: "all",
1156
+ shortPath: opts.filePath,
1157
+ priority: 0,
1158
+ meta: {},
1159
+ ...opts
1160
+ };
1161
+ }
1354
1162
  function addTemplate(_template) {
1355
- const nuxt = useNuxt();
1356
- const template = normalizeTemplate(_template);
1357
- filterInPlace(nuxt.options.build.templates, (p) => (p.dst || normalizeTemplate(p).dst) !== template.dst);
1358
- try {
1359
- const distDir = distDirURL.toString();
1360
- const { source } = captureStackTrace().find((e) => e.source && !e.source.startsWith(distDir)) ?? {};
1361
- if (source) {
1362
- const path = normalize(fileURLToPath(source));
1363
- if (existsSync(path)) {
1364
- template._path = path;
1365
- }
1366
- }
1367
- } catch {
1368
- }
1369
- nuxt.options.build.templates.push(template);
1370
- return template;
1163
+ const nuxt = useNuxt();
1164
+ const template = normalizeTemplate(_template);
1165
+ filterInPlace(nuxt.options.build.templates, (p) => (p.dst || normalizeTemplate(p).dst) !== template.dst);
1166
+ try {
1167
+ const distDir = distDirURL.toString();
1168
+ const { source } = captureStackTrace().find((e) => e.source && !e.source.startsWith(distDir)) ?? {};
1169
+ if (source) {
1170
+ const path = normalize(fileURLToPath(source));
1171
+ if (existsSync(path)) template._path = path;
1172
+ }
1173
+ } catch {}
1174
+ nuxt.options.build.templates.push(template);
1175
+ return template;
1371
1176
  }
1372
1177
  function addServerTemplate(template) {
1373
- const nuxt = useNuxt();
1374
- nuxt.options.nitro.virtual ||= {};
1375
- nuxt.options.nitro.virtual[template.filename] = template.getContents;
1376
- return template;
1178
+ const nuxt = useNuxt();
1179
+ nuxt.options.nitro.virtual ||= {};
1180
+ nuxt.options.nitro.virtual[template.filename] = template.getContents;
1181
+ return template;
1377
1182
  }
1378
1183
  function addTypeTemplate(_template, context) {
1379
- const nuxt = useNuxt();
1380
- const template = addTemplate(_template);
1381
- if (!template.filename.endsWith(".d.ts")) {
1382
- throw new Error(`Invalid type template. Filename must end with .d.ts : "${template.filename}"`);
1383
- }
1384
- if (!context || context.nuxt) {
1385
- nuxt.hook("prepare:types", (payload) => {
1386
- payload.references ||= [];
1387
- payload.references.push({ path: template.dst });
1388
- });
1389
- }
1390
- if (context?.node) {
1391
- nuxt.hook("prepare:types", (payload) => {
1392
- payload.nodeReferences ||= [];
1393
- payload.nodeReferences.push({ path: template.dst });
1394
- });
1395
- }
1396
- if (context?.shared) {
1397
- nuxt.hook("prepare:types", (payload) => {
1398
- payload.sharedReferences ||= [];
1399
- payload.sharedReferences.push({ path: template.dst });
1400
- });
1401
- }
1402
- if (!context || context.nuxt || context.shared) {
1403
- nuxt.options.vite.vue = defu(nuxt.options.vite.vue, {
1404
- script: {
1405
- globalTypeFiles: [template.dst]
1406
- }
1407
- });
1408
- }
1409
- if (context?.nitro) {
1410
- nuxt.hook("nitro:prepare:types", (payload) => {
1411
- payload.references ||= [];
1412
- payload.references.push({ path: template.dst });
1413
- });
1414
- }
1415
- return template;
1184
+ const nuxt = useNuxt();
1185
+ const template = addTemplate(_template);
1186
+ if (!template.filename.endsWith(".d.ts")) throw new Error(`Invalid type template. Filename must end with .d.ts : "${template.filename}"`);
1187
+ if (!context || context.nuxt) nuxt.hook("prepare:types", (payload) => {
1188
+ payload.references ||= [];
1189
+ payload.references.push({ path: template.dst });
1190
+ });
1191
+ if (context?.node) nuxt.hook("prepare:types", (payload) => {
1192
+ payload.nodeReferences ||= [];
1193
+ payload.nodeReferences.push({ path: template.dst });
1194
+ });
1195
+ if (context?.shared) nuxt.hook("prepare:types", (payload) => {
1196
+ payload.sharedReferences ||= [];
1197
+ payload.sharedReferences.push({ path: template.dst });
1198
+ });
1199
+ if (!context || context.nuxt || context.shared) nuxt.options.vite.vue = defu(nuxt.options.vite.vue, { script: { globalTypeFiles: [template.dst] } });
1200
+ if (context?.nitro) nuxt.hook("nitro:prepare:types", (payload) => {
1201
+ payload.references ||= [];
1202
+ payload.references.push({ path: template.dst });
1203
+ });
1204
+ return template;
1416
1205
  }
1417
1206
  function normalizeTemplate(template, buildDir) {
1418
- if (!template) {
1419
- throw new Error("Invalid template: " + JSON.stringify(template));
1420
- }
1421
- if (typeof template === "string") {
1422
- template = { src: template };
1423
- } else {
1424
- template = { ...template };
1425
- }
1426
- if (template.src) {
1427
- if (!existsSync(template.src)) {
1428
- throw new Error("Template not found: " + template.src);
1429
- }
1430
- if (!template.filename) {
1431
- const srcPath = parse(template.src);
1432
- template.filename = template.fileName || `${basename(srcPath.dir)}.${srcPath.name}.${hash(template.src).replace(/-/g, "_")}${srcPath.ext}`;
1433
- }
1434
- }
1435
- if (!template.src && !template.getContents) {
1436
- throw new Error("Invalid template. Either `getContents` or `src` should be provided: " + JSON.stringify(template));
1437
- }
1438
- if (!template.filename) {
1439
- throw new Error("Invalid template. `filename` must be provided: " + JSON.stringify(template));
1440
- }
1441
- if (template.filename.endsWith(".d.ts")) {
1442
- template.write = true;
1443
- }
1444
- template.dst ||= resolve(buildDir ?? useNuxt().options.buildDir, template.filename);
1445
- return template;
1207
+ if (!template) throw new Error("Invalid template: " + JSON.stringify(template));
1208
+ if (typeof template === "string") template = { src: template };
1209
+ else template = { ...template };
1210
+ if (template.src) {
1211
+ if (!existsSync(template.src)) throw new Error("Template not found: " + template.src);
1212
+ if (!template.filename) {
1213
+ const srcPath = parse(template.src);
1214
+ template.filename = template.fileName || `${basename(srcPath.dir)}.${srcPath.name}.${hash(template.src).replace(/-/g, "_")}${srcPath.ext}`;
1215
+ }
1216
+ }
1217
+ if (!template.src && !template.getContents) throw new Error("Invalid template. Either `getContents` or `src` should be provided: " + JSON.stringify(template));
1218
+ if (!template.filename) throw new Error("Invalid template. `filename` must be provided: " + JSON.stringify(template));
1219
+ if (template.filename.endsWith(".d.ts")) template.write = true;
1220
+ template.dst ||= resolve(buildDir ?? useNuxt().options.buildDir, template.filename);
1221
+ return template;
1446
1222
  }
1447
1223
  async function updateTemplates(options) {
1448
- return await tryUseNuxt()?.hooks.callHook("builder:generateApp", options);
1224
+ return await tryUseNuxt()?.hooks.callHook("builder:generateApp", options);
1449
1225
  }
1450
1226
  function resolveLayerPaths(dirs, projectBuildDir) {
1451
- const relativeRootDir = relativeWithDot(projectBuildDir, dirs.root);
1452
- const relativeSrcDir = relativeWithDot(projectBuildDir, dirs.app);
1453
- const relativeModulesDir = relativeWithDot(projectBuildDir, dirs.modules);
1454
- const relativeSharedDir = relativeWithDot(projectBuildDir, dirs.shared);
1455
- return {
1456
- nuxt: [
1457
- join(relativeSrcDir, "**/*"),
1458
- join(relativeModulesDir, `*/runtime/**/*`),
1459
- join(relativeRootDir, `test/nuxt/**/*`),
1460
- join(relativeRootDir, `tests/nuxt/**/*`),
1461
- join(relativeRootDir, `layers/*/app/**/*`),
1462
- join(relativeRootDir, `layers/*/modules/*/runtime/**/*`)
1463
- ],
1464
- nitro: [
1465
- join(relativeModulesDir, `*/runtime/server/**/*`),
1466
- join(relativeRootDir, `layers/*/server/**/*`),
1467
- join(relativeRootDir, `layers/*/modules/*/runtime/server/**/*`)
1468
- ],
1469
- node: [
1470
- join(relativeModulesDir, `*.*`),
1471
- join(relativeRootDir, `nuxt.config.*`),
1472
- join(relativeRootDir, `.config/nuxt.*`),
1473
- join(relativeRootDir, `layers/*/nuxt.config.*`),
1474
- join(relativeRootDir, `layers/*/.config/nuxt.*`),
1475
- join(relativeRootDir, `layers/*/modules/**/*`)
1476
- ],
1477
- shared: [
1478
- join(relativeSharedDir, `**/*`),
1479
- join(relativeModulesDir, `*/shared/**/*`),
1480
- join(relativeRootDir, `layers/*/shared/**/*`)
1481
- ],
1482
- sharedDeclarations: [
1483
- join(relativeSharedDir, `**/*.d.ts`),
1484
- join(relativeModulesDir, `*/shared/**/*.d.ts`),
1485
- join(relativeRootDir, `layers/*/shared/**/*.d.ts`)
1486
- ],
1487
- globalDeclarations: [
1488
- join(relativeRootDir, `*.d.ts`),
1489
- join(relativeRootDir, `layers/*/*.d.ts`)
1490
- ]
1491
- };
1227
+ const relativeRootDir = relativeWithDot(projectBuildDir, dirs.root);
1228
+ const relativeSrcDir = relativeWithDot(projectBuildDir, dirs.app);
1229
+ const relativeModulesDir = relativeWithDot(projectBuildDir, dirs.modules);
1230
+ const relativeSharedDir = relativeWithDot(projectBuildDir, dirs.shared);
1231
+ return {
1232
+ nuxt: [
1233
+ join(relativeSrcDir, "**/*"),
1234
+ join(relativeModulesDir, `*/runtime/**/*`),
1235
+ join(relativeRootDir, `test/nuxt/**/*`),
1236
+ join(relativeRootDir, `tests/nuxt/**/*`),
1237
+ join(relativeRootDir, `layers/*/app/**/*`),
1238
+ join(relativeRootDir, `layers/*/modules/*/runtime/**/*`)
1239
+ ],
1240
+ nitro: [
1241
+ join(relativeModulesDir, `*/runtime/server/**/*`),
1242
+ join(relativeRootDir, `layers/*/server/**/*`),
1243
+ join(relativeRootDir, `layers/*/modules/*/runtime/server/**/*`)
1244
+ ],
1245
+ node: [
1246
+ join(relativeModulesDir, `*.*`),
1247
+ join(relativeRootDir, `nuxt.config.*`),
1248
+ join(relativeRootDir, `.config/nuxt.*`),
1249
+ join(relativeRootDir, `layers/*/nuxt.config.*`),
1250
+ join(relativeRootDir, `layers/*/.config/nuxt.*`),
1251
+ join(relativeRootDir, `layers/*/modules/**/*`)
1252
+ ],
1253
+ shared: [
1254
+ join(relativeSharedDir, `**/*`),
1255
+ join(relativeModulesDir, `*/shared/**/*`),
1256
+ join(relativeRootDir, `layers/*/shared/**/*`)
1257
+ ],
1258
+ sharedDeclarations: [
1259
+ join(relativeSharedDir, `**/*.d.ts`),
1260
+ join(relativeModulesDir, `*/shared/**/*.d.ts`),
1261
+ join(relativeRootDir, `layers/*/shared/**/*.d.ts`)
1262
+ ],
1263
+ globalDeclarations: [join(relativeRootDir, `*.d.ts`), join(relativeRootDir, `layers/*/*.d.ts`)]
1264
+ };
1492
1265
  }
1493
1266
  const EXTENSION_RE = /\b(?:\.d\.[cm]?ts|\.\w+)$/g;
1494
1267
  const excludedAlias = [/^@vue\/.*$/, /^#internal\/nuxt/];
1495
1268
  async function _generateTypes(nuxt) {
1496
- const include = /* @__PURE__ */ new Set(["./nuxt.d.ts"]);
1497
- const nodeInclude = /* @__PURE__ */ new Set(["./nuxt.node.d.ts"]);
1498
- const sharedInclude = /* @__PURE__ */ new Set(["./nuxt.shared.d.ts"]);
1499
- const legacyInclude = /* @__PURE__ */ new Set([...include, ...nodeInclude]);
1500
- const exclude = /* @__PURE__ */ new Set();
1501
- const nodeExclude = /* @__PURE__ */ new Set();
1502
- const sharedExclude = /* @__PURE__ */ new Set();
1503
- const legacyExclude = /* @__PURE__ */ new Set();
1504
- if (nuxt.options.typescript.includeWorkspace && nuxt.options.workspaceDir !== nuxt.options.srcDir) {
1505
- include.add(join(relative(nuxt.options.buildDir, nuxt.options.workspaceDir), "**/*"));
1506
- legacyInclude.add(join(relative(nuxt.options.buildDir, nuxt.options.workspaceDir), "**/*"));
1507
- }
1508
- const layerDirs = getLayerDirectories(nuxt);
1509
- const sourceDirs = layerDirs.map((layer) => layer.app);
1510
- for (const dir of nuxt.options.modulesDir) {
1511
- if (!sourceDirs.some((srcDir) => dir.startsWith(srcDir))) {
1512
- exclude.add(relativeWithDot(nuxt.options.buildDir, dir));
1513
- }
1514
- nodeExclude.add(relativeWithDot(nuxt.options.buildDir, dir));
1515
- legacyExclude.add(relativeWithDot(nuxt.options.buildDir, dir));
1516
- }
1517
- for (const dir of ["dist", ".data"]) {
1518
- exclude.add(relativeWithDot(nuxt.options.buildDir, resolve(nuxt.options.rootDir, dir)));
1519
- nodeExclude.add(relativeWithDot(nuxt.options.buildDir, resolve(nuxt.options.rootDir, dir)));
1520
- legacyExclude.add(relativeWithDot(nuxt.options.buildDir, resolve(nuxt.options.rootDir, dir)));
1521
- }
1522
- const rootDirWithSlash = withTrailingSlash(nuxt.options.rootDir);
1523
- for (const dirs of layerDirs) {
1524
- if (!dirs.app.startsWith(rootDirWithSlash) || dirs.root === rootDirWithSlash || dirs.app.includes("node_modules")) {
1525
- const rootGlob = join(relativeWithDot(nuxt.options.buildDir, dirs.root), "**/*");
1526
- const paths = resolveLayerPaths(dirs, nuxt.options.buildDir);
1527
- for (const path of paths.nuxt) {
1528
- include.add(path);
1529
- legacyInclude.add(path);
1530
- if (path !== rootGlob) {
1531
- nodeExclude.add(path);
1532
- }
1533
- }
1534
- for (const path of paths.nitro) {
1535
- exclude.add(path);
1536
- nodeExclude.add(path);
1537
- legacyExclude.add(path);
1538
- }
1539
- for (const path of paths.node) {
1540
- nodeInclude.add(path);
1541
- legacyInclude.add(path);
1542
- exclude.add(path);
1543
- }
1544
- for (const path of paths.shared) {
1545
- legacyInclude.add(path);
1546
- sharedInclude.add(path);
1547
- }
1548
- for (const path of paths.sharedDeclarations) {
1549
- include.add(path);
1550
- }
1551
- for (const path of paths.globalDeclarations) {
1552
- include.add(path);
1553
- legacyInclude.add(path);
1554
- sharedInclude.add(path);
1555
- }
1556
- }
1557
- }
1558
- const moduleEntryPaths = [];
1559
- for (const m of nuxt.options._installedModules) {
1560
- const path = m.meta?.rawPath || m.entryPath;
1561
- if (path) {
1562
- moduleEntryPaths.push(getDirectory(path));
1563
- }
1564
- }
1565
- const modulePaths = await resolveNuxtModule(rootDirWithSlash, moduleEntryPaths);
1566
- for (const path of modulePaths) {
1567
- const relative2 = relativeWithDot(nuxt.options.buildDir, path);
1568
- if (!path.includes("node_modules") && path.startsWith(rootDirWithSlash)) {
1569
- include.add(join(relative2, "runtime"));
1570
- include.add(join(relative2, "dist/runtime"));
1571
- nodeInclude.add(join(relative2, "*.*"));
1572
- }
1573
- legacyInclude.add(join(relative2, "runtime"));
1574
- legacyInclude.add(join(relative2, "dist/runtime"));
1575
- nodeExclude.add(join(relative2, "runtime"));
1576
- nodeExclude.add(join(relative2, "dist/runtime"));
1577
- exclude.add(join(relative2, "runtime/server"));
1578
- exclude.add(join(relative2, "dist/runtime/server"));
1579
- exclude.add(join(relative2, "*.*"));
1580
- exclude.add(join(relative2, "dist/*.*"));
1581
- legacyExclude.add(join(relative2, "runtime/server"));
1582
- legacyExclude.add(join(relative2, "dist/runtime/server"));
1583
- }
1584
- const nestedModulesDirs = [];
1585
- for (const dir of [...nuxt.options.modulesDir].sort()) {
1586
- const withSlash = withTrailingSlash(dir);
1587
- if (nestedModulesDirs.every((d) => !d.startsWith(withSlash))) {
1588
- nestedModulesDirs.push(withSlash);
1589
- }
1590
- }
1591
- let hasTypescriptVersionWithModulePreserve;
1592
- for (const parent of nestedModulesDirs) {
1593
- hasTypescriptVersionWithModulePreserve ??= await readPackageJSON("typescript", { parent }).then((r) => r?.version && gte(r.version, "5.4.0")).catch(() => void 0);
1594
- }
1595
- hasTypescriptVersionWithModulePreserve ??= true;
1596
- const useDecorators = Boolean(nuxt.options.experimental?.decorators);
1597
- const tsConfig = defu(nuxt.options.typescript?.tsConfig, {
1598
- compilerOptions: {
1599
- /* Base options: */
1600
- esModuleInterop: true,
1601
- skipLibCheck: true,
1602
- target: "ESNext",
1603
- allowJs: true,
1604
- resolveJsonModule: true,
1605
- moduleDetection: "force",
1606
- isolatedModules: true,
1607
- verbatimModuleSyntax: true,
1608
- /* Strictness */
1609
- strict: nuxt.options.typescript?.strict ?? true,
1610
- noUncheckedIndexedAccess: true,
1611
- forceConsistentCasingInFileNames: true,
1612
- noImplicitOverride: true,
1613
- /* Decorator support */
1614
- ...useDecorators ? {
1615
- experimentalDecorators: false
1616
- } : {},
1617
- /* If NOT transpiling with TypeScript: */
1618
- module: hasTypescriptVersionWithModulePreserve ? "preserve" : "ESNext",
1619
- noEmit: true,
1620
- /* If your code runs in the DOM: */
1621
- lib: [
1622
- "ESNext",
1623
- ...useDecorators ? ["esnext.decorators"] : [],
1624
- "dom",
1625
- "dom.iterable",
1626
- "webworker"
1627
- ],
1628
- /* JSX support for Vue */
1629
- jsx: "preserve",
1630
- jsxImportSource: "vue",
1631
- /* remove auto-scanning for types */
1632
- types: [],
1633
- /* add paths object for filling-in later */
1634
- paths: {},
1635
- /* Possibly consider removing the following in future */
1636
- moduleResolution: nuxt.options.future?.typescriptBundlerResolution || nuxt.options.experimental?.typescriptBundlerResolution ? "Bundler" : "Node",
1637
- /* implied by module: preserve */
1638
- useDefineForClassFields: true,
1639
- /* implied by target: es2022+ */
1640
- noImplicitThis: true,
1641
- /* enabled with `strict` */
1642
- allowSyntheticDefaultImports: true
1643
- },
1644
- include: [...include],
1645
- exclude: [...exclude]
1646
- });
1647
- const nodeTsConfig = defu(nuxt.options.typescript?.nodeTsConfig, {
1648
- compilerOptions: {
1649
- /* Base options: */
1650
- esModuleInterop: tsConfig.compilerOptions?.esModuleInterop,
1651
- skipLibCheck: tsConfig.compilerOptions?.skipLibCheck,
1652
- target: tsConfig.compilerOptions?.target,
1653
- allowJs: tsConfig.compilerOptions?.allowJs,
1654
- resolveJsonModule: tsConfig.compilerOptions?.resolveJsonModule,
1655
- moduleDetection: tsConfig.compilerOptions?.moduleDetection,
1656
- isolatedModules: tsConfig.compilerOptions?.isolatedModules,
1657
- verbatimModuleSyntax: tsConfig.compilerOptions?.verbatimModuleSyntax,
1658
- /* Strictness */
1659
- strict: tsConfig.compilerOptions?.strict,
1660
- noUncheckedIndexedAccess: tsConfig.compilerOptions?.noUncheckedIndexedAccess,
1661
- forceConsistentCasingInFileNames: tsConfig.compilerOptions?.forceConsistentCasingInFileNames,
1662
- noImplicitOverride: tsConfig.compilerOptions?.noImplicitOverride,
1663
- /* If NOT transpiling with TypeScript: */
1664
- module: tsConfig.compilerOptions?.module,
1665
- noEmit: true,
1666
- /* remove auto-scanning for types */
1667
- types: [],
1668
- /* add paths object for filling-in later */
1669
- paths: {},
1670
- /* Possibly consider removing the following in future */
1671
- moduleResolution: tsConfig.compilerOptions?.moduleResolution,
1672
- useDefineForClassFields: tsConfig.compilerOptions?.useDefineForClassFields,
1673
- noImplicitThis: tsConfig.compilerOptions?.noImplicitThis,
1674
- allowSyntheticDefaultImports: tsConfig.compilerOptions?.allowSyntheticDefaultImports
1675
- },
1676
- include: [...nodeInclude],
1677
- exclude: [...nodeExclude]
1678
- });
1679
- const sharedTsConfig = defu(nuxt.options.typescript?.sharedTsConfig, {
1680
- compilerOptions: {
1681
- /* Base options: */
1682
- esModuleInterop: tsConfig.compilerOptions?.esModuleInterop,
1683
- skipLibCheck: tsConfig.compilerOptions?.skipLibCheck,
1684
- target: tsConfig.compilerOptions?.target,
1685
- allowJs: tsConfig.compilerOptions?.allowJs,
1686
- resolveJsonModule: tsConfig.compilerOptions?.resolveJsonModule,
1687
- moduleDetection: tsConfig.compilerOptions?.moduleDetection,
1688
- isolatedModules: tsConfig.compilerOptions?.isolatedModules,
1689
- verbatimModuleSyntax: tsConfig.compilerOptions?.verbatimModuleSyntax,
1690
- /* Strictness */
1691
- strict: tsConfig.compilerOptions?.strict,
1692
- noUncheckedIndexedAccess: tsConfig.compilerOptions?.noUncheckedIndexedAccess,
1693
- forceConsistentCasingInFileNames: tsConfig.compilerOptions?.forceConsistentCasingInFileNames,
1694
- noImplicitOverride: tsConfig.compilerOptions?.noImplicitOverride,
1695
- /* If NOT transpiling with TypeScript: */
1696
- module: tsConfig.compilerOptions?.module,
1697
- noEmit: true,
1698
- /* remove auto-scanning for types */
1699
- types: [],
1700
- /* add paths object for filling-in later */
1701
- paths: {},
1702
- /* Possibly consider removing the following in future */
1703
- moduleResolution: tsConfig.compilerOptions?.moduleResolution,
1704
- useDefineForClassFields: tsConfig.compilerOptions?.useDefineForClassFields,
1705
- noImplicitThis: tsConfig.compilerOptions?.noImplicitThis,
1706
- allowSyntheticDefaultImports: tsConfig.compilerOptions?.allowSyntheticDefaultImports
1707
- },
1708
- include: [...sharedInclude],
1709
- exclude: [...sharedExclude]
1710
- });
1711
- const aliases = nuxt.options.alias;
1712
- const basePath = tsConfig.compilerOptions.baseUrl ? resolve(nuxt.options.buildDir, tsConfig.compilerOptions.baseUrl) : nuxt.options.buildDir;
1713
- tsConfig.compilerOptions ||= {};
1714
- tsConfig.compilerOptions.paths ||= {};
1715
- tsConfig.include ||= [];
1716
- const importPaths = nuxt.options.modulesDir.map((d) => directoryToURL(d));
1717
- for (const alias in aliases) {
1718
- if (excludedAlias.some((re) => re.test(alias))) {
1719
- continue;
1720
- }
1721
- let absolutePath = resolve(basePath, aliases[alias]);
1722
- let stats = await promises.stat(absolutePath).catch(
1723
- () => null
1724
- /* file does not exist */
1725
- );
1726
- if (!stats) {
1727
- const resolvedModule = resolveModulePath(aliases[alias], {
1728
- try: true,
1729
- from: importPaths,
1730
- extensions: [...nuxt.options.extensions, ".d.ts", ".d.mts", ".d.cts"]
1731
- });
1732
- if (resolvedModule) {
1733
- absolutePath = resolvedModule;
1734
- stats = await promises.stat(resolvedModule).catch(() => null);
1735
- }
1736
- }
1737
- const relativePath = relativeWithDot(nuxt.options.buildDir, absolutePath);
1738
- if (stats?.isDirectory() || aliases[alias].endsWith("/")) {
1739
- tsConfig.compilerOptions.paths[alias] = [relativePath];
1740
- tsConfig.compilerOptions.paths[`${alias}/*`] = [`${relativePath}/*`];
1741
- } else {
1742
- const path = stats?.isFile() ? relativePath.replace(EXTENSION_RE, "") : aliases[alias];
1743
- tsConfig.compilerOptions.paths[alias] = [path];
1744
- }
1745
- }
1746
- const references = [];
1747
- const nodeReferences = [];
1748
- const sharedReferences = [];
1749
- await Promise.all([...nuxt.options.modules, ...nuxt.options._modules].map(async (id) => {
1750
- if (typeof id !== "string") {
1751
- return;
1752
- }
1753
- for (const parent of nestedModulesDirs) {
1754
- const pkg = await readPackageJSON(id, { parent }).catch(() => null);
1755
- if (pkg) {
1756
- nodeReferences.push({ types: pkg.name ?? id });
1757
- references.push({ types: pkg.name ?? id });
1758
- return;
1759
- }
1760
- }
1761
- nodeReferences.push({ types: id });
1762
- references.push({ types: id });
1763
- }));
1764
- const declarations = [];
1765
- await nuxt.callHook("prepare:types", { references, declarations, tsConfig, nodeTsConfig, nodeReferences, sharedTsConfig, sharedReferences });
1766
- const legacyTsConfig = defu({}, {
1767
- ...tsConfig,
1768
- include: [...tsConfig.include, ...legacyInclude],
1769
- exclude: [...legacyExclude]
1770
- });
1771
- async function resolveConfig(tsConfig2) {
1772
- for (const alias in tsConfig2.compilerOptions.paths) {
1773
- const paths = tsConfig2.compilerOptions.paths[alias];
1774
- tsConfig2.compilerOptions.paths[alias] = [...new Set(await Promise.all(paths.map(async (path) => {
1775
- if (!isAbsolute(path)) {
1776
- return path;
1777
- }
1778
- const stats = await promises.stat(path).catch(
1779
- () => null
1780
- /* file does not exist */
1781
- );
1782
- return relativeWithDot(nuxt.options.buildDir, stats?.isFile() ? path.replace(EXTENSION_RE, "") : path);
1783
- })))];
1784
- }
1785
- sortTsPaths(tsConfig2.compilerOptions.paths);
1786
- tsConfig2.include = [...new Set(tsConfig2.include.map((p) => isAbsolute(p) ? relativeWithDot(nuxt.options.buildDir, p) : p))];
1787
- tsConfig2.exclude = [...new Set(tsConfig2.exclude.map((p) => isAbsolute(p) ? relativeWithDot(nuxt.options.buildDir, p) : p))];
1788
- }
1789
- await Promise.all([
1790
- resolveConfig(tsConfig),
1791
- resolveConfig(nodeTsConfig),
1792
- resolveConfig(sharedTsConfig),
1793
- resolveConfig(legacyTsConfig)
1794
- ]);
1795
- const declaration = [
1796
- ...references.map((ref) => {
1797
- if ("path" in ref && isAbsolute(ref.path)) {
1798
- ref.path = relative(nuxt.options.buildDir, ref.path);
1799
- }
1800
- return `/// <reference ${renderAttrs(ref)} />`;
1801
- }),
1802
- ...declarations,
1803
- "",
1804
- "export {}",
1805
- ""
1806
- ].join("\n");
1807
- const nodeDeclaration = [
1808
- ...nodeReferences.map((ref) => {
1809
- if ("path" in ref && isAbsolute(ref.path)) {
1810
- ref.path = relative(nuxt.options.buildDir, ref.path);
1811
- }
1812
- return `/// <reference ${renderAttrs(ref)} />`;
1813
- }),
1814
- "",
1815
- "export {}",
1816
- ""
1817
- ].join("\n");
1818
- const sharedDeclaration = [
1819
- ...sharedReferences.map((ref) => {
1820
- if ("path" in ref && isAbsolute(ref.path)) {
1821
- ref.path = relative(nuxt.options.buildDir, ref.path);
1822
- }
1823
- return `/// <reference ${renderAttrs(ref)} />`;
1824
- }),
1825
- "",
1826
- "export {}",
1827
- ""
1828
- ].join("\n");
1829
- return {
1830
- declaration,
1831
- sharedTsConfig,
1832
- sharedDeclaration,
1833
- nodeTsConfig,
1834
- nodeDeclaration,
1835
- tsConfig,
1836
- legacyTsConfig
1837
- };
1269
+ const include = new Set(["./nuxt.d.ts"]);
1270
+ const nodeInclude = new Set(["./nuxt.node.d.ts"]);
1271
+ const sharedInclude = new Set(["./nuxt.shared.d.ts"]);
1272
+ const legacyInclude = new Set([...include, ...nodeInclude]);
1273
+ const exclude = /* @__PURE__ */ new Set();
1274
+ const nodeExclude = /* @__PURE__ */ new Set();
1275
+ const sharedExclude = /* @__PURE__ */ new Set();
1276
+ const legacyExclude = /* @__PURE__ */ new Set();
1277
+ if (nuxt.options.typescript.includeWorkspace && nuxt.options.workspaceDir !== nuxt.options.srcDir) {
1278
+ include.add(join(relative(nuxt.options.buildDir, nuxt.options.workspaceDir), "**/*"));
1279
+ legacyInclude.add(join(relative(nuxt.options.buildDir, nuxt.options.workspaceDir), "**/*"));
1280
+ }
1281
+ const layerDirs = getLayerDirectories(nuxt);
1282
+ const sourceDirs = layerDirs.map((layer) => layer.app);
1283
+ for (const dir of nuxt.options.modulesDir) {
1284
+ if (!sourceDirs.some((srcDir) => dir.startsWith(srcDir))) exclude.add(relativeWithDot(nuxt.options.buildDir, dir));
1285
+ nodeExclude.add(relativeWithDot(nuxt.options.buildDir, dir));
1286
+ legacyExclude.add(relativeWithDot(nuxt.options.buildDir, dir));
1287
+ }
1288
+ for (const dir of ["dist", ".data"]) {
1289
+ exclude.add(relativeWithDot(nuxt.options.buildDir, resolve(nuxt.options.rootDir, dir)));
1290
+ nodeExclude.add(relativeWithDot(nuxt.options.buildDir, resolve(nuxt.options.rootDir, dir)));
1291
+ legacyExclude.add(relativeWithDot(nuxt.options.buildDir, resolve(nuxt.options.rootDir, dir)));
1292
+ }
1293
+ const rootDirWithSlash = withTrailingSlash$1(nuxt.options.rootDir);
1294
+ for (const dirs of layerDirs) if (!dirs.app.startsWith(rootDirWithSlash) || dirs.root === rootDirWithSlash || dirs.app.includes("node_modules")) {
1295
+ const rootGlob = join(relativeWithDot(nuxt.options.buildDir, dirs.root), "**/*");
1296
+ const paths = resolveLayerPaths(dirs, nuxt.options.buildDir);
1297
+ for (const path of paths.nuxt) {
1298
+ include.add(path);
1299
+ legacyInclude.add(path);
1300
+ if (path !== rootGlob) nodeExclude.add(path);
1301
+ }
1302
+ for (const path of paths.nitro) {
1303
+ exclude.add(path);
1304
+ nodeExclude.add(path);
1305
+ legacyExclude.add(path);
1306
+ }
1307
+ for (const path of paths.node) {
1308
+ nodeInclude.add(path);
1309
+ legacyInclude.add(path);
1310
+ exclude.add(path);
1311
+ }
1312
+ for (const path of paths.shared) {
1313
+ legacyInclude.add(path);
1314
+ sharedInclude.add(path);
1315
+ }
1316
+ for (const path of paths.sharedDeclarations) include.add(path);
1317
+ for (const path of paths.globalDeclarations) {
1318
+ include.add(path);
1319
+ legacyInclude.add(path);
1320
+ sharedInclude.add(path);
1321
+ }
1322
+ }
1323
+ const moduleEntryPaths = [];
1324
+ for (const m of nuxt.options._installedModules) {
1325
+ const path = m.meta?.rawPath || m.entryPath;
1326
+ if (path) moduleEntryPaths.push(getDirectory(path));
1327
+ }
1328
+ const modulePaths = await resolveNuxtModule(rootDirWithSlash, moduleEntryPaths);
1329
+ for (const path of modulePaths) {
1330
+ const relative = relativeWithDot(nuxt.options.buildDir, path);
1331
+ if (!path.includes("node_modules") && path.startsWith(rootDirWithSlash)) {
1332
+ include.add(join(relative, "runtime"));
1333
+ include.add(join(relative, "dist/runtime"));
1334
+ nodeInclude.add(join(relative, "*.*"));
1335
+ }
1336
+ legacyInclude.add(join(relative, "runtime"));
1337
+ legacyInclude.add(join(relative, "dist/runtime"));
1338
+ nodeExclude.add(join(relative, "runtime"));
1339
+ nodeExclude.add(join(relative, "dist/runtime"));
1340
+ exclude.add(join(relative, "runtime/server"));
1341
+ exclude.add(join(relative, "dist/runtime/server"));
1342
+ exclude.add(join(relative, "*.*"));
1343
+ exclude.add(join(relative, "dist/*.*"));
1344
+ legacyExclude.add(join(relative, "runtime/server"));
1345
+ legacyExclude.add(join(relative, "dist/runtime/server"));
1346
+ }
1347
+ const nestedModulesDirs = [];
1348
+ for (const dir of [...nuxt.options.modulesDir].sort()) {
1349
+ const withSlash = withTrailingSlash$1(dir);
1350
+ if (nestedModulesDirs.every((d) => !d.startsWith(withSlash))) nestedModulesDirs.push(withSlash);
1351
+ }
1352
+ let hasTypescriptVersionWithModulePreserve;
1353
+ for (const parent of nestedModulesDirs) hasTypescriptVersionWithModulePreserve ??= await readPackageJSON("typescript", { parent }).then((r) => r?.version && gte(r.version, "5.4.0")).catch(() => void 0);
1354
+ hasTypescriptVersionWithModulePreserve ??= true;
1355
+ const useDecorators = Boolean(nuxt.options.experimental?.decorators);
1356
+ const tsConfig = defu(nuxt.options.typescript?.tsConfig, {
1357
+ compilerOptions: {
1358
+ esModuleInterop: true,
1359
+ skipLibCheck: true,
1360
+ target: "ESNext",
1361
+ allowJs: true,
1362
+ resolveJsonModule: true,
1363
+ moduleDetection: "force",
1364
+ isolatedModules: true,
1365
+ verbatimModuleSyntax: true,
1366
+ allowArbitraryExtensions: true,
1367
+ strict: nuxt.options.typescript?.strict ?? true,
1368
+ noUncheckedIndexedAccess: true,
1369
+ forceConsistentCasingInFileNames: true,
1370
+ noImplicitOverride: true,
1371
+ ...useDecorators ? { experimentalDecorators: false } : {},
1372
+ module: hasTypescriptVersionWithModulePreserve ? "preserve" : "ESNext",
1373
+ noEmit: true,
1374
+ lib: [
1375
+ "ESNext",
1376
+ ...useDecorators ? ["esnext.decorators"] : [],
1377
+ "dom",
1378
+ "dom.iterable",
1379
+ "webworker"
1380
+ ],
1381
+ jsx: "preserve",
1382
+ jsxImportSource: "vue",
1383
+ types: [],
1384
+ paths: {},
1385
+ moduleResolution: nuxt.options.future?.typescriptBundlerResolution || nuxt.options.experimental?.typescriptBundlerResolution ? "Bundler" : "Node",
1386
+ useDefineForClassFields: true,
1387
+ noImplicitThis: true,
1388
+ allowSyntheticDefaultImports: true
1389
+ },
1390
+ include: [...include],
1391
+ exclude: [...exclude]
1392
+ });
1393
+ const nodeTsConfig = defu(nuxt.options.typescript?.nodeTsConfig, {
1394
+ compilerOptions: {
1395
+ esModuleInterop: tsConfig.compilerOptions?.esModuleInterop,
1396
+ skipLibCheck: tsConfig.compilerOptions?.skipLibCheck,
1397
+ target: tsConfig.compilerOptions?.target,
1398
+ allowJs: tsConfig.compilerOptions?.allowJs,
1399
+ resolveJsonModule: tsConfig.compilerOptions?.resolveJsonModule,
1400
+ moduleDetection: tsConfig.compilerOptions?.moduleDetection,
1401
+ isolatedModules: tsConfig.compilerOptions?.isolatedModules,
1402
+ verbatimModuleSyntax: tsConfig.compilerOptions?.verbatimModuleSyntax,
1403
+ allowArbitraryExtensions: tsConfig.compilerOptions?.allowArbitraryExtensions,
1404
+ strict: tsConfig.compilerOptions?.strict,
1405
+ noUncheckedIndexedAccess: tsConfig.compilerOptions?.noUncheckedIndexedAccess,
1406
+ forceConsistentCasingInFileNames: tsConfig.compilerOptions?.forceConsistentCasingInFileNames,
1407
+ noImplicitOverride: tsConfig.compilerOptions?.noImplicitOverride,
1408
+ module: tsConfig.compilerOptions?.module,
1409
+ noEmit: true,
1410
+ types: [],
1411
+ paths: {},
1412
+ moduleResolution: tsConfig.compilerOptions?.moduleResolution,
1413
+ useDefineForClassFields: tsConfig.compilerOptions?.useDefineForClassFields,
1414
+ noImplicitThis: tsConfig.compilerOptions?.noImplicitThis,
1415
+ allowSyntheticDefaultImports: tsConfig.compilerOptions?.allowSyntheticDefaultImports
1416
+ },
1417
+ include: [...nodeInclude],
1418
+ exclude: [...nodeExclude]
1419
+ });
1420
+ const sharedTsConfig = defu(nuxt.options.typescript?.sharedTsConfig, {
1421
+ compilerOptions: {
1422
+ esModuleInterop: tsConfig.compilerOptions?.esModuleInterop,
1423
+ skipLibCheck: tsConfig.compilerOptions?.skipLibCheck,
1424
+ target: tsConfig.compilerOptions?.target,
1425
+ allowJs: tsConfig.compilerOptions?.allowJs,
1426
+ resolveJsonModule: tsConfig.compilerOptions?.resolveJsonModule,
1427
+ moduleDetection: tsConfig.compilerOptions?.moduleDetection,
1428
+ isolatedModules: tsConfig.compilerOptions?.isolatedModules,
1429
+ verbatimModuleSyntax: tsConfig.compilerOptions?.verbatimModuleSyntax,
1430
+ allowArbitraryExtensions: tsConfig.compilerOptions?.allowArbitraryExtensions,
1431
+ strict: tsConfig.compilerOptions?.strict,
1432
+ noUncheckedIndexedAccess: tsConfig.compilerOptions?.noUncheckedIndexedAccess,
1433
+ forceConsistentCasingInFileNames: tsConfig.compilerOptions?.forceConsistentCasingInFileNames,
1434
+ noImplicitOverride: tsConfig.compilerOptions?.noImplicitOverride,
1435
+ module: tsConfig.compilerOptions?.module,
1436
+ noEmit: true,
1437
+ types: [],
1438
+ paths: {},
1439
+ moduleResolution: tsConfig.compilerOptions?.moduleResolution,
1440
+ useDefineForClassFields: tsConfig.compilerOptions?.useDefineForClassFields,
1441
+ noImplicitThis: tsConfig.compilerOptions?.noImplicitThis,
1442
+ allowSyntheticDefaultImports: tsConfig.compilerOptions?.allowSyntheticDefaultImports
1443
+ },
1444
+ include: [...sharedInclude],
1445
+ exclude: [...sharedExclude]
1446
+ });
1447
+ const aliases = nuxt.options.alias;
1448
+ const basePath = tsConfig.compilerOptions.baseUrl ? resolve(nuxt.options.buildDir, tsConfig.compilerOptions.baseUrl) : nuxt.options.buildDir;
1449
+ tsConfig.compilerOptions ||= {};
1450
+ tsConfig.compilerOptions.paths ||= {};
1451
+ tsConfig.include ||= [];
1452
+ const importPaths = nuxt.options.modulesDir.map((d) => directoryToURL(d));
1453
+ for (const alias in aliases) {
1454
+ if (excludedAlias.some((re) => re.test(alias))) continue;
1455
+ let absolutePath = resolve(basePath, aliases[alias]);
1456
+ let stats = await promises.stat(absolutePath).catch(() => null);
1457
+ if (!stats) {
1458
+ const resolvedModule = resolveModulePath(aliases[alias], {
1459
+ try: true,
1460
+ from: importPaths,
1461
+ extensions: [
1462
+ ...nuxt.options.extensions,
1463
+ ".d.ts",
1464
+ ".d.mts",
1465
+ ".d.cts"
1466
+ ]
1467
+ });
1468
+ if (resolvedModule) {
1469
+ absolutePath = resolvedModule;
1470
+ stats = await promises.stat(resolvedModule).catch(() => null);
1471
+ }
1472
+ }
1473
+ const relativePath = relativeWithDot(nuxt.options.buildDir, absolutePath);
1474
+ if (stats?.isDirectory() || aliases[alias].endsWith("/")) {
1475
+ tsConfig.compilerOptions.paths[alias] = [relativePath];
1476
+ tsConfig.compilerOptions.paths[`${alias}/*`] = [`${relativePath}/*`];
1477
+ } else {
1478
+ const path = stats?.isFile() ? relativePath.replace(EXTENSION_RE, "") : aliases[alias];
1479
+ tsConfig.compilerOptions.paths[alias] = [path];
1480
+ }
1481
+ }
1482
+ const references = [];
1483
+ const nodeReferences = [];
1484
+ const sharedReferences = [];
1485
+ await Promise.all([...nuxt.options.modules, ...nuxt.options._modules].map(async (id) => {
1486
+ if (typeof id !== "string") return;
1487
+ for (const parent of nestedModulesDirs) {
1488
+ const pkg = await readPackageJSON(id, { parent }).catch(() => null);
1489
+ if (pkg) {
1490
+ nodeReferences.push({ types: pkg.name ?? id });
1491
+ references.push({ types: pkg.name ?? id });
1492
+ return;
1493
+ }
1494
+ }
1495
+ nodeReferences.push({ types: id });
1496
+ references.push({ types: id });
1497
+ }));
1498
+ const declarations = [];
1499
+ await nuxt.callHook("prepare:types", {
1500
+ references,
1501
+ declarations,
1502
+ tsConfig,
1503
+ nodeTsConfig,
1504
+ nodeReferences,
1505
+ sharedTsConfig,
1506
+ sharedReferences
1507
+ });
1508
+ const legacyTsConfig = defu({}, {
1509
+ ...tsConfig,
1510
+ include: [...tsConfig.include, ...legacyInclude],
1511
+ exclude: [...legacyExclude]
1512
+ });
1513
+ async function resolveConfig(tsConfig) {
1514
+ for (const alias in tsConfig.compilerOptions.paths) {
1515
+ const paths = tsConfig.compilerOptions.paths[alias];
1516
+ tsConfig.compilerOptions.paths[alias] = [...new Set(await Promise.all(paths.map(async (path) => {
1517
+ if (!isAbsolute(path)) return path;
1518
+ const stats = await promises.stat(path).catch(() => null);
1519
+ return relativeWithDot(nuxt.options.buildDir, stats?.isFile() ? path.replace(EXTENSION_RE, "") : path);
1520
+ })))];
1521
+ }
1522
+ sortTsPaths(tsConfig.compilerOptions.paths);
1523
+ tsConfig.include = [...new Set(tsConfig.include.map((p) => isAbsolute(p) ? relativeWithDot(nuxt.options.buildDir, p) : p))];
1524
+ tsConfig.exclude = [...new Set(tsConfig.exclude.map((p) => isAbsolute(p) ? relativeWithDot(nuxt.options.buildDir, p) : p))];
1525
+ }
1526
+ await Promise.all([
1527
+ resolveConfig(tsConfig),
1528
+ resolveConfig(nodeTsConfig),
1529
+ resolveConfig(sharedTsConfig),
1530
+ resolveConfig(legacyTsConfig)
1531
+ ]);
1532
+ const declaration = [
1533
+ ...references.map((ref) => renderReference(ref, nuxt.options.buildDir)),
1534
+ ...declarations,
1535
+ "",
1536
+ "export {}",
1537
+ ""
1538
+ ].join("\n");
1539
+ const nodeDeclaration = [
1540
+ ...nodeReferences.map((ref) => renderReference(ref, nuxt.options.buildDir)),
1541
+ "",
1542
+ "export {}",
1543
+ ""
1544
+ ].join("\n");
1545
+ return {
1546
+ declaration,
1547
+ sharedTsConfig,
1548
+ sharedDeclaration: [
1549
+ ...sharedReferences.map((ref) => renderReference(ref, nuxt.options.buildDir)),
1550
+ "",
1551
+ "export {}",
1552
+ ""
1553
+ ].join("\n"),
1554
+ nodeTsConfig,
1555
+ nodeDeclaration,
1556
+ tsConfig,
1557
+ legacyTsConfig
1558
+ };
1838
1559
  }
1839
1560
  async function writeTypes(nuxt) {
1840
- const { tsConfig, nodeTsConfig, nodeDeclaration, declaration, legacyTsConfig, sharedDeclaration, sharedTsConfig } = await _generateTypes(nuxt);
1841
- const appTsConfigPath = resolve(nuxt.options.buildDir, "tsconfig.app.json");
1842
- const legacyTsConfigPath = resolve(nuxt.options.buildDir, "tsconfig.json");
1843
- const nodeTsConfigPath = resolve(nuxt.options.buildDir, "tsconfig.node.json");
1844
- const sharedTsConfigPath = resolve(nuxt.options.buildDir, "tsconfig.shared.json");
1845
- const declarationPath = resolve(nuxt.options.buildDir, "nuxt.d.ts");
1846
- const nodeDeclarationPath = resolve(nuxt.options.buildDir, "nuxt.node.d.ts");
1847
- const sharedDeclarationPath = resolve(nuxt.options.buildDir, "nuxt.shared.d.ts");
1848
- await promises.mkdir(nuxt.options.buildDir, { recursive: true });
1849
- await Promise.all([
1850
- promises.writeFile(appTsConfigPath, JSON.stringify(tsConfig, null, 2)),
1851
- promises.writeFile(legacyTsConfigPath, JSON.stringify(legacyTsConfig, null, 2)),
1852
- promises.writeFile(nodeTsConfigPath, JSON.stringify(nodeTsConfig, null, 2)),
1853
- promises.writeFile(sharedTsConfigPath, JSON.stringify(sharedTsConfig, null, 2)),
1854
- promises.writeFile(declarationPath, declaration),
1855
- promises.writeFile(nodeDeclarationPath, nodeDeclaration),
1856
- promises.writeFile(sharedDeclarationPath, sharedDeclaration)
1857
- ]);
1561
+ const { tsConfig, nodeTsConfig, nodeDeclaration, declaration, legacyTsConfig, sharedDeclaration, sharedTsConfig } = await _generateTypes(nuxt);
1562
+ const appTsConfigPath = resolve(nuxt.options.buildDir, "tsconfig.app.json");
1563
+ const legacyTsConfigPath = resolve(nuxt.options.buildDir, "tsconfig.json");
1564
+ const nodeTsConfigPath = resolve(nuxt.options.buildDir, "tsconfig.node.json");
1565
+ const sharedTsConfigPath = resolve(nuxt.options.buildDir, "tsconfig.shared.json");
1566
+ const declarationPath = resolve(nuxt.options.buildDir, "nuxt.d.ts");
1567
+ const nodeDeclarationPath = resolve(nuxt.options.buildDir, "nuxt.node.d.ts");
1568
+ const sharedDeclarationPath = resolve(nuxt.options.buildDir, "nuxt.shared.d.ts");
1569
+ await promises.mkdir(nuxt.options.buildDir, { recursive: true });
1570
+ await Promise.all([
1571
+ promises.writeFile(appTsConfigPath, JSON.stringify(tsConfig, null, 2)),
1572
+ promises.writeFile(legacyTsConfigPath, JSON.stringify(legacyTsConfig, null, 2)),
1573
+ promises.writeFile(nodeTsConfigPath, JSON.stringify(nodeTsConfig, null, 2)),
1574
+ promises.writeFile(sharedTsConfigPath, JSON.stringify(sharedTsConfig, null, 2)),
1575
+ promises.writeFile(declarationPath, declaration),
1576
+ promises.writeFile(nodeDeclarationPath, nodeDeclaration),
1577
+ promises.writeFile(sharedDeclarationPath, sharedDeclaration)
1578
+ ]);
1858
1579
  }
1859
1580
  function sortTsPaths(paths) {
1860
- for (const pathKey in paths) {
1861
- if (pathKey.startsWith("#build")) {
1862
- const pathValue = paths[pathKey];
1863
- delete paths[pathKey];
1864
- paths[pathKey] = pathValue;
1865
- }
1866
- }
1867
- }
1868
- function renderAttrs(obj) {
1869
- const attrs = [];
1870
- for (const key in obj) {
1871
- attrs.push(renderAttr(key, obj[key]));
1872
- }
1873
- return attrs.join(" ");
1874
- }
1875
- function renderAttr(key, value) {
1876
- return value ? `${key}="${value}"` : "";
1581
+ for (const pathKey in paths) if (pathKey.startsWith("#build")) {
1582
+ const pathValue = paths[pathKey];
1583
+ delete paths[pathKey];
1584
+ paths[pathKey] = pathValue;
1585
+ }
1586
+ }
1587
+ function renderReference(ref, baseDir) {
1588
+ return `/// <reference ${"path" in ref ? `path="${isAbsolute(ref.path) ? relative(baseDir, ref.path) : ref.path}"` : `types="${ref.types}"`} />`;
1877
1589
  }
1878
1590
  const RELATIVE_WITH_DOT_RE = /^([^.])/;
1879
1591
  function relativeWithDot(from, to) {
1880
- return relative(from, to).replace(RELATIVE_WITH_DOT_RE, "./$1") || ".";
1592
+ return relative(from, to).replace(RELATIVE_WITH_DOT_RE, "./$1") || ".";
1881
1593
  }
1882
- function withTrailingSlash(dir) {
1883
- return dir.replace(/[^/]$/, "$&/");
1594
+ function withTrailingSlash$1(dir) {
1595
+ return dir.replace(/[^/]$/, "$&/");
1884
1596
  }
1885
-
1886
1597
  const LAYOUT_RE = /["']/g;
1887
1598
  function addLayout(template, name) {
1888
- const nuxt = useNuxt();
1889
- const { filename, src } = addTemplate(template);
1890
- const layoutName = kebabCase(name || parse(filename).name).replace(LAYOUT_RE, "");
1891
- nuxt.hook("app:templates", (app) => {
1892
- if (layoutName in app.layouts) {
1893
- const relativePath = reverseResolveAlias(app.layouts[layoutName].file, { ...nuxt?.options.alias || {}, ...strippedAtAliases }).pop() || app.layouts[layoutName].file;
1894
- return logger.warn(
1895
- `Not overriding \`${layoutName}\` (provided by \`${relativePath}\`) with \`${src || filename}\`.`
1896
- );
1897
- }
1898
- app.layouts[layoutName] = {
1899
- file: join("#build", filename),
1900
- name: layoutName
1901
- };
1902
- });
1599
+ const nuxt = useNuxt();
1600
+ const { filename, src } = addTemplate(template);
1601
+ const layoutName = kebabCase(name || parse(filename).name).replace(LAYOUT_RE, "");
1602
+ nuxt.hook("app:templates", (app) => {
1603
+ if (layoutName in app.layouts) {
1604
+ const relativePath = reverseResolveAlias(app.layouts[layoutName].file, {
1605
+ ...nuxt?.options.alias || {},
1606
+ ...strippedAtAliases
1607
+ }).pop() || app.layouts[layoutName].file;
1608
+ return logger.warn(`Not overriding \`${layoutName}\` (provided by \`${relativePath}\`) with \`${src || filename}\`.`);
1609
+ }
1610
+ app.layouts[layoutName] = {
1611
+ file: join("#build", filename),
1612
+ name: layoutName
1613
+ };
1614
+ });
1903
1615
  }
1904
1616
  const strippedAtAliases = {
1905
- "@": "",
1906
- "@@": ""
1617
+ "@": "",
1618
+ "@@": ""
1907
1619
  };
1908
-
1909
1620
  function extendPages(cb) {
1910
- useNuxt().hook("pages:extend", cb);
1621
+ useNuxt().hook("pages:extend", cb);
1911
1622
  }
1912
1623
  function extendRouteRules(route, rule, options = {}) {
1913
- const nuxt = useNuxt();
1914
- for (const opts of [nuxt.options, nuxt.options.nitro]) {
1915
- opts.routeRules ||= {};
1916
- opts.routeRules[route] = options.override ? defu(rule, opts.routeRules[route]) : defu(opts.routeRules[route], rule);
1917
- }
1624
+ const nuxt = useNuxt();
1625
+ for (const opts of [nuxt.options, nuxt.options.nitro]) {
1626
+ opts.routeRules ||= {};
1627
+ opts.routeRules[route] = options.override ? defu(rule, opts.routeRules[route]) : defu(opts.routeRules[route], rule);
1628
+ }
1918
1629
  }
1919
1630
  function addRouteMiddleware(input, options = {}) {
1920
- const nuxt = useNuxt();
1921
- const middlewares = toArray(input);
1922
- nuxt.hook("app:resolve", (app) => {
1923
- for (const middleware of middlewares) {
1924
- const find = app.middleware.findIndex((item) => item.name === middleware.name);
1925
- if (find >= 0) {
1926
- const foundPath = app.middleware[find].path;
1927
- if (foundPath === middleware.path) {
1928
- continue;
1929
- }
1930
- if (options.override === true) {
1931
- app.middleware[find] = { ...middleware };
1932
- } else {
1933
- logger.warn(`'${middleware.name}' middleware already exists at '${foundPath}'. You can set \`override: true\` to replace it.`);
1934
- }
1935
- } else if (options.prepend === true) {
1936
- app.middleware.unshift({ ...middleware });
1937
- } else {
1938
- app.middleware.push({ ...middleware });
1939
- }
1940
- }
1941
- });
1942
- }
1943
-
1631
+ const nuxt = useNuxt();
1632
+ const middlewares = toArray(input);
1633
+ nuxt.hook("app:resolve", (app) => {
1634
+ for (const middleware of middlewares) {
1635
+ const find = app.middleware.findIndex((item) => item.name === middleware.name);
1636
+ if (find >= 0) {
1637
+ const foundPath = app.middleware[find].path;
1638
+ if (foundPath === middleware.path) continue;
1639
+ if (options.override === true) app.middleware[find] = { ...middleware };
1640
+ else logger.warn(`'${middleware.name}' middleware already exists at '${foundPath}'. You can set \`override: true\` to replace it.`);
1641
+ } else if (options.prepend === true) app.middleware.unshift({ ...middleware });
1642
+ else app.middleware.push({ ...middleware });
1643
+ }
1644
+ });
1645
+ }
1944
1646
  const pluginSymbol = Symbol.for("nuxt plugin");
1945
1647
  function normalizePlugin(plugin) {
1946
- if (typeof plugin === "string") {
1947
- plugin = { src: plugin };
1948
- } else {
1949
- plugin = { ...plugin };
1950
- }
1951
- if (pluginSymbol in plugin) {
1952
- return plugin;
1953
- }
1954
- if (!plugin.src) {
1955
- throw new Error("Invalid plugin. src option is required: " + JSON.stringify(plugin));
1956
- }
1957
- plugin.src = normalize(resolveAlias(plugin.src));
1958
- if (!existsSync(plugin.src) && isAbsolute$1(plugin.src)) {
1959
- try {
1960
- plugin.src = resolveModulePath(plugin.src, {
1961
- extensions: tryUseNuxt()?.options.extensions ?? [".js", ".mjs", ".cjs", ".ts", ".tsx", ".mts", ".cts"]
1962
- });
1963
- } catch {
1964
- }
1965
- }
1966
- if (plugin.ssr) {
1967
- plugin.mode = "server";
1968
- }
1969
- if (!plugin.mode) {
1970
- const [, mode = "all"] = plugin.src.match(MODE_RE) || [];
1971
- plugin.mode = mode;
1972
- }
1973
- plugin[pluginSymbol] = true;
1974
- return plugin;
1648
+ if (typeof plugin === "string") plugin = { src: plugin };
1649
+ else plugin = { ...plugin };
1650
+ if (pluginSymbol in plugin) return plugin;
1651
+ if (!plugin.src) throw new Error("Invalid plugin. src option is required: " + JSON.stringify(plugin));
1652
+ plugin.src = normalize(resolveAlias(plugin.src));
1653
+ if (!existsSync(plugin.src) && isAbsolute$1(plugin.src)) try {
1654
+ plugin.src = resolveModulePath(plugin.src, { extensions: tryUseNuxt()?.options.extensions ?? [
1655
+ ".js",
1656
+ ".mjs",
1657
+ ".cjs",
1658
+ ".ts",
1659
+ ".tsx",
1660
+ ".mts",
1661
+ ".cts"
1662
+ ] });
1663
+ } catch {}
1664
+ if (plugin.ssr) plugin.mode = "server";
1665
+ if (!plugin.mode) {
1666
+ const [, mode = "all"] = plugin.src.match(MODE_RE) || [];
1667
+ plugin.mode = mode;
1668
+ }
1669
+ plugin[pluginSymbol] = true;
1670
+ return plugin;
1975
1671
  }
1976
1672
  function addPlugin(_plugin, opts = {}) {
1977
- const nuxt = useNuxt();
1978
- const plugin = normalizePlugin(_plugin);
1979
- filterInPlace(nuxt.options.plugins, (p) => normalizePlugin(p).src !== plugin.src);
1980
- nuxt.options.plugins[opts.append ? "push" : "unshift"](plugin);
1981
- return plugin;
1673
+ const nuxt = useNuxt();
1674
+ const plugin = normalizePlugin(_plugin);
1675
+ filterInPlace(nuxt.options.plugins, (p) => normalizePlugin(p).src !== plugin.src);
1676
+ nuxt.options.plugins[opts.append ? "push" : "unshift"](plugin);
1677
+ return plugin;
1982
1678
  }
1983
1679
  function addPluginTemplate(plugin, opts = {}) {
1984
- const normalizedPlugin = typeof plugin === "string" ? { src: plugin } : { ...plugin, src: addTemplate(plugin).dst };
1985
- return addPlugin(normalizedPlugin, opts);
1680
+ return addPlugin(typeof plugin === "string" ? { src: plugin } : {
1681
+ ...plugin,
1682
+ src: addTemplate(plugin).dst
1683
+ }, opts);
1986
1684
  }
1987
-
1988
1685
  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 };