@monkeyplus/flow 5.0.0-rc.86 → 5.0.0-rc.87

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