@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.
Files changed (57) hide show
  1. package/dist/app/composables/index.d.ts +2 -1
  2. package/dist/core/runtime/nitro/renderer.mjs +5 -1
  3. package/dist/index.mjs +25 -6
  4. package/dist/pages/runtime/index.d.ts +2 -2
  5. package/dist/pages/runtime/index.mjs +4 -4
  6. package/dist/pages/runtime/plugin.mjs +16 -10
  7. package/package.json +21 -9
  8. package/build.config.ts +0 -25
  9. package/src/app/composables/index.ts +0 -20
  10. package/src/app/entry.ts +0 -36
  11. package/src/app/flow.ts +0 -157
  12. package/src/app/index.ts +0 -5
  13. package/src/auto-imports/module.ts +0 -143
  14. package/src/auto-imports/presets.ts +0 -49
  15. package/src/auto-imports/transform.ts +0 -48
  16. package/src/core/app.ts +0 -90
  17. package/src/core/builder.ts +0 -60
  18. package/src/core/flow.ts +0 -93
  19. package/src/core/modules.ts +0 -32
  20. package/src/core/nitro.ts +0 -206
  21. package/src/core/plugins/import-protection.ts +0 -49
  22. package/src/core/plugins/unctx.ts +0 -31
  23. package/src/core/runtime/nitro/flow.ts +0 -43
  24. package/src/core/runtime/nitro/paths.ts +0 -20
  25. package/src/core/runtime/nitro/renderer.ts +0 -74
  26. package/src/core/templates.ts +0 -119
  27. package/src/core/vite/builder/css.ts +0 -28
  28. package/src/core/vite/builder/dev-bundler.ts +0 -248
  29. package/src/core/vite/builder/index.ts +0 -96
  30. package/src/core/vite/builder/manifest.ts +0 -33
  31. package/src/core/vite/builder/plugins/analyze.ts +0 -32
  32. package/src/core/vite/builder/plugins/cache-dir.ts +0 -13
  33. package/src/core/vite/builder/plugins/dynamic-base.ts +0 -64
  34. package/src/core/vite/builder/plugins/virtual.ts +0 -45
  35. package/src/core/vite/builder/server.ts +0 -164
  36. package/src/core/vite/builder/types/index.ts +0 -13
  37. package/src/core/vite/builder/utils/index.ts +0 -53
  38. package/src/core/vite/builder/utils/warmup.ts +0 -27
  39. package/src/core/vite/builder/utils/wpfs.ts +0 -7
  40. package/src/core/vite/builder/vite-node.ts +0 -110
  41. package/src/core/vite/client/index.ts +0 -63
  42. package/src/dirs.ts +0 -8
  43. package/src/head/module.ts +0 -37
  44. package/src/head/runtime/composables.ts +0 -16
  45. package/src/head/runtime/index.ts +0 -1
  46. package/src/head/runtime/plugin.ts +0 -12
  47. package/src/index.ts +0 -2
  48. package/src/pages/module.ts +0 -55
  49. package/src/pages/runtime/helpers/chunks.ts +0 -0
  50. package/src/pages/runtime/helpers/index.ts +0 -33
  51. package/src/pages/runtime/index.ts +0 -9
  52. package/src/pages/runtime/plugin.ts +0 -65
  53. package/src/pages/templates.ts +0 -20
  54. package/src/pages/utils.ts +0 -49
  55. package/src/vite-client/module.ts +0 -84
  56. package/src/vite-client/runtime/injectManifest.ts +0 -188
  57. package/src/vite-client/runtime/plugin.ts +0 -33
@@ -1,4 +1,5 @@
1
+ import type { RouteLocationNormalizedLoaded } from 'vue-router';
1
2
  export declare function useCookie(name: string, _opts?: any): {};
2
3
  export declare function refreshNuxtData(keys?: string | string[]): Promise<void>;
3
4
  export declare function useAsyncData(key: string, handlers: () => Promise<any>): Promise<any>;
