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

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,9 +1,6 @@
1
1
  import { joinURL, withTrailingSlash } from "ufo";
2
- const buildPages = (page) => (location, language, _locales) => {
3
- const locales = _locales.map((key) => {
4
- const _page = page.locales[key];
5
- return [key, _page];
6
- }).filter((el) => !!el[1]);
2
+ const buildPages = (page) => (location, language) => {
3
+ const locales = Object.entries(page.locales);
7
4
  return locales.map(([locale, localePage]) => {
8
5
  const [_language, _location] = locale.split("-");
9
6
  const name = joinURL("/", _location, _language, page.name);
@@ -1,10 +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
- export interface SharedContext {
5
- assign?: 'global' | 'local';
6
- merge?: boolean;
7
- setup: (cxt: PageCtx) => any;
8
- locales?: Record<string, (ctx: PageCtx) => any>;
9
- }
10
- export declare function defineSharedContext(shared: SharedContext): SharedContext;
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,56 @@
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 "#pages";
6
+ export default defineFlowPlugin(async (flow) => {
7
+ const { app } = useRuntimeConfig();
8
+ const allPages = [];
9
+ const basePages = Object.entries(pages);
10
+ consola.success("Parsed %i pages", basePages.length);
11
+ basePages.forEach(([name, page]) => {
12
+ const { getPages } = definePage({
13
+ name,
14
+ ...page
15
+ });
16
+ const _pages = getPages(app.locale.location, app.locale.language);
17
+ _pages.forEach((page2) => {
18
+ flow.router.byUrl.insert(page2.url, page2.context);
19
+ flow.router.byName.insert(page2.name, page2.context);
20
+ allPages.push(page2.context);
21
+ });
22
+ });
23
+ function getUrl(namePage, localeCode) {
24
+ const code = localeCode || this?.getLocale()?.code;
25
+ const [lang, loc] = code.split("-");
26
+ const name = joinURL("/", loc, lang, namePage);
27
+ const { path } = flow.router.byName.lookup(name) || {};
28
+ return path || "/404";
29
+ }
30
+ async function getUrls(withLocale = false) {
31
+ const urls = [];
32
+ for (const page of allPages) {
33
+ if (!page.path.includes("/**")) {
34
+ urls.push(withLocale ? { url: page.path, locale: page.locale.code, name: page.name } : page.path);
35
+ } else {
36
+ const dPages = await page.page.dynamic.method({
37
+ locale: page.locale,
38
+ utils: Object.assign({ getLocale: () => page.locale }, flow.app.utils)
39
+ });
40
+ dPages.forEach((dPage) => {
41
+ const _path = joinURL(page.path.replace("/**", ""), dPage.url);
42
+ urls.push(withLocale ? { url: _path, locale: page.locale.code, name: joinURL(page.name, dPage.name) } : _path);
43
+ });
44
+ }
45
+ }
46
+ return urls.sort();
47
+ }
48
+ flow.setUtil("getUrl", getUrl);
49
+ flow.setUtil("getUrls", getUrls);
50
+ flow.setUtil("getPages", () => allPages);
51
+ return {
52
+ provide: {
53
+ pages: { allPages }
54
+ }
55
+ };
56
+ });
@@ -5,8 +5,7 @@ export const generateBundle = (config, bundle, _id) => {
5
5
  const chunks = [];
6
6
  chunk2.imports?.forEach((file) => {
7
7
  const importee = bundle[file];
8
- const isChunk = file.startsWith("_") || importee.isEntry;
9
- if (isChunk && !seen.has(file)) {
8
+ if (file.startsWith("_") && !seen.has(file)) {
10
9
  seen.add(file);
11
10
  chunks.push(...getImportedChunks(importee, seen));
12
11
  chunks.push(importee);
@@ -37,7 +36,7 @@ export const generateBundle = (config, bundle, _id) => {
37
36
  analyzedChunk.set(chunk2, 1);
38
37
  chunk2.imports?.forEach((file) => {
39
38
  const importee = bundle[file];
40
- if (file.startsWith("_") || importee.isEntry)
39
+ if (file.startsWith("_"))
41
40
  tags.push(...getCssTagsForChunk(importee, publicBase2, seen));
42
41
  });
43
42
  }
@@ -72,7 +71,7 @@ export const generateBundle = (config, bundle, _id) => {
72
71
  export const externalRE = /^(https?:)?\/\//;
73
72
  export const isExternalUrl = (url) => externalRE.test(url);
74
73
  function toPublicPath(filename, publicBase) {
75
- return isExternalUrl(filename) ? filename : joinURL(publicBase, filename);
74
+ return isExternalUrl(filename) ? filename : joinURL(publicBase, filename.replace("scripts", "assets"));
76
75
  }
77
76
  const unaryTags = new Set(["link", "meta", "base"]);
78
77
  function serializeTag({ tag, attrs, children }, indent = "") {
@@ -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.87",
3
+ "version": "5.0.0-rc.9",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "main": "./dist/index.mjs",
@@ -25,57 +25,52 @@
25
25
  "dist"
26
26
  ],
27
27
  "dependencies": {
28
- "@monkeyplus/flow-cli": "5.0.0-rc.87",
29
- "@monkeyplus/flow-kit": "5.0.0-rc.87",
30
- "@monkeyplus/flow-schema": "5.0.0-rc.87",
28
+ "@monkeyplus/flow-cli": "5.0.0-rc.9",
29
+ "@monkeyplus/flow-kit": "5.0.0-rc.9",
30
+ "@monkeyplus/flow-schema": "5.0.0-rc.9",
31
31
  "@rollup/plugin-replace": "^4.0.0",
32
32
  "@vueuse/head": "^0.7.6",
33
- "c12": "^0.2.8",
33
+ "c12": "^0.2.7",
34
34
  "chokidar": "^3.5.3",
35
35
  "consola": "^2.15.3",
36
36
  "defu": "^6.0.0",
37
- "esbuild": "^0.14.49",
37
+ "esbuild": "^0.14.38",
38
38
  "escape-string-regexp": "^5.0.0",
39
- "esno": "^0.16.3",
39
+ "esno": "^0.14.1",
40
40
  "eta": "^1.12.3",
41
- "externality": "^0.2.2",
41
+ "externality": "^0.2.1",
42
42
  "fs-extra": "^10.1.0",
43
43
  "get-port-please": "^2.5.0",
44
- "globby": "^13.1.2",
45
- "h3": "^0.7.16",
44
+ "globby": "^13.1.1",
45
+ "h3": "^0.7.4",
46
46
  "hookable": "^5.1.1",
47
- "jiti": "^1.14.0",
48
- "ohash": "^0.1.5",
49
- "knitwork": "^0.1.2",
50
- "listhen": "^0.2.13",
47
+ "jiti": "^1.13.0",
48
+ "knitwork": "^0.1.1",
49
+ "listhen": "^0.2.10",
51
50
  "magic-string": "^0.26.2",
52
- "mlly": "^0.5.4",
51
+ "mlly": "^0.5.2",
53
52
  "mri": "^1.2.0",
54
- "nitropack": "^0.4.12",
55
- "pathe": "^0.3.2",
53
+ "nitropack": "^0.4.4",
54
+ "pathe": "^0.2.0",
56
55
  "perfect-debounce": "^0.1.3",
57
56
  "radix3": "^0.1.2",
58
57
  "unenv": "^0.5.2",
59
58
  "ohmyfetch": "^0.4.18",
60
- "node-fetch-native": "^0.1.4",
61
- "rollup": "^2.77.0",
62
- "rollup-plugin-visualizer": "^5.7.1",
59
+ "node-fetch-native": "^0.1.3",
60
+ "rollup": "^2.72.1",
61
+ "rollup-plugin-visualizer": "^5.6.0",
63
62
  "scule": "^0.2.1",
64
- "ufo": "^0.8.5",
63
+ "ufo": "^0.8.3",
65
64
  "unctx": "^1.1.4",
66
- "unimport": "^0.4.5",
67
- "unplugin": "^0.7.2",
68
- "untyped": "^0.4.5",
69
- "pkg-types": "^0.3.3",
70
- "vite": "~3.0.9",
71
- "vite-node": "^0.22.1",
72
- "vite-plugin-checker": "^0.4.9",
73
- "vue-bundle-renderer": "^0.4.2",
74
- "vue": "^3.2.37"
65
+ "unimport": "^0.2.1",
66
+ "unplugin": "^0.6.3",
67
+ "untyped": "^0.4.4",
68
+ "vite": "^2.9.9",
69
+ "vue": "^3.2.33"
75
70
  },
76
71
  "devDependencies": {
77
72
  "@types/fs-extra": "^9.0.13",
78
- "vue-router": "^4.1.2"
73
+ "vue-router": "^4.0.15"
79
74
  },
80
75
  "engines": {
81
76
  "node": "^16.11.0 || ^17.0.0 || ^18.0.0"
@@ -1,3 +0,0 @@
1
- import type { RuntimeConfig } from '@monkeyplus/flow-schema';
2
- declare const _default: (ctx?: RuntimeConfig) => Promise<any>;
3
- export default _default;
@@ -1 +0,0 @@
1
- export default (ctx) => import("#app/entry").then((m) => m.default(ctx));
@@ -1,245 +0,0 @@
1
- import { pathToFileURL } from 'node:url';
2
- import { existsSync } from 'node:fs';
3
- import { builtinModules } from 'node:module';
4
- import { resolve, normalize, isAbsolute } from 'pathe';
5
- import { genObjectFromRawEntries, genDynamicImport } from 'knitwork';
6
- import fse from 'fs-extra';
7
- import { debounce } from 'perfect-debounce';
8
- import { isIgnored, logger } from '@monkeyplus/flow-kit';
9
- import { h as hashId, c as createIsExternal, u as uniq, i as isCSS } from './external.mjs';
10
- import { withTrailingSlash, withoutLeadingSlash } from 'ufo';
11
- import escapeRE from 'escape-string-regexp';
12
- import { normalizeViteManifest } from 'vue-bundle-renderer';
13
- import 'ohash';
14
- import 'externality';
15
-
16
- async function writeManifest(ctx, css = []) {
17
- const clientDist = resolve(ctx.nuxt.options.buildDir, "dist/client");
18
- const serverDist = resolve(ctx.nuxt.options.buildDir, "dist/server");
19
- const devClientManifest = {
20
- "@vite/client": {
21
- isEntry: true,
22
- file: "@vite/client",
23
- css,
24
- module: true,
25
- resourceType: "script"
26
- },
27
- [ctx.entry]: {
28
- isEntry: true,
29
- file: ctx.entry,
30
- module: true,
31
- resourceType: "script"
32
- }
33
- };
34
- const clientManifest = ctx.nuxt.options.dev ? devClientManifest : await fse.readJSON(resolve(clientDist, "manifest.json"));
35
- const buildAssetsDir = withTrailingSlash(withoutLeadingSlash(ctx.nuxt.options.app.buildAssetsDir));
36
- const BASE_RE = new RegExp(`^${escapeRE(buildAssetsDir)}`);
37
- for (const key in clientManifest) {
38
- if (clientManifest[key].file)
39
- clientManifest[key].file = clientManifest[key].file.replace(BASE_RE, "");
40
- for (const item of ["css", "assets"]) {
41
- if (clientManifest[key][item])
42
- clientManifest[key][item] = clientManifest[key][item].map((i) => i.replace(BASE_RE, ""));
43
- }
44
- }
45
- await fse.mkdirp(serverDist);
46
- const manifest = normalizeViteManifest(clientManifest);
47
- await ctx.nuxt.callHook("build:manifest", manifest);
48
- await fse.writeFile(resolve(serverDist, "client.manifest.json"), JSON.stringify(manifest, null, 2), "utf8");
49
- await fse.writeFile(resolve(serverDist, "client.manifest.mjs"), `export default ${JSON.stringify(manifest, null, 2)}`, "utf8");
50
- }
51
-
52
- async function transformRequest(opts, id) {
53
- if (id && id.startsWith("/@id/__x00__"))
54
- id = `\0${id.slice("/@id/__x00__".length)}`;
55
- if (id && id.startsWith("/@id/"))
56
- id = id.slice("/@id/".length);
57
- if (id && !id.startsWith("/@fs/") && id.startsWith("/")) {
58
- const resolvedPath = resolve(opts.viteServer.config.root, `.${id}`);
59
- if (existsSync(resolvedPath))
60
- id = resolvedPath;
61
- }
62
- id = id.replace(/^\/?(?=\w:)/, "/@fs/");
63
- const externalId = id.replace(/\?v=\w+$|^\/@fs/, "");
64
- if (await opts.isExternal(externalId)) {
65
- const path = builtinModules.includes(externalId.split("node:").pop()) ? externalId : isAbsolute(externalId) ? pathToFileURL(externalId).href : externalId;
66
- return {
67
- code: `(global, module, _, exports, importMeta, ssrImport, ssrDynamicImport, ssrExportAll) =>
68
- ${genDynamicImport(path, { wrapper: false })}
69
- .then(r => {
70
- if (r.default && r.default.__esModule)
71
- r = r.default
72
- exports.default = r.default
73
- ssrExportAll(r)
74
- })
75
- .catch(e => {
76
- console.error(e)
77
- throw new Error(${JSON.stringify(`[vite dev] Error loading external "${id}".`)})
78
- })`,
79
- deps: [],
80
- dynamicDeps: []
81
- };
82
- }
83
- const res = await opts.viteServer.transformRequest(id, { ssr: true }).catch((err) => {
84
- console.warn(`[SSR] Error transforming ${id}:`, err);
85
- }) || { code: "", map: {}, deps: [], dynamicDeps: [] };
86
- const code = `async function (global, module, exports, __vite_ssr_exports__, __vite_ssr_import_meta__, __vite_ssr_import__, __vite_ssr_dynamic_import__, __vite_ssr_exportAll__) {
87
- ${res.code || "/* empty */"};
88
- }`;
89
- return { code, deps: res.deps || [], dynamicDeps: res.dynamicDeps || [] };
90
- }
91
- async function transformRequestRecursive(opts, id, parent = "<entry>", chunks = {}) {
92
- if (chunks[id]) {
93
- chunks[id].parents.push(parent);
94
- return;
95
- }
96
- const res = await transformRequest(opts, id);
97
- const deps = uniq([...res.deps, ...res.dynamicDeps]);
98
- chunks[id] = {
99
- id,
100
- code: res.code,
101
- deps,
102
- parents: [parent]
103
- };
104
- for (const dep of deps)
105
- await transformRequestRecursive(opts, dep, id, chunks);
106
- return Object.values(chunks);
107
- }
108
- async function bundleRequest(opts, entryURL) {
109
- const chunks = await transformRequestRecursive(opts, entryURL);
110
- const listIds = (ids) => ids.map((id) => `// - ${id} (${hashId(id)})`).join("\n");
111
- const chunksCode = chunks.map((chunk) => `
112
- // --------------------
113
- // Request: ${chunk.id}
114
- // Parents:
115
- ${listIds(chunk.parents)}
116
- // Dependencies:
117
- ${listIds(chunk.deps)}
118
- // --------------------
119
- const ${hashId(`${chunk.id}-${chunk.code}`)} = ${chunk.code}
120
- `).join("\n");
121
- const manifestCode = `const __modules__ = ${genObjectFromRawEntries(chunks.map((chunk) => [chunk.id, hashId(`${chunk.id}-${chunk.code}`)]))}`;
122
- const ssrModuleLoader = `
123
- const __pendingModules__ = new Map()
124
- const __pendingImports__ = new Map()
125
- const __ssrContext__ = { global: globalThis }
126
-
127
- function __ssrLoadModule__(url, urlStack = []) {
128
- const pendingModule = __pendingModules__.get(url)
129
- if (pendingModule) { return pendingModule }
130
- const modulePromise = __instantiateModule__(url, urlStack)
131
- __pendingModules__.set(url, modulePromise)
132
- modulePromise.catch(() => { __pendingModules__.delete(url) })
133
- .finally(() => { __pendingModules__.delete(url) })
134
- return modulePromise
135
- }
136
-
137
- async function __instantiateModule__(url, urlStack) {
138
- const mod = __modules__[url]
139
- if (mod.stubModule) { return mod.stubModule }
140
- const stubModule = { [Symbol.toStringTag]: 'Module' }
141
- Object.defineProperty(stubModule, '__esModule', { value: true })
142
- mod.stubModule = stubModule
143
- // https://vitejs.dev/guide/api-hmr.html
144
- const importMeta = { url, hot: { accept() {}, prune() {}, dispose() {}, invalidate() {}, decline() {}, on() {} } }
145
- urlStack = urlStack.concat(url)
146
- const isCircular = url => urlStack.includes(url)
147
- const pendingDeps = []
148
- const ssrImport = async (dep) => {
149
- // TODO: Handle externals if dep[0] !== '.' | '/'
150
- if (!isCircular(dep) && !__pendingImports__.get(dep)?.some(isCircular)) {
151
- pendingDeps.push(dep)
152
- if (pendingDeps.length === 1) {
153
- __pendingImports__.set(url, pendingDeps)
154
- }
155
- await __ssrLoadModule__(dep, urlStack)
156
- if (pendingDeps.length === 1) {
157
- __pendingImports__.delete(url)
158
- } else {
159
- pendingDeps.splice(pendingDeps.indexOf(dep), 1)
160
- }
161
- }
162
- return __modules__[dep].stubModule
163
- }
164
- function ssrDynamicImport (dep) {
165
- // TODO: Handle dynamic import starting with . relative to url
166
- return ssrImport(dep)
167
- }
168
-
169
- function ssrExportAll(sourceModule) {
170
- for (const key in sourceModule) {
171
- if (key !== 'default') {
172
- try {
173
- Object.defineProperty(stubModule, key, {
174
- enumerable: true,
175
- configurable: true,
176
- get() { return sourceModule[key] }
177
- })
178
- } catch (_err) { }
179
- }
180
- }
181
- }
182
-
183
- const cjsModule = {
184
- get exports () {
185
- return stubModule.default
186
- },
187
- set exports (v) {
188
- stubModule.default = v
189
- },
190
- }
191
-
192
- await mod(
193
- __ssrContext__.global,
194
- cjsModule,
195
- stubModule.default,
196
- stubModule,
197
- importMeta,
198
- ssrImport,
199
- ssrDynamicImport,
200
- ssrExportAll
201
- )
202
-
203
- return stubModule
204
- }
205
- `;
206
- const code = [
207
- chunksCode,
208
- manifestCode,
209
- ssrModuleLoader,
210
- `export default await __ssrLoadModule__(${JSON.stringify(entryURL)})`
211
- ].join("\n\n");
212
- return {
213
- code,
214
- ids: chunks.map((i) => i.id)
215
- };
216
- }
217
- async function initViteDevBundler(ctx, onBuild) {
218
- const viteServer = ctx.ssrServer;
219
- const options = {
220
- viteServer,
221
- isExternal: createIsExternal(viteServer, ctx.nuxt.options.rootDir)
222
- };
223
- const _doBuild = async () => {
224
- const start = Date.now();
225
- const { code, ids } = await bundleRequest(options, ctx.entry);
226
- await fse.ensureFile(resolve(ctx.nuxt.options.buildDir, "dist/server/server.mjs"));
227
- await fse.writeFile(resolve(ctx.nuxt.options.buildDir, "dist/server/server.mjs"), code, "utf-8");
228
- await writeManifest(ctx, ids.filter(isCSS).map((i) => i.slice(1)));
229
- const time = Date.now() - start;
230
- logger.success(`Vite server built in ${time}ms`);
231
- await onBuild();
232
- ctx.nuxt.callHook("bundler:change", {});
233
- };
234
- const doBuild = debounce(_doBuild);
235
- await _doBuild();
236
- viteServer.watcher.on("all", (_event, file) => {
237
- file = normalize(file);
238
- if (file.indexOf(ctx.nuxt.options.buildDir) === 0 || isIgnored(file))
239
- return;
240
- doBuild();
241
- });
242
- ctx.nuxt.hook("app:templatesGenerated", () => doBuild());
243
- }
244
-
245
- export { bundleRequest, initViteDevBundler };
@@ -1,37 +0,0 @@
1
- import 'node:fs';
2
- import { hash } from 'ohash';
3
- import 'pathe';
4
- import { isExternal, ExternalsDefaults } from 'externality';
5
-
6
- function uniq(arr) {
7
- return Array.from(new Set(arr));
8
- }
9
- const IS_CSS_RE = /\.(?:css|scss|sass|postcss|less|stylus|styl)(\?[^.]+)?$/;
10
- function isCSS(file) {
11
- return IS_CSS_RE.test(file);
12
- }
13
- function hashId(id) {
14
- return `$id_${hash(id)}`;
15
- }
16
-
17
- function createIsExternal(viteServer, rootDir) {
18
- const externalOpts = {
19
- inline: [
20
- /virtual:/,
21
- /\.ts$/,
22
- ...ExternalsDefaults.inline || [],
23
- ...viteServer.config.ssr.noExternal
24
- ],
25
- external: [
26
- ...viteServer.config.ssr.external || [],
27
- /node_modules/
28
- ],
29
- resolve: {
30
- type: "module",
31
- extensions: [".ts", ".js", ".json", ".vue", ".mjs", ".jsx", ".tsx", ".wasm"]
32
- }
33
- };
34
- return (id) => isExternal(id, rootDir, externalOpts);
35
- }
36
-
37
- export { createIsExternal as c, hashId as h, isCSS as i, uniq as u };