@monkeyplus/flow 5.0.0-rc.1 → 5.0.0-rc.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/app/composables/index.d.ts +2 -1
- package/dist/core/runtime/nitro/renderer.mjs +5 -1
- package/dist/index.mjs +25 -6
- package/dist/pages/runtime/index.d.ts +2 -2
- package/dist/pages/runtime/index.mjs +4 -4
- package/dist/pages/runtime/plugin.mjs +16 -10
- package/package.json +21 -9
- package/build.config.ts +0 -25
- package/src/app/composables/index.ts +0 -20
- package/src/app/entry.ts +0 -36
- package/src/app/flow.ts +0 -157
- package/src/app/index.ts +0 -5
- package/src/auto-imports/module.ts +0 -143
- package/src/auto-imports/presets.ts +0 -49
- package/src/auto-imports/transform.ts +0 -48
- package/src/core/app.ts +0 -90
- package/src/core/builder.ts +0 -60
- package/src/core/flow.ts +0 -93
- package/src/core/modules.ts +0 -32
- package/src/core/nitro.ts +0 -206
- package/src/core/plugins/import-protection.ts +0 -49
- package/src/core/plugins/unctx.ts +0 -31
- package/src/core/runtime/nitro/flow.ts +0 -43
- package/src/core/runtime/nitro/paths.ts +0 -20
- package/src/core/runtime/nitro/renderer.ts +0 -74
- package/src/core/templates.ts +0 -119
- package/src/core/vite/builder/css.ts +0 -28
- package/src/core/vite/builder/dev-bundler.ts +0 -248
- package/src/core/vite/builder/index.ts +0 -96
- package/src/core/vite/builder/manifest.ts +0 -33
- package/src/core/vite/builder/plugins/analyze.ts +0 -32
- package/src/core/vite/builder/plugins/cache-dir.ts +0 -13
- package/src/core/vite/builder/plugins/dynamic-base.ts +0 -64
- package/src/core/vite/builder/plugins/virtual.ts +0 -45
- package/src/core/vite/builder/server.ts +0 -164
- package/src/core/vite/builder/types/index.ts +0 -13
- package/src/core/vite/builder/utils/index.ts +0 -53
- package/src/core/vite/builder/utils/warmup.ts +0 -27
- package/src/core/vite/builder/utils/wpfs.ts +0 -7
- package/src/core/vite/builder/vite-node.ts +0 -110
- package/src/core/vite/client/index.ts +0 -63
- package/src/dirs.ts +0 -8
- package/src/head/module.ts +0 -37
- package/src/head/runtime/composables.ts +0 -16
- package/src/head/runtime/index.ts +0 -1
- package/src/head/runtime/plugin.ts +0 -12
- package/src/index.ts +0 -2
- package/src/pages/module.ts +0 -55
- package/src/pages/runtime/helpers/chunks.ts +0 -0
- package/src/pages/runtime/helpers/index.ts +0 -33
- package/src/pages/runtime/index.ts +0 -9
- package/src/pages/runtime/plugin.ts +0 -65
- package/src/pages/templates.ts +0 -20
- package/src/pages/utils.ts +0 -49
- package/src/vite-client/module.ts +0 -84
- package/src/vite-client/runtime/injectManifest.ts +0 -188
- package/src/vite-client/runtime/plugin.ts +0 -33
|
@@ -1,74 +0,0 @@
|
|
|
1
|
-
import { eventHandler, useQuery } from 'h3';
|
|
2
|
-
import type{ FlowApp } from '#app/flow';
|
|
3
|
-
|
|
4
|
-
export default eventHandler(async(event) => {
|
|
5
|
-
const url = event.req.url?.split('?')[0];
|
|
6
|
-
|
|
7
|
-
// console.debug(url);
|
|
8
|
-
|
|
9
|
-
const flow = event.context.flow as FlowApp;
|
|
10
|
-
if (url.includes('_urls')) {
|
|
11
|
-
const urls = await flow.app.utils.getUrls();
|
|
12
|
-
return urls;
|
|
13
|
-
}
|
|
14
|
-
const scripts = { head: [], bodyStart: [], bodyEnd: [] };
|
|
15
|
-
const chunks = { head: [], body: [] };
|
|
16
|
-
const generate = {};
|
|
17
|
-
|
|
18
|
-
// console.log(flow);
|
|
19
|
-
const { page, locale, params, view } = flow.router.byUrl.lookup(url!) || {};
|
|
20
|
-
// Truncate page
|
|
21
|
-
if (!page) return;
|
|
22
|
-
|
|
23
|
-
await flow.callHook('page:scripts', scripts);
|
|
24
|
-
if (view.bundle)
|
|
25
|
-
await flow.callHook('page:chunks', view.bundle, chunks);
|
|
26
|
-
|
|
27
|
-
const templateContext = {} as any;
|
|
28
|
-
|
|
29
|
-
const dynamyc = params?._;
|
|
30
|
-
const contextPage = {} as any;
|
|
31
|
-
const utils = Object.assign({ getLocale: () => locale }, flow.app.utils);
|
|
32
|
-
templateContext.url = url;
|
|
33
|
-
templateContext.locale = locale;
|
|
34
|
-
templateContext.view = view;
|
|
35
|
-
|
|
36
|
-
if (dynamyc && page.dynamic) {
|
|
37
|
-
const pages = await page.dynamic.method({ locale, utils });
|
|
38
|
-
const dynamicPage = pages.find((_page) => _page.url === dynamyc);
|
|
39
|
-
if (!dynamicPage) return;
|
|
40
|
-
if (page.dynamic.assign)
|
|
41
|
-
templateContext[page.dynamic.assign] = dynamicPage.context;
|
|
42
|
-
|
|
43
|
-
contextPage.dynamyc = dynamicPage;
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
templateContext.seo = {};
|
|
47
|
-
templateContext.context = {};
|
|
48
|
-
templateContext.sharedContext = {};
|
|
49
|
-
templateContext.utils = utils;
|
|
50
|
-
templateContext.seo = await page.seo?.({ ...contextPage, utils }) || {};
|
|
51
|
-
templateContext.context = await page.context?.({ ...contextPage, utils }) || {};
|
|
52
|
-
templateContext.getHeadScripts = () => {
|
|
53
|
-
return scripts.head.join('\n');
|
|
54
|
-
};
|
|
55
|
-
templateContext.getHeadChunks = () => {
|
|
56
|
-
return chunks.head.join('\n');
|
|
57
|
-
};
|
|
58
|
-
templateContext.getBodyChunks = () => {
|
|
59
|
-
return chunks.body.join('\n');
|
|
60
|
-
};
|
|
61
|
-
const query = useQuery(event);
|
|
62
|
-
if (query?.context)
|
|
63
|
-
return { ...templateContext, utils: Object.keys(utils) };
|
|
64
|
-
|
|
65
|
-
const html = await flow.render(view as any, templateContext);
|
|
66
|
-
event.res.setHeader('Content-Type', 'text/html;charset=UTF-8');
|
|
67
|
-
|
|
68
|
-
if (flow.generate) {
|
|
69
|
-
await flow.callHook('page:generate', generate);
|
|
70
|
-
globalThis.generate = generate;
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
return html;
|
|
74
|
-
});
|
package/src/core/templates.ts
DELETED
|
@@ -1,119 +0,0 @@
|
|
|
1
|
-
import { templateUtils } from '@monkeyplus/flow-kit';
|
|
2
|
-
import type { Nuxt, NuxtApp, NuxtTemplate } from '@monkeyplus/flow-schema';
|
|
3
|
-
import { genArrayFromRaw, genDynamicImport, genString } from 'knitwork';
|
|
4
|
-
import { isAbsolute, join, relative } from 'pathe';
|
|
5
|
-
import { generateTypes, resolveSchema } from 'untyped';
|
|
6
|
-
|
|
7
|
-
import escapeRE from 'escape-string-regexp';
|
|
8
|
-
|
|
9
|
-
export interface TemplateContext {
|
|
10
|
-
nuxt: Nuxt
|
|
11
|
-
app: NuxtApp
|
|
12
|
-
}
|
|
13
|
-
// export const cssTemplate = {
|
|
14
|
-
// filename: 'css.mjs',
|
|
15
|
-
// getContents: (ctx: TemplateContext) => ctx.flow.options.css.map((i) => genImport(i)).join('\n'),
|
|
16
|
-
// };
|
|
17
|
-
|
|
18
|
-
export const serverPluginTemplate = {
|
|
19
|
-
filename: 'plugins/server.mjs',
|
|
20
|
-
getContents(ctx: TemplateContext) {
|
|
21
|
-
const serverPlugins = ctx.app.plugins;
|
|
22
|
-
return [
|
|
23
|
-
templateUtils.importSources(serverPlugins.map((p) => p.src)),
|
|
24
|
-
`export default ${genArrayFromRaw([
|
|
25
|
-
...serverPlugins.map((p) => templateUtils.importName(p.src)),
|
|
26
|
-
])}`,
|
|
27
|
-
].join('\n');
|
|
28
|
-
},
|
|
29
|
-
};
|
|
30
|
-
|
|
31
|
-
export const pluginsDeclaration = {
|
|
32
|
-
filename: 'types/plugins.d.ts',
|
|
33
|
-
getContents: (ctx: TemplateContext) => {
|
|
34
|
-
// console.log(ctx);
|
|
35
|
-
|
|
36
|
-
const EXTENSION_RE = new RegExp(`(?<=\\w)(${ctx.nuxt.options.extensions.map((e) => escapeRE(e)).join('|')})$`, 'g');
|
|
37
|
-
const tsImports = ctx.app.plugins.map((p) => (isAbsolute(p.src) ? relative(join(ctx.nuxt.options.buildDir, 'types'), p.src) : p.src).replace(EXTENSION_RE, ''));
|
|
38
|
-
|
|
39
|
-
return `// Generated by Flow'
|
|
40
|
-
import type { Plugin } from '#app'
|
|
41
|
-
|
|
42
|
-
type Decorate<T extends Record<string, any>> = { [K in keyof T as K extends string ? \`$\${K}\` : never]: T[K] }
|
|
43
|
-
|
|
44
|
-
type InjectionType<A extends Plugin> = A extends Plugin<infer T> ? Decorate<T> : unknown
|
|
45
|
-
|
|
46
|
-
type FlowAppInjections = \n ${tsImports.map((p) => `InjectionType<typeof ${genDynamicImport(p, { wrapper: false })}.default>`).join(' &\n ')}
|
|
47
|
-
|
|
48
|
-
declare module '#app' {
|
|
49
|
-
interface FlowApp extends FlowAppInjections { }
|
|
50
|
-
}
|
|
51
|
-
// TODO: Insert extend types
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
export { }
|
|
55
|
-
`;
|
|
56
|
-
},
|
|
57
|
-
};
|
|
58
|
-
|
|
59
|
-
const adHocModules = ['auto-imports', 'meta', 'pages', 'vite-client'];
|
|
60
|
-
export const schemaTemplate = {
|
|
61
|
-
filename: 'types/schema.d.ts',
|
|
62
|
-
getContents: ({ nuxt }: TemplateContext) => {
|
|
63
|
-
const moduleInfo = nuxt.options._installedModules.map((m) => ({
|
|
64
|
-
...m.meta || {},
|
|
65
|
-
importName: m.entryPath || m.meta?.name,
|
|
66
|
-
})).filter((m) => m.configKey && m.name && !adHocModules.includes(m.name));
|
|
67
|
-
|
|
68
|
-
return [
|
|
69
|
-
'import { FlowModule } from \'@monkeyplus/flow-schema\'',
|
|
70
|
-
'declare module \'@monkeyplus/flow-schema\' {',
|
|
71
|
-
' interface FlowConfig {',
|
|
72
|
-
...moduleInfo.filter(Boolean).map((meta) =>
|
|
73
|
-
` [${genString(meta.configKey)}]?: typeof ${genDynamicImport(meta.importName, { wrapper: false })}.default extends FlowModule<infer O> ? Partial<O> : Record<string, any>`,
|
|
74
|
-
),
|
|
75
|
-
' }',
|
|
76
|
-
generateTypes(resolveSchema(Object.fromEntries(Object.entries(nuxt.options.runtimeConfig).filter(([key]) => key !== 'public'))),
|
|
77
|
-
{
|
|
78
|
-
interfaceName: 'RuntimeConfig',
|
|
79
|
-
addExport: false,
|
|
80
|
-
addDefaults: false,
|
|
81
|
-
allowExtraKeys: false,
|
|
82
|
-
indentation: 2,
|
|
83
|
-
}),
|
|
84
|
-
generateTypes(resolveSchema(nuxt.options.runtimeConfig.public),
|
|
85
|
-
{
|
|
86
|
-
interfaceName: 'PublicRuntimeConfig',
|
|
87
|
-
addExport: false,
|
|
88
|
-
addDefaults: false,
|
|
89
|
-
allowExtraKeys: false,
|
|
90
|
-
indentation: 2,
|
|
91
|
-
}),
|
|
92
|
-
'}',
|
|
93
|
-
].join('\n');
|
|
94
|
-
},
|
|
95
|
-
};
|
|
96
|
-
|
|
97
|
-
export const publicPathTemplate: NuxtTemplate = {
|
|
98
|
-
filename: 'paths.mjs',
|
|
99
|
-
getContents({ nuxt }) {
|
|
100
|
-
return [
|
|
101
|
-
'import { joinURL } from \'ufo\'',
|
|
102
|
-
!nuxt.options.dev && 'import { useRuntimeConfig } from \'#internal/nitro\'',
|
|
103
|
-
|
|
104
|
-
nuxt.options.dev
|
|
105
|
-
? `const appConfig = ${JSON.stringify(nuxt.options.app)}`
|
|
106
|
-
: 'const appConfig = useRuntimeConfig().app',
|
|
107
|
-
|
|
108
|
-
'export const baseURL = () => appConfig.baseURL',
|
|
109
|
-
'export const buildAssetsDir = () => appConfig.buildAssetsDir',
|
|
110
|
-
|
|
111
|
-
'export const buildAssetsURL = (...path) => joinURL(publicAssetsURL(), buildAssetsDir(), ...path)',
|
|
112
|
-
|
|
113
|
-
'export const publicAssetsURL = (...path) => {',
|
|
114
|
-
' const publicBase = appConfig.cdnURL || appConfig.baseURL',
|
|
115
|
-
' return path.length ? joinURL(publicBase, ...path) : publicBase',
|
|
116
|
-
'}',
|
|
117
|
-
].filter(Boolean).join('\n');
|
|
118
|
-
},
|
|
119
|
-
};
|
|
@@ -1,28 +0,0 @@
|
|
|
1
|
-
import { requireModule } from '@monkeyplus/flow-kit';
|
|
2
|
-
import type { Flow } from '@monkeyplus/flow-schema';
|
|
3
|
-
import { distDir } from '../../../dirs';
|
|
4
|
-
import type { ViteOptions } from './types';
|
|
5
|
-
|
|
6
|
-
export function resolveCSSOptions(flow: Flow): ViteOptions['css'] {
|
|
7
|
-
const css: ViteOptions['css'] & { postcss: Exclude<ViteOptions['css']['postcss'], string> } = {
|
|
8
|
-
postcss: {
|
|
9
|
-
plugins: [],
|
|
10
|
-
},
|
|
11
|
-
};
|
|
12
|
-
|
|
13
|
-
const lastPlugins = ['autoprefixer', 'cssnano'];
|
|
14
|
-
css.postcss.plugins = Object.entries(flow.options.postcss?.plugins || {})
|
|
15
|
-
.sort((a, b) => lastPlugins.indexOf(a[0]) - lastPlugins.indexOf(b[0]))
|
|
16
|
-
.filter(([, opts]) => opts)
|
|
17
|
-
.map(([name, opts]) => {
|
|
18
|
-
const plugin = requireModule(name, {
|
|
19
|
-
paths: [
|
|
20
|
-
...flow.options.modulesDir,
|
|
21
|
-
distDir,
|
|
22
|
-
],
|
|
23
|
-
});
|
|
24
|
-
return plugin(opts);
|
|
25
|
-
});
|
|
26
|
-
|
|
27
|
-
return css;
|
|
28
|
-
}
|
|
@@ -1,248 +0,0 @@
|
|
|
1
|
-
import { pathToFileURL } from 'node:url';
|
|
2
|
-
import { existsSync } from 'node:fs';
|
|
3
|
-
import { builtinModules } from 'node:module';
|
|
4
|
-
import { resolve } from 'pathe';
|
|
5
|
-
import type * as vite from 'vite';
|
|
6
|
-
import type { ExternalsOptions } from 'externality';
|
|
7
|
-
import { ExternalsDefaults, isExternal as _isExternal } from 'externality';
|
|
8
|
-
import { genDynamicImport, genObjectFromRawEntries } from 'knitwork';
|
|
9
|
-
import { hashId, uniq } from './utils';
|
|
10
|
-
|
|
11
|
-
export interface TransformChunk {
|
|
12
|
-
id: string
|
|
13
|
-
code: string
|
|
14
|
-
deps: string[]
|
|
15
|
-
parents: string[]
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
export interface SSRTransformResult {
|
|
19
|
-
code: string
|
|
20
|
-
map: object
|
|
21
|
-
deps: string[]
|
|
22
|
-
dynamicDeps: string[]
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
export interface TransformOptions {
|
|
26
|
-
viteServer: vite.ViteDevServer
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
function isExternal(opts: TransformOptions, id: string) {
|
|
30
|
-
// Externals
|
|
31
|
-
const ssrConfig = (opts.viteServer.config as any).ssr;
|
|
32
|
-
|
|
33
|
-
const externalOpts: ExternalsOptions = {
|
|
34
|
-
inline: [
|
|
35
|
-
/virtual:/,
|
|
36
|
-
/\.ts$/,
|
|
37
|
-
...ExternalsDefaults.inline,
|
|
38
|
-
...ssrConfig.noExternal,
|
|
39
|
-
],
|
|
40
|
-
external: [
|
|
41
|
-
// * Remove to omit fixed un build
|
|
42
|
-
// ...ssrConfig.external,
|
|
43
|
-
/node_modules/,
|
|
44
|
-
],
|
|
45
|
-
resolve: {
|
|
46
|
-
type: 'module',
|
|
47
|
-
extensions: ['.ts', '.js', '.json', '.vue', '.mjs', '.jsx', '.tsx', '.wasm'],
|
|
48
|
-
},
|
|
49
|
-
};
|
|
50
|
-
return _isExternal(id, opts.viteServer.config.root, externalOpts);
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
async function transformRequest(opts: TransformOptions, id: string) {
|
|
54
|
-
// Virtual modules start with `\0`
|
|
55
|
-
if (id && id.startsWith('/@id/__x00__'))
|
|
56
|
-
id = `\0${id.slice('/@id/__x00__'.length)}`;
|
|
57
|
-
|
|
58
|
-
if (id && id.startsWith('/@id/'))
|
|
59
|
-
id = id.slice('/@id/'.length);
|
|
60
|
-
|
|
61
|
-
if (id && id.startsWith('/@fs/')) {
|
|
62
|
-
// Absolute path
|
|
63
|
-
id = id.slice('/@fs'.length);
|
|
64
|
-
// On Windows, this may be `/C:/my/path` at this point, in which case we want to remove the `/`
|
|
65
|
-
if (id.match(/^\/\w:/))
|
|
66
|
-
id = id.slice(1);
|
|
67
|
-
}
|
|
68
|
-
else if (!id.includes('entry') && id.startsWith('/')) {
|
|
69
|
-
// Relative to the root directory
|
|
70
|
-
const resolvedPath = resolve(opts.viteServer.config.root, `.${id}`);
|
|
71
|
-
if (existsSync(resolvedPath))
|
|
72
|
-
id = resolvedPath;
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
// Vite will add ?v=123 to bypass browser cache
|
|
76
|
-
// Remove for externals
|
|
77
|
-
const withoutVersionQuery = id.replace(/\?v=\w+$/, '');
|
|
78
|
-
if (await isExternal(opts, withoutVersionQuery)) {
|
|
79
|
-
const path = builtinModules.includes(withoutVersionQuery.split('node:').pop())
|
|
80
|
-
? withoutVersionQuery
|
|
81
|
-
: pathToFileURL(withoutVersionQuery).href;
|
|
82
|
-
return {
|
|
83
|
-
code: `(global, module, _, exports, importMeta, ssrImport, ssrDynamicImport, ssrExportAll) =>
|
|
84
|
-
${genDynamicImport(path, { wrapper: false })}
|
|
85
|
-
.then(r => {
|
|
86
|
-
if (r.default && r.default.__esModule)
|
|
87
|
-
r = r.default
|
|
88
|
-
exports.default = r.default
|
|
89
|
-
ssrExportAll(r)
|
|
90
|
-
})
|
|
91
|
-
.catch(e => {
|
|
92
|
-
console.error(e)
|
|
93
|
-
throw new Error(${JSON.stringify(`[vite dev] Error loading external "${id}".`)})
|
|
94
|
-
})`,
|
|
95
|
-
deps: [],
|
|
96
|
-
dynamicDeps: [],
|
|
97
|
-
};
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
// Transform
|
|
101
|
-
const res: SSRTransformResult = await opts.viteServer.transformRequest(id, { ssr: true }).catch((err) => {
|
|
102
|
-
// eslint-disable-next-line no-console
|
|
103
|
-
console.warn(`[SSR] Error transforming ${id}:`, err);
|
|
104
|
-
// console.error(err)
|
|
105
|
-
}) as SSRTransformResult || { code: '', map: {}, deps: [], dynamicDeps: [] };
|
|
106
|
-
|
|
107
|
-
// Wrap into a vite module
|
|
108
|
-
const code = `async function (global, module, exports, __vite_ssr_exports__, __vite_ssr_import_meta__, __vite_ssr_import__, __vite_ssr_dynamic_import__, __vite_ssr_exportAll__) {
|
|
109
|
-
${res.code || '/* empty */'};
|
|
110
|
-
}`;
|
|
111
|
-
return { code, deps: res.deps || [], dynamicDeps: res.dynamicDeps || [] };
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
async function transformRequestRecursive(opts: TransformOptions, id: any, parent = '<entry>', chunks: Record<string, TransformChunk> = {}) {
|
|
115
|
-
if (chunks[id]) {
|
|
116
|
-
chunks[id].parents.push(parent);
|
|
117
|
-
return;
|
|
118
|
-
}
|
|
119
|
-
const res = await transformRequest(opts, id);
|
|
120
|
-
const deps = uniq([...res.deps, ...res.dynamicDeps]);
|
|
121
|
-
|
|
122
|
-
chunks[id] = {
|
|
123
|
-
id,
|
|
124
|
-
code: res.code,
|
|
125
|
-
deps,
|
|
126
|
-
parents: [parent],
|
|
127
|
-
} as TransformChunk;
|
|
128
|
-
for (const dep of deps)
|
|
129
|
-
await transformRequestRecursive(opts, dep, id, chunks);
|
|
130
|
-
|
|
131
|
-
return Object.values(chunks);
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
export async function bundleRequest(opts: TransformOptions, entryURL: string) {
|
|
135
|
-
const chunks = await transformRequestRecursive(opts, entryURL);
|
|
136
|
-
|
|
137
|
-
const listIds = (ids: string[]) => ids.map((id) => `// - ${id} (${hashId(id)})`).join('\n');
|
|
138
|
-
const chunksCode = chunks!.map((chunk) => `
|
|
139
|
-
// --------------------
|
|
140
|
-
// Request: ${chunk.id}
|
|
141
|
-
// Parents: \n${listIds(chunk.parents)}
|
|
142
|
-
// Dependencies: \n${listIds(chunk.deps)}
|
|
143
|
-
// --------------------
|
|
144
|
-
const ${hashId(chunk.id)} = ${chunk.code}
|
|
145
|
-
`).join('\n');
|
|
146
|
-
|
|
147
|
-
const manifestCode = `const __modules__ = ${
|
|
148
|
-
genObjectFromRawEntries(chunks!.map((chunk) => [chunk.id, hashId(chunk.id)]))
|
|
149
|
-
}`;
|
|
150
|
-
|
|
151
|
-
// https://github.com/vitejs/vite/blob/main/packages/vite/src/node/ssr/ssrModuleLoader.ts
|
|
152
|
-
const ssrModuleLoader = `
|
|
153
|
-
const __pendingModules__ = new Map()
|
|
154
|
-
const __pendingImports__ = new Map()
|
|
155
|
-
const __ssrContext__ = { global: globalThis }
|
|
156
|
-
|
|
157
|
-
function __ssrLoadModule__(url, urlStack = []) {
|
|
158
|
-
const pendingModule = __pendingModules__.get(url)
|
|
159
|
-
if (pendingModule) { return pendingModule }
|
|
160
|
-
const modulePromise = __instantiateModule__(url, urlStack)
|
|
161
|
-
__pendingModules__.set(url, modulePromise)
|
|
162
|
-
modulePromise.catch(() => { __pendingModules__.delete(url) })
|
|
163
|
-
.finally(() => { __pendingModules__.delete(url) })
|
|
164
|
-
return modulePromise
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
async function __instantiateModule__(url, urlStack) {
|
|
168
|
-
const mod = __modules__[url]
|
|
169
|
-
if (mod.stubModule) { return mod.stubModule }
|
|
170
|
-
const stubModule = { [Symbol.toStringTag]: 'Module' }
|
|
171
|
-
Object.defineProperty(stubModule, '__esModule', { value: true })
|
|
172
|
-
mod.stubModule = stubModule
|
|
173
|
-
// https://vitejs.dev/guide/api-hmr.html
|
|
174
|
-
const importMeta = { url, hot: { accept() {}, prune() {}, dispose() {}, invalidate() {}, decline() {}, on() {} } }
|
|
175
|
-
urlStack = urlStack.concat(url)
|
|
176
|
-
const isCircular = url => urlStack.includes(url)
|
|
177
|
-
const pendingDeps = []
|
|
178
|
-
const ssrImport = async (dep) => {
|
|
179
|
-
// TODO: Handle externals if dep[0] !== '.' | '/'
|
|
180
|
-
if (!isCircular(dep) && !__pendingImports__.get(dep)?.some(isCircular)) {
|
|
181
|
-
pendingDeps.push(dep)
|
|
182
|
-
if (pendingDeps.length === 1) {
|
|
183
|
-
__pendingImports__.set(url, pendingDeps)
|
|
184
|
-
}
|
|
185
|
-
await __ssrLoadModule__(dep, urlStack)
|
|
186
|
-
if (pendingDeps.length === 1) {
|
|
187
|
-
__pendingImports__.delete(url)
|
|
188
|
-
} else {
|
|
189
|
-
pendingDeps.splice(pendingDeps.indexOf(dep), 1)
|
|
190
|
-
}
|
|
191
|
-
}
|
|
192
|
-
return __modules__[dep].stubModule
|
|
193
|
-
}
|
|
194
|
-
function ssrDynamicImport (dep) {
|
|
195
|
-
// TODO: Handle dynamic import starting with . relative to url
|
|
196
|
-
return ssrImport(dep)
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
function ssrExportAll(sourceModule) {
|
|
200
|
-
for (const key in sourceModule) {
|
|
201
|
-
if (key !== 'default') {
|
|
202
|
-
try {
|
|
203
|
-
Object.defineProperty(stubModule, key, {
|
|
204
|
-
enumerable: true,
|
|
205
|
-
configurable: true,
|
|
206
|
-
get() { return sourceModule[key] }
|
|
207
|
-
})
|
|
208
|
-
} catch (_err) { }
|
|
209
|
-
}
|
|
210
|
-
}
|
|
211
|
-
}
|
|
212
|
-
|
|
213
|
-
const cjsModule = {
|
|
214
|
-
get exports () {
|
|
215
|
-
return stubModule.default
|
|
216
|
-
},
|
|
217
|
-
set exports (v) {
|
|
218
|
-
stubModule.default = v
|
|
219
|
-
},
|
|
220
|
-
}
|
|
221
|
-
|
|
222
|
-
await mod(
|
|
223
|
-
__ssrContext__.global,
|
|
224
|
-
cjsModule,
|
|
225
|
-
stubModule.default,
|
|
226
|
-
stubModule,
|
|
227
|
-
importMeta,
|
|
228
|
-
ssrImport,
|
|
229
|
-
ssrDynamicImport,
|
|
230
|
-
ssrExportAll
|
|
231
|
-
)
|
|
232
|
-
|
|
233
|
-
return stubModule
|
|
234
|
-
}
|
|
235
|
-
`;
|
|
236
|
-
|
|
237
|
-
const code = [
|
|
238
|
-
chunksCode,
|
|
239
|
-
manifestCode,
|
|
240
|
-
ssrModuleLoader,
|
|
241
|
-
`export default await __ssrLoadModule__(${JSON.stringify(entryURL)})`,
|
|
242
|
-
].join('\n\n');
|
|
243
|
-
|
|
244
|
-
return {
|
|
245
|
-
code,
|
|
246
|
-
ids: chunks!.map((i) => i.id),
|
|
247
|
-
};
|
|
248
|
-
}
|
|
@@ -1,96 +0,0 @@
|
|
|
1
|
-
import { isIgnoredFlow, logger } from '@monkeyplus/flow-kit';
|
|
2
|
-
import type { Flow } from '@monkeyplus/flow-schema';
|
|
3
|
-
import { getPort } from 'get-port-please';
|
|
4
|
-
import * as vite from 'vite';
|
|
5
|
-
import { resolve } from 'pathe';
|
|
6
|
-
import { sanitizeFilePath } from 'mlly';
|
|
7
|
-
import replace from '@rollup/plugin-replace';
|
|
8
|
-
import { warmupViteServer } from './utils/warmup';
|
|
9
|
-
import { buildServer } from './server';
|
|
10
|
-
import type { ViteBuildContext } from './types';
|
|
11
|
-
import virtual from './plugins/virtual';
|
|
12
|
-
import { DynamicBasePlugin } from './plugins/dynamic-base';
|
|
13
|
-
|
|
14
|
-
export async function bundleVite(flow: Flow) {
|
|
15
|
-
const hmrPortDefault = 24678; // Vite's default HMR port
|
|
16
|
-
const hmrPort = await getPort({
|
|
17
|
-
port: hmrPortDefault,
|
|
18
|
-
ports: Array.from({ length: 20 }, (_, i) => hmrPortDefault + 1 + i),
|
|
19
|
-
});
|
|
20
|
-
|
|
21
|
-
const ctx: ViteBuildContext = {
|
|
22
|
-
nuxt: flow,
|
|
23
|
-
flow,
|
|
24
|
-
config: vite.mergeConfig({
|
|
25
|
-
mode: flow.options.dev ? 'development' : undefined,
|
|
26
|
-
resolve: {
|
|
27
|
-
alias: {
|
|
28
|
-
...flow.options.alias,
|
|
29
|
-
'#app': flow.options.appDir,
|
|
30
|
-
'#build/plugins': resolve(flow.options.buildDir, 'plugins/server'),
|
|
31
|
-
'#build': flow.options.buildDir,
|
|
32
|
-
'/entry.mjs': resolve(flow.options.appDir, 'entry'),
|
|
33
|
-
|
|
34
|
-
},
|
|
35
|
-
},
|
|
36
|
-
optimizeDeps: {
|
|
37
|
-
entries: [
|
|
38
|
-
resolve(flow.options.appDir, 'entry.ts'),
|
|
39
|
-
],
|
|
40
|
-
include: [],
|
|
41
|
-
},
|
|
42
|
-
// css: resolveCSSOptions(nuxt),
|
|
43
|
-
build: {
|
|
44
|
-
rollupOptions: {
|
|
45
|
-
output: { sanitizeFileName: sanitizeFilePath },
|
|
46
|
-
input: resolve(flow.options.appDir, 'entry'),
|
|
47
|
-
},
|
|
48
|
-
},
|
|
49
|
-
plugins: [
|
|
50
|
-
replace({
|
|
51
|
-
...Object.fromEntries([';', '(', '{', '}', ' ', '\t', '\n'].map((d) => [`${d}global.`, `${d}globalThis.`])),
|
|
52
|
-
preventAssignment: true,
|
|
53
|
-
}),
|
|
54
|
-
virtual(flow.vfs),
|
|
55
|
-
DynamicBasePlugin.vite({ sourcemap: flow.options.sourcemap }),
|
|
56
|
-
],
|
|
57
|
-
server: {
|
|
58
|
-
watch: {
|
|
59
|
-
ignored: isIgnoredFlow,
|
|
60
|
-
},
|
|
61
|
-
hmr: {
|
|
62
|
-
// https://github.com/nuxt/framework/issues/4191
|
|
63
|
-
protocol: 'ws',
|
|
64
|
-
clientPort: hmrPort,
|
|
65
|
-
port: hmrPort,
|
|
66
|
-
},
|
|
67
|
-
fs: {
|
|
68
|
-
allow: [
|
|
69
|
-
flow.options.appDir,
|
|
70
|
-
],
|
|
71
|
-
},
|
|
72
|
-
},
|
|
73
|
-
}, flow.options.vite),
|
|
74
|
-
};
|
|
75
|
-
if (flow.options.dev)
|
|
76
|
-
ctx.config.mode = process.env.NODE_ENV || 'development';
|
|
77
|
-
|
|
78
|
-
await flow.callHook('vite:extend', ctx);
|
|
79
|
-
|
|
80
|
-
flow.hook('vite:serverCreated', (server: vite.ViteDevServer) => {
|
|
81
|
-
// Invalidate virtual modules when templates are re-generated
|
|
82
|
-
ctx.nuxt.hook('app:templatesGenerated', () => {
|
|
83
|
-
for (const [id, mod] of server.moduleGraph.idToModuleMap) {
|
|
84
|
-
if (id.startsWith('\x00virtual:'))
|
|
85
|
-
server.moduleGraph.invalidateModule(mod);
|
|
86
|
-
}
|
|
87
|
-
});
|
|
88
|
-
|
|
89
|
-
const start = Date.now();
|
|
90
|
-
warmupViteServer(server, ['/entry.mjs'])
|
|
91
|
-
.then(() => logger.info(`Vite server warmed up in ${Date.now() - start}ms`))
|
|
92
|
-
.catch(logger.error);
|
|
93
|
-
});
|
|
94
|
-
|
|
95
|
-
await buildServer(ctx);
|
|
96
|
-
}
|
|
@@ -1,33 +0,0 @@
|
|
|
1
|
-
import fse from 'fs-extra';
|
|
2
|
-
import { resolve } from 'pathe';
|
|
3
|
-
import { joinURL } from 'ufo';
|
|
4
|
-
import type { ViteBuildContext } from './types';
|
|
5
|
-
|
|
6
|
-
export async function writeManifest(ctx: ViteBuildContext, extraEntries: string[] = []) {
|
|
7
|
-
// Write client manifest for use in vue-bundle-renderer
|
|
8
|
-
const clientDist = resolve(ctx.flow.options.buildDir, 'dist/client');
|
|
9
|
-
const serverDist = resolve(ctx.flow.options.buildDir, 'dist/server');
|
|
10
|
-
|
|
11
|
-
const entries = [
|
|
12
|
-
'@vite/client',
|
|
13
|
-
'entry.mjs',
|
|
14
|
-
...extraEntries,
|
|
15
|
-
];
|
|
16
|
-
|
|
17
|
-
// Legacy dev manifest
|
|
18
|
-
const devClientManifest = {
|
|
19
|
-
publicPath: joinURL(ctx.flow.options.app.baseURL, ctx.flow.options.app.buildAssetsDir),
|
|
20
|
-
all: entries,
|
|
21
|
-
initial: entries,
|
|
22
|
-
async: [],
|
|
23
|
-
modules: {},
|
|
24
|
-
};
|
|
25
|
-
|
|
26
|
-
const clientManifest = ctx.flow.options.dev
|
|
27
|
-
? devClientManifest
|
|
28
|
-
: await fse.readJSON(resolve(clientDist, 'manifest.json'));
|
|
29
|
-
|
|
30
|
-
await fse.mkdirp(serverDist);
|
|
31
|
-
await fse.writeFile(resolve(serverDist, 'client.manifest.json'), JSON.stringify(clientManifest, null, 2), 'utf8');
|
|
32
|
-
await fse.writeFile(resolve(serverDist, 'client.manifest.mjs'), `export default ${JSON.stringify(clientManifest, null, 2)}`, 'utf8');
|
|
33
|
-
}
|
|
@@ -1,32 +0,0 @@
|
|
|
1
|
-
// import type { Plugin } from 'vite';
|
|
2
|
-
// import { transform } from 'esbuild';
|
|
3
|
-
// // import { visualizer } from 'rollup-plugin-visualizer';
|
|
4
|
-
// import type { ViteBuildContext } from '../types';
|
|
5
|
-
|
|
6
|
-
// export function analyzePlugin(ctx: ViteBuildContext): Plugin[] {
|
|
7
|
-
// return [
|
|
8
|
-
// {
|
|
9
|
-
// name: 'nuxt:analyze-minify',
|
|
10
|
-
// async generateBundle(_opts, outputBundle) {
|
|
11
|
-
// for (const [_bundleId, bundle] of Object.entries(outputBundle)) {
|
|
12
|
-
// if (bundle.type !== 'chunk') continue;
|
|
13
|
-
// const originalEntries = Object.entries(bundle.modules);
|
|
14
|
-
// const minifiedEntries = await Promise.all(originalEntries.map(async([moduleId, module]) => {
|
|
15
|
-
// const { code } = await transform(module.code || '', { minify: true });
|
|
16
|
-
// return [moduleId, { ...module, code }];
|
|
17
|
-
// }));
|
|
18
|
-
// bundle.modules = Object.fromEntries(minifiedEntries);
|
|
19
|
-
// }
|
|
20
|
-
// return null;
|
|
21
|
-
// },
|
|
22
|
-
// },
|
|
23
|
-
// // visualizer({
|
|
24
|
-
// // // @ts-ignore
|
|
25
|
-
// // ...ctx.flow.options?.build?.analyze as any,
|
|
26
|
-
// // // @ts-ignore
|
|
27
|
-
// // filename: ctx.flow.options.build.analyze.filename.replace('{name}', 'client'),
|
|
28
|
-
// // title: 'Client bundle stats',
|
|
29
|
-
// // gzipSize: true,
|
|
30
|
-
// // }),
|
|
31
|
-
// ];
|
|
32
|
-
// }
|
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
import { resolve } from 'pathe';
|
|
2
|
-
import type { Plugin } from 'vite';
|
|
3
|
-
|
|
4
|
-
export function cacheDirPlugin(rootDir: string, name: string) {
|
|
5
|
-
const optimizeCacheDir = resolve(rootDir, 'node_modules/.cache/vite', name);
|
|
6
|
-
return <Plugin> {
|
|
7
|
-
name: 'flow:cache-dir',
|
|
8
|
-
configResolved(resolvedConfig) {
|
|
9
|
-
// @ts-ignore
|
|
10
|
-
resolvedConfig.optimizeCacheDir = optimizeCacheDir;
|
|
11
|
-
},
|
|
12
|
-
};
|
|
13
|
-
}
|