@mono-lit/utility 0.0.0-stage → 0.0.2

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 (54) hide show
  1. package/LICENSE.md +54 -0
  2. package/README.md +157 -3
  3. package/dist/app-roots-CvJnmXcs.js +128 -0
  4. package/dist/app-roots-DK41xMWj.d.ts +90 -0
  5. package/dist/config-node-UzJrXg0Z.js +76 -0
  6. package/dist/config-node.d.ts +923 -0
  7. package/dist/config-node.js +7 -0
  8. package/dist/config.d.ts +2 -0
  9. package/dist/config.js +3 -0
  10. package/dist/create-config-B8IhX4ht.d.ts +735 -0
  11. package/dist/create-config-DdL3Fh6T.js +357 -0
  12. package/dist/fetching.d.ts +244 -0
  13. package/dist/fetching.js +1015 -0
  14. package/dist/generate-CJ7MtcDd.js +291 -0
  15. package/dist/index-BAy6tbOG.d.ts +371 -0
  16. package/dist/index-DYlzhHq7.d.ts +514 -0
  17. package/dist/index.d.ts +25 -0
  18. package/dist/index.js +941 -0
  19. package/dist/merge-file-CLc3wxY4.d.ts +99 -0
  20. package/dist/merge-file-CtyKTu5L.js +133 -0
  21. package/dist/mock-db-4tTWrF-P.js +1282 -0
  22. package/dist/mock-db.d.ts +2 -0
  23. package/dist/mock-db.js +4 -0
  24. package/dist/mono-alias-DNDm-jB_.js +508 -0
  25. package/dist/mono-clone.mjs +958 -0
  26. package/dist/mono-db.d.ts +1 -0
  27. package/dist/mono-db.js +158 -0
  28. package/dist/mono-env.mjs +231 -0
  29. package/dist/mono-git.mjs +798 -0
  30. package/dist/mono-link-YlOQ2PVS.js +488 -0
  31. package/dist/mono-prepare.d.ts +1 -0
  32. package/dist/mono-prepare.js +28 -0
  33. package/dist/mono-skills.d.ts +1 -0
  34. package/dist/mono-skills.js +837 -0
  35. package/dist/mono-tsconfig-D2qRL9_R.js +204 -0
  36. package/dist/mono.mjs +34 -0
  37. package/dist/nuxt-layers-DP1m7f1-.js +176 -0
  38. package/dist/nuxt-layers.d.ts +36 -0
  39. package/dist/nuxt-layers.js +3 -0
  40. package/dist/nuxt-runtime.d.ts +17 -0
  41. package/dist/nuxt-runtime.js +102 -0
  42. package/dist/nuxt.d.ts +390 -0
  43. package/dist/nuxt.js +737 -0
  44. package/dist/runtime-vs7U9Ed4.js +6054 -0
  45. package/dist/runtime.d.ts +2518 -0
  46. package/dist/runtime.js +4 -0
  47. package/dist/session-Bcig-rPi.js +1721 -0
  48. package/dist/types-B6FdB7LJ.d.ts +57 -0
  49. package/dist/universal-BR0O7Qwk.d.ts +59 -0
  50. package/dist/universal-DIVEzCvN.js +600 -0
  51. package/dist/virtual-mono-apps.d.ts +16 -0
  52. package/dist/vite.d.ts +943 -0
  53. package/dist/vite.js +1132 -0
  54. package/package.json +141 -3
