@monkeyplus/flow 5.0.0-rc.98 → 6.0.0

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.
Files changed (127) hide show
  1. package/README.md +34 -0
  2. package/entry-server.d.ts +1 -0
  3. package/entry-server.mjs +5 -0
  4. package/modules/content/module.d.ts +6 -0
  5. package/modules/content/module.mjs +32 -0
  6. package/modules/content/query.mjs +104 -0
  7. package/modules/sitemap/handler.mjs +17 -0
  8. package/modules/sitemap/module.d.ts +6 -0
  9. package/modules/sitemap/module.mjs +28 -0
  10. package/modules/strapi/README.md +235 -0
  11. package/modules/strapi/module.d.ts +11 -0
  12. package/modules/strapi/module.mjs +69 -0
  13. package/modules/strapi/proxy.mjs +54 -0
  14. package/modules/strapi/runtime/client.d.ts +30 -0
  15. package/modules/strapi/runtime/client.mjs +248 -0
  16. package/package.json +73 -77
  17. package/server/lib/handler.d.ts +1 -0
  18. package/server/lib/handler.mjs +43 -0
  19. package/server/lib/pages.d.ts +20 -0
  20. package/server/lib/pages.mjs +276 -0
  21. package/server/lib/render.d.ts +7 -0
  22. package/server/lib/render.mjs +156 -0
  23. package/server/plugins/00.lifecycle.d.ts +2 -0
  24. package/server/plugins/00.lifecycle.mjs +9 -0
  25. package/server/renderer.d.ts +3 -0
  26. package/server/renderer.mjs +14 -0
  27. package/server/routes/api/health.get.d.ts +2 -0
  28. package/server/routes/api/health.get.mjs +5 -0
  29. package/server.d.ts +1 -0
  30. package/server.mjs +32 -0
  31. package/src/main.d.ts +1 -0
  32. package/src/main.mjs +29 -0
  33. package/src/public/boot.d.ts +1 -0
  34. package/src/public/components.d.ts +1 -0
  35. package/src/public/components.mjs +1 -0
  36. package/src/public/head.d.ts +1 -0
  37. package/src/public/head.mjs +1 -0
  38. package/src/public/index.d.ts +5 -0
  39. package/src/public/index.mjs +2 -0
  40. package/src/public/modules/content.d.ts +2 -0
  41. package/src/public/modules/content.mjs +1 -0
  42. package/src/public/modules/sitemap.d.ts +2 -0
  43. package/src/public/modules/sitemap.mjs +1 -0
  44. package/src/public/modules/strapi.d.ts +2 -0
  45. package/src/public/modules/strapi.mjs +1 -0
  46. package/src/public/nitro.d.ts +6 -0
  47. package/src/public/nitro.mjs +78 -0
  48. package/src/public/shared.d.ts +2 -0
  49. package/src/public/shared.mjs +18 -0
  50. package/src/public/vite.d.ts +6 -0
  51. package/src/public/vite.mjs +273 -0
  52. package/src/public/vue.d.ts +1 -0
  53. package/src/public/vue.mjs +1 -0
  54. package/src/runtime/boot.d.ts +9 -0
  55. package/src/runtime/components/FlowIsland.d.ts +42 -0
  56. package/src/runtime/components/FlowIsland.mjs +35 -0
  57. package/src/runtime/config.d.ts +73 -0
  58. package/src/runtime/config.mjs +26 -0
  59. package/src/runtime/head.d.ts +3 -0
  60. package/src/runtime/head.mjs +7 -0
  61. package/src/runtime/islands.d.ts +2 -0
  62. package/src/runtime/islands.mjs +52 -0
  63. package/src/runtime/modules.d.ts +12 -0
  64. package/src/runtime/modules.mjs +115 -0
  65. package/src/runtime/page-discovery.d.ts +6 -0
  66. package/src/runtime/page-discovery.mjs +175 -0
  67. package/src/runtime/pages.d.ts +107 -0
  68. package/src/runtime/pages.mjs +3 -0
  69. package/src/runtime/ssg.d.ts +9 -0
  70. package/src/runtime/ssg.mjs +37 -0
  71. package/src/runtime/virtual-pages.d.ts +8 -0
  72. package/src/runtime/virtual-pages.mjs +151 -0
  73. package/src/runtime/virtual.d.ts +103 -0
  74. package/src/runtime/vite-assets.d.ts +9 -0
  75. package/src/runtime/vue.d.ts +6 -0
  76. package/src/runtime/vue.mjs +6 -0
  77. package/src/styles.css +1 -0
  78. package/app.d.ts +0 -1
  79. package/bin/flow.mjs +0 -2
  80. package/dist/app/composables/index.d.ts +0 -5
  81. package/dist/app/composables/index.mjs +0 -12
  82. package/dist/app/entry.async.d.ts +0 -3
  83. package/dist/app/entry.async.mjs +0 -1
  84. package/dist/app/entry.d.ts +0 -3
  85. package/dist/app/entry.mjs +0 -23
  86. package/dist/app/flow.d.ts +0 -80
  87. package/dist/app/flow.mjs +0 -88
  88. package/dist/app/index.d.ts +0 -3
  89. package/dist/app/index.mjs +0 -3
  90. package/dist/chunks/dev-bundler.mjs +0 -247
  91. package/dist/chunks/external.mjs +0 -37
  92. package/dist/chunks/index.mjs +0 -1140
  93. package/dist/chunks/vite-node.mjs +0 -155
  94. package/dist/core/runtime/client.manifest.d.mts +0 -2
  95. package/dist/core/runtime/client.manifest.mjs +0 -6
  96. package/dist/core/runtime/nitro/flow.d.ts +0 -3
  97. package/dist/core/runtime/nitro/flow.mjs +0 -33
  98. package/dist/core/runtime/nitro/paths.d.ts +0 -4
  99. package/dist/core/runtime/nitro/paths.mjs +0 -15
  100. package/dist/core/runtime/nitro/renderer.d.ts +0 -2
  101. package/dist/core/runtime/nitro/renderer.mjs +0 -101
  102. package/dist/core/runtime/vite-node-shared.d.mts +0 -1
  103. package/dist/core/runtime/vite-node-shared.d.ts +0 -8
  104. package/dist/core/runtime/vite-node-shared.mjs +0 -3
  105. package/dist/core/runtime/vite-node.d.mts +0 -2
  106. package/dist/core/runtime/vite-node.mjs +0 -42
  107. package/dist/head/runtime/composables.d.ts +0 -9
  108. package/dist/head/runtime/composables.mjs +0 -2
  109. package/dist/head/runtime/index.d.ts +0 -1
  110. package/dist/head/runtime/index.mjs +0 -1
  111. package/dist/head/runtime/plugin.mjs +0 -5
  112. package/dist/index.d.ts +0 -11
  113. package/dist/index.mjs +0 -27
  114. package/dist/pages/runtime/helpers/index.d.ts +0 -5
  115. package/dist/pages/runtime/helpers/index.mjs +0 -31
  116. package/dist/pages/runtime/index.d.ts +0 -10
  117. package/dist/pages/runtime/index.mjs +0 -13
  118. package/dist/pages/runtime/pages.mjs +0 -100
  119. package/dist/vite-client/runtime/injectManifest.d.ts +0 -26
  120. package/dist/vite-client/runtime/injectManifest.mjs +0 -110
  121. package/dist/vite-client/runtime/plugin.mjs +0 -28
  122. package/types.d.ts +0 -2
  123. /package/{dist/head/runtime/plugin.d.ts → modules/content/query.d.ts} +0 -0
  124. /package/{dist/pages/runtime/pages.d.ts → modules/sitemap/handler.d.ts} +0 -0
  125. /package/{dist/vite-client/runtime/plugin.d.ts → modules/strapi/proxy.d.ts} +0 -0
  126. /package/{dist/pages/runtime/helpers/chunks.d.ts → src/public/boot.mjs} +0 -0
  127. /package/{dist/pages/runtime/helpers/chunks.mjs → src/runtime/boot.mjs} +0 -0
