@monkeyplus/flow 5.0.0-rc.13 → 5.0.0-rc.131

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,36 +1,33 @@
1
1
  import { createHooks } from 'hookable';
2
2
  import { dirname, resolve, normalize, join, isAbsolute, relative, extname } from 'pathe';
3
- import { defineFlowModule, addPlugin, defineNuxtModule, logger, addTemplate, addPluginTemplate, addVitePlugin, useNuxt, resolveAlias, resolveFilesFlow, nuxtCtx, installModule, loadFlowConfig, templateUtils, normalizeTemplate, compileTemplate, normalizePlugin, isIgnoredFlow } from '@monkeyplus/flow-kit';
3
+ import { defineFlowModule, addPlugin, defineNuxtModule, logger, addTemplate, addPluginTemplate, addVitePlugin, addWebpackPlugin, updateTemplates, useNuxt, resolveAlias, resolveFilesFlow, nuxtCtx, installModule, loadFlowConfig, normalizeTemplate, compileTemplate, normalizePlugin, findPath, templateUtils, isIgnoredFlow } from '@monkeyplus/flow-kit';
4
+ import escapeRE from 'escape-string-regexp';
4
5
  import { fileURLToPath, pathToFileURL } from 'node:url';
5
6
  import { defineUnimportPreset, createUnimport, toImports, scanDirExports } from 'unimport';
7
+ import defu from 'defu';
6
8
  import { createUnplugin } from 'unplugin';
7
- import { parseURL, parseQuery, joinURL, withoutTrailingSlash } from 'ufo';
8
- import escapeRE from 'escape-string-regexp';
9
+ import { parseURL, parseQuery, joinURL } from 'ufo';
10
+ import fs from 'fs';
9
11
  import { camelCase, pascalCase } from 'scule';
10
- import { genImport, genDynamicImport, genArrayFromRaw, genString, genObjectFromRawEntries } from 'knitwork';
11
- import fse from 'fs-extra';
12
- import logger$1 from 'consola';
13
- import * as vite from 'vite';
14
- import { createServer, build as build$1 } from 'vite';
15
- import { debounce } from 'perfect-debounce';
16
- import { existsSync, promises, readdirSync, statSync } from 'node:fs';
17
- import { createNitro, scanHandlers, writeTypes, build as build$2, prepare, copyPublicAssets, prerender, createDevServer } from 'nitropack';
18
- import defu from 'defu';
19
- import { dynamicEventHandler, toEventHandler } from 'h3';
20
- import { createRequire, builtinModules } from 'node:module';
12
+ import { genImport, genDynamicImport, genSafeVariableName, genArrayFromRaw, genString } from 'knitwork';
13
+ import { existsSync, promises } from 'node:fs';
14
+ import { createNitro, scanHandlers, writeTypes, build as build$1, prepare, copyPublicAssets, prerender, createDevServer } from 'nitropack';
15
+ import { dynamicEventHandler } from 'h3';
16
+ import { createRequire } from 'node:module';
21
17
  import chokidar from 'chokidar';
18
+ import { debounce } from 'perfect-debounce';
22
19
  import { generateTypes, resolveSchema } from 'untyped';
23
- import { getPort } from 'get-port-please';
24
- import { sanitizeFilePath } from 'mlly';
20
+ import { hash } from 'ohash';
21
+ import { resolvePath, sanitizeFilePath } from 'mlly';
22
+ import * as vite from 'vite';
25
23
  import replace from '@rollup/plugin-replace';
26
- import { isExternal as isExternal$1, ExternalsDefaults } from 'externality';
27
- import { createHash } from 'node:crypto';
28
- import MagicString from 'magic-string';
24
+ import { resolveTSConfig } from 'pkg-types';
25
+ import fse from 'fs-extra';
29
26
 
30
- const version = "5.0.0-rc.13";
27
+ const version = "5.0.0-rc.131";
31
28
 
32
29
  let _distDir = dirname(fileURLToPath(import.meta.url));
33
- if (_distDir.endsWith("chunks"))
30
+ if (_distDir.match(/(chunks|shared)$/))
34
31
  _distDir = dirname(_distDir);
35
32
  const distDir = _distDir;
36
33
  const pkgDir = resolve(distDir, "..");
