@monkeyplus/flow 5.0.0-rc.38 → 5.0.0-rc.4

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.
@@ -1,6 +1,6 @@
1
1
  import type { RadixRouter } from 'radix3';
2
2
  import type { Hookable } from 'hookable';
3
- import type { FlowAppUtils, FlowPage, RuntimeConfig } from '@monkeyplus/flow-schema';
3
+ import type { FlowPage, RuntimeConfig } from '@monkeyplus/flow-schema';
4
4
  declare type HookResult = Promise<void> | void;
5
5
  export interface FlowAppHooks {
6
6
  'flow:pages': (page: FlowPage[]) => HookResult;
@@ -27,7 +27,7 @@ export interface FlowApp {
27
27
  callHook: FlowApp['hooks']['callHook'];
28
28
  eta: any;
29
29
  app: {
30
- utils: FlowAppUtils;
30
+ utils: Record<string, any>;
31
31
  plugins: Record<string, any>;
32
32
  globals: Record<string, any>;
33
33
  };
@@ -1,6 +1,6 @@
1
- import "node-fetch-native/polyfill";
2
1
  import { defineEventHandler } from "h3";
3
- import { defineCachedFunction, useRuntimeConfig } from "#internal/nitro";
2
+ import "node-fetch-native/polyfill";
3
+ import { useRuntimeConfig } from "#internal/nitro";
4
4
  const getServerApp = cachedImport(() => import("#server"));
5
5
  const getFlowRenderer = cachedResult(async () => {
6
6
  const createFlowApp = await getServerApp();
@@ -12,7 +12,6 @@ export default defineEventHandler(async ({ context }) => {
12
12
  const flow = await getFlowRenderer();
13
13
  context.flow = flow;
14
14
  context.render = flow.render;
15
- context.defineCachedFunction = defineCachedFunction;
16
15
  });
17
16
  function _interopDefault(e) {
18
17
  return e && typeof e === "object" && "default" in e ? e.default : e;
@@ -16,32 +16,27 @@ export default eventHandler(async (event) => {
16
16
  if (view.bundle)
17
17
  await flow.callHook("page:chunks", view.bundle, chunks);
18
18
  const templateContext = {};
19
- const dynamic = params?._;
20
- const contextPage = {
21
- chunks,
22
- locale
23
- };
24
- const contextInject = {};
25
- const utils = Object.assign({ getLocale: () => locale, injectContext: (key, value) => contextInject[key] = value, defineCachedFunction: event.context.defineCachedFunction }, flow.app.utils);
19
+ const dynamyc = params?._;
20
+ const contextPage = {};
21
+ const utils = Object.assign({ getLocale: () => locale }, flow.app.utils);
26
22
  templateContext.url = url;
27
23
  templateContext.locale = locale;
28
24
  templateContext.view = view;
29
- if (dynamic && page.dynamic) {
25
+ if (dynamyc && page.dynamic) {
30
26
  const pages = await page.dynamic.method({ locale, utils });
31
- const dynamicPage = pages.find((_page) => _page.url === dynamic);
27
+ const dynamicPage = pages.find((_page) => _page.url === dynamyc);
32
28
  if (!dynamicPage)
33
29
  return;
34
30
  if (page.dynamic.assign)
35
31
  templateContext[page.dynamic.assign] = dynamicPage.context;
36
- contextPage.dynamic = dynamicPage;
32
+ contextPage.dynamyc = dynamicPage;
37
33
  }
38
34
  templateContext.seo = {};
39
35
  templateContext.context = {};
40
- const sharedContext = await utils.getSharedContext(utils);
41
- templateContext.sharedContext = sharedContext || {};
36
+ templateContext.sharedContext = {};
42
37
  templateContext.utils = utils;
43
- templateContext.seo = await page.seo?.({ ...contextPage, utils, sharedContext }) || {};
44
- templateContext.context = await page.context?.({ ...contextPage, utils, sharedContext }) || {};
38
+ templateContext.seo = await page.seo?.({ ...contextPage, utils }) || {};
39
+ templateContext.context = await page.context?.({ ...contextPage, utils }) || {};
45
40
  templateContext.getHeadScripts = () => {
46
41
  return scripts.head.join("\n");
47
42
  };
@@ -51,20 +46,11 @@ export default eventHandler(async (event) => {
51
46
  templateContext.getBodyChunks = () => {
52
47
  return chunks.body.join("\n");
53
48
  };
54
- templateContext.getInjectContext = () => {
55
- return `<script id="__FLOW_DATA__" type="application/json">${JSON.stringify(contextInject)}<\/script>`;
56
- };
57
49
  const query = useQuery(event);
58
50
  if (query?.context)
59
51
  return { ...templateContext, utils: Object.keys(utils) };
60
- let html;
61
- if (view.render)
62
- html = await view.render(templateContext, event);
63
- else
64
- html = await flow.render(view, templateContext);
65
- event.res.setHeader("Content-Type", view.contentType || "text/html;charset=UTF-8");
66
- if (view.postRender)
67
- html = await view.postRender(html, event);
52
+ const html = await flow.render(view, templateContext);
53
+ event.res.setHeader("Content-Type", "text/html;charset=UTF-8");
68
54
  if (flow.generate) {
69
55
  await flow.callHook("page:generate", generate);
70
56
  globalThis.generate = generate;
package/dist/index.mjs CHANGED
@@ -1,12 +1,10 @@
1
1
  import { createHooks } from 'hookable';
2
2
  import { dirname, resolve, normalize, join, isAbsolute, relative, extname } from 'pathe';
3
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';
4
+ import { fileURLToPath, pathToFileURL } from 'node:url';
5
5
  import { defineUnimportPreset, createUnimport, toImports, scanDirExports } from 'unimport';
6
- import { pathToFileURL } from 'node:url';
7
6
  import { createUnplugin } from 'unplugin';
8
7
  import { parseURL, parseQuery, joinURL, withoutTrailingSlash } from 'ufo';
9
- import fs from 'fs';
10
8
  import escapeRE from 'escape-string-regexp';
11
9
  import { camelCase, pascalCase } from 'scule';
12
10
  import { genImport, genDynamicImport, genArrayFromRaw, genString, genObjectFromRawEntries } from 'knitwork';
@@ -29,7 +27,7 @@ import { isExternal as isExternal$1, ExternalsDefaults } from 'externality';
29
27
  import { createHash } from 'node:crypto';
30
28
  import MagicString from 'magic-string';
31
29
 
32
- const version = "5.0.0-rc.38";
30
+ const version = "5.0.0-rc.4";
33
31
 
34
32
  let _distDir = dirname(fileURLToPath(import.meta.url));
35
33
  if (_distDir.endsWith("chunks"))
@@ -94,8 +92,7 @@ const commonPresets = [
94
92
  from: "#_pages",
95
93
  imports: [
96
94
  "definePage",
97
- "defineDynamicPage",
98
- "defineSharedContext"
95
+ "defineDinamycPage"
99
96
  ]
100
97
  })
101
98
  ];
@@ -231,20 +228,14 @@ ${ctx.generateTypeDecarations({ resolvePath: r })}`
231
228
  });
232
229
  }
233
230
 
234
- async function resolveFiles(dir) {
231
+ async function resolvePagesRoutes() {
235
232
  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(",")}}`);
233
+ const pagesDirs = [...new Set(nuxt.options._layers.map((layer) => resolve(layer.config.srcDir, layer.config.dir?.pages || "pages")))];
234
+ const allRoutes = (await Promise.all(pagesDirs.map(async (dir) => {
235
+ const files = await resolveFilesFlow(dir, `**/*{${nuxt.options.extensions.join(",")}}`);
239
236
  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("_");
237
+ return files.map((file) => {
238
+ const segments = relative(dir, file).replace(new RegExp(`${escapeRE(extname(file))}$`), "").split("/").join("_");
248
239
  return {
249
240
  file,
250
241
  name: camelCase(segments)
@@ -253,31 +244,24 @@ async function resolveFiles(dir) {
253
244
  }))).flat();
254
245
  return allRoutes;
255
246
  }
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
- }, "");
247
+ function normalizePages(pages) {
248
+ const imports = pages.map((page) => genImport(page.file, [{ name: "pages", as: page.name }])).join("\n");
262
249
  return {
263
250
  imports,
264
- exports
251
+ exports: pages.reduce((acc, curr) => {
252
+ const name = curr.name;
253
+ return `${name}:typeof ${name}==='function'?${name}():${name},${acc}`;
254
+ }, "")
265
255
  };
266
256
  }
267
257
 
268
258
  const pagesTypeTemplate = {
269
- filename: "types/pages.d.ts",
259
+ filename: "pages.d.ts",
270
260
  getContents: ({ options }) => `// Generated by pages discovery
271
261
  export {}
272
262
  declare global {
273
- type ArrElement<ArrType> = ArrType extends readonly (infer ElementType)[]
274
- ? ElementType
275
- : never;
276
263
 
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")}
264
+ ${options.pages.map((c) => `export type ${pascalCase(c.name)}Context=Awaited<ReturnType<typeof ${genDynamicImport(isAbsolute(c.file) ? relative(options.buildDir, c.file) : c.file, { wrapper: false })}['pages']['locales']['es-ec']['context']>>`).join("\n")}
281
265
  }
282
266
  export const pagesNames: string[]
283
267
  `.replaceAll(".ts", "")
@@ -289,54 +273,38 @@ const pagesModule = defineNuxtModule({
289
273
  },
290
274
  async setup(_options, flow) {
291
275
  const runtimeDir = resolve(distDir, "pages/runtime");
292
- flow.options.alias["#_pages"] = runtimeDir;
293
276
  const pages = [];
294
- const contexts = [];
295
- const options = { pages, buildDir: flow.options.buildDir, contexts };
277
+ flow.hook("builder:watch", async (event, path) => {
278
+ const dirs = [
279
+ flow.options.dir.pages,
280
+ flow.options.dir.layouts,
281
+ flow.options.dir.middleware
282
+ ].filter(Boolean);
283
+ const pathPattern = new RegExp(`^(${dirs.map(escapeRE).join("|")})/`);
284
+ if (event !== "change" && path.match(pathPattern))
285
+ await flow.callHook("builder:generateApp");
286
+ });
287
+ const options = { pages, buildDir: flow.options.buildDir };
296
288
  addTemplate({
297
289
  ...pagesTypeTemplate,
298
290
  options
299
291
  });
300
- const pagesDirs = [{ path: resolve(flow.options.srcDir, flow.options.dir.pages) }];
301
292
  flow.options.alias["#pages"] = resolve(flow.options.buildDir, "pages.mjs");
302
- flow.options.alias["#pagesContexts"] = resolve(flow.options.buildDir, "pages.contexts.mjs");
303
293
  addTemplate({
304
294
  filename: "pages.mjs",
305
295
  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;
296
+ const { exports, imports } = normalizePages(options2.pages);
297
+ return [imports, `export default {${exports}}`].join("\n");
318
298
  },
319
299
  options
320
300
  });
321
301
  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");
302
+ options.pages = await resolvePagesRoutes();
326
303
  });
327
304
  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");
305
+ references.push({ path: resolve(flow.options.buildDir, "pages.d.ts") });
338
306
  });
339
- addPlugin(resolve(runtimeDir, "pages"));
307
+ addPlugin({ src: resolve(runtimeDir, "plugin") });
340
308
  }
341
309
  });
342
310
 
@@ -364,7 +332,7 @@ const createClient = async (flow) => {
364
332
  if (vite)
365
333
  vite?.ws?.send({ type: "full-reload" });
366
334
  };
367
- const doReload = debounce(_doReload, 75);
335
+ const doReload = debounce(_doReload, 60);
368
336
  flow.hook("bundler:change", () => {
369
337
  doReload();
370
338
  });
@@ -420,24 +388,23 @@ const viteModule = defineFlowModule({
420
388
  }
421
389
  });
422
390
  } 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 () => {
391
+ flow.hook("modules:done", async () => {
437
392
  const start = Date.now();
438
393
  logger$1.info("Building client...");
439
394
  await builClient(flow);
395
+ const file = resolve(flow.options.rootDir, ".vite/manifest.json");
396
+ const manifest = await fse.readFile(file, "utf8");
440
397
  logger$1.success(`Client build in ${Date.now() - start}ms`);
398
+ addTemplate({
399
+ filename: "viteManifest.mjs",
400
+ async getContents() {
401
+ return [
402
+ "export default ()=>(",
403
+ manifest,
404
+ ")"
405
+ ].join("\n");
406
+ }
407
+ });
441
408
  });
442
409
  flow.hook("generate:before", async () => {
443
410
  const files = resolve(flow.options.rootDir, ".vite/scripts");
@@ -521,8 +488,7 @@ async function initNitro(flow) {
521
488
  externals: {
522
489
  inline: [
523
490
  ...flow.options.dev ? [] : ["eta", "@monkeyplus/", "@vue/", "@nuxt/", flow.options.buildDir],
524
- "@monkeyplus/flow/dist",
525
- "C:/Users/gnu/Documents/GitHub/flow/packages/flow/dist/app"
491
+ "@monkeyplus/flow/dist"
526
492
  ]
527
493
  },
528
494
  alias: {
@@ -533,8 +499,7 @@ async function initNitro(flow) {
533
499
  ...flow.options.alias
534
500
  },
535
501
  rollupConfig: {
536
- plugins: [],
537
- external: [""]
502
+ plugins: []
538
503
  }
539
504
  });
540
505
  await flow.callHook("nitro:config", nitroConfig);
@@ -1126,8 +1091,6 @@ const buildServer = async (ctx) => {
1126
1091
  "/__vue-jsx",
1127
1092
  "#app",
1128
1093
  /(nuxt|nuxt3)\/(dist|src|app)/,
1129
- /flow\/(dist|src|app)/,
1130
- /flow\/modules\/(content|icons|images|netlify|netlify-cms|seo|sitemap|vue)/,
1131
1094
  /@monkeyplus\/flow\/(dist|src|app)/,
1132
1095
  /@nuxt\/nitro\/(dist|src)/
1133
1096
  ]
@@ -1205,11 +1168,9 @@ const buildServer = async (ctx) => {
1205
1168
  await onBuild();
1206
1169
  ctx.flow.callHook("bundler:change", {});
1207
1170
  };
1208
- const doBuild = debounce(_doBuild, 50);
1171
+ const doBuild = debounce(_doBuild);
1209
1172
  await _doBuild();
1210
1173
  viteServer.watcher.on("all", (_event, file) => {
1211
- if (file.includes("/pages/"))
1212
- return;
1213
1174
  file = normalize(file);
1214
1175
  if (file.indexOf(ctx.flow.options.buildDir) === 0)
1215
1176
  return;
@@ -1329,7 +1290,6 @@ async function bundleVite(flow) {
1329
1290
  include: []
1330
1291
  },
1331
1292
  build: {
1332
- ssr: true,
1333
1293
  rollupOptions: {
1334
1294
  output: { sanitizeFileName: sanitizeFilePath },
1335
1295
  input: resolve(flow.options.appDir, "entry")
@@ -1366,8 +1326,6 @@ async function bundleVite(flow) {
1366
1326
  flow.hook("vite:serverCreated", (server) => {
1367
1327
  ctx.nuxt.hook("app:templatesGenerated", () => {
1368
1328
  for (const [id, mod] of server.moduleGraph.idToModuleMap) {
1369
- if (id.includes("pages.mjs"))
1370
- server.moduleGraph.invalidateModule(mod);
1371
1329
  if (id.startsWith("\0virtual:"))
1372
1330
  server.moduleGraph.invalidateModule(mod);
1373
1331
  }
@@ -1409,7 +1367,8 @@ function watch(flow) {
1409
1367
  "node_modules"
1410
1368
  ]
1411
1369
  });
1412
- watcher.on("all", (event, path) => flow.callHook("builder:watch", event, normalize(path)));
1370
+ const watchHook = debounce((event, path) => flow.callHook("builder:watch", event, normalize(path)));
1371
+ watcher.on("all", watchHook);
1413
1372
  flow.hook("close", () => watcher.close());
1414
1373
  return watcher;
1415
1374
  }
@@ -1,9 +1,3 @@
1
- import type { DynamicPage, PageCtx, SimplePage } from '@monkeyplus/flow-schema';
2
- export declare function definePage<T>(...pages: SimplePage<T>[]): SimplePage<T>[];
3
- export declare function defineDynamicPage<T>(...pages: DynamicPage<T>[]): DynamicPage<T>[];
4
- interface SharedContext {
5
- assign?: 'global' | 'local';
6
- setup: (cxt: PageCtx) => any;
7
- }
8
- export declare function defineSharedContext(shared: SharedContext): SharedContext;
9
- export {};
1
+ import type { DynamicPage, SimplePage } from '@monkeyplus/flow-schema';
2
+ export declare function definePage(page: SimplePage): SimplePage;
3
+ export declare function defineDinamycPage(page: DynamicPage): DynamicPage;
@@ -1,13 +1,6 @@
1
- export function definePage(...pages) {
2
- return pages;
1
+ export function definePage(page) {
2
+ return page;
3
3
  }
4
- export function defineDynamicPage(...pages) {
5
- return pages.map((page) => {
6
- if (!page.name.endsWith("/**"))
7
- page.name = `${page.name}/**`;
8
- return page;
9
- });
10
- }
11
- export function defineSharedContext(shared) {
12
- return shared;
4
+ export function defineDinamycPage(page) {
5
+ return page;
13
6
  }
@@ -0,0 +1,53 @@
1
+ import { joinURL } from "ufo";
2
+ import { definePage } from "./helpers/index.mjs";
3
+ import { defineFlowPlugin, useRuntimeConfig } from "#app";
4
+ import pages from "#pages";
5
+ export default defineFlowPlugin(async (flow) => {
6
+ const { app } = useRuntimeConfig();
7
+ const allPages = [];
8
+ Object.entries(pages).forEach(([name, page]) => {
9
+ const { getPages } = definePage({
10
+ name,
11
+ ...page
12
+ });
13
+ const _pages = getPages(app.locale.location, app.locale.language);
14
+ _pages.forEach((page2) => {
15
+ flow.router.byUrl.insert(page2.url, page2.context);
16
+ flow.router.byName.insert(page2.name, page2.context);
17
+ allPages.push(page2.context);
18
+ });
19
+ });
20
+ function getUrl(namePage, localeCode) {
21
+ const code = localeCode || this?.getLocale()?.code;
22
+ const [lang, loc] = code.split("-");
23
+ const name = joinURL("/", loc, lang, namePage);
24
+ const { path } = flow.router.byName.lookup(name) || {};
25
+ return path || "/404";
26
+ }
27
+ async function getUrls(withLocale = false) {
28
+ const urls = [];
29
+ for (const page of allPages) {
30
+ if (!page.path.includes("/**")) {
31
+ urls.push(withLocale ? { url: page.path, locale: page.locale.code, name: page.name } : page.path);
32
+ } else {
33
+ const dPages = await page.page.dynamic.method({
34
+ locale: page.locale,
35
+ utils: Object.assign({ getLocale: () => page.locale }, flow.app.utils)
36
+ });
37
+ dPages.forEach((dPage) => {
38
+ const _path = joinURL(page.path.replace("/**", ""), dPage.url);
39
+ urls.push(withLocale ? { url: _path, locale: page.locale.code, name: joinURL(page.name, dPage.name) } : _path);
40
+ });
41
+ }
42
+ }
43
+ return urls.sort();
44
+ }
45
+ flow.setUtil("getUrl", getUrl);
46
+ flow.setUtil("getUrls", getUrls);
47
+ flow.setUtil("getPages", () => allPages);
48
+ return {
49
+ provide: {
50
+ pages: { allPages }
51
+ }
52
+ };
53
+ });
@@ -1,14 +1,13 @@
1
1
  import logger from "consola";
2
- import { joinURL } from "ufo";
3
2
  import { generateBundle } from "./injectManifest.mjs";
4
3
  import { defineFlowPlugin } from "#app";
5
4
  import manifest from "#viteManifest";
6
5
  export default defineFlowPlugin((flow) => {
7
6
  if (typeof manifest === "function") {
7
+ const _manifest = manifest();
8
8
  flow.hook("page:chunks", (bundle, chunks) => {
9
9
  try {
10
- const data = manifest();
11
- const chunk = generateBundle(flow.$config.app || {}, data.manifest, joinURL("/", data.base, `${bundle}.ts`).replace("/", ""));
10
+ const chunk = generateBundle(flow.$config.app || {}, _manifest, `client/pages/${bundle}.ts`);
12
11
  if (chunk) {
13
12
  chunks.head.push(chunk.head);
14
13
  chunks.body.push(chunk.body);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@monkeyplus/flow",
3
- "version": "5.0.0-rc.38",
3
+ "version": "5.0.0-rc.4",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "main": "./dist/index.mjs",
@@ -25,9 +25,9 @@
25
25
  "dist"
26
26
  ],
27
27
  "dependencies": {
28
- "@monkeyplus/flow-cli": "5.0.0-rc.38",
29
- "@monkeyplus/flow-kit": "5.0.0-rc.38",
30
- "@monkeyplus/flow-schema": "5.0.0-rc.38",
28
+ "@monkeyplus/flow-cli": "5.0.0-rc.4",
29
+ "@monkeyplus/flow-kit": "5.0.0-rc.4",
30
+ "@monkeyplus/flow-schema": "5.0.0-rc.4",
31
31
  "@rollup/plugin-replace": "^4.0.0",
32
32
  "@vueuse/head": "^0.7.6",
33
33
  "c12": "^0.2.7",
@@ -50,7 +50,7 @@
50
50
  "magic-string": "^0.26.2",
51
51
  "mlly": "^0.5.2",
52
52
  "mri": "^1.2.0",
53
- "nitropack": "^0.4.8",
53
+ "nitropack": "^0.4.4",
54
54
  "pathe": "^0.2.0",
55
55
  "perfect-debounce": "^0.1.3",
56
56
  "radix3": "^0.1.2",
@@ -1,90 +0,0 @@
1
- import { joinURL } from "ufo";
2
- import consola from "consola";
3
- import { definePage } from "./helpers/index.mjs";
4
- import { defineFlowPlugin, useRuntimeConfig } from "#app";
5
- import pages from "#build/pages";
6
- import contexts from "#build/pages.contexts";
7
- export default defineFlowPlugin(async (flow) => {
8
- const { app } = useRuntimeConfig();
9
- const allPages = [];
10
- const basePages = Object.entries(pages);
11
- consola.success("Parsed %i pages files", basePages.length);
12
- basePages.forEach(([name, _pages]) => {
13
- const __pages = Array.isArray(_pages) ? _pages : [_pages];
14
- __pages.forEach((page) => {
15
- const { getPages } = definePage({
16
- name,
17
- ...page
18
- });
19
- const _pages2 = getPages(app.locale.location, app.locale.language);
20
- _pages2.forEach((page2) => {
21
- flow.router.byUrl.insert(page2.url, page2.context);
22
- flow.router.byName.insert(page2.name, page2.context);
23
- allPages.push(page2.context);
24
- });
25
- });
26
- });
27
- const cache = {};
28
- async function getUrl(namePage, localeCode) {
29
- const code = localeCode || this?.getLocale()?.code;
30
- const [lang, loc] = code.split("-");
31
- const name = joinURL("/", loc, lang, namePage);
32
- const { path, params, page } = flow.router.byName.lookup(name) || {};
33
- if (params?._ && page.dynamic) {
34
- if (!cache[path]) {
35
- cache[path] = this.defineCachedFunction(async (_ctx) => {
36
- return await page.dynamic.method(_ctx);
37
- }, { maxAge: 8, getKey: () => path, swr: false });
38
- }
39
- const fn = cache[path];
40
- const list = await fn({ utils: this, locale: this.getLocale() });
41
- const dPage = list.find((el) => el.name === params._);
42
- return dPage ? path.replace("**", dPage.url) : "/404";
43
- }
44
- return path || "/404";
45
- }
46
- async function getUrls(withLocale = false) {
47
- const urls = [];
48
- for (const page of allPages) {
49
- if (page.path.includes("/**") && page.page.dynamic) {
50
- const dPages = await page.page.dynamic.method({
51
- locale: page.locale,
52
- utils: Object.assign({ getLocale: () => page.locale }, flow.app.utils),
53
- chunks: {}
54
- });
55
- dPages.forEach((dPage) => {
56
- const _path = joinURL(page.path.replace("/**", ""), dPage.url);
57
- urls.push(withLocale ? { url: _path, locale: page.locale.code, name: joinURL(page.name, dPage.name) } : _path);
58
- });
59
- } else {
60
- const url = page.path.replaceAll("*", "");
61
- urls.push(withLocale ? { url, locale: page.locale.code, name: page.name } : url);
62
- }
63
- }
64
- return urls.sort();
65
- }
66
- async function getSharedContext(utils) {
67
- const entries = Object.entries(contexts);
68
- if (!entries.length)
69
- return {};
70
- const _contexts = await Promise.all(entries.map(async ([key, method]) => {
71
- const data = await method.setup(utils);
72
- return { [key]: data };
73
- }));
74
- return _contexts.reduce((acc, curr) => {
75
- return {
76
- ...acc,
77
- ...curr
78
- };
79
- }, {});
80
- }
81
- flow.setUtil("getUrl", getUrl);
82
- flow.setUtil("getUrls", getUrls);
83
- flow.setUtil("getPages", () => allPages);
84
- flow.setUtil("getSharedContext", getSharedContext);
85
- return {
86
- provide: {
87
- pages: { allPages }
88
- }
89
- };
90
- });
File without changes