@@ -0,0 +1,103 @@
1
+ declare module 'virtual:flow/pages' {
2
+ const pages: import('./pages').PageDefinition[];
3
+
4
+ export default pages;
5
+ }
6
+
7
+ declare module 'virtual:flow/client-pages' {
8
+ export interface FlowClientBundleModule {
9
+ default?: (payload: import('./boot').FlowBootPayload) => void | Promise<void>;
10
+ }
11
+
12
+ const bundles: Record<string, () => Promise<FlowClientBundleModule>>;
13
+
14
+ export default bundles;
15
+ }
16
+
17
+ declare module 'virtual:flow/client-page-assets' {
18
+ export interface FlowClientBundleAssets {
19
+ entry?: string;
20
+ css?: Array<Record<string, string>>;
21
+ js?: Array<Record<string, string>>;
22
+ }
23
+
24
+ const bundles: Record<string, FlowClientBundleAssets>;
25
+
26
+ export default bundles;
27
+ }
28
+
29
+ declare module 'virtual:flow/strapi-config' {
30
+ const config: {
31
+ apiBase: string;
32
+ url: string;
33
+ prefix: string;
34
+ admin: string;
35
+ version: 'v5' | 'v4' | 'v3';
36
+ };
37
+
38
+ export default config;
39
+ }
40
+
41
+ declare module '#strapi' {
42
+ export interface StrapiFetchOptions extends RequestInit {
43
+ params?: Record<string, unknown>;
44
+ }
45
+
46
+ export interface StrapiPublicConfig {
47
+ apiBase: string;
48
+ url: string;
49
+ prefix: string;
50
+ admin: string;
51
+ version: 'v5' | 'v4' | 'v3';
52
+ }
53
+
54
+ export function useStrapiVersion(): StrapiPublicConfig['version'];
55
+ export function useStrapiUrl(path?: string): string;
56
+ export function useStrapiAdminUrl(path?: string): string;
57
+ export function useStrapiMedia(url?: string | null): string | null | undefined;
58
+ export function useStrapiClient(): <T>(url: string, options?: StrapiFetchOptions) => Promise<T>;
59
+ export function useStrapi<T = unknown>(): {
60
+ find<TResult = T>(contentType: string, params?: Record<string, unknown>, options?: StrapiFetchOptions): Promise<TResult>;
61
+ findOne<TResult = T>(contentType: string, documentId: string, params?: Record<string, unknown>, options?: StrapiFetchOptions): Promise<TResult>;
62
+ create<TResult = T>(contentType: string, data: Partial<TResult>, params?: Record<string, unknown>, options?: StrapiFetchOptions): Promise<TResult>;
63
+ update<TResult = T>(contentType: string, documentId: string, data?: Partial<TResult>, params?: Record<string, unknown>, options?: StrapiFetchOptions): Promise<TResult>;
64
+ delete(contentType: string, documentId?: string, params?: Record<string, unknown>, options?: StrapiFetchOptions): Promise<void>;
65
+ };
66
+ export function useStrapiGraphQL(): <T>(query: string | { loc?: { source?: { body?: string } } }, variables?: Record<string, unknown>, options?: StrapiFetchOptions) => Promise<T>;
67
+ export const strapiConfig: StrapiPublicConfig;
68
+ }
69
+
70
+ declare module 'virtual:flow/islands' {
71
+ export interface FlowIslandHydrateContext {
72
+ element: HTMLElement;
73
+ props: Record<string, unknown>;
74
+ boot?: import('./boot').FlowBootPayload;
75
+ }
76
+
77
+ export interface FlowIslandModule {
78
+ default?: import('vue').Component;
79
+ hydrate?: (ctx: FlowIslandHydrateContext) => void | Promise<void>;
80
+ }
81
+
82
+ const islands: Record<string, () => Promise<FlowIslandModule>>;
83
+
84
+ export default islands;
85
+ }
86
+
87
+ declare module 'virtual:flow/templates' {
88
+ const templates: Record<string, import('vue').Component>;
89
+
90
+ export default templates;
91
+ }
92
+
93
+ declare module 'virtual:flow/layouts' {
94
+ const layouts: Record<string, import('vue').Component>;
95
+
96
+ export default layouts;
97
+ }
98
+
99
+ declare module 'virtual:flow/bases' {
100
+ const bases: Record<string, string>;
101
+
102
+ export default bases;
103
+ }
@@ -0,0 +1,9 @@
1
+ declare module '*?assets=client' {
2
+ const assets: {
3
+ entry: string;
4
+ css?: Array<Record<string, string>>;
5
+ js?: Array<Record<string, string>>;
6
+ };
7
+
8
+ export default assets;
9
+ }
@@ -0,0 +1,6 @@
1
+ import type { App } from 'vue';
2
+ interface DefaultPlugins {
3
+ ui: boolean;
4
+ }
5
+ export declare function installFlowVuePlugins(app: App, {}?: DefaultPlugins): App<any>;
6
+ export {};
@@ -0,0 +1,6 @@
1
+ import ui from "@nuxt/ui/vue-plugin";
2
+ export function installFlowVuePlugins(app, {} = { ui: true }) {
3
+ if (ui)
4
+ app.use(ui);
5
+ return app;
6
+ }
package/src/styles.css ADDED
@@ -0,0 +1 @@
1
+ @import "tailwindcss";@import "@nuxt/ui";
package/app.d.ts DELETED
@@ -1 +0,0 @@
1
- export * from './dist/app';
package/bin/flow.mjs DELETED
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- import '@monkeyplus/flow-cli/cli';
@@ -1,5 +0,0 @@
1
- import type { RouteLocationNormalizedLoaded } from 'vue-router';
2
- export declare function useCookie(name: string, _opts?: any): {};
3
- export declare function refreshNuxtData(keys?: string | string[]): Promise<void>;
4
- export declare function useAsyncData(key: string, handlers: () => Promise<any>): Promise<any>;
5
- export declare function useRoute(): RouteLocationNormalizedLoaded;
@@ -1,12 +0,0 @@
1
- export function useCookie(name, _opts) {
2
- return {};
3
- }
4
- export function refreshNuxtData(keys) {
5
- return Promise.resolve();
6
- }
7
- export function useAsyncData(key, handlers) {
8
- return handlers();
9
- }
10
- export function useRoute() {
11
- return {};
12
- }
@@ -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,3 +0,0 @@
1
- import type { RuntimeConfig } from '@monkeyplus/flow-schema';
2
- declare const _default: (runtimeConfig: RuntimeConfig) => Promise<import("./flow").FlowApp>;
3
- export default _default;
@@ -1,23 +0,0 @@
1
- import { config, configure, render } from "eta";
2
- import { applyPlugins, createFlowApp } from "./flow.mjs";
3
- import plugins from "#build/plugins";
4
- export default async (runtimeConfig) => {
5
- const flow = createFlowApp({ runtimeConfig });
6
- try {
7
- await applyPlugins(flow, plugins);
8
- configure(flow.eta);
9
- flow.render = (view, data) => {
10
- const layout = "<%layout(`layouts/${it.view?.layout||'default'}`)%>";
11
- const getTemplate = flow.engines[view.engine || flow.engine];
12
- const base = `${layout}
13
- ${getTemplate(view.template)}`;
14
- return render(base, data || {}, {
15
- ...config,
16
- async: true
17
- });
18
- };
19
- } catch (err) {
20
- console.log(err);
21
- }
22
- return flow;
23
- };
@@ -1,80 +0,0 @@
1
- import type { RadixRouter } from 'radix3';
2
- import type { Hookable } from 'hookable';
3
- import type { FlowAppUtils, FlowPage, RuntimeConfig } from '@monkeyplus/flow-schema';
4
- declare type HookResult = Promise<void> | void;
5
- export interface FlowAppHooks {
6
- 'flow:pages': (page: FlowPage[]) => HookResult;
7
- 'eta:plugin': (options: any) => HookResult;
8
- 'page:scripts': (scripts: {
9
- head: string[];
10
- bodyEnd: string[];
11
- bodyStart: string[];
12
- }) => HookResult;
13
- 'page:links': (links: string[]) => HookResult;
14
- 'page:context': (ctx: {
15
- page: string;
16
- localeCode: string;
17
- }, utils: any, data: Record<string, any>) => HookResult;
18
- 'page:chunks': (bundle: string, scripts: {
19
- head: string[];
20
- body: string[];
21
- }) => HookResult;
22
- 'page:generate': (generate: any) => HookResult;
23
- }
24
- export interface FlowApp {
25
- router: {
26
- byUrl: RadixRouter<FlowPage['context']>;
27
- byName: RadixRouter<FlowPage['context']>;
28
- };
29
- hooks: Hookable<FlowAppHooks>;
30
- hook: FlowApp['hooks']['hook'];
31
- callHook: FlowApp['hooks']['callHook'];
32
- eta: any;
33
- app: {
34
- utils: FlowAppUtils;
35
- plugins: Record<string, any>;
36
- globals: Record<string, any>;
37
- };
38
- engine: string;
39
- site: {
40
- origin: string;
41
- };
42
- engines: Record<string, (template: string) => string>;
43
- generate: boolean;
44
- render: (view: Record<string, string>, data: any) => Promise<string> | void | string;
45
- provide: (name: string, value: any) => void;
46
- setUtil: (name: string, value: any) => void;
47
- [key: string]: any;
48
- }
49
- export declare const FlowPluginIndicator = "__flow_plugin";
50
- export declare const NuxtPluginIndicator = "__nuxt_plugin";
51
- export interface Plugin<Injections extends Record<string, any> = Record<string, any>> {
52
- (flow: FlowApp): Promise<void> | Promise<{
53
- provide?: Injections;
54
- }> | void | {
55
- provide?: Injections;
56
- };
57
- [FlowPluginIndicator]?: true;
58
- }
59
- interface OptionsApp {
60
- runtimeConfig: RuntimeConfig;
61
- }
62
- export declare function createFlowApp({ runtimeConfig }: OptionsApp): FlowApp;
63
- export declare function defineFlowPlugin<T>(plugin: Plugin<T>): Plugin<T>;
64
- export declare function defineNuxtPlugin<T>(plugin: Plugin<T>): Plugin<T>;
65
- export declare function applyPlugin(flowApp: FlowApp, plugin: Plugin): Promise<void>;
66
- export declare function applyPlugins(flowApp: FlowApp, plugins: Plugin[]): Promise<void>;
67
- /**
68
- * Ensures that the setup function passed in has access to the Nuxt instance via `useNuxt`.
69
- *
70
- * @param flow A Flow instance
71
- * @param setup The function to call
72
- */
73
- export declare function callWithFlow<T extends (...args: any[]) => any>(flow: FlowApp, setup: T, args?: Parameters<T>): Promise<ReturnType<T>>;
74
- /**
75
- * Returns the current Nuxt instance.
76
- */
77
- export declare function useFlowApp(): FlowApp;
78
- export declare function useRuntimeConfig(): RuntimeConfig;
79
- export declare function resolveFiles(path: string, pattern: string | string[]): Promise<any[]>;
80
- export {};
package/dist/app/flow.mjs DELETED
@@ -1,88 +0,0 @@
1
- import { createRouter } from "radix3";
2
- import { createHooks } from "hookable";
3
- import { getContext } from "unctx";
4
- import { globby } from "globby";
5
- import { join, resolve } from "pathe";
6
- const flowAppCtx = getContext("flow-app");
7
- export const FlowPluginIndicator = "__flow_plugin";
8
- export const NuxtPluginIndicator = "__nuxt_plugin";
9
- export function createFlowApp({ runtimeConfig }) {
10
- const viewsDir = join(runtimeConfig.app.rootDir, "views");
11
- const flowApp = {
12
- router: { byUrl: createRouter(), byName: createRouter() },
13
- app: {
14
- utils: {},
15
- globals: {}
16
- },
17
- eta: {
18
- views: viewsDir,
19
- plugins: []
20
- },
21
- engine: "eta",
22
- engines: {},
23
- site: {
24
- origin: `${process.env.URL || "http://localhost"}`
25
- },
26
- generate: runtimeConfig.generate
27
- };
28
- flowApp.engines.eta = (template) => {
29
- return `<%~ await includeFile('templates/${template}',it) %>`;
30
- };
31
- flowApp.hooks = createHooks();
32
- flowApp.hook = flowApp.hooks.hook;
33
- flowApp.callHook = flowApp.hooks.callHook;
34
- flowApp.provide = (name, value) => {
35
- const $name = `$${name}`;
36
- defineGetter(flowApp, $name, value);
37
- };
38
- flowApp.setUtil = (name, method) => {
39
- flowApp.app.utils[name] = method;
40
- };
41
- flowApp.hook("eta:plugin", (_plugin) => {
42
- flowApp.eta.plugins.push(_plugin);
43
- });
44
- flowApp.provide("config", runtimeConfig);
45
- return flowApp;
46
- }
47
- export function defineFlowPlugin(plugin) {
48
- plugin[FlowPluginIndicator] = true;
49
- return plugin;
50
- }
51
- export function defineNuxtPlugin(plugin) {
52
- plugin[NuxtPluginIndicator] = true;
53
- return plugin;
54
- }
55
- export async function applyPlugin(flowApp, plugin) {
56
- if (typeof plugin !== "function")
57
- return;
58
- const { provide } = await callWithFlow(flowApp, plugin, [flowApp]) || {};
59
- if (provide && typeof provide === "object") {
60
- for (const key in provide)
61
- flowApp.provide(key, provide[key]);
62
- }
63
- }
64
- export async function applyPlugins(flowApp, plugins) {
65
- for (const plugin of plugins)
66
- await applyPlugin(flowApp, plugin);
67
- }
68
- export function callWithFlow(flow, setup, args) {
69
- const fn = () => args ? setup(...args) : setup();
70
- flowAppCtx.set(flow);
71
- return flowAppCtx.callAsync(flow, fn);
72
- }
73
- export function useFlowApp() {
74
- const flowAppInstance = flowAppCtx.use();
75
- if (!flowAppInstance)
76
- throw new Error("flow instance unavailable");
77
- return flowAppInstance;
78
- }
79
- export function useRuntimeConfig() {
80
- return useFlowApp().$config;
81
- }
82
- function defineGetter(obj, key, val) {
83
- Object.defineProperty(obj, key, { get: () => val });
84
- }
85
- export async function resolveFiles(path, pattern) {
86
- const files = await globby(pattern, { cwd: path, followSymbolicLinks: true });
87
- return files.filter((file) => !file.includes("copy.ts")).map((p) => resolve(path, p));
88
- }
@@ -1,3 +0,0 @@
1
- export * from './flow';
2
- export * from './composables';
3
- export { useHead } from '#head';
@@ -1,3 +0,0 @@
1
- export * from "./flow.mjs";
2
- export * from "./composables/index.mjs";
3
- export { useHead } from "#head";
@@ -1,247 +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 { isIgnoredFlow, 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, 60);
235
- await _doBuild();
236
- viteServer.watcher.on("all", (_event, file) => {
237
- if (file.includes("/pages/"))
238
- return;
239
- file = normalize(file);
240
- if (file.indexOf(ctx.nuxt.options.buildDir) === 0 || isIgnoredFlow(file))
241
- return;
242
- doBuild();
243
- });
244
- ctx.nuxt.hook("app:templatesGenerated", () => doBuild());
245
- }
246
-
247
- export { bundleRequest, initViteDevBundler };
@@ -1,37 +0,0 @@
1
- import 'node:fs';
2
- import { hash } from 'ohash';
3
- import 'pathe';
4
- import { ExternalsDefaults, isExternal } 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 };