@monkeyplus/flow 5.0.0-rc.9 → 5.0.0-rc.91

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