package/dist/vite.js ADDED
@@ -0,0 +1,1132 @@
1
+ import { o as pathAppRoots, t as appRootDirs } from "./app-roots-CvJnmXcs.js";
2
+ import { c as resolveMonoConfig, l as srcDirForType, o as resolveExtendsAppNames, s as resolveExtendsEcosystems } from "./create-config-DdL3Fh6T.js";
3
+ import { r as monoEcosystem } from "./merge-file-CtyKTu5L.js";
4
+ import { t as getMonoConfig } from "./config-node-UzJrXg0Z.js";
5
+ import { c as monoConfigFileFor, d as resolveFederatedRoots, n as extractConfig, o as formatMissingApps, s as monoAlias, t as assertAppSources, u as monoStubAliases } from "./mono-alias-DNDm-jB_.js";
6
+ import { a as defaultMonoExpose, c as parsePageMetaFromFile, i as monoRouterLinkToNuxtLink, l as remoteGate, n as monoNuxtLinkToRouterLink, o as sanitizeForExpose, r as monoRouterLink, s as parsePageMeta, t as monoNuxtLink } from "./mono-link-YlOQ2PVS.js";
7
+ import { existsSync } from "node:fs";
8
+ import { isAbsolute, join, resolve } from "node:path";
9
+ import { createRequire } from "node:module";
10
+ import { pathToFileURL } from "node:url";
11
+
12
+ //#region src/vite/mono-pagemeta.ts
13
+ /**
14
+ * Remove every `definePageMeta( … )` call from `code`, matching the call's
15
+ * argument list with a balanced-delimiter scan (so nested `{}`/`[]`/`()`,
16
+ * strings, template literals and comments inside the args are handled). Returns
17
+ * the original string unchanged if there's nothing to strip, or `null` if the
18
+ * source looks malformed (unterminated call) so the caller can bail safely.
19
+ */
20
+ function stripDefinePageMeta(code) {
21
+ const MACRO = "definePageMeta";
22
+ let out = "";
23
+ let last = 0;
24
+ let i = 0;
25
+ while (i < code.length) {
26
+ const at = code.indexOf(MACRO, i);
27
+ if (at === -1) break;
28
+ const before = at > 0 ? code[at - 1] : "";
29
+ if (before && /[A-Za-z0-9_$]/.test(before)) {
30
+ i = at + 14;
31
+ continue;
32
+ }
33
+ let p = at + 14;
34
+ while (p < code.length && /\s/.test(code[p])) p++;
35
+ if (code[p] !== "(") {
36
+ i = at + 14;
37
+ continue;
38
+ }
39
+ const close = matchClose(code, p);
40
+ if (close === -1) return null;
41
+ out += code.slice(last, at);
42
+ last = close + 1;
43
+ i = close + 1;
44
+ }
45
+ if (last === 0) return code;
46
+ out += code.slice(last);
47
+ return out;
48
+ }
49
+ /** Index of the `)` matching the `(` at `open`, or -1 if unbalanced. */
50
+ function matchClose(code, open) {
51
+ let depth = 0;
52
+ for (let i = open; i < code.length; i++) {
53
+ const c = code[i];
54
+ if (c === "\"" || c === "'" || c === "`") {
55
+ i = skipString(code, i);
56
+ if (i === -1) return -1;
57
+ continue;
58
+ }
59
+ if (c === "/" && code[i + 1] === "/") {
60
+ const nl = code.indexOf("\n", i + 2);
61
+ if (nl === -1) return -1;
62
+ i = nl;
63
+ continue;
64
+ }
65
+ if (c === "/" && code[i + 1] === "*") {
66
+ const end = code.indexOf("*/", i + 2);
67
+ if (end === -1) return -1;
68
+ i = end + 1;
69
+ continue;
70
+ }
71
+ if (c === "(" || c === "{" || c === "[") depth++;
72
+ else if (c === ")" || c === "}" || c === "]") {
73
+ depth--;
74
+ if (depth === 0) return i;
75
+ }
76
+ }
77
+ return -1;
78
+ }
79
+ /** Index of the closing quote for the string/template starting at `start`. */
80
+ function skipString(code, start) {
81
+ const quote = code[start];
82
+ for (let i = start + 1; i < code.length; i++) {
83
+ const c = code[i];
84
+ if (c === "\\") {
85
+ i++;
86
+ continue;
87
+ }
88
+ if (c === quote) return i;
89
+ }
90
+ return -1;
91
+ }
92
+ /**
93
+ * Vite plugin: strip the Nuxt page macro `definePageMeta({ … })` from synced
94
+ * remote `.vue` files (those under `.mono/apps/`) so it never reaches the Vue/Vite
95
+ * host's runtime.
96
+ *
97
+ * The Vue host doesn't need the macro: route META (layout/title) is injected
98
+ * separately by the host's `extendRoute` via `parsePageMetaFromFile`, which reads
99
+ * the page from disk (and so is unaffected by this in-memory strip). Removing the
100
+ * call outright — rather than rewriting it to unplugin-vue-router's `definePage`
101
+ * — means we don't depend on vue-router's own macro-stripping transform (and its
102
+ * `transform.filter`/ordering) ever running on the same module. Our single
103
+ * `enforce: 'pre'` transform, before `@vitejs/plugin-vue` compiles the SFC, is
104
+ * all that's required.
105
+ *
106
+ * `enforce: 'pre'` so it runs before the SFC is compiled — place `monoVue()`
107
+ * before `VueRouter()` in the plugins array.
108
+ */
109
+ function monoPageMetaToDefinePage(options = {}) {
110
+ const isRemote = remoteGate(options);
111
+ return {
112
+ name: "mono-strip-pagemeta",
113
+ enforce: "pre",
114
+ transform(code, id) {
115
+ const file = id?.split("?")[0]?.replace(/\\/g, "/");
116
+ if (!file || !file.endsWith(".vue") || !isRemote(file)) return;
117
+ if (!code.includes("definePageMeta")) return;
118
+ const out = stripDefinePageMeta(code);
119
+ return !out || out === code ? void 0 : {
120
+ code: out,
121
+ map: null
122
+ };
123
+ }
124
+ };
125
+ }
126
+ /** Clearer alias for {@link monoPageMetaToDefinePage}. */
127
+ const monoStripPageMeta = monoPageMetaToDefinePage;
128
+
129
+ //#endregion
130
+ //#region src/vite/mono-layout-slot.ts
131
+ /**
132
+ * Vite plugin: rewrite a synced remote **layout**'s default `<slot/>` (the
133
+ * Nuxt page outlet) into `<router-view />` for the Vue/Vite host.
134
+ *
135
+ * `vite-plugin-vue-layouts-next`'s `setupLayouts` wraps each page as a CHILD
136
+ * route of its layout, so the layout component must render `<router-view/>` for
137
+ * the page to appear. Nuxt layouts instead use `<slot/>` (NuxtLayout injects the
138
+ * page into the default slot). Without this rewrite the page renders nowhere — the
139
+ * layout chrome shows but the page content is blank.
140
+ *
141
+ * Scope: `.vue` files under a remote `.mono/apps/.../layouts/` dir. Only the DEFAULT
142
+ * slot is rewritten — named slots (`<slot name="…">`) are left untouched, since
143
+ * those are real content slots, not the page outlet. `<router-view>` is globally
144
+ * registered by `app.use(router)`, so no import is needed.
145
+ *
146
+ * Mirror of `mono-pagemeta`'s transform; the Nuxt host never runs this (it uses
147
+ * the same layout files via `<slot/>`).
148
+ */
149
+ function monoLayoutSlotToRouterView(options = {}) {
150
+ const isRemote = remoteGate(options);
151
+ return {
152
+ name: "mono-layout-slot-to-router-view",
153
+ enforce: "pre",
154
+ transform(code, id) {
155
+ const file = id?.split("?")[0]?.replace(/\\/g, "/");
156
+ if (!file || !file.endsWith(".vue") || !isRemote(file) || !file.includes("/layouts/")) return;
157
+ if (!code.includes("<slot")) return;
158
+ const out = code.replace(/<slot(?![^>]*\bname=)\b[^>]*\/>/g, "<router-view />").replace(/<slot(?![^>]*\bname=)\b[^>]*>\s*<\/slot>/g, "<router-view />");
159
+ return out === code ? void 0 : {
160
+ code: out,
161
+ map: null
162
+ };
163
+ }
164
+ };
165
+ }
166
+
167
+ //#endregion
168
+ //#region src/vite/mono-nuxt-state.ts
169
+ /** Files we can inject an import into. */
170
+ const SCRIPT_RE = /\.(?:vue|[cm]?[jt]sx?)$/;
171
+ /** `<script …> … <\/script>` — captured as (open, body, close). */
172
+ const SCRIPT_BLOCK_RE = /(<script\b[^>]*>)([\s\S]*?)(<\/script>)/g;
173
+ /** `import <clause> from '…'` — clause captured, lazy so it stops at its own `from`. */
174
+ const IMPORT_CLAUSE_RE = /import\s+([\s\S]*?)\s+from\s*['"][^'"]+['"]/g;
175
+ /** `import { … } from '#imports' | '#app' | '#app/…'` — Nuxt's virtual modules. */
176
+ const NUXT_VIRTUAL_IMPORT_RE = /import\s*\{([^}]*)\}\s*from\s*(['"])#[^'"]*\2\s*;?[^\S\n]*\n?/g;
177
+ const DEFAULT_COMPOSABLES = ["useState", "clearNuxtState"];
178
+ /**
179
+ * Vite plugin: make Nuxt's `useState()` work in a Vue/Vite host.
180
+ *
181
+ * A synced Nuxt remote writes `const msg = useState('msg', () => 'hello')` and
182
+ * relies on Nuxt auto-importing it. Nothing provides that name in a plain Vue app,
183
+ * so the page dies with `useState is not defined`. This plugin rewrites the
184
+ * remote's modules to pull the name from `@mono-lit/utility/runtime`, whose
185
+ * {@link ../composables/nuxt-state.useState | shim} is the same thing minus the
186
+ * SSR payload: a keyed ref registry, so `useState('msg', () => 'hello')` resolves
187
+ * to a shared `ref('hello')` and a keyless call to a plain one.
188
+ *
189
+ * Injecting an import (rather than textually rewriting the call to `ref(...)`)
190
+ * keeps the KEY meaningful — two components on the same key must see one ref,
191
+ * which a per-call `ref()` can't do — and doesn't depend on the host auto-importing
192
+ * `ref`.
193
+ *
194
+ * Scope: files under `.mono/apps/` (the `appsMarker` option; pass `''` to cover the
195
+ * host's own sources too). A file is left alone when it already binds the name
196
+ * itself — an explicit import, a local `const`/`function`, or an aliased
197
+ * (`useState as x`) Nuxt import. A PLAIN import from a Nuxt virtual module
198
+ * (`#imports` / `#app`) is stripped first, since those specifiers resolve to
199
+ * nothing outside Nuxt.
200
+ *
201
+ * `enforce: 'pre'` so `.vue` files are still raw SFC source — register before
202
+ * `@vitejs/plugin-vue`, alongside the other `monoVue()` plugins.
203
+ */
204
+ function monoNuxtStateToRef(options = {}) {
205
+ const isRemote = remoteGate(options);
206
+ const importFrom = options.importFrom ?? "@mono-lit/utility/runtime";
207
+ const composables = options.composables?.length ? options.composables : DEFAULT_COMPOSABLES;
208
+ return {
209
+ name: "mono-nuxt-state-to-ref",
210
+ enforce: "pre",
211
+ transform(code, id) {
212
+ const file = id?.split("?")[0]?.replace(/\\/g, "/");
213
+ if (!file || !SCRIPT_RE.test(file) || !isRemote(file)) return;
214
+ if (!composables.some((name) => code.includes(name))) return;
215
+ const source = stripNuxtVirtualImports(code, composables);
216
+ const out = file.endsWith(".vue") ? injectIntoSfc(source, composables, importFrom) : injectIntoModule(source, composables, importFrom);
217
+ return out === code ? void 0 : {
218
+ code: out,
219
+ map: null
220
+ };
221
+ }
222
+ };
223
+ }
224
+ /** Clearer alias for {@link monoNuxtStateToRef}. */
225
+ const monoNuxtState = monoNuxtStateToRef;
226
+ /**
227
+ * Drop the shimmed names from `import { … } from '#imports'`-style statements
228
+ * (dead specifiers in a Vue/Vite host), removing the statement entirely once it's
229
+ * empty. ALIASED specifiers (`useState as counter`) are kept as-is: the local name
230
+ * is the alias, so our injected import wouldn't satisfy the call — better to leave
231
+ * the file untouched and let the unresolved `#imports` error say so.
232
+ */
233
+ function stripNuxtVirtualImports(code, composables) {
234
+ if (!code.includes("#")) return code;
235
+ return code.replace(NUXT_VIRTUAL_IMPORT_RE, (statement, specifiers) => {
236
+ const all = specifiers.split(",").map((s) => s.trim()).filter(Boolean);
237
+ const kept = all.filter((s) => !composables.includes(s));
238
+ if (kept.length === all.length) return statement;
239
+ if (!kept.length) return "";
240
+ return statement.replace(specifiers, ` ${kept.join(", ")} `);
241
+ });
242
+ }
243
+ /** The names `code` actually uses that nothing else in it already binds. */
244
+ function missingBindings(code, composables) {
245
+ return composables.filter((name) => isReferenced(code, name) && !isBound(code, name));
246
+ }
247
+ /**
248
+ * `name` used as a free identifier — a call, or a bare reference like
249
+ * `onUnmounted(clearNuxtState)`. Not `obj.name`, not `myName`, not an object key
250
+ * (`{ useState: … }`). A mention inside a comment or string can slip through; the
251
+ * cost is one unused import, so the false positive is the cheap direction.
252
+ */
253
+ function isReferenced(code, name) {
254
+ return new RegExp(`(?<![\\w$.])${name}(?![\\w$])\\s*(?!:)`).test(code);
255
+ }
256
+ /** Already imported, declared, or aliased-in under this exact name. */
257
+ function isBound(code, name) {
258
+ for (const match of code.matchAll(IMPORT_CLAUSE_RE)) if (new RegExp(`\\b${name}\\b`).test(match[1] ?? "")) return true;
259
+ return new RegExp(`(?:const|let|var|function)\\s+${name}\\b`).test(code) || new RegExp(`as\\s+${name}\\b`).test(code);
260
+ }
261
+ function importStatement(names, from) {
262
+ return `import { ${names.join(", ")} } from '${from}'`;
263
+ }
264
+ /** Non-SFC module: imports hoist, so the top of the file is always safe. */
265
+ function injectIntoModule(code, composables, from) {
266
+ const missing = missingBindings(code, composables);
267
+ if (!missing.length) return code;
268
+ return `${importStatement(missing, from)}\n${code}`;
269
+ }
270
+ /**
271
+ * SFC: inject per `<script>` block, right after its opening tag (each block is its
272
+ * own module — `<script>` and `<script setup>` don't share bindings). A call that
273
+ * appears only in the template is skipped: that name has to come from setup, and
274
+ * there's no scope to put an import in.
275
+ */
276
+ function injectIntoSfc(code, composables, from) {
277
+ return code.replace(SCRIPT_BLOCK_RE, (block, open, body, close) => {
278
+ const missing = missingBindings(body, composables);
279
+ if (!missing.length) return block;
280
+ return `${open}\n${importStatement(missing, from)}${body}${close}`;
281
+ });
282
+ }
283
+
284
+ //#endregion
285
+ //#region src/vite/extend-route.ts
286
+ /** Resolved default-component filepath, tolerating the Map or a plain-object shape. */
287
+ function componentFile(route) {
288
+ if (typeof route.component === "string") return route.component;
289
+ const c = route.components;
290
+ if (!c) return void 0;
291
+ if (c instanceof Map) return c.get("default") ?? c.values().next().value;
292
+ return Object.values(c)[0];
293
+ }
294
+ /**
295
+ * Build a `VueRouter({ extendRoute })` callback that does two things.
296
+ *
297
+ * **1. Seeds meta for synced remote pages** (component path under `appsMarker`,
298
+ * default `/.mono/apps/`). Remote Nuxt pages declare meta with `definePageMeta`,
299
+ * which vue-router does not read from disk (and which `monoVue()` strips from the
300
+ * runtime build), so it's parsed from the source and added to the route where
301
+ * `setupLayouts` can see `meta.layout`.
302
+ *
303
+ * **2. Gives every route an explicit layout, so no page is wrapped twice.**
304
+ * `setupLayouts` wraps in two independent places: every TOP-LEVEL record, and any
305
+ * record that declares `meta.layout`. A page folder becomes a component-less GROUP
306
+ * record (`{ path: '/module-one', children: [{ path: 'example', … }] }`), and the
307
+ * plugin's guard against wrapping such a group only fires when the group's `''`
308
+ * child is already a layout — i.e. only when the folder has an `index.vue` that
309
+ * itself declares a layout. Any other shape gets the default layout around the
310
+ * group AND the page's own layout inside it:
311
+ *
312
+ * "/module-one" L(default) <-- group, wrapped because it is top-level
313
+ * "" (group)
314
+ * "example" L(home) <-- page, wrapped because it declares a layout
315
+ * "" PAGE
316
+ *
317
+ * So `pages/module-one/example.vue` renders two nested layouts while
318
+ * `pages/flow/{index,create}.vue` renders one. Fixed per node, no child lookahead:
319
+ * - a group (no component) gets `layout: false`, which `setupLayouts` honours by
320
+ * leaving the record alone — killing the outer wrapper
321
+ * - a page that declares no layout gets `defaultLayout`, so removing that wrapper
322
+ * can't leave a page unwrapped
323
+ *
324
+ * Layout normalisation applies to EVERY route, not just remote ones: a host-owned
325
+ * nested folder doubles exactly the same way. `meta.layout` is read from the page
326
+ * SOURCE because `EditableTreeNode.meta` deliberately excludes `definePage()` meta.
327
+ * A page declaring `layout: false` keeps it — never overwrite an explicit value.
328
+ *
329
+ * Reads the default component filepath via `route.component` — NOT
330
+ * `Object.values(route.components)`, which yields `[]` because `components` is a `Map`.
331
+ *
332
+ * import { monoExtendRoute } from '@mono-lit/utility/vite'
333
+ * VueRouter({ routesFolder: [...], extendRoute: monoExtendRoute() })
334
+ */
335
+ function monoExtendRoute(options = {}) {
336
+ const isRemote = remoteGate(options);
337
+ const normalizeLayouts = options.normalizeLayouts !== false;
338
+ const defaultLayout = options.defaultLayout ?? "default";
339
+ return (route) => {
340
+ const file = componentFile(route);
341
+ if (!file) {
342
+ if (normalizeLayouts) route.addToMeta({ layout: false });
343
+ return;
344
+ }
345
+ const meta = parsePageMetaFromFile(file);
346
+ if (isRemote(file) && (meta.layout !== void 0 || meta.title)) route.addToMeta(meta);
347
+ if (!normalizeLayouts) return;
348
+ if ((meta.layout ?? route.meta?.layout) === void 0) route.addToMeta({ layout: defaultLayout });
349
+ };
350
+ }
351
+
352
+ //#endregion
353
+ //#region src/vite/mono-lith.ts
354
+ const MONO_APPS_VIRTUAL_ID = "virtual:mono-apps";
355
+ const RESOLVED_VIRTUAL_ID = "\0virtual:mono-apps";
356
+ /** `C:\a\B` -> `c:/a/b` — chokidar and Vite slash paths differently, and Windows is case-insensitive. */
357
+ function normalizeFsPath(value) {
358
+ const slashed = value.replace(/\\/g, "/");
359
+ return process.platform === "win32" ? slashed.toLowerCase() : slashed;
360
+ }
361
+ /** Forward-slashed absolute path, safe inside a JS string literal. */
362
+ function importSpecifier(file) {
363
+ return JSON.stringify(file.replace(/\\/g, "/"));
364
+ }
365
+ function createMonoLithHooks(options = {}) {
366
+ const rootDir = options.dirname ?? process.cwd();
367
+ const appRoots = options.appRoots ?? resolveFederatedRoots({
368
+ dirname: rootDir,
369
+ ...options.appsDir ? { appsDir: options.appsDir } : {}
370
+ });
371
+ const siblings = pathAppRoots(appRoots);
372
+ const active = options.activeNames ? appRoots.filter((r) => options.activeNames.includes(r.name)) : appRoots;
373
+ const configFiles = [];
374
+ const ownName = extractConfig(rootDir).name ?? "<root>";
375
+ const ownConfig = monoConfigFileFor(rootDir);
376
+ if (ownConfig) configFiles.push({
377
+ name: ownName,
378
+ file: ownConfig
379
+ });
380
+ for (const root of active) {
381
+ const file = monoConfigFileFor(root.root);
382
+ if (file) configFiles.push({
383
+ name: root.name,
384
+ file
385
+ });
386
+ }
387
+ const configByPath = new Map(configFiles.map((c) => [normalizeFsPath(c.file), c.name]));
388
+ const load = (id) => {
389
+ if (id !== RESOLVED_VIRTUAL_ID) return void 0;
390
+ return [
391
+ "// Generated by @mono-lit/utility (virtual:mono-apps): one lazy import per",
392
+ "// federated app’s mono.config, whether it is a sibling or a clone.",
393
+ "export default {",
394
+ ...active.flatMap((r) => {
395
+ const file = monoConfigFileFor(r.root);
396
+ return file ? [` ${JSON.stringify(r.name)}: () => import(${importSpecifier(file)}),`] : [];
397
+ }),
398
+ "}",
399
+ ""
400
+ ].join("\n");
401
+ };
402
+ const configureServer = (server) => {
403
+ if (options.watchSiblings !== false) for (const sibling of siblings) server.watcher.add(join(sibling.root, srcDirForType(sibling.type ?? "vue")));
404
+ if (options.restartOnConfigChange === false) return;
405
+ for (const { file } of configFiles) server.watcher.add(file);
406
+ let restarting = false;
407
+ const onConfigEvent = (file) => {
408
+ const name = configByPath.get(normalizeFsPath(file));
409
+ if (!name || restarting) return;
410
+ restarting = true;
411
+ server.config.logger.info(`[mono] mono.config changed (${name}) — restarting`, { timestamp: true });
412
+ server.restart();
413
+ };
414
+ server.watcher.on("change", onConfigEvent);
415
+ server.watcher.on("add", onConfigEvent);
416
+ server.watcher.on("unlink", onConfigEvent);
417
+ };
418
+ return {
419
+ fsAllow: siblings.map((r) => r.root),
420
+ appRoots,
421
+ configureServer,
422
+ resolveId: (id) => id === "virtual:mono-apps" ? RESOLVED_VIRTUAL_ID : void 0,
423
+ load
424
+ };
425
+ }
426
+ /**
427
+ * Standalone plugin for a long-hand `vite.config.ts`. `monoRepo().vite()` /
428
+ * `mono.plugin` already include these hooks — do not register both.
429
+ *
430
+ * ```ts
431
+ * import { monoLith } from '@mono-lit/utility/vite'
432
+ * plugins: [VueRouter({ … }), vue(), monoLith({ dirname: __dirname })]
433
+ * ```
434
+ */
435
+ function monoLith(options = {}) {
436
+ const hooks = createMonoLithHooks(options);
437
+ return {
438
+ name: "mono-lith",
439
+ config() {
440
+ if (!hooks.fsAllow.length) return;
441
+ return { server: { fs: { allow: [options.dirname ?? process.cwd(), ...hooks.fsAllow] } } };
442
+ },
443
+ configureServer: hooks.configureServer,
444
+ resolveId: hooks.resolveId,
445
+ load: hooks.load
446
+ };
447
+ }
448
+
449
+ //#endregion
450
+ //#region src/vite/resolve-from-root.ts
451
+ /**
452
+ * Import the consumer's own copy of an ecosystem plugin.
453
+ *
454
+ * `mono.vite()` registers plugins (`vue-router/vite`, `unplugin-auto-import`,
455
+ * …) that belong to the **app**, not to @mono-lit/utility. Two ways to reach them, and
456
+ * only one is correct:
457
+ *
458
+ * - A bare `await import('unocss/vite')` happens to work from the plain
459
+ * `.pnpm/mono-utils@…/` layout, because the app's `node_modules` is an
460
+ * ancestor of the real path and Node's upward walk finds it. But that is
461
+ * phantom-dependency resolution: undeclared, unversioned, and silently
462
+ * dependent on the plugin being a *direct* dep of the app.
463
+ *
464
+ * - Declaring them as peerDependencies is worse. pnpm's `autoInstallPeers` is on
465
+ * (no `.npmrc` in any template), so declaring a peer installs a SECOND copy
466
+ * under @mono-lit/utility's own `node_modules/`. That already happens:
467
+ * `mono-nuxt-host` carries `@unhead/vue` twice at the identical version 3.1.3
468
+ * under different peer-hash directories. Two `vue-router` instances would mean
469
+ * two `vue-router/auto-routes` virtual modules, two UnoCSS contexts, two
470
+ * auto-import dts writers racing on the same file.
471
+ *
472
+ * So resolve from the app root explicitly. `monoRepo()` already computes it.
473
+ */
474
+ /**
475
+ * Build a {@link RootLoader} anchored at `rootDir`.
476
+ *
477
+ * `createRequire` needs a *file* to resolve from — `noop.js` never has to exist,
478
+ * it only fixes the directory the walk starts in.
479
+ */
480
+ function createRootLoader(rootDir) {
481
+ const req = createRequire(pathToFileURL(join(rootDir, "noop.js")));
482
+ return async (id) => {
483
+ try {
484
+ return await import(pathToFileURL(req.resolve(id)).href);
485
+ } catch {
486
+ return await import(id);
487
+ }
488
+ };
489
+ }
490
+ /**
491
+ * Pull the plugin factory out of a module namespace.
492
+ *
493
+ * `createRequire().resolve()` picks the **`require`** condition, so a package
494
+ * that ships both (vue-router does: `dist/unplugin/vite.cjs`) resolves to CJS.
495
+ * Importing a `.cjs` puts `module.exports` on `default` — and since that export
496
+ * is itself `{ default: fn }`, the factory ends up at `default.default`. ESM
497
+ * builds put it at `default` directly, and a few packages are the bare
498
+ * namespace. Unwrap all three rather than guessing per package.
499
+ */
500
+ function interopDefault(mod) {
501
+ const first = mod?.default ?? mod;
502
+ if (typeof first !== "function" && typeof first?.default === "function") return first.default;
503
+ return first;
504
+ }
505
+ /** Read a named export, looking through the same CJS `default` wrapper. */
506
+ function interopNamed(mod, key) {
507
+ return mod?.[key] ?? mod?.default?.[key];
508
+ }
509
+ /** `true` when `id` can be resolved from the app root. Never throws. */
510
+ function canResolveFromRoot(rootDir, id) {
511
+ const req = createRequire(pathToFileURL(join(rootDir, "noop.js")));
512
+ try {
513
+ req.resolve(id);
514
+ return true;
515
+ } catch (error) {
516
+ return error?.code === "ERR_PACKAGE_PATH_NOT_EXPORTED";
517
+ }
518
+ }
519
+
520
+ //#endregion
521
+ //#region src/vite/mono-vite.ts
522
+ /** Upstream plugin name for each key — used for the duplicate warning. */
523
+ const MONO_ECO_PLUGIN_NAMES = {
524
+ pages: "vue-router",
525
+ layouts: "vite-plugin-vue-layouts-next",
526
+ composables: "unplugin-auto-import",
527
+ components: "unplugin-vue-components"
528
+ };
529
+ /**
530
+ * Which ecosystem a `mono.ecosystem(sub)` call belongs to, by first path
531
+ * segment — `composables/shared` and `stores/shared` both feed auto-import.
532
+ */
533
+ const MONO_ECO_SUB_KEYS = {
534
+ pages: "pages",
535
+ layouts: "layouts",
536
+ components: "components",
537
+ composables: "composables",
538
+ stores: "composables"
539
+ };
540
+ /** Map one ecosystem subpath to the plugin that consumes it, if any. */
541
+ function ecoKeyForSub(sub) {
542
+ return MONO_ECO_SUB_KEYS[String(sub).split("/")[0]];
543
+ }
544
+ /**
545
+ * Resolve `own` to absolute, existing dirs. `undefined` falls back to
546
+ * `fallback`, which may name several dirs — auto-import wants both
547
+ * `composables/` and `composables/shared/`, the same pair it already asks every
548
+ * federated app for. Non-existent dirs are dropped, so naming one an app does
549
+ * not have costs nothing.
550
+ */
551
+ function ownDirs(rootDir, own, fallback) {
552
+ if (own === false) return [];
553
+ return (own === void 0 ? Array.isArray(fallback) ? fallback : [fallback] : Array.isArray(own) ? own : [own]).map((dir) => isAbsolute(dir) ? dir : resolve(rootDir, dir)).filter((dir) => existsSync(dir));
554
+ }
555
+ /**
556
+ * The auto-import presets worth defaulting. Each is gated on being resolvable
557
+ * from the app root — an app without `pinia` must not have its dev server die
558
+ * because mono assumed the template's dependency list.
559
+ */
560
+ async function defaultAutoImports(rootDir, load) {
561
+ const presets = [
562
+ "vue",
563
+ "vue-router",
564
+ "@vueuse/core",
565
+ "pinia"
566
+ ].filter((id) => canResolveFromRoot(rootDir, id));
567
+ if (canResolveFromRoot(rootDir, "@unhead/vue")) {
568
+ const preset = interopNamed(await load("@unhead/vue"), "unheadVueComposablesImports");
569
+ if (preset) presets.push(preset);
570
+ }
571
+ if (canResolveFromRoot(rootDir, "vue-router/unplugin")) {
572
+ const preset = interopNamed(await load("vue-router/unplugin"), "VueRouterAutoImports");
573
+ if (preset) presets.push(preset);
574
+ }
575
+ return presets;
576
+ }
577
+ /**
578
+ * Make the compat transforms beat `vue-router`'s own macro transform no matter
579
+ * where they land in the array.
580
+ *
581
+ * `enforce: 'pre'` only buckets them WITH vue-router (which is also `pre`);
582
+ * within a bucket, array order decides. That was fine while `vite()` owned the
583
+ * whole array, but the moment a consumer writes `mono.pages()` above
584
+ * `mono.vite()` the compat rewrites would run *after* vue-router had already
585
+ * transformed the module — and `mono-strip-pagemeta` has to get there first.
586
+ *
587
+ * Vite re-partitions on the HOOK-level `order` field globally
588
+ * (`getSortedPluginsByHook`), so promoting `transform` to its object form makes
589
+ * the ordering intrinsic rather than positional. Applied here rather than in
590
+ * each plugin file so `monoVue()`'s existing standalone behaviour is untouched.
591
+ */
592
+ function transformFirst(plugins) {
593
+ return plugins.map((plugin) => {
594
+ const hook = plugin.transform;
595
+ if (typeof hook !== "function") return plugin;
596
+ return {
597
+ ...plugin,
598
+ transform: {
599
+ order: "pre",
600
+ handler: hook
601
+ }
602
+ };
603
+ });
604
+ }
605
+ /** `VueRouter()` options: own + federated page folders, plus `extendRoute`. */
606
+ function monoPagesOptions(ctx, opts = {}, extendRouteOpts) {
607
+ ctx.built.add("pages");
608
+ const { rootDir, ownType, ecosystem, extendRoute } = ctx;
609
+ const { own, ...pass } = opts;
610
+ const pagesDirs = ownDirs(rootDir, own, `${srcDirForType(ownType)}/pages`);
611
+ const remote = pagesDirs.some((dir) => existsSync(join(dir, "index.vue"))) ? { exclude: ["*/index.vue"] } : {};
612
+ return {
613
+ routesFolder: [...pagesDirs.map((dir) => ({ src: dir })), ...ecosystem("pages").map((dir) => ({
614
+ src: dir,
615
+ ...remote
616
+ }))],
617
+ ...extendRouteOpts !== false && { extendRoute: extendRoute(extendRouteOpts || void 0) },
618
+ ...pass
619
+ };
620
+ }
621
+ /**
622
+ * `Layouts()` options: own layout dirs, plus the federated ones unless this app
623
+ * is the host.
624
+ *
625
+ * Layouts are the one ecosystem where the two roles genuinely disagree. A HOST
626
+ * ships the shared shell, so it renders its own `layouts/` and must not adopt a
627
+ * remote's — a remote's `default.vue` would otherwise compete with the shell's.
628
+ * A REMOTE is the opposite: it has no shell of its own and consumes the host's.
629
+ * `template` in `mono.config.ts` is what says which, and it is the only thing
630
+ * that can — the distinction is not visible on disk (an app with no `layouts/`
631
+ * looks the same either way, and `ownDirs` already drops it).
632
+ *
633
+ * `template` sets a DEFAULT, not a lock: `layoutsDirs` replaces the whole list,
634
+ * so one call can always opt out without a mono-specific knob.
635
+ */
636
+ function monoLayoutsOptions(ctx, opts = {}) {
637
+ ctx.built.add("layouts");
638
+ const { rootDir, ownType, ecosystem, template } = ctx;
639
+ const { own, ...pass } = opts;
640
+ return {
641
+ layoutsDirs: [...ownDirs(rootDir, own, `${srcDirForType(ownType)}/layouts`), ...template === "host" ? [] : ecosystem("layouts")],
642
+ defaultLayout: "default",
643
+ ...pass
644
+ };
645
+ }
646
+ /**
647
+ * `AutoImport()` options: own + federated composables AND stores dirs.
648
+ *
649
+ * `imports` covers only the preset NAMES that resolve from this app. The object
650
+ * presets (`unheadVueComposablesImports`, `VueRouterAutoImports`) need a module
651
+ * load, which cannot happen synchronously — import them in your config and pass
652
+ * your own `imports`, or use `mono.autoImport()`, which resolves them for you.
653
+ */
654
+ function monoAutoImportOptions(ctx, opts = {}) {
655
+ ctx.built.add("composables");
656
+ const { rootDir, ownType, ecosystem } = ctx;
657
+ const { composables = {}, stores = {}, ...pass } = opts;
658
+ const src = srcDirForType(ownType);
659
+ const wantComposables = composables !== false;
660
+ const wantStores = stores !== false;
661
+ return {
662
+ imports: [
663
+ "vue",
664
+ "vue-router",
665
+ "@vueuse/core",
666
+ "pinia"
667
+ ].filter((id) => canResolveFromRoot(rootDir, id)),
668
+ dts: `${src}/auto-imports.d.ts`,
669
+ vueTemplate: true,
670
+ dirs: [
671
+ ...wantComposables ? ownDirs(rootDir, (composables || {}).own, [`${src}/composables`, `${src}/composables/shared`]) : [],
672
+ ...wantStores ? ownDirs(rootDir, (stores || {}).own, [`${src}/stores`, `${src}/stores/shared`]) : [],
673
+ ...ecosystem([...wantComposables ? ["composables/shared", "composables"] : [], ...wantStores ? ["stores/shared", "stores"] : []])
674
+ ],
675
+ ...pass
676
+ };
677
+ }
678
+ /** `Components()` options: own + federated component dirs. */
679
+ function monoComponentsOptions(ctx, opts = {}) {
680
+ ctx.built.add("components");
681
+ const { rootDir, ownType, ecosystem } = ctx;
682
+ const { own, ...pass } = opts;
683
+ const src = srcDirForType(ownType);
684
+ return {
685
+ extensions: ["vue"],
686
+ include: [/\.vue$/, /\.vue\?vue/],
687
+ dts: `${src}/components.d.ts`,
688
+ directoryAsNamespace: true,
689
+ collapseSamePrefixes: true,
690
+ dirs: [...ownDirs(rootDir, own, `${src}/components`), ...ecosystem("components")],
691
+ ...pass
692
+ };
693
+ }
694
+ /** `vue-router/vite` + `ecosystem('pages')` + `extendRoute`. `enforce: 'pre'`. */
695
+ function monoPages(ctx, opts = {}, extendRouteOpts) {
696
+ const options = monoPagesOptions(ctx, opts, extendRouteOpts);
697
+ return (async () => {
698
+ return tagEco(interopDefault(await createRootLoader(ctx.rootDir)("vue-router/vite"))(options), "pages");
699
+ })();
700
+ }
701
+ /** `vite-plugin-vue-layouts-next` + `ecosystem('layouts')`. `enforce: 'pre'`. */
702
+ function monoLayouts(ctx, opts = {}) {
703
+ const options = monoLayoutsOptions(ctx, opts);
704
+ return (async () => {
705
+ return tagEco(interopDefault(await createRootLoader(ctx.rootDir)("vite-plugin-vue-layouts-next"))(options), "layouts");
706
+ })();
707
+ }
708
+ /**
709
+ * `unplugin-auto-import/vite` + the federated composables AND stores dirs.
710
+ * `enforce: 'post'`. One plugin covers both ecosystems, so `stores` is a
711
+ * dirs-only companion option rather than its own factory.
712
+ */
713
+ function monoAutoImport(ctx, opts = {}) {
714
+ const options = monoAutoImportOptions(ctx, opts);
715
+ return (async () => {
716
+ const load = createRootLoader(ctx.rootDir);
717
+ return tagEco(interopDefault(await load("unplugin-auto-import/vite"))({
718
+ ...options,
719
+ imports: opts.imports ?? await defaultAutoImports(ctx.rootDir, load)
720
+ }), "composables");
721
+ })();
722
+ }
723
+ /** `unplugin-vue-components/vite` + `ecosystem('components')`. `enforce: 'post'`. */
724
+ function monoComponents(ctx, opts = {}) {
725
+ const options = monoComponentsOptions(ctx, opts);
726
+ return (async () => {
727
+ return tagEco(interopDefault(await createRootLoader(ctx.rootDir)("unplugin-vue-components/vite"))(options), "components");
728
+ })();
729
+ }
730
+ /**
731
+ * Build the federated plugin stack.
732
+ *
733
+ * Returned order matters only WITHIN each `enforce` bucket, and that is exactly
734
+ * what this controls: compat transforms before `VueRouter` (both `pre`), and
735
+ * `mono.plugin` after auto-import/components (both `post`).
736
+ *
737
+ * Any ecosystem plugin already built via its own factory earlier in the same
738
+ * `plugins` array is skipped, so mixing the two styles never double-registers.
739
+ */
740
+ async function monoVite(ctx, opts = {}) {
741
+ const { apps, hostResolver, plugin, built } = ctx;
742
+ const out = [];
743
+ // @vitejs/plugin-vue then read.
744
+ const compat = opts.nuxtCompat;
745
+ if (typeof compat === "boolean" ? compat : compat != null || !built.has("compat") && apps.some((app) => app.type === "nuxt")) out.push(...transformFirst(hostResolver(typeof compat === "object" ? compat : {})));
746
+ /**
747
+ * Should `vite()` build this ecosystem's plugin?
748
+ *
749
+ * - `false` never
750
+ * - an object always — an explicit option outranks the skip, so
751
+ * `vite({ components: {…} })` wins even if something else
752
+ * marked it
753
+ * - `undefined` only if the consumer has not already wired it (via a mono
754
+ * factory, `.options()`, or `mono.ecosystem(<that sub>)`)
755
+ */
756
+ const wanted = (key, value) => value !== false && (value != null || !built.has(key));
757
+ if (wanted("pages", opts.pages)) out.push(await monoPages(ctx, opts.pages || {}, opts.extendRoute));
758
+ if (wanted("layouts", opts.layouts)) out.push(await monoLayouts(ctx, opts.layouts || {}));
759
+ if (wanted("composables", opts.composables) || wanted("composables", opts.stores)) {
760
+ const { own, ...rest } = (opts.composables === false ? {} : opts.composables) ?? {};
761
+ out.push(await monoAutoImport(ctx, {
762
+ ...rest,
763
+ composables: opts.composables === false ? false : own === void 0 ? {} : { own },
764
+ stores: opts.stores
765
+ }));
766
+ }
767
+ if (wanted("components", opts.components)) out.push(await monoComponents(ctx, opts.components || {}));
768
+ if (!built.has("plugin")) out.push(plugin);
769
+ return out;
770
+ }
771
+ /** Marks a plugin instance mono built, and for which ecosystem. */
772
+ const MONO_ECO_TAG = "__monoEco";
773
+ /** Marks an instance mono has already stood down. */
774
+ const MONO_NEUTRALIZED = "__monoNeutralized";
775
+ /** Tag every plugin object a builder produced (a factory may return an array). */
776
+ function tagEco(built, key) {
777
+ const walk = (entry) => {
778
+ if (Array.isArray(entry)) return entry.forEach(walk);
779
+ if (entry && typeof entry === "object") entry[MONO_ECO_TAG] = key;
780
+ };
781
+ walk(built);
782
+ return built;
783
+ }
784
+ /** A hook that does nothing. `transform`/`resolveId`/`load` must return null. */
785
+ function noopHook(name) {
786
+ return [
787
+ "transform",
788
+ "resolveId",
789
+ "load"
790
+ ].includes(name) ? () => null : () => void 0;
791
+ }
792
+ /**
793
+ * Stand a plugin instance down without removing it.
794
+ *
795
+ * Vite fixes the plugin list before any `config()` hook runs, so a duplicate
796
+ * cannot be spliced out. Its hooks CAN be replaced, though. Hooks are replaced with
797
+ * no-ops rather than deleted, because `getSortedPluginsByHook` may already have
798
+ * captured this plugin as a hook owner, and it would then call `undefined`.
799
+ */
800
+ function neutralize(plugin) {
801
+ if (plugin[MONO_NEUTRALIZED]) return;
802
+ plugin[MONO_NEUTRALIZED] = true;
803
+ if (plugin.transformInclude) plugin.transformInclude = () => false;
804
+ for (const name of [
805
+ "transform",
806
+ "resolveId",
807
+ "load",
808
+ "buildStart",
809
+ "buildEnd",
810
+ "configureServer",
811
+ "closeBundle",
812
+ "writeBundle",
813
+ "generateBundle"
814
+ ]) {
815
+ const hook = plugin[name];
816
+ if (hook == null) continue;
817
+ plugin[name] = typeof hook === "object" ? {
818
+ ...hook,
819
+ handler: noopHook(name)
820
+ } : noopHook(name);
821
+ }
822
+ }
823
+ /**
824
+ * Make `mono.vite()` win when an ecosystem is registered twice.
825
+ *
826
+ * The long-hand config registers `VueRouter`/`AutoImport`/`Components`/`Layouts`
827
+ * by hand. Passing that ecosystem to `vite({ components: {…} })` says "mono owns
828
+ * this one now" — so mono's instance stays live and the hand-written one is
829
+ * stood down, leaving exactly one active plugin per ecosystem.
830
+ *
831
+ * When neither instance is mono's, nothing is touched: that is the consumer's
832
+ * own duplicate, and silently disabling one would be worse than saying so.
833
+ */
834
+ function reconcileEcoPlugins(plugins) {
835
+ const known = new Set(Object.values(MONO_ECO_PLUGIN_NAMES));
836
+ const byName = /* @__PURE__ */ new Map();
837
+ const walk = (entry) => {
838
+ if (Array.isArray(entry)) return entry.forEach(walk);
839
+ const plugin = entry;
840
+ if (!plugin || typeof plugin !== "object") return;
841
+ const name = plugin.name;
842
+ if (!name || !known.has(name)) return;
843
+ byName.set(name, [...byName.get(name) ?? [], plugin]);
844
+ };
845
+ walk(plugins);
846
+ const won = [];
847
+ const conflicting = [];
848
+ for (const [name, list] of byName) {
849
+ if (list.length < 2) continue;
850
+ const mine = list.find((plugin) => plugin[MONO_ECO_TAG]);
851
+ if (!mine) {
852
+ conflicting.push(name);
853
+ continue;
854
+ }
855
+ for (const plugin of list) if (plugin !== mine) neutralize(plugin);
856
+ won.push(name);
857
+ }
858
+ if (won.length) console.info(`[mono] ${won.join(", ")}: mono.vite() options given, so mono's instance is active and the hand-written one was stood down.`);
859
+ if (conflicting.length) console.warn(`[mono] ${conflicting.join(", ")} registered more than once, neither by mono.\n[mono] Two unplugin-auto-import instances race on one auto-imports.d.ts and two\n[mono] vue-router instances scan every page twice. Remove one, or hand the\n[mono] ecosystem to mono.vite({ … }) and let it own the plugin.`);
860
+ return {
861
+ won,
862
+ conflicting
863
+ };
864
+ }
865
+
866
+ //#endregion
867
+ //#region src/vite/mono-repo.ts
868
+ /** Default `__MONO_CONFIG_EXPOSE__` shape — kept in sync with `host-nuxt.ts`. */
869
+ /**
870
+ * Merge the computed `monoAlias` UNDER the host's own `resolve.alias` so the
871
+ * host's explicit aliases always win (mirrors `nuxt.options.alias = { ...alias,
872
+ * ...nuxt.options.alias }` in `host-nuxt.ts`). Handles both the object and the
873
+ * `[{ find, replacement }]` array forms Vite accepts.
874
+ */
875
+ function composeAlias(userAlias, mono) {
876
+ if (Array.isArray(userAlias)) return [...userAlias, ...Object.entries(mono).map(([find, replacement]) => ({
877
+ find,
878
+ replacement
879
+ }))];
880
+ if (userAlias && typeof userAlias === "object") return {
881
+ ...mono,
882
+ ...userAlias
883
+ };
884
+ return mono;
885
+ }
886
+ /**
887
+ * Mono Vite host helper — the single-call Vite equivalent of the Nuxt host's
888
+ * `@mono-lit/utility/nuxt` module.
889
+ *
890
+ * Loads `mono.config.ts` ONCE (c12/jiti, taught the `monoAlias` map), resolves
891
+ * the `extends`-active apps, and returns:
892
+ * - `plugin`: a Vite plugin (register LAST) wiring `resolve.alias`,
893
+ * `__MONO_CONFIG_EXPOSE__`, `server.fs.allow` and dep dedup
894
+ * - `ecosystem(subs)`: type-aware remote dir discovery (`nuxt` -> `app/<sub>`,
895
+ * `vue` -> `src/<sub>`) to feed AutoImport / Components / Layouts / VueRouter
896
+ * `routesFolder` at registration time
897
+ * - `config` / `alias` / `apps`: the resolved values, for advanced use
898
+ *
899
+ * Why async + explicit dirs (not post-registration injection): current
900
+ * `unplugin-auto-import` exposes no `api`, `unplugin-vue-components`' `api` has
901
+ * no `options`, and `vue-router` / `vite-plugin-vue-layouts-next` capture their
902
+ * dirs option in a closure — so none of them can be mutated after registration.
903
+ * Passing dirs at registration is the only reliable path; this helper just
904
+ * centralises the config load so you discover them with one-liner
905
+ * `mono.ecosystem(...)` instead of repeating `monoAlias` / `getMonoConfig` /
906
+ * `activeApps` / `define` / `server.fs` in every host.
907
+ *
908
+ * import { monoRepo } from '@mono-lit/utility/vite'
909
+ *
910
+ * export default defineConfig(async ({ mode }) => {
911
+ * const mono = await monoRepo()
912
+ * return {
913
+ * plugins: [
914
+ * vue({ template: { compilerOptions: { isCustomElement } } }),
915
+ * UnoCSS(),
916
+ * mono.vite(), // ← VueRouter + layouts + auto-import + components + plugin
917
+ * ],
918
+ * }
919
+ * })
920
+ *
921
+ * The same file works whether the federated remote is a Nuxt app or a Vue one —
922
+ * `vite()` reads `apps[].type` and adds the Nuxt-compat transforms only when one
923
+ * is a Nuxt remote. `ecosystem()` stays public for anything `vite()` does not
924
+ * own, and any ecosystem key can be turned off to register it by hand:
925
+ *
926
+ * mono.vite({ layouts: false }),
927
+ * Layouts({ layoutsDirs: mono.ecosystem('layouts') }),
928
+ */
929
+ async function monoRepo(options = {}) {
930
+ const rootDir = options.dirname ?? process.cwd();
931
+ assertAppSources(extractConfig(rootDir).apps, rootDir);
932
+ const alias = monoAlias({
933
+ dirname: rootDir,
934
+ ...options.appsDir ? { appsDir: options.appsDir } : {}
935
+ });
936
+ const appRoots = resolveFederatedRoots({
937
+ dirname: rootDir,
938
+ ...options.appsDir ? { appsDir: options.appsDir } : {}
939
+ });
940
+ const linked = pathAppRoots(appRoots);
941
+ if (linked.length && options.warnMissing !== false) console.info(`[mono] reading ${linked.map((a) => a.name).join(", ")} from apps[].path — the same directories are used by build, prepare and sync.`);
942
+ for (const [key, value] of Object.entries(options.alias ?? {})) {
943
+ const dir = value?.dir;
944
+ if (!dir) continue;
945
+ alias[key] = isAbsolute(dir) ? dir : resolve(rootDir, dir);
946
+ }
947
+ const { alias: stubAlias, missing } = options.stubMissing === false ? {
948
+ alias: {},
949
+ missing: []
950
+ } : monoStubAliases({
951
+ dirname: rootDir,
952
+ ...options.appsDir ? { appsDir: options.appsDir } : {}
953
+ });
954
+ if (missing.length && options.warnMissing !== false) console.warn(formatMissingApps(missing));
955
+ const rawConfig = await getMonoConfig({
956
+ cwd: rootDir,
957
+ jitiOptions: { alias: {
958
+ ...alias,
959
+ ...stubAlias
960
+ } }
961
+ });
962
+ const hasExtends = rawConfig.extends != null;
963
+ const activeNames = resolveExtendsAppNames(rawConfig);
964
+ const apps = (rawConfig.apps ?? []).filter((a) => hasExtends ? activeNames.includes(a.name) : true).map((a) => ({
965
+ name: a.name,
966
+ type: a.type,
967
+ ...a.path ? { path: a.path } : {}
968
+ }));
969
+ const monoConfig = {
970
+ ...resolveMonoConfig(rawConfig),
971
+ apps: rawConfig.apps,
972
+ ...rawConfig.extends != null ? { extends: rawConfig.extends } : {}
973
+ };
974
+ const ecosystems = resolveExtendsEcosystems(rawConfig);
975
+ const built = /* @__PURE__ */ new Set();
976
+ const ecosystem = (subs) => {
977
+ for (const sub of Array.isArray(subs) ? subs : [subs]) {
978
+ const key = ecoKeyForSub(sub);
979
+ if (key) built.add(key);
980
+ }
981
+ return monoEcosystem({
982
+ dirname: rootDir,
983
+ apps,
984
+ subs,
985
+ ecosystems
986
+ });
987
+ };
988
+ const nuxt = () => ({
989
+ hostResolver: (userOpts = {}) => {
990
+ built.add("compat");
991
+ const opts = {
992
+ ...userOpts,
993
+ appsRoots: userOpts.appsRoots ?? appRootDirs(appRoots)
994
+ };
995
+ const plugins = [monoPageMetaToDefinePage(opts), monoLayoutSlotToRouterView(opts)];
996
+ if (opts.nuxtState !== false) plugins.push(monoNuxtStateToRef(opts));
997
+ if (opts.nuxtLink !== false) plugins.push(monoNuxtLinkToRouterLink(opts));
998
+ if (opts.defineImportMeta !== false) plugins.push({
999
+ name: "mono-define-import-meta",
1000
+ config() {
1001
+ return { define: {
1002
+ "import.meta.server": "false",
1003
+ "import.meta.client": "true"
1004
+ } };
1005
+ }
1006
+ });
1007
+ return plugins;
1008
+ },
1009
+ extendRoute: (opts = {}) => extendRoute(opts)
1010
+ });
1011
+ let didConfig = false;
1012
+ let didConfigResolved = false;
1013
+ const lith = createMonoLithHooks({
1014
+ dirname: rootDir,
1015
+ appRoots,
1016
+ activeNames: apps.map((a) => a.name),
1017
+ restartOnConfigChange: options.restartOnConfigChange,
1018
+ watchSiblings: options.watchSiblings
1019
+ });
1020
+ const plugin = {
1021
+ name: "mono-repo",
1022
+ enforce: "post",
1023
+ configureServer: lith.configureServer,
1024
+ resolveId: lith.resolveId,
1025
+ load: lith.load,
1026
+ configResolved(resolved) {
1027
+ if (didConfigResolved) return;
1028
+ didConfigResolved = true;
1029
+ reconcileEcoPlugins(resolved.plugins);
1030
+ },
1031
+ config(config) {
1032
+ if (didConfig) return;
1033
+ didConfig = true;
1034
+ return {
1035
+ resolve: { alias: composeAlias(config.resolve?.alias, {
1036
+ ...stubAlias,
1037
+ ...alias
1038
+ }) },
1039
+ define: { __MONO_CONFIG_EXPOSE__: JSON.stringify(sanitizeForExpose((options.expose ?? defaultMonoExpose)(monoConfig)) ?? null) },
1040
+ server: { fs: { allow: [
1041
+ rootDir,
1042
+ join(rootDir, ".mono", "apps"),
1043
+ ...appRootDirs(linked)
1044
+ ] } },
1045
+ optimizeDeps: { exclude: [...options.optimizeExclude ?? ["@mono-lit/helper"]] }
1046
+ };
1047
+ }
1048
+ };
1049
+ const extendRoute = (opts = {}) => monoExtendRoute({
1050
+ appsRoots: appRootDirs(appRoots),
1051
+ ...opts
1052
+ });
1053
+ const viteCtx = {
1054
+ rootDir,
1055
+ ownType: monoConfig.type ?? "vue",
1056
+ ...monoConfig.template ? { template: monoConfig.template } : {},
1057
+ apps,
1058
+ ecosystem,
1059
+ extendRoute,
1060
+ hostResolver: nuxt().hostResolver,
1061
+ plugin,
1062
+ built
1063
+ };
1064
+ const vite = (opts = {}) => monoVite(viteCtx, opts);
1065
+ const pages = Object.assign((opts = {}) => monoPages(viteCtx, opts), { options: (opts = {}) => monoPagesOptions(viteCtx, opts) });
1066
+ const layouts = Object.assign((opts = {}) => monoLayouts(viteCtx, opts), { options: (opts = {}) => monoLayoutsOptions(viteCtx, opts) });
1067
+ const autoImport = Object.assign((opts = {}) => monoAutoImport(viteCtx, opts), { options: (opts = {}) => monoAutoImportOptions(viteCtx, opts) });
1068
+ const result = {
1069
+ vite,
1070
+ pages,
1071
+ layouts,
1072
+ autoImport,
1073
+ composables: autoImport,
1074
+ components: Object.assign((opts = {}) => monoComponents(viteCtx, opts), { options: (opts = {}) => monoComponentsOptions(viteCtx, opts) }),
1075
+ plugin,
1076
+ ecosystem,
1077
+ extendRoute,
1078
+ nuxt,
1079
+ config: monoConfig,
1080
+ alias,
1081
+ apps,
1082
+ appRoots
1083
+ };
1084
+ Object.defineProperty(result, "plugin", {
1085
+ enumerable: true,
1086
+ configurable: true,
1087
+ get() {
1088
+ built.add("plugin");
1089
+ return plugin;
1090
+ }
1091
+ });
1092
+ return result;
1093
+ }
1094
+
1095
+ //#endregion
1096
+ //#region src/vite/index.ts
1097
+ /**
1098
+ * Vite-host compatibility layer for running a **Nuxt remote** inside a plain
1099
+ * Vue 3 + Vite host. Returns the plugins needed for the narrow Nuxt surface the
1100
+ * synced remote code uses:
1101
+ * - strips the Nuxt `definePageMeta({…})` macro from `.mono/apps/*.vue` (route meta is
1102
+ * injected separately by the host's `extendRoute` via `parsePageMetaFromFile`)
1103
+ * - rewrites a remote layout's default `<slot/>` -> `<router-view/>` (so Nuxt
1104
+ * `<slot>` layouts render the page under `setupLayouts`' nested routes)
1105
+ * - points Nuxt's auto-imported `useState()` at the `@mono-lit/utility/runtime` shim
1106
+ * (a keyed ref registry — `useState('k', () => 'hello')` -> a shared `ref('hello')`)
1107
+ * - rewrites `<NuxtLink>` -> `<RouterLink>` (`external` adds `target="_blank"`,
1108
+ * so the browser navigates for real; an absolute-URL `to` becomes an `<a>`)
1109
+ * - defines `import.meta.server`/`import.meta.client` (SPA client constants)
1110
+ *
1111
+ * Mirrors `@mono-lit/helper/vite`'s `monoSsr()` shape. Register before `VueRouter()`:
1112
+ * import { monoVue } from '@mono-lit/utility/vite'
1113
+ * plugins: [ ...monoVue(), VueRouter({...}), vue(), ... ]
1114
+ */
1115
+ function monoVue(options = {}) {
1116
+ const plugins = [monoPageMetaToDefinePage(options), monoLayoutSlotToRouterView(options)];
1117
+ if (options.nuxtState !== false) plugins.push(monoNuxtStateToRef(options));
1118
+ if (options.nuxtLink !== false) plugins.push(monoNuxtLinkToRouterLink(options));
1119
+ if (options.defineImportMeta !== false) plugins.push({
1120
+ name: "mono-define-import-meta",
1121
+ config() {
1122
+ return { define: {
1123
+ "import.meta.server": "false",
1124
+ "import.meta.client": "true"
1125
+ } };
1126
+ }
1127
+ });
1128
+ return plugins;
1129
+ }
1130
+
1131
+ //#endregion
1132
+ export { MONO_APPS_VIRTUAL_ID, MONO_ECO_PLUGIN_NAMES, MONO_ECO_SUB_KEYS, canResolveFromRoot, createMonoLithHooks, createRootLoader, ecoKeyForSub, monoAutoImport, monoAutoImportOptions, monoComponents, monoComponentsOptions, monoExtendRoute, monoLayoutSlotToRouterView, monoLayouts, monoLayoutsOptions, monoLith, monoVue as monoNuxtHost, monoVue, monoNuxtLink, monoNuxtLinkToRouterLink, monoNuxtState, monoNuxtStateToRef, monoPageMetaToDefinePage, monoPages, monoPagesOptions, monoRepo, monoRouterLink, monoRouterLinkToNuxtLink, monoStripPageMeta, monoVite, parsePageMeta, parsePageMetaFromFile, reconcileEcoPlugins, sanitizeForExpose };