4
- export declare function useRoute(): {};
5
+ export declare function useRoute(): RouteLocationNormalizedLoaded;
@@ -18,7 +18,8 @@ export default eventHandler(async (event) => {
18
18
  const templateContext = {};
19
19
  const dynamyc = params?._;
20
20
  const contextPage = {};
21
- const utils = Object.assign({ getLocale: () => locale }, flow.app.utils);
21
+ const contextInject = {};
22
+ const utils = Object.assign({ getLocale: () => locale, injectContext: (key, value) => contextInject[key] = value }, flow.app.utils);
22
23
  templateContext.url = url;
23
24
  templateContext.locale = locale;
24
25
  templateContext.view = view;
@@ -46,6 +47,9 @@ export default eventHandler(async (event) => {
46
47
  templateContext.getBodyChunks = () => {
47
48
  return chunks.body.join("\n");
48
49
  };
50
+ templateContext.getInjectContext = () => {
51
+ return `<script id="__FLOW_DATA__" type="application/json">${JSON.stringify(contextInject)}<\/script>`;
52
+ };
49
53
  const query = useQuery(event);
50
54
  if (query?.context)
51
55
  return { ...templateContext, utils: Object.keys(utils) };
package/dist/index.mjs CHANGED
@@ -27,7 +27,7 @@ import { isExternal as isExternal$1, ExternalsDefaults } from 'externality';
27
27
  import { createHash } from 'node:crypto';
28
28
  import MagicString from 'magic-string';
29
29
 
30
- const version = "5.0.0-rc.1";
30
+ const version = "5.0.0-rc.10";
31
31
 
32
32
  let _distDir = dirname(fileURLToPath(import.meta.url));
33
33
  if (_distDir.endsWith("chunks"))
@@ -87,6 +87,13 @@ const commonPresets = [
87
87
  imports: [
88
88
  "useHead"
89
89
  ]
90
+ }),
91
+ defineUnimportPreset({
92
+ from: "#_pages",
93
+ imports: [
94
+ "definePage",
95
+ "defineDinamycPage"
96
+ ]
90
97
  })
91
98
  ];
92
99
  const appPreset = defineUnimportPreset({
@@ -223,11 +230,11 @@ ${ctx.generateTypeDecarations({ resolvePath: r })}`
223
230
 
224
231
  async function resolvePagesRoutes() {
225
232
  const nuxt = useNuxt();
226
- const pagesDirs = [...new Set(nuxt.options._layers.map((layer) => resolve(layer.config.srcDir, layer.config.dir?.pages || "pages")))];
233
+ const pagesDirs = [resolve(nuxt.options.srcDir, nuxt.options.dir?.pages || "pages")];
227
234
  const allRoutes = (await Promise.all(pagesDirs.map(async (dir) => {
228
235
  const files = await resolveFilesFlow(dir, `**/*{${nuxt.options.extensions.join(",")}}`);
229
236
  files.sort();
230
- return files.map((file) => {
237
+ return files.filter((file) => !file.includes(" copy")).map((file) => {
231
238
  const segments = relative(dir, file).replace(new RegExp(`${escapeRE(extname(file))}$`), "").split("/").join("_");
232
239
  return {
233
240
  file,
@@ -241,7 +248,10 @@ function normalizePages(pages) {
241
248
  const imports = pages.map((page) => genImport(page.file, [{ name: "pages", as: page.name }])).join("\n");
242
249
  return {
243
250
  imports,
244
- exports: pages.reduce((acc, curr) => `${curr.name || ""},${acc}`, "")
251
+ exports: pages.reduce((acc, curr) => {
252
+ const name = curr.name;
253
+ return `${name}:typeof ${name}==='function'?${name}():${name},${acc}`;
254
+ }, "")
245
255
  };
246
256
  }
247
257
 
@@ -263,6 +273,7 @@ const pagesModule = defineNuxtModule({
263
273
  },
264
274
  async setup(_options, flow) {
265
275
  const runtimeDir = resolve(distDir, "pages/runtime");
276
+ flow.options.alias["#_pages"] = runtimeDir;
266
277
  const pages = [];
267
278
  flow.hook("builder:watch", async (event, path) => {
268
279
  const dirs = [
@@ -279,6 +290,7 @@ const pagesModule = defineNuxtModule({
279
290
  ...pagesTypeTemplate,
280
291
  options
281
292
  });
293
+ const pagesDirs = [{ path: resolve(flow.options.srcDir, flow.options.dir.pages) }];
282
294
  flow.options.alias["#pages"] = resolve(flow.options.buildDir, "pages.mjs");
283
295
  addTemplate({
284
296
  filename: "pages.mjs",
@@ -294,6 +306,13 @@ const pagesModule = defineNuxtModule({
294
306
  flow.hook("prepare:types", ({ references }) => {
295
307
  references.push({ path: resolve(flow.options.buildDir, "pages.d.ts") });
296
308
  });
309
+ flow.hook("builder:watch", async (event, path) => {
310
+ if (!["add", "unlink"].includes(event))
311
+ return;
312
+ const fPath = resolve(flow.options.rootDir, path);
313
+ if (pagesDirs.find((dir) => fPath.startsWith(dir.path)))
314
+ await flow.callHook("builder:generateApp");
315
+ });
297
316
  addPlugin({ src: resolve(runtimeDir, "plugin") });
298
317
  }
299
318
  });
@@ -486,7 +505,6 @@ async function initNitro(flow) {
486
505
  "@babel/parser": "unenv/runtime/mock/proxy",
487
506
  "#paths": resolve(distDir, "core/runtime/nitro/paths"),
488
507
  "#server": "#build/dist/server/server.mjs",
489
- "#app": flow.options.appDir,
490
508
  ...flow.options.alias
491
509
  },
492
510
  rollupConfig: {
@@ -630,6 +648,7 @@ async function initFlow(flow) {
630
648
  async function loadFlow(opts) {
631
649
  const options = await loadFlowConfig(opts);
632
650
  options.appDir = resolve(distDir, "app");
651
+ options.alias["#app"] = resolve(distDir, "app/index");
633
652
  options._majorVersion = 3;
634
653
  options._modules.push(pagesModule, metaModule, autoImportsModule, viteModule);
635
654
  options.modulesDir.push(resolve(pkgDir, "node_modules"));
@@ -1158,7 +1177,7 @@ const buildServer = async (ctx) => {
1158
1177
  await onBuild();
1159
1178
  ctx.flow.callHook("bundler:change", {});
1160
1179
  };
1161
- const doBuild = debounce(_doBuild);
1180
+ const doBuild = debounce(_doBuild, 50);
1162
1181
  await _doBuild();
1163
1182
  viteServer.watcher.on("all", (_event, file) => {
1164
1183
  file = normalize(file);
@@ -1,3 +1,3 @@
1
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;
2
+ export declare function definePage(...pages: SimplePage[]): SimplePage[];
3
+ export declare function defineDinamycPage(...pages: DynamicPage[]): DynamicPage[];
@@ -1,6 +1,6 @@
1
- export function definePage(page) {
2
- return page;
1
+ export function definePage(...pages) {
2
+ return pages;
3
3
  }
4
- export function defineDinamycPage(page) {
5
- return page;
4
+ export function defineDinamycPage(...pages) {
5
+ return pages;
6
6
  }
@@ -1,20 +1,26 @@
1
1
  import { joinURL } from "ufo";
2
+ import consola from "consola";
2
3
  import { definePage } from "./helpers/index.mjs";
3
4
  import { defineFlowPlugin, useRuntimeConfig } from "#app";
4
5
  import pages from "#pages";
5
6
  export default defineFlowPlugin(async (flow) => {
6
7
  const { app } = useRuntimeConfig();
7
8
  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);
9
+ const basePages = Object.entries(pages);
10
+ consola.success("Parsed %i pages files", basePages.length);
11
+ basePages.forEach(([name, _pages]) => {
12
+ const __pages = Array.isArray(_pages) ? _pages : [_pages];
13
+ __pages.forEach((page) => {
14
+ const { getPages } = definePage({
15
+ name,
16
+ ...page
17
+ });
18
+ const _pages2 = getPages(app.locale.location, app.locale.language);
19
+ _pages2.forEach((page2) => {
20
+ flow.router.byUrl.insert(page2.url, page2.context);
21
+ flow.router.byName.insert(page2.name, page2.context);
22
+ allPages.push(page2.context);
23
+ });
18
24
  });
19
25
  });
20
26
  function getUrl(namePage, localeCode) {
package/package.json CHANGED
@@ -1,22 +1,33 @@
1
1
  {
2
2
  "name": "@monkeyplus/flow",
3
- "version": "5.0.0-rc.1",
3
+ "version": "5.0.0-rc.10",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
+ "main": "./dist/index.mjs",
7
+ "types": "./types.d.ts",
8
+ "bin": {
9
+ "flow": "./bin/flow.mjs"
10
+ },
6
11
  "exports": {
7
12
  ".": "./dist/index.mjs",
8
13
  "./app": "./dist/app/index.mjs",
9
14
  "./package.json": "./package.json"
10
15
  },
11
- "main": "./dist/index.mjs",
12
- "types": "./types.d.ts",
13
- "bin": {
14
- "flow": "./bin/flow.mjs"
16
+ "imports": {
17
+ "#app": "./dist/app/index.mjs",
18
+ "#head": "./dist/head/runtime/index.mjs",
19
+ "#pages": "./dist/pages/runtime/index.mjs"
15
20
  },
21
+ "files": [
22
+ "app.d.ts",
23
+ "bin",
24
+ "types.d.ts",
25
+ "dist"
26
+ ],
16
27
  "dependencies": {
17
- "@monkeyplus/flow-cli": "5.0.0-rc.1",
18
- "@monkeyplus/flow-kit": "5.0.0-rc.1",
19
- "@monkeyplus/flow-schema": "5.0.0-rc.1",
28
+ "@monkeyplus/flow-cli": "5.0.0-rc.10",
29
+ "@monkeyplus/flow-kit": "5.0.0-rc.10",
30
+ "@monkeyplus/flow-schema": "5.0.0-rc.10",
20
31
  "@rollup/plugin-replace": "^4.0.0",
21
32
  "@vueuse/head": "^0.7.6",
22
33
  "c12": "^0.2.7",
@@ -58,7 +69,8 @@
58
69
  "vue": "^3.2.33"
59
70
  },
60
71
  "devDependencies": {
61
- "@types/fs-extra": "^9.0.13"
72
+ "@types/fs-extra": "^9.0.13",
73
+ "vue-router": "^4.0.15"
62
74
  },
63
75
  "engines": {
64
76
  "node": "^16.11.0 || ^17.0.0 || ^18.0.0"
package/build.config.ts DELETED
@@ -1,25 +0,0 @@
1
- import type { BuildEntry } from 'unbuild';
2
- import { defineBuildConfig } from 'unbuild';
3
-
4
- export default defineBuildConfig({
5
- declaration: true,
6
- entries: [
7
- 'src/index',
8
- { input: 'src/app/', outDir: 'dist/app/' },
9
- ...[
10
- 'core',
11
- 'head',
12
- 'pages',
13
- 'vite-client',
14
- ].map((name) => ({ input: `src/${name}/runtime/`, outDir: `dist/${name}/runtime`, format: 'esm' } as BuildEntry)),
15
- // { input: 'src/runtime/', outDir: 'dist/runtime', format: 'esm' },
16
- ],
17
- dependencies: [
18
- '@monkeyplus/flow-cli',
19
- 'ohmyfetch',
20
-
21
- ],
22
- externals: [
23
-
24
- ],
25
- });
@@ -1,20 +0,0 @@
1
- /* eslint-disable @typescript-eslint/no-unused-vars */
2
- //* fake to nuxt Compatibilities
3
-
4
- export function useCookie(name: string, _opts?: any) {
5
- // console.log('Cookie', name, _opts);
6
-
7
- return {};
8
- }
9
-
10
- export function refreshNuxtData(keys?: string | string[]): Promise<void> {
11
- return Promise.resolve();
12
- }
13
-
14
- export function useAsyncData(key: string, handlers: () => Promise<any>) {
15
- return handlers();
16
- }
17
-
18
- export function useRoute() {
19
- return {};
20
- }
package/src/app/entry.ts DELETED
@@ -1,36 +0,0 @@
1
-
2
- import type { RuntimeConfig } from '@monkeyplus/flow-schema';
3
- import { config, configure, render } from 'eta';
4
- import { applyPlugins, createFlowApp } from './flow';
5
- // @ts-ignore
6
- import plugins from '#build/plugins';
7
-
8
- export default async(runtimeConfig: RuntimeConfig) => {
9
- const flow = createFlowApp({ runtimeConfig });
10
- try {
11
- await applyPlugins(flow, plugins);
12
- // console.log(flow.eta);
13
-
14
- configure(flow.eta);
15
- flow.render = (view: Record<string, string>, data: any) => {
16
- // eslint-disable-next-line no-template-curly-in-string
17
- const layout = '<%layout(`layouts/${it.view?.layout||\'default\'}`)%>';
18
- const getTemplate = flow.engines[view.engine || flow.engine];
19
- const base = `${layout}
20
- ${getTemplate(view.template)}`;
21
- return render(base, data || {}, {
22
- ...config,
23
- async: true,
24
- });
25
- };
26
-
27
- // await flow.hooks.callHook('app:created', vueApp);
28
- }
29
- catch (err) {
30
- console.log(err);
31
- // await flow.callHook('app:error', err);
32
- // ssrContext.error = ssrContext.error || err;
33
- }
34
-
35
- return flow;
36
- };
package/src/app/flow.ts DELETED
@@ -1,157 +0,0 @@
1
- import type { RadixRouter } from 'radix3';
2
- import { createRouter } from 'radix3';
3
- import type { Hookable } from 'hookable';
4
- import { createHooks } from 'hookable';
5
- import type { FlowPage, RuntimeConfig } from '@monkeyplus/flow-schema';
6
- import { getContext } from 'unctx';
7
- import { globby } from 'globby';
8
- import { join, resolve } from 'pathe';
9
-
10
- const flowAppCtx = getContext<FlowApp>('flow-app');
11
-
12
- type HookResult = Promise<void> | void;
13
- export interface FlowAppHooks{
14
- 'flow:pages': (page: FlowPage[]) => HookResult
15
- 'eta:plugin': (options: any) => HookResult
16
- 'page:scripts': (scripts: { head: string[]; bodyEnd: string[]; bodyStart: string[] }) => HookResult
17
- 'page:links': (links: string[]) => HookResult
18
- 'page:chunks': (bundle: string, scripts: { head: string[]; body: string[] }) => HookResult
19
- 'page:generate': (generate: any) => HookResult
20
-
21
- }
22
- export interface FlowApp {
23
- router: { byUrl: RadixRouter<FlowPage['context']>; byName: RadixRouter<FlowPage['context']> }
24
- hooks: Hookable<FlowAppHooks>
25
- hook: FlowApp['hooks']['hook']
26
- callHook: FlowApp['hooks']['callHook']
27
- eta: any
28
- app: {
29
- utils: Record<string, any>
30
- plugins: Record<string, any>
31
- globals: Record<string, any>
32
- }
33
- engine: string
34
-
35
- engines: Record<string, (template: string) => string>
36
- generate: boolean
37
- render: (view: Record<string, string>, data: any) => Promise<string>|void|string
38
- provide: (name: string, value: any) => void
39
- setUtil: (name: string, value: any) => void
40
-
41
- [key: string]: any
42
-
43
- }
44
-
45
- export const FlowPluginIndicator = '__flow_plugin';
46
- export const NuxtPluginIndicator = '__nuxt_plugin';
47
-
48
- export interface Plugin<Injections extends Record<string, any> = Record<string, any>> {
49
- (flow: FlowApp): Promise<void> | Promise<{ provide?: Injections }> | void | { provide?: Injections }
50
- [FlowPluginIndicator]?: true
51
- }
52
- interface OptionsApp {
53
- runtimeConfig: RuntimeConfig
54
- }
55
-
56
- export function createFlowApp({ runtimeConfig }: OptionsApp): FlowApp {
57
- //
58
-
59
- const viewsDir = join(runtimeConfig.app.rootDir, 'views');
60
-
61
- const flowApp: FlowApp = {
62
- router: { byUrl: createRouter(), byName: createRouter() },
63
- app: {
64
- utils: {},
65
- globals: {},
66
- },
67
- eta: {
68
- views: viewsDir,
69
- plugins: [],
70
- },
71
- engine: 'eta',
72
- engines: { },
73
- generate: runtimeConfig.generate,
74
- } as FlowApp;
75
-
76
- flowApp.engines.eta = (template: string) => {
77
- return `<%~ await includeFile('templates/${template}',it) %>`;
78
- };
79
- flowApp.hooks = createHooks<FlowAppHooks>();
80
- flowApp.hook = flowApp.hooks.hook;
81
- flowApp.callHook = flowApp.hooks.callHook;
82
-
83
- flowApp.provide = (name: string, value: any) => {
84
- const $name = `$${name}`;
85
- defineGetter(flowApp, $name, value);
86
- // defineGetter(nuxtApp.vueApp.config.globalProperties, $name, value);
87
- };
88
- flowApp.setUtil = (name: string, method: any) => {
89
- flowApp.app.utils[name] = method;
90
- };
91
-
92
- flowApp.hook('eta:plugin', (_plugin) => {
93
- flowApp.eta.plugins.push(_plugin);
94
- });
95
-
96
- flowApp.provide('config', runtimeConfig);
97
-
98
- return flowApp;
99
- }
100
-
101
- export function defineFlowPlugin<T>(plugin: Plugin<T>) {
102
- plugin[FlowPluginIndicator] = true;
103
- return plugin;
104
- }
105
-
106
- export function defineNuxtPlugin<T>(plugin: Plugin<T>) {
107
- plugin[NuxtPluginIndicator] = true;
108
- return plugin;
109
- }
110
-
111
- export async function applyPlugin(flowApp: FlowApp, plugin: Plugin) {
112
- if (typeof plugin !== 'function') return;
113
- const { provide } = await callWithFlow(flowApp, plugin, [flowApp]) || {};
114
- if (provide && typeof provide === 'object') {
115
- for (const key in provide)
116
- flowApp.provide(key, provide[key]);
117
- }
118
- }
119
- export async function applyPlugins(flowApp: FlowApp, plugins: Plugin[]) {
120
- for (const plugin of plugins)
121
- await applyPlugin(flowApp, plugin);
122
- }
123
-
124
- /**
125
- * Ensures that the setup function passed in has access to the Nuxt instance via `useNuxt`.
126
- *
127
- * @param flow A Flow instance
128
- * @param setup The function to call
129
- */
130
- export function callWithFlow<T extends(...args: any[]) => any> (flow: FlowApp, setup: T, args?: Parameters<T>) {
131
- const fn = () => args ? setup(...args as Parameters<T>) : setup();
132
- // TODO: posible error
133
- flowAppCtx.set(flow);
134
- return flowAppCtx.callAsync<ReturnType<T>>(flow, fn);
135
- }
136
- /**
137
- * Returns the current Nuxt instance.
138
- */
139
- export function useFlowApp() {
140
- const flowAppInstance = flowAppCtx.use();
141
- if (!flowAppInstance)
142
- throw new Error('flow instance unavailable');
143
-
144
- return flowAppInstance;
145
- }
146
- export function useRuntimeConfig(): RuntimeConfig {
147
- return useFlowApp().$config;
148
- }
149
-
150
- function defineGetter<K extends string | number | symbol, V>(obj: Record<K, V>, key: K, val: V) {
151
- Object.defineProperty(obj, key, { get: () => val });
152
- }
153
-
154
- export async function resolveFiles(path: string, pattern: string | string[]) {
155
- const files = await globby(pattern, { cwd: path, followSymbolicLinks: true });
156
- return files.filter((file) => !file.includes('copy.ts')).map((p) => resolve(path, p));
157
- }
package/src/app/index.ts DELETED
@@ -1,5 +0,0 @@
1
- export * from './flow';
2
- export * from './composables';
3
-
4
- // @ts-ignore
5
- export { useHead } from '#head';
@@ -1,143 +0,0 @@
1
- import { addPluginTemplate, addTemplate, addVitePlugin, defineNuxtModule, logger, resolveAlias, useNuxt } from '@monkeyplus/flow-kit';
2
- import { isAbsolute, join, normalize, relative, resolve } from 'pathe';
3
- import type { Import, Unimport } from 'unimport';
4
- import { createUnimport, scanDirExports, toImports } from 'unimport';
5
- import type { AutoImportsOptions, FlowModule, ImportPresetWithDeprecation } from '@monkeyplus/flow-schema';
6
- import { TransformPlugin } from './transform';
7
- import { defaultPresets } from './presets';
8
-
9
- export default defineNuxtModule<Partial<AutoImportsOptions>>({
10
- meta: {
11
- name: 'auto-imports',
12
- configKey: 'autoImports',
13
- },
14
- defaults: {
15
- presets: defaultPresets,
16
- global: false,
17
- imports: [],
18
- dirs: [],
19
- transform: {
20
- exclude: undefined,
21
- },
22
- },
23
- async setup(options, flow) {
24
- // Allow modules extending sources
25
- await flow.callHook('autoImports:sources', options.presets as ImportPresetWithDeprecation[]);
26
-
27
- options.presets.forEach((i: ImportPresetWithDeprecation) => {
28
- if (typeof i !== 'string' && i.names && !i.imports) {
29
- i.imports = i.names;
30
- logger.warn('auto-imports: presets.names is deprecated, use presets.imports instead');
31
- }
32
- });
33
-
34
- // Filter disabled sources
35
- // options.sources = options.sources.filter(source => source.disabled !== true)
36
-
37
- // Create a context to share state between module internals
38
- const ctx = createUnimport({
39
- presets: options.presets,
40
- imports: options.imports,
41
- });
42
-
43
- // composables/ dirs from all layers
44
- let composablesDirs = [];
45
- for (const layer of flow.options._layers) {
46
- composablesDirs.push(resolve(layer.config.srcDir, 'composables'));
47
- for (const dir of (layer.config.autoImports?.dirs ?? []))
48
- composablesDirs.push(resolve(layer.config.srcDir, dir));
49
- }
50
-
51
- await flow.callHook('autoImports:dirs', composablesDirs);
52
- composablesDirs = composablesDirs.map((dir) => normalize(dir));
53
-
54
- // Support for importing from '#imports'
55
- addTemplate({
56
- filename: 'imports.mjs',
57
- getContents: () => ctx.toExports(),
58
- });
59
- flow.options.alias['#imports'] = join(flow.options.buildDir, 'imports');
60
-
61
- // Transpile and injection
62
- // @ts-ignore temporary disabled due to #746
63
- if (flow.options.dev && options.global) {
64
- // Add all imports to globalThis in development mode
65
- addPluginTemplate({
66
- filename: 'auto-imports.mjs',
67
- getContents: () => {
68
- const imports = ctx.getImports();
69
- const importStatement = toImports(imports);
70
- const globalThisSet = imports.map((i) => `globalThis.${i.as} = ${i.as};`).join('\n');
71
- return `${importStatement}\n\n${globalThisSet}\n\nexport default () => {};`;
72
- },
73
- });
74
- }
75
- else {
76
- // Transform to inject imports in production mode
77
- addVitePlugin(TransformPlugin.vite({ ctx, options, sourcemap: flow.options.sourcemap }));
78
- }
79
-
80
- const regenerateAutoImports = async() => {
81
- ctx.clearDynamicImports();
82
- await ctx.modifyDynamicImports(async(imports) => {
83
- // Scan composables/
84
- imports.push(...await scanDirExports(composablesDirs));
85
- // Modules extending
86
- await flow.callHook('autoImports:extend', imports);
87
- });
88
- };
89
-
90
- await regenerateAutoImports();
91
-
92
- // Generate types
93
- addDeclarationTemplates(ctx);
94
-
95
- // Add generated types to `nuxt.d.ts`
96
- flow.hook('prepare:types', ({ references }) => {
97
- references.push({ path: resolve(flow.options.buildDir, 'types/auto-imports.d.ts') });
98
- references.push({ path: resolve(flow.options.buildDir, 'imports.d.ts') });
99
- });
100
-
101
- // Watch composables/ directory
102
- flow.hook('builder:watch', async(_, path) => {
103
- const _resolved = resolve(flow.options.srcDir, path);
104
- if (composablesDirs.find((dir) => _resolved.startsWith(dir)))
105
- await flow.callHook('builder:generateApp');
106
- });
107
-
108
- flow.hook('builder:generateApp', async() => {
109
- await regenerateAutoImports();
110
- });
111
- },
112
- }) as FlowModule<any>;
113
-
114
- function addDeclarationTemplates(ctx: Unimport) {
115
- const nuxt = useNuxt();
116
-
117
- // Remove file extension for benefit of TypeScript
118
- const stripExtension = (path: string) => path.replace(/\.[a-z]+$/, '');
119
-
120
- const resolved = {};
121
- const r = ({ from }: Import) => {
122
- if (resolved[from])
123
- return resolved[from];
124
-
125
- let path = resolveAlias(from);
126
- if (isAbsolute(path))
127
- path = relative(join(nuxt.options.buildDir, 'types'), path);
128
-
129
- path = stripExtension(path);
130
- resolved[from] = path;
131
- return path;
132
- };
133
-
134
- addTemplate({
135
- filename: 'imports.d.ts',
136
- getContents: () => ctx.toExports(),
137
- });
138
-
139
- addTemplate({
140
- filename: 'types/auto-imports.d.ts',
141
- getContents: () => `// Generated by auto imports\n${ctx.generateTypeDecarations({ resolvePath: r })}`,
142
- });
143
- }
@@ -1,49 +0,0 @@
1
- import type { Preset } from 'unimport';
2
- import { defineUnimportPreset } from 'unimport';
3
-
4
- export const commonPresets: Preset[] = [
5
- // #head
6
- defineUnimportPreset({
7
- from: '#head',
8
- imports: [
9
- 'useHead',
10
- ],
11
- }),
12
-
13
- ];
14
-
15
- export const appPreset = defineUnimportPreset({
16
- from: '#app',
17
- imports: [
18
- 'useRuntimeConfig',
19
- 'defineFlowPlugin',
20
- 'defineNuxtPlugin',
21
- 'useCookie',
22
- 'refreshNuxtData',
23
- 'useAsyncData',
24
- 'useRoute',
25
-
26
- ],
27
- });
28
-
29
- // * Compatibilitie Nuxt
30
- export const vuePreset = defineUnimportPreset({
31
- from: 'vue',
32
- imports: [
33
- // Components
34
- 'defineComponent',
35
- 'getCurrentInstance',
36
- 'useSlots',
37
- 'h',
38
-
39
- // Reactivity
40
- 'computed',
41
-
42
- ],
43
- });
44
-
45
- export const defaultPresets = [
46
- ...commonPresets,
47
- appPreset,
48
- vuePreset,
49
- ];