@@ -53,30 +50,32 @@ const metaModule = defineFlowModule({
53
50
 
54
51
  const TransformPlugin = createUnplugin(({ ctx, options, sourcemap }) => {
55
52
  return {
56
- name: "flow:auto-imports-transform",
53
+ name: "nuxt:imports-transform",
57
54
  enforce: "post",
58
55
  transformInclude(id) {
59
56
  const { pathname, search } = parseURL(decodeURIComponent(pathToFileURL(id).href));
60
- const { type, macro } = parseQuery(search);
61
- const exclude = options.transform?.exclude || [/[\\/]node_modules[\\/]/];
62
- const include = options.transform?.include || [];
63
- if (exclude.some((pattern) => id.match(pattern)))
64
- return false;
65
- if (include.some((pattern) => id.match(pattern)))
57
+ const query = parseQuery(search);
58
+ if (options.transform?.include?.some((pattern) => id.match(pattern)))
66
59
  return true;
67
- if (pathname.endsWith(".vue") && (type === "template" || type === "script" || macro || !search))
60
+ if (options.transform?.exclude?.some((pattern) => id.match(pattern)))
61
+ return false;
62
+ if (id.endsWith(".vue") || "macro" in query || "vue" in query && (query.type === "template" || query.type === "script" || "setup" in query))
68
63
  return true;
69
64
  if (pathname.match(/\.((c|m)?j|t)sx?$/g))
70
65
  return true;
71
66
  },
72
- async transform(_code, id) {
73
- const { code, s } = await ctx.injectImports(_code);
74
- if (code === _code)
67
+ async transform(code, id) {
68
+ id = normalize(id);
69
+ const isNodeModule = id.match(/[\\/]node_modules[\\/]/) && !options.transform?.include?.some((pattern) => id.match(pattern));
70
+ if (isNodeModule && !code.match(/(['"])#imports\1/))
75
71
  return;
76
- return {
77
- code,
78
- map: sourcemap && s.generateMap({ source: id, includeContent: true })
79
- };
72
+ const { s } = await ctx.injectImports(code, id, { autoImport: options.autoImport && !isNodeModule });
73
+ if (s.hasChanged()) {
74
+ return {
75
+ code: s.toString(),
76
+ map: sourcemap ? s.generateMap({ source: id, includeContent: true }) : void 0
77
+ };
78
+ }
80
79
  }
81
80
  };
82
81
  });
@@ -92,7 +91,8 @@ const commonPresets = [
92
91
  from: "#_pages",
93
92
  imports: [
94
93
  "definePage",
95
- "defineDinamycPage"
94
+ "defineDynamicPage",
95
+ "defineSharedContext"
96
96
  ]
97
97
  })
98
98
  ];
@@ -124,50 +124,65 @@ const defaultPresets = [
124
124
  vuePreset
125
125
  ];
126
126
 
127
- const autoImportsModule = defineNuxtModule({
127
+ const importsModule = defineNuxtModule({
128
128
  meta: {
129
- name: "auto-imports",
130
- configKey: "autoImports"
129
+ name: "imports",
130
+ configKey: "imports"
131
131
  },
132
132
  defaults: {
133
+ autoImport: true,
133
134
  presets: defaultPresets,
134
135
  global: false,
135
136
  imports: [],
136
137
  dirs: [],
137
138
  transform: {
139
+ include: [],
138
140
  exclude: void 0
139
141
  }
140
142
  },
141
- async setup(options, flow) {
142
- await flow.callHook("autoImports:sources", options.presets);
143
- options.presets.forEach((i) => {
143
+ async setup(options, nuxt) {
144
+ if (nuxt.options.autoImports) {
145
+ logger.warn("`autoImports` config is deprecated, use `imports` instead.");
146
+ options = defu(nuxt.options.autoImports, options);
147
+ }
148
+ await nuxt.callHook("imports:sources", options.presets);
149
+ options.presets?.forEach((_i) => {
150
+ const i = _i;
144
151
  if (typeof i !== "string" && i.names && !i.imports) {
145
152
  i.imports = i.names;
146
- logger.warn("auto-imports: presets.names is deprecated, use presets.imports instead");
153
+ logger.warn("imports: presets.names is deprecated, use presets.imports instead");
147
154
  }
148
155
  });
149
156
  const ctx = createUnimport({
150
157
  presets: options.presets,
151
- imports: options.imports
158
+ imports: options.imports,
159
+ virtualImports: ["#imports"],
160
+ addons: {
161
+ vueTemplate: options.autoImport
162
+ }
152
163
  });
153
164
  let composablesDirs = [];
154
- for (const layer of flow.options._layers) {
165
+ for (const layer of nuxt.options._layers) {
155
166
  composablesDirs.push(resolve(layer.config.srcDir, "composables"));
156
- for (const dir of layer.config.autoImports?.dirs ?? [])
167
+ for (const dir of layer.config.imports?.dirs ?? []) {
168
+ if (!dir)
169
+ continue;
157
170
  composablesDirs.push(resolve(layer.config.srcDir, dir));
171
+ }
158
172
  }
159
- await flow.callHook("autoImports:dirs", composablesDirs);
173
+ await nuxt.callHook("imports:dirs", composablesDirs);
160
174
  composablesDirs = composablesDirs.map((dir) => normalize(dir));
161
175
  addTemplate({
162
176
  filename: "imports.mjs",
163
- getContents: () => ctx.toExports()
177
+ getContents: async () => `${await ctx.toExports()}
178
+ if (process.dev) { console.warn("[nuxt] \`#imports\` should be transformed with real imports. There seems to be something wrong with the imports plugin.") }`
164
179
  });
165
- flow.options.alias["#imports"] = join(flow.options.buildDir, "imports");
166
- if (flow.options.dev && options.global) {
180
+ nuxt.options.alias["#imports"] = join(nuxt.options.buildDir, "imports");
181
+ if (nuxt.options.dev && options.global) {
167
182
  addPluginTemplate({
168
- filename: "auto-imports.mjs",
169
- getContents: () => {
170
- const imports = ctx.getImports();
183
+ filename: "imports.mjs",
184
+ getContents: async () => {
185
+ const imports = await ctx.getImports();
171
186
  const importStatement = toImports(imports);
172
187
  const globalThisSet = imports.map((i) => `globalThis.${i.as} = ${i.as};`).join("\n");
173
188
  return `${importStatement}
@@ -178,32 +193,41 @@ export default () => {};`;
178
193
  }
179
194
  });
180
195
  } else {
181
- addVitePlugin(TransformPlugin.vite({ ctx, options, sourcemap: flow.options.sourcemap }));
196
+ addVitePlugin(TransformPlugin.vite({ ctx, options, sourcemap: nuxt.options.sourcemap.server || nuxt.options.sourcemap.client }));
197
+ addWebpackPlugin(TransformPlugin.webpack({ ctx, options, sourcemap: nuxt.options.sourcemap.server || nuxt.options.sourcemap.client }));
182
198
  }
183
- const regenerateAutoImports = async () => {
199
+ const regenerateImports = async () => {
184
200
  ctx.clearDynamicImports();
185
201
  await ctx.modifyDynamicImports(async (imports) => {
186
202
  imports.push(...await scanDirExports(composablesDirs));
187
- await flow.callHook("autoImports:extend", imports);
203
+ await nuxt.callHook("imports:extend", imports);
188
204
  });
189
205
  };
190
- await regenerateAutoImports();
191
- addDeclarationTemplates(ctx);
192
- flow.hook("prepare:types", ({ references }) => {
193
- references.push({ path: resolve(flow.options.buildDir, "types/auto-imports.d.ts") });
194
- references.push({ path: resolve(flow.options.buildDir, "imports.d.ts") });
206
+ await regenerateImports();
207
+ addDeclarationTemplates(ctx, options);
208
+ nuxt.hook("prepare:types", ({ references }) => {
209
+ references.push({ path: resolve(nuxt.options.buildDir, "types/imports.d.ts") });
210
+ references.push({ path: resolve(nuxt.options.buildDir, "imports.d.ts") });
195
211
  });
196
- flow.hook("builder:watch", async (_, path) => {
197
- const _resolved = resolve(flow.options.srcDir, path);
198
- if (composablesDirs.find((dir) => _resolved.startsWith(dir)))
199
- await flow.callHook("builder:generateApp");
212
+ const templates = [
213
+ "types/imports.d.ts",
214
+ "imports.d.ts",
215
+ "imports.mjs"
216
+ ];
217
+ nuxt.hook("builder:watch", async (_, path) => {
218
+ const _resolved = resolve(nuxt.options.srcDir, path);
219
+ if (composablesDirs.find((dir) => _resolved.startsWith(dir))) {
220
+ await updateTemplates({
221
+ filter: (template) => templates.includes(template.filename)
222
+ });
223
+ }
200
224
  });
201
- flow.hook("builder:generateApp", async () => {
202
- await regenerateAutoImports();
225
+ nuxt.hook("builder:generateApp", async () => {
226
+ await regenerateImports();
203
227
  });
204
228
  }
205
229
  });
206
- function addDeclarationTemplates(ctx) {
230
+ function addDeclarationTemplates(ctx, options) {
207
231
  const nuxt = useNuxt();
208
232
  const stripExtension = (path) => path.replace(/\.[a-z]+$/, "");
209
233
  const resolved = {};
@@ -219,49 +243,64 @@ function addDeclarationTemplates(ctx) {
219
243
  };
220
244
  addTemplate({
221
245
  filename: "imports.d.ts",
222
- getContents: () => ctx.toExports()
246
+ getContents: () => ctx.toExports(nuxt.options.buildDir)
223
247
  });
224
248
  addTemplate({
225
- filename: "types/auto-imports.d.ts",
226
- getContents: () => `// Generated by auto imports
227
- ${ctx.generateTypeDecarations({ resolvePath: r })}`
249
+ filename: "types/imports.d.ts",
250
+ getContents: async () => `// Generated by auto imports
251
+ ${options.autoImport ? await ctx.generateTypeDeclarations({ resolvePath: r }) : "// Implicit auto importing is disabled, you can use explicitly import from `#imports` instead."}`
228
252
  });
229
253
  }
230
254
 
231
- async function resolvePagesRoutes() {
255
+ async function resolveFiles(dir) {
232
256
  const nuxt = useNuxt();
233
- const pagesDirs = [resolve(nuxt.options.srcDir, nuxt.options.dir?.pages || "pages")];
234
- const allRoutes = (await Promise.all(pagesDirs.map(async (dir) => {
235
- const files = await resolveFilesFlow(dir, `**/*{${nuxt.options.extensions.join(",")}}`);
236
- files.sort();
237
- return files.filter((file) => !file.includes(" copy")).map((file) => {
238
- const segments = relative(dir, file).replace(new RegExp(`${escapeRE(extname(file))}$`), "").split("/").join("_");
239
- return {
240
- file,
241
- name: camelCase(segments)
242
- };
243
- });
244
- }))).flat();
257
+ const dirs = [resolve(nuxt.options.srcDir, dir)];
258
+ const allRoutes = (await Promise.all(
259
+ dirs.map(async (dir2) => {
260
+ const files = await resolveFilesFlow(dir2, `**/*{${nuxt.options.extensions.join(",")}}`);
261
+ files.sort();
262
+ return files.filter((file) => {
263
+ if (file.includes(" copy"))
264
+ return false;
265
+ if (!fs.readFileSync(file, "utf8").includes("export"))
266
+ return false;
267
+ return true;
268
+ }).map((file) => {
269
+ const segments = relative(dir2, file).replace(new RegExp(`${escapeRE(extname(file))}$`), "").split("/").join("_");
270
+ return {
271
+ file,
272
+ name: camelCase(segments)
273
+ };
274
+ });
275
+ })
276
+ )).flat();
245
277
  return allRoutes;
246
278
  }
247
- function normalizePages(pages) {
248
- const imports = pages.map((page) => genImport(page.file, [{ name: "pages", as: page.name }])).join("\n");
279
+ function normalizeExports(files) {
280
+ const imports = files.map((page) => genImport(page.file, page.name)).join("\n");
281
+ const exports = files.reduce((acc, curr) => {
282
+ const name = curr.name;
283
+ return `${name}:typeof ${name}==='function'?${name}():${name},${acc}`;
284
+ }, "");
249
285
  return {
250
286
  imports,
251
- exports: pages.reduce((acc, curr) => {
252
- const name = curr.name;
253
- return `${name}:typeof ${name}==='function'?${name}():${name},${acc}`;
254
- }, "")
287
+ exports
255
288
  };
256
289
  }
257
290
 
258
291
  const pagesTypeTemplate = {
259
- filename: "pages.d.ts",
292
+ filename: "types/pages.d.ts",
260
293
  getContents: ({ options }) => `// Generated by pages discovery
261
294
  export {}
262
295
  declare global {
296
+ type ArrElement<ArrType> = ArrType extends readonly (infer ElementType)[]
297
+ ? ElementType
298
+ : never;
263
299
 
264
- ${options.pages.map((c) => `export type ${pascalCase(c.name)}Context=Awaited<ReturnType<typeof ${genDynamicImport(isAbsolute(c.file) ? relative(options.buildDir, c.file) : c.file, { wrapper: false })}['pages']['locales']['es-ec']['context']>>`).join("\n")}
300
+ ${options.pages.map((c) => {
301
+ const _type = `ArrElement<typeof ${genDynamicImport(isAbsolute(c.file) ? relative(join(options.buildDir, "types"), c.file) : c.file, { wrapper: false })}['default']>`;
302
+ return `export type ${pascalCase(c.name)}Context=Awaited<ReturnType<${_type}['locales']['es-ec']['context']>>`;
303
+ }).join("\n")}
265
304
  }
266
305
  export const pagesNames: string[]
267
306
  `.replaceAll(".ts", "")
@@ -275,164 +314,73 @@ const pagesModule = defineNuxtModule({
275
314
  const runtimeDir = resolve(distDir, "pages/runtime");
276
315
  flow.options.alias["#_pages"] = runtimeDir;
277
316
  const pages = [];
278
- flow.hook("builder:watch", async (event, path) => {
279
- const dirs = [
280
- flow.options.dir.pages,
281
- flow.options.dir.layouts,
282
- flow.options.dir.middleware
283
- ].filter(Boolean);
284
- const pathPattern = new RegExp(`^(${dirs.map(escapeRE).join("|")})/`);
285
- if (event !== "change" && path.match(pathPattern))
286
- await flow.callHook("builder:generateApp");
287
- });
288
- const options = { pages, buildDir: flow.options.buildDir };
317
+ const contexts = [];
318
+ const options = { pages, buildDir: flow.options.buildDir, contexts };
289
319
  addTemplate({
290
320
  ...pagesTypeTemplate,
291
321
  options
292
322
  });
293
323
  const pagesDirs = [{ path: resolve(flow.options.srcDir, flow.options.dir.pages) }];
294
324
  flow.options.alias["#pages"] = resolve(flow.options.buildDir, "pages.mjs");
325
+ flow.options.alias["#pagesContexts"] = resolve(flow.options.buildDir, "pages.contexts.mjs");
295
326
  addTemplate({
296
327
  filename: "pages.mjs",
297
328
  async getContents({ options: options2 }) {
298
- const { exports, imports } = normalizePages(options2.pages);
299
- return [imports, `export default {${exports}}`].join("\n");
329
+ const { exports, imports } = normalizeExports(options2.pages);
330
+ const module = [imports, `export default {${exports}}`].join("\n");
331
+ return module;
332
+ },
333
+ options
334
+ });
335
+ addTemplate({
336
+ filename: "pages.contexts.mjs",
337
+ async getContents({ options: options2 }) {
338
+ const { exports, imports } = normalizeExports(options2.contexts);
339
+ const module = [imports, `export default {${exports}}`].join("\n");
340
+ return module;
300
341
  },
301
342
  options
302
343
  });
303
344
  flow.hook("app:templates", async () => {
304
- options.pages = await resolvePagesRoutes();
345
+ options.pages = await resolveFiles(flow.options.dir?.pages || "pages");
346
+ });
347
+ flow.hook("app:templates", async () => {
348
+ options.contexts = await resolveFiles("shared/contexts");
305
349
  });
306
350
  flow.hook("prepare:types", ({ references }) => {
307
- references.push({ path: resolve(flow.options.buildDir, "pages.d.ts") });
351
+ references.push({ path: resolve(flow.options.buildDir, "types/pages.d.ts") });
308
352
  });
309
353
  flow.hook("builder:watch", async (event, path) => {
310
- if (!["add", "unlink"].includes(event))
354
+ if (!["add", "unlink", "change"].includes(event))
355
+ return;
356
+ if (path.includes(" copy"))
311
357
  return;
312
358
  const fPath = resolve(flow.options.rootDir, path);
313
359
  if (pagesDirs.find((dir) => fPath.startsWith(dir.path)))
314
360
  await flow.callHook("builder:generateApp");
315
361
  });
316
- addPlugin({ src: resolve(runtimeDir, "plugin") });
317
- }
318
- });
319
-
320
- const createClient = async (flow) => {
321
- let vite;
322
- if (globalThis.viteClient) {
323
- vite = globalThis.viteClient;
324
- } else {
325
- vite = await createServer({
326
- root: resolve(flow.options.rootDir),
327
- base: "/_vite/",
328
- build: {
329
- manifest: true
330
- },
331
- server: {
332
- watch: {
333
- ignored: ["**/.env/**", "**/.env*"]
334
- },
335
- middlewareMode: "ssr"
336
- }
337
- });
338
- globalThis.viteClient = vite;
339
- }
340
- const _doReload = () => {
341
- if (vite)
342
- vite?.ws?.send({ type: "full-reload" });
343
- };
344
- const doReload = debounce(_doReload, 60);
345
- flow.hook("bundler:change", () => {
346
- doReload();
347
- });
348
- flow.hook("close", async () => {
349
- vite.restart();
350
- });
351
- return vite;
352
- };
353
- const builClient = async (flow) => {
354
- return await build$1({
355
- root: flow.options.rootDir,
356
- mode: "production",
357
- build: {
358
- assetsDir: "scripts",
359
- target: "es2017",
360
- outDir: ".vite",
361
- manifest: true
362
- }
363
- });
364
- };
365
-
366
- const viteModule = defineFlowModule({
367
- meta: {
368
- name: "vite-client",
369
- configKey: "bundle"
370
- },
371
- defaults: {
372
- route: "/_vite/",
373
- dir: "/client/pages"
374
- },
375
- async setup(_options, flow) {
376
- const runtimeDir = resolve(distDir, "vite-client/runtime");
377
- flow.options.alias["#viteManifest"] = resolve(flow.options.buildDir, "viteManifest.mjs");
378
- let vite;
379
- if (flow.options.dev) {
380
- flow.hook("nitro:init", async (nitro) => {
381
- vite = await createClient(flow);
382
- nitro.options.devHandlers.push({
383
- handler: vite.middlewares,
384
- route: _options.route
385
- });
386
- });
387
- addTemplate({
388
- filename: "viteManifest.mjs",
389
- async getContents() {
390
- return [
391
- "export default {",
392
- `head:()=>'<script type="module" src="${joinURL("/", _options.route, "/@vite/client")}"><\/script>'`,
393
- ",",
394
- `body: (bundle)=>\`<script type="module" src="${joinURL("/", _options.route, _options.dir)}/\${bundle}.ts"><\/script>\``,
395
- "}"
396
- ].join("\n");
397
- }
398
- });
399
- } else {
400
- flow.hook("modules:done", async () => {
401
- const start = Date.now();
402
- logger$1.info("Building client...");
403
- await builClient(flow);
404
- const file = resolve(flow.options.rootDir, ".vite/manifest.json");
405
- const manifest = await fse.readFile(file, "utf8");
406
- logger$1.success(`Client build in ${Date.now() - start}ms`);
407
- addTemplate({
408
- filename: "viteManifest.mjs",
409
- async getContents() {
410
- return [
411
- "export default ()=>(",
412
- manifest,
413
- ")"
414
- ].join("\n");
415
- }
416
- });
417
- });
418
- flow.hook("generate:before", async () => {
419
- const files = resolve(flow.options.rootDir, ".vite/scripts");
420
- await fse.copy(files, resolve(flow.options.generate.dir, "assets"));
421
- });
422
- }
423
- addPlugin({ src: resolve(runtimeDir, "plugin") });
362
+ addPlugin(resolve(runtimeDir, "pages"));
424
363
  }
425
364
  });
426
365
 
427
366
  const _require = createRequire(import.meta.url);
428
367
  const ImportProtectionPlugin = createUnplugin((options) => {
429
368
  const cache = {};
369
+ const importersToExclude = options?.exclude || [];
430
370
  return {
431
- name: "flow:import-protection",
371
+ name: "nuxt:import-protection",
432
372
  enforce: "pre",
433
373
  resolveId(id, importer) {
374
+ if (!importer)
375
+ return;
376
+ if (id.startsWith("."))
377
+ id = join(importer, "..", id);
378
+ if (isAbsolute(id))
379
+ id = relative(options.rootDir, id);
380
+ if (importersToExclude.some((p) => typeof p === "string" ? importer === p : p.test(importer)))
381
+ return;
434
382
  const invalidImports = options.patterns.filter(([pattern]) => pattern instanceof RegExp ? pattern.test(id) : pattern === id);
435
- let matched;
383
+ let matched = false;
436
384
  for (const match of invalidImports) {
437
385
  cache[id] = cache[id] || /* @__PURE__ */ new Map();
438
386
  const [pattern, warning] = match;
@@ -451,25 +399,36 @@ const ImportProtectionPlugin = createUnplugin((options) => {
451
399
  });
452
400
 
453
401
  async function initNitro(flow) {
454
- const { handlers, devHandlers } = await resolveHandlers(flow);
455
402
  const _nitroConfig = flow.options.nitro || {};
456
403
  globalThis.generate = {};
404
+ const scanDirs = flow.options._layers.map((layer) => (layer.config.serverDir || layer.config.srcDir) && resolve(layer.cwd, layer.config.serverDir || resolve(layer.config.srcDir, "server"))).filter(Boolean);
457
405
  const nitroConfig = defu(_nitroConfig, {
458
406
  rootDir: flow.options.rootDir,
459
- srcDir: join(flow.options.srcDir, "server"),
407
+ workspaceDir: flow.options.workspaceDir,
408
+ srcDir: flow.options.serverDir,
460
409
  dev: flow.options.dev,
461
- preset: flow.options.dev ? "nitro-dev" : void 0,
462
410
  buildDir: flow.options.buildDir,
463
- scanDirs: flow.options._layers.map((layer) => join(layer.config.srcDir, "server")),
411
+ scanDirs,
464
412
  renderer: resolve(distDir, "core/runtime/nitro/renderer"),
465
413
  nodeModulesDirs: flow.options.modulesDir,
466
- handlers,
414
+ handlers: [
415
+ {
416
+ middleware: true,
417
+ handler: resolve(distDir, "core/runtime/nitro/flow")
418
+ },
419
+ ...flow.options.serverHandlers
420
+ ],
421
+ output: {
422
+ dir: resolve(flow.options.buildDir, "output")
423
+ },
467
424
  devHandlers: [],
468
425
  baseURL: flow.options.app.baseURL,
426
+ virtual: {},
469
427
  runtimeConfig: {
470
428
  ...flow.options.runtimeConfig,
471
429
  app: {
472
430
  ...flow.options.runtimeConfig.app,
431
+ baseURL: flow.options.dev ? "/" : flow.options.app.baseURL,
473
432
  rootDir: flow.options.rootDir,
474
433
  locale: flow.options.locale
475
434
  },
@@ -484,22 +443,26 @@ async function initNitro(flow) {
484
443
  },
485
444
  publicAssets: [
486
445
  {
487
- baseURL: flow.options.app.buildAssetsDir,
488
446
  dir: resolve(flow.options.buildDir, "dist/client")
489
447
  },
490
448
  ...flow.options._layers.map((layer) => join(layer.config.srcDir, layer.config.dir?.public || "public")).filter((dir) => existsSync(dir)).map((dir) => ({ dir }))
491
449
  ],
492
450
  prerender: {
493
- crawlLinks: flow.options._generate ? flow.options.generate.crawler : false,
494
- routes: [].concat(flow.options._generate ? ["/_urls", ...flow.options.generate.routes] : [])
451
+ crawlLinks: flow.options._generate ?? void 0,
452
+ routes: [].concat(flow.options.generate.routes).concat(flow.options._generate ? ["/_urls", ...flow.options.generate.routes] : [])
495
453
  },
496
- sourcemap: flow.options.sourcemap,
454
+ sourceMap: flow.options.sourcemap.server,
497
455
  externals: {
498
456
  inline: [
499
457
  ...flow.options.dev ? [] : ["eta", "@monkeyplus/", "@vue/", "@nuxt/", flow.options.buildDir],
500
- "@monkeyplus/flow/dist"
458
+ "@monkeyplus/flow/dist",
459
+ "C:/Users/gnu/Documents/GitHub/flow/packages/flow/dist/app",
460
+ distDir
501
461
  ]
502
462
  },
463
+ replace: {
464
+ "process.dev": flow.options.dev
465
+ },
503
466
  alias: {
504
467
  "estree-walker": "unenv/runtime/mock/proxy",
505
468
  "@babel/parser": "unenv/runtime/mock/proxy",
@@ -509,36 +472,40 @@ async function initNitro(flow) {
509
472
  },
510
473
  rollupConfig: {
511
474
  plugins: []
475
+ },
476
+ devServer: {
477
+ watch: [resolve(flow.options.buildDir, "dist/server/server.mjs")]
512
478
  }
513
479
  });
480
+ nitroConfig.rollupConfig.plugins.push(
481
+ ImportProtectionPlugin.rollup({
482
+ rootDir: flow.options.rootDir,
483
+ patterns: [
484
+ ...["#app", /^#build(\/|$)/].map((p) => [p, "Vue app aliases are not allowed in server routes."])
485
+ ],
486
+ exclude: [/core[\\/]runtime[\\/]nitro[\\/]renderer/]
487
+ })
488
+ );
514
489
  await flow.callHook("nitro:config", nitroConfig);
515
- nitroConfig.handlers.unshift({
516
- middleware: true,
517
- handler: resolve(distDir, "core/runtime/nitro/flow")
518
- });
519
490
  const nitro = await createNitro(nitroConfig);
491
+ flow._nitro = nitro;
492
+ flow.nitro = nitro;
520
493
  await flow.callHook("nitro:init", nitro);
521
494
  nitro.vfs = flow.vfs = nitro.vfs || flow.vfs || {};
522
495
  flow.hook("close", () => nitro.hooks.callHook("close"));
523
- nitro.hooks.hook("rollup:before", (nitro2) => {
524
- const plugin = ImportProtectionPlugin.rollup({
525
- rootDir: flow.options.rootDir,
526
- patterns: [
527
- ...["#app", /^#build(\/|$)/].map((p) => [p, "Flow app aliases are not allowed in server routes."])
528
- ]
529
- });
530
- nitro2.options.rollupConfig.plugins.push(plugin);
496
+ nitro.hooks.hook("prerender:routes", (routes) => {
497
+ flow.callHook("prerender:routes", { routes });
531
498
  });
532
- const devMidlewareHandler = dynamicEventHandler();
533
- nitro.options.devHandlers.unshift({ handler: devMidlewareHandler });
534
- nitro.options.devHandlers.push(...devHandlers);
499
+ const devMiddlewareHandler = dynamicEventHandler();
500
+ nitro.options.devHandlers.unshift({ handler: devMiddlewareHandler });
501
+ nitro.options.devHandlers.push(...flow.options.devServerHandlers);
535
502
  nitro.options.handlers.unshift({
536
- route: "/__flow_error",
503
+ route: "/__nuxt_error",
537
504
  lazy: true,
538
505
  handler: resolve(distDir, "core/runtime/nitro/renderer")
539
506
  });
540
507
  flow.hook("prepare:types", async (opts) => {
541
- if (flow.options._prepare) {
508
+ if (!flow.options.dev) {
542
509
  await scanHandlers(nitro);
543
510
  await writeTypes(nitro);
544
511
  }
@@ -547,21 +514,14 @@ async function initNitro(flow) {
547
514
  flow.hook("build:done", async () => {
548
515
  await flow.callHook("nitro:build:before", nitro);
549
516
  if (flow.options.dev) {
550
- await build$2(nitro);
517
+ await build$1(nitro);
551
518
  } else {
552
519
  await prepare(nitro);
553
520
  await copyPublicAssets(nitro);
554
521
  await prerender(nitro);
555
522
  if (!flow.options._generate) {
556
- await build$2(nitro);
523
+ await build$1(nitro);
557
524
  } else {
558
- const nitroDev = await createNitro({
559
- ...nitro.options._config,
560
- rootDir: nitro.options.rootDir,
561
- logLevel: 0,
562
- preset: "nitro-prerender"
563
- });
564
- flow.server = nitroDev;
565
525
  const distDir2 = resolve(flow.options.rootDir, "dist");
566
526
  if (!existsSync(distDir2))
567
527
  await promises.symlink(nitro.options.output.publicDir, distDir2, "junction").catch(() => {
@@ -570,28 +530,17 @@ async function initNitro(flow) {
570
530
  }
571
531
  });
572
532
  if (flow.options.dev) {
573
- flow.hook("build:compile", ({ compiler }) => {
574
- compiler.outputFileSystem = { ...fse, join };
533
+ flow.hook("vite:compiled", () => {
534
+ flow.server.reload();
575
535
  });
576
- flow.hook("server:devMiddleware", (m) => {
577
- devMidlewareHandler.set(toEventHandler(m));
536
+ flow.hook("server:devHandler", (h) => {
537
+ devMiddlewareHandler.set(h);
578
538
  });
579
539
  flow.server = createDevServer(nitro);
580
- flow.hook("build:resources", () => {
581
- flow.server.reload();
582
- });
583
540
  const waitUntilCompile = new Promise((resolve2) => nitro.hooks.hook("compiled", () => resolve2()));
584
541
  flow.hook("build:done", () => waitUntilCompile);
585
542
  }
586
543
  }
587
- async function resolveHandlers(flow) {
588
- const handlers = [...flow.options.serverHandlers];
589
- const devHandlers = [...flow.options.devServerHandlers];
590
- return {
591
- handlers,
592
- devHandlers
593
- };
594
- }
595
544
 
596
545
  const addModuleTranspiles = (opts = {}) => {
597
546
  const flow = useNuxt();
@@ -600,7 +549,7 @@ const addModuleTranspiles = (opts = {}) => {
600
549
  ...flow.options.modules,
601
550
  ...flow.options._modules
602
551
  ].map((m) => typeof m === "string" ? m : Array.isArray(m) ? m[0] : m.src).filter((m) => typeof m === "string").map((m) => m.split("node_modules/").pop());
603
- flow.options.build.transpile = flow.options.build.transpile.map((m) => typeof m === "string" ? m.split("node_modules/").pop() : m);
552
+ flow.options.build.transpile = flow.options.build.transpile.map((m) => typeof m === "string" ? m.split("node_modules/").pop() : m).filter((x) => !!x);
604
553
  function isTranspilePresent(mod) {
605
554
  return flow.options.build.transpile.some((t) => !(t instanceof Function) && (t instanceof RegExp ? t.test(mod) : new RegExp(t).test(mod)));
606
555
  }
@@ -613,7 +562,7 @@ const addModuleTranspiles = (opts = {}) => {
613
562
  function createFlow(options) {
614
563
  const hooks = createHooks();
615
564
  const flow = {
616
- _version: "3.0.0-rc.3",
565
+ _version: "3.0.0",
617
566
  version,
618
567
  options,
619
568
  hooks,
@@ -627,9 +576,10 @@ function createFlow(options) {
627
576
  return flow;
628
577
  }
629
578
  async function initFlow(flow) {
579
+ flow.hooks.addHooks(flow.options.hooks);
630
580
  nuxtCtx.set(flow);
631
581
  flow.hook("close", () => nuxtCtx.unset());
632
- await flow.callHook("modules:before", { nuxt: flow });
582
+ await flow.callHook("modules:before");
633
583
  const modulesToInstall = [
634
584
  ...flow.options.modules,
635
585
  ...flow.options._modules
@@ -640,17 +590,26 @@ async function initFlow(flow) {
640
590
  else
641
591
  await installModule(m, {});
642
592
  }
643
- await flow.callHook("modules:done", { nuxt: flow });
644
- await addModuleTranspiles();
593
+ await flow.callHook("modules:done");
594
+ flow.options.build.transpile = flow.options.build.transpile.map((t) => typeof t === "string" ? normalize(t) : t);
595
+ addModuleTranspiles();
645
596
  await initNitro(flow);
646
597
  await flow.callHook("ready", flow);
647
598
  }
648
599
  async function loadFlow(opts) {
600
+ const start1 = Date.now();
649
601
  const options = await loadFlowConfig(opts);
602
+ logger.info(`Config loading in ${Date.now() - start1}ms`);
650
603
  options.appDir = resolve(distDir, "app");
651
604
  options.alias["#app"] = resolve(distDir, "app/index");
652
605
  options._majorVersion = 3;
653
- options._modules.push(pagesModule, metaModule, autoImportsModule, viteModule);
606
+ options._modules.push(pagesModule, metaModule);
607
+ options._modules.push([importsModule, {
608
+ transform: {
609
+ include: options._layers.filter((i) => i.cwd && i.cwd.includes("node_modules")).map((i) => new RegExp(`(^|\\/)${escapeRE(i.cwd.split("node_modules/").pop())}(\\/|$)(?!node_modules\\/)`))
610
+ }
611
+ }]);
612
+ options.modulesDir.push(resolve(options.workspaceDir, "node_modules"));
654
613
  options.modulesDir.push(resolve(pkgDir, "node_modules"));
655
614
  const flow = createFlow(options);
656
615
  if (opts.ready !== false)
@@ -665,11 +624,17 @@ const serverPluginTemplate = {
665
624
  filename: "plugins/server.mjs",
666
625
  getContents(ctx) {
667
626
  const serverPlugins = ctx.app.plugins;
627
+ const exports = [];
628
+ const imports = [];
629
+ for (const plugin of serverPlugins) {
630
+ const path = relative(ctx.nuxt.options.rootDir, plugin.src);
631
+ const variable = `${genSafeVariableName(path).replace(/_(45|46|47)/g, "_")}_${hash(path)}`;
632
+ exports.push(variable);
633
+ imports.push(genImport(plugin.src, variable));
634
+ }
668
635
  return [
669
- templateUtils.importSources(serverPlugins.map((p) => p.src)),
670
- `export default ${genArrayFromRaw([
671
- ...serverPlugins.map((p) => templateUtils.importName(p.src))
672
- ])}`
636
+ ...imports,
637
+ `export default ${genArrayFromRaw(exports)}`
673
638
  ].join("\n");
674
639
  }
675
640
  };
@@ -698,43 +663,52 @@ export { }
698
663
  `;
699
664
  }
700
665
  };
701
- const adHocModules = ["auto-imports", "meta", "pages", "vite-client"];
666
+ const adHocModules = ["imports", "meta", "pages"];
702
667
  const schemaTemplate = {
703
668
  filename: "types/schema.d.ts",
704
- getContents: ({ nuxt }) => {
669
+ getContents: async ({ nuxt }) => {
705
670
  const moduleInfo = nuxt.options._installedModules.map((m) => ({
706
671
  ...m.meta || {},
707
672
  importName: m.entryPath || m.meta?.name
708
673
  })).filter((m) => m.configKey && m.name && !adHocModules.includes(m.name));
674
+ const relativeRoot = relative(resolve(nuxt.options.buildDir, "types"), nuxt.options.rootDir);
709
675
  return [
710
676
  "import { FlowModule } from '@monkeyplus/flow-schema'",
711
677
  "declare module '@monkeyplus/flow-schema' {",
712
678
  " interface FlowConfig {",
713
- ...moduleInfo.filter(Boolean).map((meta) => ` [${genString(meta.configKey)}]?: typeof ${genDynamicImport(meta.importName, { wrapper: false })}.default extends FlowModule<infer O> ? Partial<O> : Record<string, any>`),
679
+ ...moduleInfo.filter(Boolean).map(
680
+ (meta) => ` [${genString(meta.configKey)}]?: typeof ${genDynamicImport(meta.importName.startsWith(".") ? `./${join(relativeRoot, meta.importName)}` : meta.importName, { wrapper: false })}.default extends FlowModule<infer O> ? Partial<O> : Record<string, any>`
681
+ ),
714
682
  " }",
715
- generateTypes(resolveSchema(Object.fromEntries(Object.entries(nuxt.options.runtimeConfig).filter(([key]) => key !== "public"))), {
716
- interfaceName: "RuntimeConfig",
717
- addExport: false,
718
- addDefaults: false,
719
- allowExtraKeys: false,
720
- indentation: 2
721
- }),
722
- generateTypes(resolveSchema(nuxt.options.runtimeConfig.public), {
723
- interfaceName: "PublicRuntimeConfig",
724
- addExport: false,
725
- addDefaults: false,
726
- allowExtraKeys: false,
727
- indentation: 2
728
- }),
683
+ generateTypes(
684
+ await resolveSchema(Object.fromEntries(Object.entries(nuxt.options.runtimeConfig).filter(([key]) => key !== "public"))),
685
+ {
686
+ interfaceName: "RuntimeConfig",
687
+ addExport: false,
688
+ addDefaults: false,
689
+ allowExtraKeys: false,
690
+ indentation: 2
691
+ }
692
+ ),
693
+ generateTypes(
694
+ await resolveSchema(nuxt.options.runtimeConfig.public),
695
+ {
696
+ interfaceName: "PublicRuntimeConfig",
697
+ addExport: false,
698
+ addDefaults: false,
699
+ allowExtraKeys: false,
700
+ indentation: 2
701
+ }
702
+ ),
729
703
  "}"
730
704
  ].join("\n");
731
705
  }
732
706
  };
733
707
  const publicPathTemplate = {
734
708
  filename: "paths.mjs",
735
- getContents({ nuxt }) {
709
+ async getContents({ nuxt }) {
736
710
  return [
737
- "import { joinURL } from 'ufo'",
711
+ `import { joinURL } from '${await _resolveId("ufo")}'`,
738
712
  !nuxt.options.dev && "import { useRuntimeConfig } from '#internal/nitro'",
739
713
  nuxt.options.dev ? `const appConfig = ${JSON.stringify(nuxt.options.app)}` : "const appConfig = useRuntimeConfig().app",
740
714
  "export const baseURL = () => appConfig.baseURL",
@@ -747,6 +721,16 @@ const publicPathTemplate = {
747
721
  ].filter(Boolean).join("\n");
748
722
  }
749
723
  };
724
+ function _resolveId(id) {
725
+ return resolvePath(id, {
726
+ url: [
727
+ global.__NUXT_PREPATHS__,
728
+ import.meta.url,
729
+ process.cwd(),
730
+ global.__NUXT_PATHS__
731
+ ]
732
+ });
733
+ }
750
734
 
751
735
  const defaultTemplates = {
752
736
  __proto__: null,
@@ -756,6 +740,18 @@ const defaultTemplates = {
756
740
  publicPathTemplate: publicPathTemplate
757
741
  };
758
742
 
743
+ function uniqueBy(arr, key) {
744
+ const res = [];
745
+ const seen = /* @__PURE__ */ new Set();
746
+ for (const item of arr) {
747
+ if (seen.has(item[key]))
748
+ continue;
749
+ seen.add(item[key]);
750
+ res.push(item);
751
+ }
752
+ return res;
753
+ }
754
+
759
755
  function createApp(flow, options = {}) {
760
756
  return defu(options, {
761
757
  dir: flow.options.srcDir,
@@ -764,51 +760,95 @@ function createApp(flow, options = {}) {
764
760
  templates: []
765
761
  });
766
762
  }
767
- async function generateApp(flow, app) {
763
+ async function generateApp(flow, app, options) {
768
764
  await resolveApp(flow, app);
769
- app.templates = Object.values(defaultTemplates).concat(flow.options.build.templates);
765
+ app.templates = Object.values(defaultTemplates).concat(
766
+ flow.options.build.templates
767
+ );
770
768
  await flow.callHook("app:templates", app);
771
769
  app.templates = app.templates.map((tmpl) => normalizeTemplate(tmpl));
772
770
  const templateContext = { utils: templateUtils, nuxt: flow, app };
773
- await Promise.all(app.templates.map(async (template) => {
774
- const contents = await compileTemplate(template, templateContext);
775
- const fullPath = template.dst || resolve(flow.options.buildDir, template.filename);
776
- flow.vfs[fullPath] = contents;
777
- const aliasPath = `#build/${template.filename.replace(/\.\w+$/, "")}`;
778
- flow.vfs[aliasPath] = contents;
779
- if (process.platform === "win32")
780
- flow.vfs[fullPath.replace(/\//g, "\\")] = contents;
781
- if (template.write) {
782
- await promises.mkdir(dirname(fullPath), { recursive: true });
783
- await promises.writeFile(fullPath, contents, "utf8");
784
- }
785
- }));
771
+ await Promise.all(
772
+ app.templates.map(async (template) => {
773
+ const contents = await compileTemplate(template, templateContext);
774
+ const fullPath = template.dst || resolve(flow.options.buildDir, template.filename);
775
+ flow.vfs[fullPath] = contents;
776
+ const aliasPath = `#build/${template.filename.replace(/\.\w+$/, "")}`;
777
+ flow.vfs[aliasPath] = contents;
778
+ if (process.platform === "win32")
779
+ flow.vfs[fullPath.replace(/\//g, "\\")] = contents;
780
+ if (template.write) {
781
+ await promises.mkdir(dirname(fullPath), { recursive: true });
782
+ await promises.writeFile(fullPath, contents, "utf8");
783
+ }
784
+ })
785
+ );
786
786
  await flow.callHook("app:templatesGenerated", app);
787
787
  }
788
788
  async function resolveApp(flow, app) {
789
- app.plugins = [...flow.options.plugins.map(normalizePlugin)];
789
+ app.plugins = [
790
+ ...flow.options.plugins.map(normalizePlugin)
791
+ ];
790
792
  for (const config of flow.options._layers.map((layer) => layer.config)) {
791
793
  app.plugins.push(...[
792
794
  ...config.plugins || [],
793
- ...await resolveFilesFlow(config.srcDir, [
794
- "plugins/*.{ts,js,mjs,cjs,mts,cts}",
795
- "plugins/*/index.*{ts,js,mjs,cjs,mts,cts}"
796
- ])
795
+ ...config.srcDir ? await resolveFilesFlow(config.srcDir, [
796
+ `${config.dir?.plugins || "plugins"}/*.{ts,js,mjs,cjs,mts,cts}`,
797
+ `${config.dir?.plugins || "plugins"}/*/index.*{ts,js,mjs,cjs,mts,cts}`
798
+ ]) : []
797
799
  ].map((plugin) => normalizePlugin(plugin)));
798
800
  }
799
- app.plugins = uniqueBy(app.plugins, "src");
801
+ app.configs = [];
802
+ for (const config of flow.options._layers.map((layer) => layer.config)) {
803
+ const appConfigPath = await findPath(resolve(config.srcDir, "app.config"));
804
+ if (appConfigPath)
805
+ app.configs.push(appConfigPath);
806
+ }
800
807
  await flow.callHook("app:resolve", app);
808
+ app.plugins = uniqueBy(app.plugins, "src");
801
809
  }
802
- function uniqueBy(arr, key) {
803
- const res = [];
804
- const seen = /* @__PURE__ */ new Set();
805
- for (const item of arr) {
806
- if (seen.has(item[key]))
807
- continue;
808
- seen.add(item[key]);
809
- res.push(item);
810
- }
811
- return res;
810
+
811
+ const PREFIX = "virtual:nuxt:";
812
+ function virtual(vfs) {
813
+ const extensions = ["", ".ts", ".vue", ".mjs", ".cjs", ".js", ".json"];
814
+ const resolveWithExt = (id) => {
815
+ for (const ext of extensions) {
816
+ const rId = id + ext;
817
+ if (rId in vfs)
818
+ return rId;
819
+ }
820
+ return null;
821
+ };
822
+ return {
823
+ name: "virtual",
824
+ resolveId(id, importer) {
825
+ if (process.platform === "win32" && isAbsolute(id)) {
826
+ id = resolve(id);
827
+ }
828
+ const resolvedId = resolveWithExt(id);
829
+ if (resolvedId)
830
+ return PREFIX + resolvedId;
831
+ if (importer && !isAbsolute(id)) {
832
+ const importerNoPrefix = importer.startsWith(PREFIX) ? importer.slice(PREFIX.length) : importer;
833
+ const importedDir = dirname(importerNoPrefix);
834
+ const resolved = resolveWithExt(join(importedDir, id));
835
+ if (resolved)
836
+ return PREFIX + resolved;
837
+ }
838
+ return null;
839
+ },
840
+ load(id) {
841
+ if (!id.startsWith(PREFIX))
842
+ return null;
843
+ const idNoPrefix = id.slice(PREFIX.length);
844
+ if (idNoPrefix in vfs) {
845
+ return {
846
+ code: vfs[idNoPrefix],
847
+ map: null
848
+ };
849
+ }
850
+ }
851
+ };
812
852
  }
813
853
 
814
854
  async function warmupViteServer(server, entries) {
@@ -829,6 +869,11 @@ async function warmupViteServer(server, entries) {
829
869
  await Promise.all(entries.map((entry) => warmup(entry)));
830
870
  }
831
871
 
872
+ const wpfs = {
873
+ ...fse,
874
+ join
875
+ };
876
+
832
877
  function cacheDirPlugin(rootDir, name) {
833
878
  const optimizeCacheDir = resolve(rootDir, "node_modules/.cache/vite", name);
834
879
  return {
@@ -839,279 +884,47 @@ function cacheDirPlugin(rootDir, name) {
839
884
  };
840
885
  }
841
886
 
842
- const wpfs = {
843
- ...fse,
844
- join
845
- };
846
-
847
- function uniq(arr) {
848
- return Array.from(new Set(arr));
849
- }
850
- const IS_CSS_RE = /\.(?:css|scss|sass|postcss|less|stylus|styl)(\?[^.]+)?$/;
851
- function isCSS(file) {
852
- return IS_CSS_RE.test(file);
853
- }
854
- function hashId(id) {
855
- return `$id_${hash(id)}`;
856
- }
857
- function hash(input, length = 8) {
858
- return createHash("sha256").update(input).digest("hex").slice(0, length);
859
- }
860
- function readDirRecursively(dir) {
861
- return readdirSync(dir).reduce((files, file) => {
862
- const name = join(dir, file);
863
- const isDirectory2 = statSync(name).isDirectory();
864
- return isDirectory2 ? [...files, ...readDirRecursively(name)] : [...files, name];
865
- }, []);
866
- }
867
- async function isDirectory(path) {
868
- try {
869
- return (await promises.stat(path)).isDirectory();
870
- } catch (_err) {
871
- return false;
872
- }
873
- }
874
-
875
- function isExternal(opts, id) {
876
- const ssrConfig = opts.viteServer.config.ssr;
877
- const externalOpts = {
878
- inline: [
879
- /virtual:/,
880
- /\.ts$/,
881
- ...ExternalsDefaults.inline,
882
- ...ssrConfig.noExternal
883
- ],
884
- external: [
885
- /node_modules/
886
- ],
887
- resolve: {
888
- type: "module",
889
- extensions: [".ts", ".js", ".json", ".vue", ".mjs", ".jsx", ".tsx", ".wasm"]
890
- }
891
- };
892
- return isExternal$1(id, opts.viteServer.config.root, externalOpts);
893
- }
894
- async function transformRequest(opts, id) {
895
- if (id && id.startsWith("/@id/__x00__"))
896
- id = `\0${id.slice("/@id/__x00__".length)}`;
897
- if (id && id.startsWith("/@id/"))
898
- id = id.slice("/@id/".length);
899
- if (id && id.startsWith("/@fs/")) {
900
- id = id.slice("/@fs".length);
901
- if (id.match(/^\/\w:/))
902
- id = id.slice(1);
903
- } else if (!id.includes("entry") && id.startsWith("/")) {
904
- const resolvedPath = resolve(opts.viteServer.config.root, `.${id}`);
905
- if (existsSync(resolvedPath))
906
- id = resolvedPath;
907
- }
908
- const withoutVersionQuery = id.replace(/\?v=\w+$/, "");
909
- if (await isExternal(opts, withoutVersionQuery)) {
910
- const path = builtinModules.includes(withoutVersionQuery.split("node:").pop()) ? withoutVersionQuery : pathToFileURL(withoutVersionQuery).href;
911
- return {
912
- code: `(global, module, _, exports, importMeta, ssrImport, ssrDynamicImport, ssrExportAll) =>
913
- ${genDynamicImport(path, { wrapper: false })}
914
- .then(r => {
915
- if (r.default && r.default.__esModule)
916
- r = r.default
917
- exports.default = r.default
918
- ssrExportAll(r)
919
- })
920
- .catch(e => {
921
- console.error(e)
922
- throw new Error(${JSON.stringify(`[vite dev] Error loading external "${id}".`)})
923
- })`,
924
- deps: [],
925
- dynamicDeps: []
926
- };
927
- }
928
- const res = await opts.viteServer.transformRequest(id, { ssr: true }).catch((err) => {
929
- console.warn(`[SSR] Error transforming ${id}:`, err);
930
- }) || { code: "", map: {}, deps: [], dynamicDeps: [] };
931
- const code = `async function (global, module, exports, __vite_ssr_exports__, __vite_ssr_import_meta__, __vite_ssr_import__, __vite_ssr_dynamic_import__, __vite_ssr_exportAll__) {
932
- ${res.code || "/* empty */"};
933
- }`;
934
- return { code, deps: res.deps || [], dynamicDeps: res.dynamicDeps || [] };
935
- }
936
- async function transformRequestRecursive(opts, id, parent = "<entry>", chunks = {}) {
937
- if (chunks[id]) {
938
- chunks[id].parents.push(parent);
939
- return;
940
- }
941
- const res = await transformRequest(opts, id);
942
- const deps = uniq([...res.deps, ...res.dynamicDeps]);
943
- chunks[id] = {
944
- id,
945
- code: res.code,
946
- deps,
947
- parents: [parent]
948
- };
949
- for (const dep of deps)
950
- await transformRequestRecursive(opts, dep, id, chunks);
951
- return Object.values(chunks);
952
- }
953
- async function bundleRequest(opts, entryURL) {
954
- const chunks = await transformRequestRecursive(opts, entryURL);
955
- const listIds = (ids) => ids.map((id) => `// - ${id} (${hashId(id)})`).join("\n");
956
- const chunksCode = chunks.map((chunk) => `
957
- // --------------------
958
- // Request: ${chunk.id}
959
- // Parents:
960
- ${listIds(chunk.parents)}
961
- // Dependencies:
962
- ${listIds(chunk.deps)}
963
- // --------------------
964
- const ${hashId(chunk.id)} = ${chunk.code}
965
- `).join("\n");
966
- const manifestCode = `const __modules__ = ${genObjectFromRawEntries(chunks.map((chunk) => [chunk.id, hashId(chunk.id)]))}`;
967
- const ssrModuleLoader = `
968
- const __pendingModules__ = new Map()
969
- const __pendingImports__ = new Map()
970
- const __ssrContext__ = { global: globalThis }
971
-
972
- function __ssrLoadModule__(url, urlStack = []) {
973
- const pendingModule = __pendingModules__.get(url)
974
- if (pendingModule) { return pendingModule }
975
- const modulePromise = __instantiateModule__(url, urlStack)
976
- __pendingModules__.set(url, modulePromise)
977
- modulePromise.catch(() => { __pendingModules__.delete(url) })
978
- .finally(() => { __pendingModules__.delete(url) })
979
- return modulePromise
980
- }
981
-
982
- async function __instantiateModule__(url, urlStack) {
983
- const mod = __modules__[url]
984
- if (mod.stubModule) { return mod.stubModule }
985
- const stubModule = { [Symbol.toStringTag]: 'Module' }
986
- Object.defineProperty(stubModule, '__esModule', { value: true })
987
- mod.stubModule = stubModule
988
- // https://vitejs.dev/guide/api-hmr.html
989
- const importMeta = { url, hot: { accept() {}, prune() {}, dispose() {}, invalidate() {}, decline() {}, on() {} } }
990
- urlStack = urlStack.concat(url)
991
- const isCircular = url => urlStack.includes(url)
992
- const pendingDeps = []
993
- const ssrImport = async (dep) => {
994
- // TODO: Handle externals if dep[0] !== '.' | '/'
995
- if (!isCircular(dep) && !__pendingImports__.get(dep)?.some(isCircular)) {
996
- pendingDeps.push(dep)
997
- if (pendingDeps.length === 1) {
998
- __pendingImports__.set(url, pendingDeps)
999
- }
1000
- await __ssrLoadModule__(dep, urlStack)
1001
- if (pendingDeps.length === 1) {
1002
- __pendingImports__.delete(url)
1003
- } else {
1004
- pendingDeps.splice(pendingDeps.indexOf(dep), 1)
1005
- }
1006
- }
1007
- return __modules__[dep].stubModule
1008
- }
1009
- function ssrDynamicImport (dep) {
1010
- // TODO: Handle dynamic import starting with . relative to url
1011
- return ssrImport(dep)
1012
- }
1013
-
1014
- function ssrExportAll(sourceModule) {
1015
- for (const key in sourceModule) {
1016
- if (key !== 'default') {
1017
- try {
1018
- Object.defineProperty(stubModule, key, {
1019
- enumerable: true,
1020
- configurable: true,
1021
- get() { return sourceModule[key] }
1022
- })
1023
- } catch (_err) { }
1024
- }
1025
- }
1026
- }
1027
-
1028
- const cjsModule = {
1029
- get exports () {
1030
- return stubModule.default
1031
- },
1032
- set exports (v) {
1033
- stubModule.default = v
1034
- },
1035
- }
1036
-
1037
- await mod(
1038
- __ssrContext__.global,
1039
- cjsModule,
1040
- stubModule.default,
1041
- stubModule,
1042
- importMeta,
1043
- ssrImport,
1044
- ssrDynamicImport,
1045
- ssrExportAll
1046
- )
1047
-
1048
- return stubModule
1049
- }
1050
- `;
1051
- const code = [
1052
- chunksCode,
1053
- manifestCode,
1054
- ssrModuleLoader,
1055
- `export default await __ssrLoadModule__(${JSON.stringify(entryURL)})`
1056
- ].join("\n\n");
1057
- return {
1058
- code,
1059
- ids: chunks.map((i) => i.id)
1060
- };
1061
- }
1062
-
1063
- async function writeManifest(ctx, extraEntries = []) {
1064
- const clientDist = resolve(ctx.flow.options.buildDir, "dist/client");
1065
- const serverDist = resolve(ctx.flow.options.buildDir, "dist/server");
1066
- const entries = [
1067
- "@vite/client",
1068
- "entry.mjs",
1069
- ...extraEntries
1070
- ];
1071
- const devClientManifest = {
1072
- publicPath: joinURL(ctx.flow.options.app.baseURL, ctx.flow.options.app.buildAssetsDir),
1073
- all: entries,
1074
- initial: entries,
1075
- async: [],
1076
- modules: {}
1077
- };
1078
- const clientManifest = ctx.flow.options.dev ? devClientManifest : await fse.readJSON(resolve(clientDist, "manifest.json"));
1079
- await fse.mkdirp(serverDist);
1080
- await fse.writeFile(resolve(serverDist, "client.manifest.json"), JSON.stringify(clientManifest, null, 2), "utf8");
1081
- await fse.writeFile(resolve(serverDist, "client.manifest.mjs"), `export default ${JSON.stringify(clientManifest, null, 2)}`, "utf8");
1082
- }
1083
-
1084
- const buildServer = async (ctx) => {
887
+ async function buildServer(ctx) {
1085
888
  const serverConfig = vite.mergeConfig(ctx.config, {
1086
- configFile: false,
889
+ base: ctx.nuxt.options.dev ? joinURL(ctx.nuxt.options.app.baseURL.replace(/^\.\//, "/") || "/", ctx.nuxt.options.app.buildAssetsDir) : void 0,
1087
890
  define: {
1088
891
  "process.server": true,
892
+ "process.client": false,
1089
893
  "typeof window": '"undefined"',
1090
894
  "typeof document": '"undefined"',
1091
895
  "typeof navigator": '"undefined"',
1092
896
  "typeof location": '"undefined"',
1093
897
  "typeof XMLHttpRequest": '"undefined"'
1094
898
  },
899
+ resolve: {
900
+ alias: {
901
+ "#build/plugins": resolve(ctx.nuxt.options.buildDir, "plugins/server")
902
+ }
903
+ },
1095
904
  ssr: {
905
+ external: ["#internal/nitro", "#internal/nitro/utils"],
1096
906
  noExternal: [
1097
- ...ctx.flow.options.build.transpile,
907
+ ...ctx.nuxt.options.build.transpile,
1098
908
  /\/esm\/.*\.js$/,
1099
909
  /\.(es|esm|esm-browser|esm-bundler).js$/,
1100
910
  "/__vue-jsx",
1101
911
  "#app",
1102
912
  /(nuxt|nuxt3)\/(dist|src|app)/,
913
+ /flow\/(dist|src|app)/,
914
+ /flow\/modules\/(content|icons|images|netlify|netlify-cms|seo|sitemap|vue)/,
1103
915
  /@monkeyplus\/flow\/(dist|src|app)/,
1104
916
  /@nuxt\/nitro\/(dist|src)/
1105
917
  ]
1106
918
  },
1107
919
  build: {
1108
- outDir: resolve(ctx.flow.options.buildDir, "dist/server"),
1109
- manifest: true,
920
+ outDir: resolve(ctx.nuxt.options.buildDir, "dist/server"),
921
+ ssr: true,
1110
922
  rollupOptions: {
1111
923
  external: ["#internal/nitro"],
1112
924
  output: {
1113
925
  entryFileNames: "server.mjs",
1114
926
  preferConst: true,
927
+ inlineDynamicImports: !ctx.nuxt.options.experimental.viteServerDynamicImports,
1115
928
  format: "module"
1116
929
  },
1117
930
  onwarn(warning, rollupWarn) {
@@ -1122,38 +935,27 @@ const buildServer = async (ctx) => {
1122
935
  },
1123
936
  server: {
1124
937
  preTransformRequests: false,
1125
- cors: true
938
+ hmr: false
1126
939
  },
1127
940
  plugins: [
1128
- cacheDirPlugin(ctx.flow.options.rootDir, "server")
941
+ cacheDirPlugin(ctx.nuxt.options.rootDir, "server"),
942
+ replace({
943
+ ...Object.fromEntries([";", "(", "{", "}", " ", " ", "\n"].map((d) => [`${d}global.`, `${d}globalThis.`])),
944
+ preventAssignment: true
945
+ })
1129
946
  ]
1130
947
  });
1131
- await ctx.flow.callHook("vite:extendConfig", serverConfig, { isClient: false, isServer: true });
1132
- ctx.flow.hook("nitro:build:before", async () => {
1133
- if (ctx.flow.options.dev)
1134
- return;
1135
- const clientDist = resolve(ctx.flow.options.buildDir, "dist/client");
1136
- const publicDir = join(ctx.flow.options.srcDir, ctx.flow.options.dir.public);
1137
- let publicFiles = [];
1138
- if (await isDirectory(publicDir)) {
1139
- publicFiles = readDirRecursively(publicDir).map((r) => r.replace(publicDir, ""));
1140
- for (const file of publicFiles) {
1141
- try {
1142
- fse.rmSync(join(clientDist, file));
1143
- } catch {
1144
- }
948
+ if (ctx.nuxt.options.typescript.typeCheck === true || ctx.nuxt.options.typescript.typeCheck === "build" && !ctx.nuxt.options.dev) {
949
+ const checker = await import('vite-plugin-checker').then((r) => r.default);
950
+ serverConfig.plugins.push(checker({
951
+ vueTsc: {
952
+ tsconfigPath: await resolveTSConfig(ctx.nuxt.options.rootDir)
1145
953
  }
1146
- }
1147
- if (await isDirectory(clientDist)) {
1148
- const nestedAssetsPath = withoutTrailingSlash(join(clientDist, ctx.flow.options.app.buildAssetsDir));
1149
- if (await isDirectory(nestedAssetsPath)) {
1150
- await fse.copy(nestedAssetsPath, clientDist, { recursive: true });
1151
- await fse.remove(nestedAssetsPath);
1152
- }
1153
- }
1154
- });
1155
- const onBuild = () => ctx.flow.callHook("build:resources", wpfs);
1156
- if (!ctx.flow.options.dev) {
954
+ }));
955
+ }
956
+ await ctx.nuxt.callHook("vite:extendConfig", serverConfig, { isClient: false, isServer: true });
957
+ const onBuild = () => ctx.nuxt.callHook("build:resources", wpfs);
958
+ if (!ctx.nuxt.options.dev) {
1157
959
  const start = Date.now();
1158
960
  logger.info("Building server...");
1159
961
  await vite.build(serverConfig);
@@ -1163,184 +965,82 @@ const buildServer = async (ctx) => {
1163
965
  }
1164
966
  const viteServer = await vite.createServer(serverConfig);
1165
967
  ctx.ssrServer = viteServer;
1166
- await ctx.flow.callHook("vite:serverCreated", viteServer, { isClient: false, isServer: true });
1167
- ctx.flow.hook("close", () => viteServer.close());
968
+ await ctx.nuxt.callHook("vite:serverCreated", viteServer, { isClient: false, isServer: true });
969
+ ctx.nuxt.hook("close", () => viteServer.close());
1168
970
  await viteServer.pluginContainer.buildStart({});
1169
- const _doBuild = async () => {
1170
- const start = Date.now();
1171
- const { code, ids } = await bundleRequest({ viteServer }, resolve(ctx.flow.options.appDir, "entry"));
1172
- await fse.ensureFile(resolve(ctx.flow.options.buildDir, "dist/server/server.mjs"));
1173
- await fse.writeFile(resolve(ctx.flow.options.buildDir, "dist/server/server.mjs"), code, "utf-8");
1174
- await writeManifest(ctx, ids.filter(isCSS).map((i) => i.slice(1)));
1175
- const time = Date.now() - start;
1176
- logger.success(`Vite server built in ${time}ms`);
1177
- await onBuild();
1178
- ctx.flow.callHook("bundler:change", {});
1179
- };
1180
- const doBuild = debounce(_doBuild, 50);
1181
- await _doBuild();
1182
- viteServer.watcher.on("all", (_event, file) => {
1183
- file = normalize(file);
1184
- if (file.indexOf(ctx.flow.options.buildDir) === 0)
1185
- return;
1186
- doBuild();
1187
- });
1188
- ctx.flow.hook("app:templatesGenerated", () => doBuild());
1189
- };
1190
-
1191
- const PREFIX = "virtual:";
1192
- function virtual(vfs) {
1193
- const extensions = ["", ".ts", ".vue", ".mjs", ".cjs", ".js", ".json"];
1194
- const resolveWithExt = (id) => {
1195
- for (const ext of extensions) {
1196
- const rId = id + ext;
1197
- if (rId in vfs)
1198
- return rId;
1199
- }
1200
- return null;
1201
- };
1202
- return {
1203
- name: "virtual",
1204
- resolveId(id, importer) {
1205
- if (process.platform === "win32" && isAbsolute(id)) {
1206
- id = resolve(id);
1207
- }
1208
- const resolvedId = resolveWithExt(id);
1209
- if (resolvedId)
1210
- return PREFIX + resolvedId;
1211
- if (importer && !isAbsolute(id)) {
1212
- const importerNoPrefix = importer.startsWith(PREFIX) ? importer.slice(PREFIX.length) : importer;
1213
- const importedDir = dirname(importerNoPrefix);
1214
- const resolved = resolveWithExt(join(importedDir, id));
1215
- if (resolved)
1216
- return PREFIX + resolved;
1217
- }
1218
- return null;
1219
- },
1220
- load(id) {
1221
- if (!id.startsWith(PREFIX))
1222
- return null;
1223
- const idNoPrefix = id.slice(PREFIX.length);
1224
- return {
1225
- code: vfs[idNoPrefix],
1226
- map: null
1227
- };
1228
- }
1229
- };
971
+ await import('./chunks/dev-bundler.mjs').then((r) => r.initViteDevBundler(ctx, onBuild));
1230
972
  }
1231
973
 
1232
- const VITE_ASSET_RE = /^export default ["'](__VITE_ASSET.*)["']$/;
1233
- const DynamicBasePlugin = createUnplugin((options = {}) => {
1234
- return {
1235
- name: "nuxt:dynamic-base-path",
1236
- resolveId(id) {
1237
- if (id.startsWith("/__NUXT_BASE__"))
1238
- return id.replace("/__NUXT_BASE__", "");
1239
- if (id === "#internal/nitro")
1240
- return "#internal/nitro";
1241
- return null;
1242
- },
1243
- enforce: "post",
1244
- transform(code, id) {
1245
- const s = new MagicString(code);
1246
- if (options.globalPublicPath && id.includes("paths.mjs") && code.includes("const appConfig = "))
1247
- s.append(`${options.globalPublicPath} = buildAssetsURL();
1248
- `);
1249
- const assetId = code.match(VITE_ASSET_RE);
1250
- if (assetId) {
1251
- s.overwrite(0, code.length, [
1252
- "import { buildAssetsURL } from '#build/paths.mjs';",
1253
- `export default buildAssetsURL("${assetId[1]}".replace("/__NUXT_BASE__", ""));`
1254
- ].join("\n"));
1255
- }
1256
- if (!id.includes("paths.mjs") && code.includes("NUXT_BASE") && !code.includes("import { publicAssetsURL as __publicAssetsURL }"))
1257
- s.prepend("import { publicAssetsURL as __publicAssetsURL } from '#build/paths.mjs';\n");
1258
- if (id === "vite/preload-helper") {
1259
- s.prepend("import { buildAssetsDir } from '#build/paths.mjs';\n");
1260
- s.replace(/const base = ['"]\/__NUXT_BASE__\/['"]/, "const base = buildAssetsDir()");
1261
- }
1262
- s.replace(/from *['"]\/__NUXT_BASE__(\/[^'"]*)['"]/g, 'from "$1"');
1263
- const delimiterRE = /(?<!(const base = |from *))(`([^`]*)\/__NUXT_BASE__\/([^`]*)`|'([^']*)\/__NUXT_BASE__\/([^']*)'|"([^"]*)\/__NUXT_BASE__\/([^"]*)")/g;
1264
- s.replace(delimiterRE, (r) => `\`${r.replace(/\/__NUXT_BASE__\//g, "${__publicAssetsURL()}").slice(1, -1)}\``);
1265
- if (s.hasChanged()) {
1266
- return {
1267
- code: s.toString(),
1268
- map: options.sourcemap && s.generateMap({ source: id, includeContent: true })
1269
- };
1270
- }
1271
- }
1272
- };
1273
- });
1274
-
1275
- async function bundleVite(flow) {
1276
- const hmrPortDefault = 24678;
1277
- const hmrPort = await getPort({
1278
- port: hmrPortDefault,
1279
- ports: Array.from({ length: 20 }, (_, i) => hmrPortDefault + 1 + i)
1280
- });
974
+ async function bundle$1(nuxt) {
975
+ const entry = resolve(nuxt.options.appDir, nuxt.options.experimental.asyncEntry ? "entry.async" : "entry");
1281
976
  const ctx = {
1282
- nuxt: flow,
1283
- flow,
1284
- config: vite.mergeConfig({
1285
- mode: flow.options.dev ? "development" : void 0,
1286
- resolve: {
1287
- alias: {
1288
- ...flow.options.alias,
1289
- "#app": flow.options.appDir,
1290
- "#build/plugins": resolve(flow.options.buildDir, "plugins/server"),
1291
- "#build": flow.options.buildDir,
1292
- "/entry.mjs": resolve(flow.options.appDir, "entry")
1293
- }
1294
- },
1295
- optimizeDeps: {
1296
- entries: [
1297
- resolve(flow.options.appDir, "entry.ts")
1298
- ],
1299
- include: []
1300
- },
1301
- build: {
1302
- rollupOptions: {
1303
- output: { sanitizeFileName: sanitizeFilePath },
1304
- input: resolve(flow.options.appDir, "entry")
1305
- }
1306
- },
1307
- plugins: [
1308
- replace({
1309
- ...Object.fromEntries([";", "(", "{", "}", " ", " ", "\n"].map((d) => [`${d}global.`, `${d}globalThis.`])),
1310
- preventAssignment: true
1311
- }),
1312
- virtual(flow.vfs),
1313
- DynamicBasePlugin.vite({ sourcemap: flow.options.sourcemap })
1314
- ],
1315
- server: {
1316
- watch: {
1317
- ignored: isIgnoredFlow
977
+ nuxt,
978
+ entry,
979
+ config: vite.mergeConfig(
980
+ {
981
+ configFile: false,
982
+ resolve: {
983
+ alias: {
984
+ ...nuxt.options.alias,
985
+ "#app": nuxt.options.appDir,
986
+ "#build/plugins": "",
987
+ "#build": nuxt.options.buildDir,
988
+ "web-streams-polyfill/ponyfill/es2018": "unenv/runtime/mock/empty",
989
+ "abort-controller": "unenv/runtime/mock/empty"
990
+ }
991
+ },
992
+ optimizeDeps: {
993
+ entries: [entry],
994
+ include: []
1318
995
  },
1319
- hmr: {
1320
- protocol: "ws",
1321
- clientPort: hmrPort,
1322
- port: hmrPort
996
+ build: {
997
+ rollupOptions: {
998
+ output: { sanitizeFileName: sanitizeFilePath },
999
+ input: resolve(nuxt.options.appDir, "entry")
1000
+ },
1001
+ watch: {
1002
+ exclude: nuxt.options.ignore
1003
+ }
1004
+ },
1005
+ plugins: [
1006
+ replace({
1007
+ ...Object.fromEntries([";", "(", "{", "}", " ", " ", "\n"].map((d) => [`${d}global.`, `${d}globalThis.`])),
1008
+ preventAssignment: true
1009
+ }),
1010
+ virtual(nuxt.vfs)
1011
+ ],
1012
+ vue: {
1013
+ reactivityTransform: nuxt.options.experimental.reactivityTransform
1323
1014
  },
1324
- fs: {
1325
- allow: [
1326
- flow.options.appDir
1327
- ]
1015
+ server: {
1016
+ watch: { ignored: isIgnoredFlow },
1017
+ fs: {
1018
+ allow: [
1019
+ nuxt.options.appDir
1020
+ ]
1021
+ },
1022
+ hmr: false
1328
1023
  }
1329
- }
1330
- }, flow.options.vite)
1024
+ },
1025
+ nuxt.options.vite
1026
+ )
1331
1027
  };
1332
- if (flow.options.dev)
1333
- ctx.config.mode = process.env.NODE_ENV || "development";
1334
- await flow.callHook("vite:extend", ctx);
1335
- flow.hook("vite:serverCreated", (server) => {
1028
+ if (!nuxt.options.dev) {
1029
+ ctx.config.server.watch = void 0;
1030
+ ctx.config.build.watch = void 0;
1031
+ }
1032
+ await nuxt.callHook("vite:extend", ctx);
1033
+ nuxt.hook("vite:serverCreated", (server, env) => {
1336
1034
  ctx.nuxt.hook("app:templatesGenerated", () => {
1337
1035
  for (const [id, mod] of server.moduleGraph.idToModuleMap) {
1338
- if (id.startsWith("\0virtual:"))
1036
+ if (id.includes("pages."))
1037
+ server.moduleGraph.invalidateModule(mod);
1038
+ if (id.startsWith("\virtual:"))
1339
1039
  server.moduleGraph.invalidateModule(mod);
1340
1040
  }
1341
1041
  });
1342
1042
  const start = Date.now();
1343
- warmupViteServer(server, ["/entry.mjs"]).then(() => logger.info(`Vite server warmed up in ${Date.now() - start}ms`)).catch(logger.error);
1043
+ warmupViteServer(server, [join("/@fs/", ctx.entry)]).then(() => logger.info(`Vite ${env.isClient ? "client" : "server"} warmed up in ${Date.now() - start}ms`)).catch(logger.error);
1344
1044
  });
1345
1045
  await buildServer(ctx);
1346
1046
  }
@@ -1355,12 +1055,16 @@ async function build(flow) {
1355
1055
  if (event !== "change" && /app|error|plugins/i.test(path))
1356
1056
  await generateApp$1();
1357
1057
  });
1358
- flow.hook("builder:generateApp", generateApp$1);
1058
+ flow.hook("builder:generateApp", (options) => {
1059
+ if (options)
1060
+ return generateApp(flow, app);
1061
+ return generateApp$1();
1062
+ });
1359
1063
  }
1360
- await flow.callHook("build:before", { flow }, flow.options.build);
1064
+ await flow.callHook("build:before");
1361
1065
  if (!flow.options._prepare) {
1362
1066
  await bundle(flow);
1363
- await flow.callHook("build:done", { flow });
1067
+ await flow.callHook("build:done");
1364
1068
  }
1365
1069
  if (!flow.options.dev)
1366
1070
  await flow.callHook("close", flow);
@@ -1376,14 +1080,13 @@ function watch(flow) {
1376
1080
  "node_modules"
1377
1081
  ]
1378
1082
  });
1379
- const watchHook = debounce((event, path) => flow.callHook("builder:watch", event, normalize(path)));
1380
- watcher.on("all", watchHook);
1083
+ watcher.on("all", (event, path) => flow.callHook("builder:watch", event, normalize(path)));
1381
1084
  flow.hook("close", () => watcher.close());
1382
1085
  return watcher;
1383
1086
  }
1384
1087
  async function bundle(nuxt) {
1385
1088
  try {
1386
- return bundleVite(nuxt);
1089
+ return bundle$1(nuxt);
1387
1090
  } catch (error) {
1388
1091
  await nuxt.callHook("build:error", error);
1389
1092
  throw error;