@i18n-micro/vitepress 1.0.1 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +73 -39
  2. package/client.d.ts +1 -0
  3. package/dist/adapter-BJ-0ltIc.cjs +2 -0
  4. package/dist/adapter-BJ-0ltIc.cjs.map +1 -0
  5. package/dist/adapter-BnsyIKhp.js +128 -0
  6. package/dist/adapter-BnsyIKhp.js.map +1 -0
  7. package/dist/config.cjs +64 -1
  8. package/dist/config.cjs.map +1 -1
  9. package/dist/config.d.cts +113 -111
  10. package/dist/config.d.ts +113 -111
  11. package/dist/config.mjs +393 -9
  12. package/dist/config.mjs.map +1 -1
  13. package/dist/create-BgMbe0w1.cjs +2 -0
  14. package/dist/create-BgMbe0w1.cjs.map +1 -0
  15. package/dist/create-Dev8Q66O.js +80 -0
  16. package/dist/create-Dev8Q66O.js.map +1 -0
  17. package/dist/index.cjs +1 -1
  18. package/dist/index.cjs.map +1 -1
  19. package/dist/index.d.cts +87 -141
  20. package/dist/index.d.ts +87 -141
  21. package/dist/index.mjs +28 -249
  22. package/dist/index.mjs.map +1 -1
  23. package/dist/node.cjs +1 -1
  24. package/dist/node.cjs.map +1 -1
  25. package/dist/node.d.cts +56 -116
  26. package/dist/node.d.ts +56 -116
  27. package/dist/node.mjs +23 -7
  28. package/dist/node.mjs.map +1 -1
  29. package/dist/{virtual-stubs → plugin/virtual-stubs}/config.d.cts +2 -1
  30. package/dist/runtime/define-theme.d.cts +39 -0
  31. package/dist/theme.cjs +2 -0
  32. package/dist/theme.cjs.map +1 -0
  33. package/dist/theme.d.cts +58 -0
  34. package/dist/theme.d.ts +58 -0
  35. package/dist/theme.mjs +35 -0
  36. package/dist/theme.mjs.map +1 -0
  37. package/dist/vitepress-locales-6msv22Sn.js +27 -0
  38. package/dist/vitepress-locales-6msv22Sn.js.map +1 -0
  39. package/dist/vitepress-locales-Cz4AutfI.cjs +2 -0
  40. package/dist/vitepress-locales-Cz4AutfI.cjs.map +1 -0
  41. package/package.json +18 -6
  42. package/dist/i18n-routing-CcppCuuS.js +0 -64
  43. package/dist/i18n-routing-CcppCuuS.js.map +0 -1
  44. package/dist/i18n-routing-D9iYAKDq.cjs +0 -46
  45. package/dist/i18n-routing-D9iYAKDq.cjs.map +0 -1
  46. package/dist/with-i18n-micro-01q-vPO9.cjs +0 -15
  47. package/dist/with-i18n-micro-01q-vPO9.cjs.map +0 -1
  48. package/dist/with-i18n-micro-DIAoqY71.js +0 -216
  49. package/dist/with-i18n-micro-DIAoqY71.js.map +0 -1
package/dist/config.mjs CHANGED
@@ -1,12 +1,396 @@
1
- import { a as o, l as r, b as t, c as e, w as l, d as n } from "./with-i18n-micro-DIAoqY71.js";
2
- import { c } from "./i18n-routing-CcppCuuS.js";
1
+ import { existsSync as I, readdirSync as G, statSync as Q, readFileSync as z } from "node:fs";
2
+ import { resolve as W, join as X, relative as F, sep as J } from "node:path";
3
+ import { storeLoadedTranslationFile as Y, classifyTranslationRelativePath as Z } from "@i18n-micro/utils/parse-path";
4
+ import { resolveHreflangAlternates as ee } from "@i18n-micro/utils/resolve-hreflang";
5
+ import { resolveOgLocale as B, warnUnresolvedOgLocale as D } from "@i18n-micro/utils/resolve-og-locale";
6
+ import { s as te, g as ae } from "./adapter-BnsyIKhp.js";
7
+ import { b as ve } from "./vitepress-locales-6msv22Sn.js";
8
+ function oe(e) {
9
+ return "switchLocalePath" in e && typeof e.switchLocalePath == "function";
10
+ }
11
+ function U(e) {
12
+ const t = oe(e) ? {
13
+ defaultLocale: e.defaultLocale,
14
+ localeCodes: e.localeCodes,
15
+ localeKeyToCode: e.localeKeyToCode ?? {},
16
+ base: e.base
17
+ } : e, a = t.defaultLocale, o = t.localeCodes, s = t.localeKeyToCode ?? {}, l = t.base && t.base !== "/" ? t.base : "";
18
+ return new Function(
19
+ "data",
20
+ "route",
21
+ "targetLocale",
22
+ `
23
+ const defaultLocale = ${JSON.stringify(a)};
24
+ const localeCodes = ${JSON.stringify(o)};
25
+ const localeKeyToCode = ${JSON.stringify(s)};
26
+ const siteBase = ${JSON.stringify(l)};
27
+ const keyFromCode = (code) => {
28
+ for (const key of Object.keys(localeKeyToCode)) {
29
+ if (localeKeyToCode[key] === code) return key;
30
+ }
31
+ return code === defaultLocale ? 'root' : code;
32
+ };
33
+ const prefixes = [];
34
+ for (let i = 0; i < localeCodes.length; i++) {
35
+ const code = localeCodes[i];
36
+ if (code === defaultLocale) continue;
37
+ const key = keyFromCode(code);
38
+ const urlKey = key === 'root' ? code : key;
39
+ prefixes.push(urlKey);
40
+ if (urlKey !== code) prefixes.push(code);
41
+ }
42
+ // VitePress passes locale *keys* (root / fr). URL prefix is the key, not the i18n code.
43
+ const urlPrefix = targetLocale === 'root' ? null : targetLocale;
44
+ let path = (route && route.path) || '/';
45
+ const hash = (route && route.hash) || '';
46
+ const query = (route && route.query) || '';
47
+ const hashIndex = path.indexOf('#');
48
+ const queryIndex = path.indexOf('?');
49
+ let cut = path.length;
50
+ if (hashIndex >= 0) cut = Math.min(cut, hashIndex);
51
+ if (queryIndex >= 0) cut = Math.min(cut, queryIndex);
52
+ let pathname = path.slice(0, cut) || '/';
53
+ const extras = path.slice(cut);
54
+ if (siteBase) {
55
+ const b = siteBase.endsWith('/') ? siteBase.slice(0, -1) : siteBase;
56
+ if (pathname === b) pathname = '/';
57
+ else if (pathname.indexOf(b + '/') === 0) pathname = pathname.slice(b.length) || '/';
58
+ }
59
+ const hadTrailingSlash = pathname === '/' || pathname.endsWith('/');
60
+ const segments = pathname.split('/').filter(Boolean);
61
+ if (segments[0] && prefixes.indexOf(segments[0]) >= 0) segments.shift();
62
+ if (urlPrefix) segments.unshift(urlPrefix);
63
+ let localized = segments.length === 0 ? '/' : '/' + segments.join('/');
64
+ if (localized !== '/' && hadTrailingSlash) localized += '/';
65
+ const q = extras.indexOf('?') >= 0
66
+ ? ''
67
+ : (query ? (query.charAt(0) === '?' ? query : '?' + query) : '');
68
+ const h = hash
69
+ ? (hash.charAt(0) === '#' ? hash : '#' + hash)
70
+ : '';
71
+ return localized + extras + q + h;
72
+ `
73
+ );
74
+ }
75
+ function se(e, t) {
76
+ const a = e.indexOf("#"), o = e.indexOf("?");
77
+ let s = e.length;
78
+ a >= 0 && (s = Math.min(s, a)), o >= 0 && (s = Math.min(s, o));
79
+ const l = e.slice(0, s) || "/";
80
+ if (o < 0 || t.length === 0) return l;
81
+ const n = new URLSearchParams(e.slice(o, a >= 0 ? a : void 0)), i = new URLSearchParams();
82
+ for (const f of t)
83
+ n.has(f) && i.set(f, n.get(f));
84
+ const h = i.toString();
85
+ return h ? `${l}?${h}` : l;
86
+ }
87
+ function N(e, t, a) {
88
+ const o = e.replace(/\/$/, ""), s = !t || t === "/" ? "" : t.replace(/\/$/, ""), l = a.startsWith("/") ? a : `/${a}`;
89
+ return `${o}${s}${l}`;
90
+ }
91
+ function R(e) {
92
+ let t = e.replace(/\\/g, "/");
93
+ return t = t.replace(/(^|\/)index\.md$/, "$1").replace(/\.md$/, ""), t.startsWith("/") || (t = `/${t}`), t.length > 1 && t.endsWith("/") && (t = t.slice(0, -1)), t || "/";
94
+ }
95
+ function E(e) {
96
+ const {
97
+ locales: t,
98
+ defaultLocale: a,
99
+ localeKeyToCode: o = {},
100
+ base: s,
101
+ metaBaseUrl: l,
102
+ hreflangBaseLanguage: n = !1,
103
+ canonicalQueryWhitelist: i = [],
104
+ addDirAttribute: h = !0,
105
+ addSeoAttributes: f = !0,
106
+ identifierAttribute: u = "id",
107
+ missingWarn: m = !0
108
+ } = e, g = te(e.path, s), r = ae(
109
+ g,
110
+ t.map((c) => c.code),
111
+ a,
112
+ o,
113
+ void 0
114
+ ), y = t.find((c) => c.code === r);
115
+ if (!y)
116
+ return { htmlAttrs: {}, head: [] };
117
+ const b = y.iso || r, p = y.dir || "auto", P = {
118
+ lang: b,
119
+ ...h ? { dir: p } : {}
120
+ };
121
+ if (!f || !l)
122
+ return { htmlAttrs: P, head: [] };
123
+ const d = U({
124
+ defaultLocale: a,
125
+ localeCodes: t.map((c) => c.code),
126
+ localeKeyToCode: o,
127
+ base: s
128
+ }), x = se(g, i), v = r === a ? "root" : (() => {
129
+ for (const [c, L] of Object.entries(o))
130
+ if (L === r) return c === "root" ? "root" : c;
131
+ return r;
132
+ })(), M = d({}, { path: x }, v), T = N(l, s, M), $ = t.filter((c) => !c.disabled && c.seo !== !1), k = B(y);
133
+ k || D(y, { missingWarn: m, tag: "og:locale" });
134
+ const C = [];
135
+ C.push(["link", { [u]: "i18n-can", rel: "canonical", href: T }]), k && C.push(["meta", { [u]: "i18n-og", property: "og:locale", content: k }]), C.push(["meta", { [u]: "i18n-og-url", property: "og:url", content: T }]);
136
+ for (const c of $) {
137
+ if (c.code === r) continue;
138
+ const L = B(c);
139
+ if (!L) {
140
+ D(c, { missingWarn: m, tag: "og:locale:alternate" });
141
+ continue;
142
+ }
143
+ C.push(["meta", { [u]: `i18n-og-alt-${L}`, property: "og:locale:alternate", content: L }]);
144
+ }
145
+ const A = /* @__PURE__ */ new Map();
146
+ for (const c of $) {
147
+ const L = c.code === a ? "root" : (() => {
148
+ for (const [O, H] of Object.entries(o))
149
+ if (H === c.code) return O === "root" ? c.code : O;
150
+ return c.code;
151
+ })(), S = d({}, { path: x }, L);
152
+ S && A.set(String(c.code), N(l, s, S));
153
+ }
154
+ for (const { hreflang: c, localeCode: L } of ee($, { hreflangBaseLanguage: n })) {
155
+ const S = A.get(L);
156
+ S && C.push(["link", { [u]: `i18n-alternate-${c}`, rel: "alternate", href: S, hreflang: c }]);
157
+ }
158
+ const K = t.find((c) => c.code === a);
159
+ if (K && K.seo !== !1) {
160
+ const c = A.get(a);
161
+ c && C.push(["link", { [u]: "i18n-xd", rel: "alternate", href: c, hreflang: "x-default" }]);
162
+ }
163
+ return { htmlAttrs: P, head: C };
164
+ }
165
+ function j(e, t) {
166
+ if (I(e))
167
+ for (const a of G(e)) {
168
+ const o = X(e, a);
169
+ if (Q(o).isDirectory()) {
170
+ j(o, t);
171
+ continue;
172
+ }
173
+ a.endsWith(".json") && t(o);
174
+ }
175
+ }
176
+ function re(e) {
177
+ const t = e.rootDir ?? process.cwd(), a = W(t, e.translationDir), o = [];
178
+ return j(a, (s) => {
179
+ o.push({
180
+ absolutePath: s,
181
+ relativePath: F(a, s).split(J).join("/")
182
+ });
183
+ }), o.sort((s, l) => s.relativePath.localeCompare(l.relativePath));
184
+ }
185
+ function ne(e) {
186
+ const t = e.rootDir ?? process.cwd(), a = W(t, e.translationDir), o = { root: {}, routes: {} }, s = e.disablePageLocales === !0;
187
+ return I(a) && j(a, (l) => {
188
+ const n = F(a, l).split(J).join("/");
189
+ try {
190
+ const i = JSON.parse(z(l, "utf-8"));
191
+ if (i === null || typeof i != "object" || Array.isArray(i)) {
192
+ console.error(
193
+ `[i18n-micro/vitepress] Skipping ${n}: expected a JSON object, got ${Array.isArray(i) ? "array" : typeof i}`
194
+ );
195
+ return;
196
+ }
197
+ Y(o, n, i, s);
198
+ } catch (i) {
199
+ console.error(`[i18n-micro/vitepress] Failed to load ${n}:`, i);
200
+ }
201
+ }), o;
202
+ }
203
+ const V = "virtual:i18n-micro/config", q = `\0${V}`, _ = "virtual:i18n-micro/messages", w = `\0${_}`;
204
+ function ce(e) {
205
+ return e.replace(/\\/g, "/");
206
+ }
207
+ function le(e, t, a) {
208
+ const o = re({ rootDir: e, translationDir: t });
209
+ if (o.length === 0)
210
+ return `export const messages = {}
211
+ export const routeMessages = {}
212
+ `;
213
+ const s = [], l = [], n = /* @__PURE__ */ new Map();
214
+ let i = 0;
215
+ for (const f of o) {
216
+ const u = Z(f.relativePath, a);
217
+ if (u.type === "ignore") continue;
218
+ const m = `__i18n_${i++}`;
219
+ if (s.push(`import ${m} from ${JSON.stringify(ce(f.absolutePath))}`), u.type === "root") {
220
+ l.push(` ${JSON.stringify(u.locale)}: ${m}`);
221
+ continue;
222
+ }
223
+ let g = n.get(u.pageName);
224
+ g || (g = /* @__PURE__ */ new Map(), n.set(u.pageName, g)), g.set(u.locale, m);
225
+ }
226
+ const h = [];
227
+ for (const [f, u] of n) {
228
+ const m = [...u.entries()].map(([g, r]) => ` ${JSON.stringify(g)}: ${r}`).join(`,
229
+ `);
230
+ h.push(` ${JSON.stringify(f)}: {
231
+ ${m}
232
+ }`);
233
+ }
234
+ return [
235
+ ...s,
236
+ `export const messages = {
237
+ ${l.join(`,
238
+ `)}
239
+ }`,
240
+ `export const routeMessages = {
241
+ ${h.join(`,
242
+ `)}
243
+ }`,
244
+ ""
245
+ ].join(`
246
+ `);
247
+ }
248
+ function ie(e, t) {
249
+ return [`export const messages = ${JSON.stringify(e)}`, `export const routeMessages = ${JSON.stringify(t)}`, ""].join(`
250
+ `);
251
+ }
252
+ function ue(e, t) {
253
+ const a = e.defaultLocale || e.locale, o = e.translationDir ?? "locales", s = e.disablePageLocales === !0, l = {
254
+ defaultLocale: a,
255
+ fallbackLocale: e.fallbackLocale || a,
256
+ locales: e.locales || [],
257
+ localeCodes: (e.locales || []).map((r) => r.code),
258
+ missingWarn: e.missingWarn ?? !0,
259
+ syncWithVitePress: e.syncWithVitePress !== !1,
260
+ translationDir: o,
261
+ disablePageLocales: s,
262
+ localeKeyToCode: e.localeKeyToCode ?? {},
263
+ base: t && t !== "/" ? t : void 0
264
+ };
265
+ let n = process.cwd(), i = !!(e.messages || e.routeMessages), h = e.messages ?? {}, f = e.routeMessages ?? {}, u;
266
+ const m = () => !e.messages || !e.routeMessages, g = () => {
267
+ if (!m()) return;
268
+ const r = ne({
269
+ rootDir: n,
270
+ translationDir: o,
271
+ disablePageLocales: s
272
+ });
273
+ e.messages || (h = r.root), e.routeMessages || (f = r.routes);
274
+ };
275
+ return {
276
+ name: "vite-plugin-i18n-vitepress",
277
+ configResolved(r) {
278
+ n = r.root, i = !!(e.messages || e.routeMessages), i && (e.messages && (h = e.messages), e.routeMessages && (f = e.routeMessages), m() && g(), e.messages && (h = e.messages), e.routeMessages && (f = e.routeMessages));
279
+ },
280
+ configureServer(r) {
281
+ if (i && !m()) return;
282
+ const y = W(n, o);
283
+ if (!I(y)) return;
284
+ r.watcher.add(y);
285
+ const b = () => {
286
+ u && clearTimeout(u), u = setTimeout(() => {
287
+ i && g();
288
+ const p = r.moduleGraph.getModuleById(w);
289
+ p && (r.moduleGraph.invalidateModule(p), r.ws.send({ type: "full-reload" }));
290
+ }, 50);
291
+ };
292
+ r.watcher.on("add", (p) => {
293
+ p.startsWith(y) && p.endsWith(".json") && b();
294
+ }), r.watcher.on("unlink", (p) => {
295
+ p.startsWith(y) && p.endsWith(".json") && b();
296
+ }), i && m() && r.watcher.on("change", (p) => {
297
+ p.startsWith(y) && p.endsWith(".json") && b();
298
+ });
299
+ },
300
+ resolveId(r) {
301
+ if (r === V) return q;
302
+ if (r === _) return w;
303
+ },
304
+ load(r) {
305
+ if (r === q)
306
+ return `export const config = ${JSON.stringify(l)}`;
307
+ if (r === w)
308
+ return i ? ie(h, f) : le(n, o, s);
309
+ }
310
+ };
311
+ }
312
+ function fe(e, t) {
313
+ if (t.warnOnLocaleMismatch === !1) return;
314
+ const a = e.locales;
315
+ if (!a || !t.locales?.length) return;
316
+ const o = t.defaultLocale || t.locale, s = Object.keys(a), l = new Set(t.locales.map((n) => n.code));
317
+ for (const n of s) {
318
+ const i = n === "root" ? o : t.localeKeyToCode?.[n] ?? n;
319
+ l.has(i) || console.warn(
320
+ `[i18n-micro/vitepress] VitePress locale key "${n}" maps to "${i}", which is not in i18n locales (${[...l].join(", ")}).`
321
+ );
322
+ }
323
+ }
324
+ function be(e, t) {
325
+ fe(e, t);
326
+ const a = typeof e.base == "string" ? e.base : void 0, o = e.vite?.plugins, s = [...Array.isArray(o) ? o.flat() : [], ue(t, a)], l = e.vite?.ssr, n = l?.noExternal, i = [
327
+ "@i18n-micro/vitepress",
328
+ ...Array.isArray(n) ? n : n && n !== !0 ? [n] : []
329
+ ], h = t.defaultLocale || t.locale, f = (t.locales || []).map((d) => d.code), u = e.themeConfig && typeof e.themeConfig == "object" ? e.themeConfig : {}, m = t.i18nRouting !== !1 && u.i18nRouting === void 0 && f.length > 0, g = t.meta ?? !!t.metaBaseUrl, r = t.locales || [], y = e.transformHead, b = e.transformPageData, p = g ? async (d) => {
330
+ const x = typeof y == "function" ? await y(d) : [], v = Array.isArray(x) ? x : [];
331
+ if (d.pageData?.frontmatter?.i18n?.disableMeta === !0) return v;
332
+ const M = d.pageData?.relativePath || "index.md", T = (typeof e.base == "string" ? e.base : void 0) ?? d.siteData?.base ?? d.siteConfig?.site?.base, $ = E({
333
+ path: R(M),
334
+ locales: r,
335
+ defaultLocale: h,
336
+ localeKeyToCode: t.localeKeyToCode,
337
+ base: T,
338
+ metaBaseUrl: t.metaBaseUrl,
339
+ hreflangBaseLanguage: t.hreflangBaseLanguage,
340
+ canonicalQueryWhitelist: t.canonicalQueryWhitelist,
341
+ missingWarn: t.missingWarn
342
+ });
343
+ return [...v, ...$.head];
344
+ } : y, P = g ? async (d, x) => {
345
+ if (typeof b == "function" && await b(d, x), d.frontmatter?.i18n?.disableMeta === !0) return;
346
+ const v = E({
347
+ path: R(d.relativePath || "index.md"),
348
+ locales: r,
349
+ defaultLocale: h,
350
+ localeKeyToCode: t.localeKeyToCode,
351
+ base: typeof e.base == "string" ? e.base : void 0,
352
+ metaBaseUrl: t.metaBaseUrl,
353
+ hreflangBaseLanguage: t.hreflangBaseLanguage,
354
+ canonicalQueryWhitelist: t.canonicalQueryWhitelist,
355
+ missingWarn: t.missingWarn,
356
+ addSeoAttributes: !1
357
+ });
358
+ v.htmlAttrs.lang && (d.frontmatter ??= {}, d.frontmatter.lang || (d.frontmatter.lang = v.htmlAttrs.lang));
359
+ } : b;
360
+ return {
361
+ ...e,
362
+ ...m ? {
363
+ themeConfig: {
364
+ ...u,
365
+ i18nRouting: U({
366
+ defaultLocale: h,
367
+ localeCodes: f,
368
+ localeKeyToCode: t.localeKeyToCode,
369
+ base: a
370
+ })
371
+ }
372
+ } : {},
373
+ ...g ? {
374
+ transformHead: p,
375
+ transformPageData: P
376
+ } : {},
377
+ vite: {
378
+ ...e.vite,
379
+ plugins: s,
380
+ // Theme entry statically imports `virtual:i18n-micro/*`; Vite must bundle
381
+ // the package during SSG so those IDs resolve (not left as bare Node imports).
382
+ ssr: {
383
+ ...l,
384
+ noExternal: n === !0 ? !0 : i
385
+ }
386
+ }
387
+ };
388
+ }
3
389
  export {
4
- o as applyLoadedTranslations,
5
- c as createI18nRoutingFromAdapter,
6
- r as listTranslationFiles,
7
- t as loadMessages,
8
- e as loadTranslationBuckets,
9
- l as warnLocaleMismatch,
10
- n as withI18nMicro
390
+ E as buildVitePressLocaleHead,
391
+ ve as buildVitePressLocales,
392
+ R as relativePathToRoutePath,
393
+ fe as warnLocaleMismatch,
394
+ be as withI18n
11
395
  };
12
396
  //# sourceMappingURL=config.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"config.mjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;"}
1
+ {"version":3,"file":"config.mjs","sources":["../src/router/i18n-routing.ts","../src/seo/locale-head.ts","../src/plugin/load-messages.ts","../src/plugin/with-i18n.ts"],"sourcesContent":["import type { VitePressRouterAdapter } from './adapter'\n\n/**\n * Minimal shapes used by VitePress `themeConfig.i18nRouting`.\n * Kept loose so we do not hard-depend on VitePress internal DefaultTheme types at compile time.\n */\nexport interface VitePressI18nRoutingData {\n site?: {\n value?: {\n locales?: Record<string, { link?: string; lang?: string }>\n }\n }\n localeIndex?: { value?: string }\n}\n\nexport interface VitePressI18nRoutingRoute {\n path: string\n hash?: string\n query?: string\n data?: {\n relativePath?: string\n }\n}\n\nexport type VitePressI18nRoutingFn = (data: VitePressI18nRoutingData, route: VitePressI18nRoutingRoute, targetLocale: string) => string\n\nexport interface I18nRoutingFromAdapterOptions {\n defaultLocale: string\n localeCodes: string[]\n localeKeyToCode?: Record<string, string>\n /**\n * VitePress `site.base`. Stripped from `route.path` before rewriting locale;\n * result is base-relative (VitePress applies `withBase`).\n */\n base?: string\n}\n\nfunction isAdapter(value: VitePressRouterAdapter | I18nRoutingFromAdapterOptions): value is VitePressRouterAdapter {\n return 'switchLocalePath' in value && typeof (value as VitePressRouterAdapter).switchLocalePath === 'function'\n}\n\n/**\n * Bridge so VitePress navbar language menu and `<I18nSwitcher>` share path logic.\n * Pass the result to `themeConfig.i18nRouting`.\n *\n * `targetLocale` is a **VitePress locale key** (`root` / `fr`). URL prefixes use that key;\n * `localeKeyToCode` is only for resolving the i18n code when callers need it elsewhere.\n *\n * Returns a **self-contained** function (no closures) so VitePress can serialize it\n * into site data via `Function#toString()` + `new Function`.\n */\nexport function createI18nRoutingFromAdapter(adapterOrOptions: VitePressRouterAdapter | I18nRoutingFromAdapterOptions): VitePressI18nRoutingFn {\n const options: I18nRoutingFromAdapterOptions = isAdapter(adapterOrOptions)\n ? {\n defaultLocale: adapterOrOptions.defaultLocale,\n localeCodes: adapterOrOptions.localeCodes,\n localeKeyToCode: adapterOrOptions.localeKeyToCode ?? {},\n base: adapterOrOptions.base,\n }\n : adapterOrOptions\n\n const defaultLocale = options.defaultLocale\n const localeCodes = options.localeCodes\n const localeKeyToCode = options.localeKeyToCode ?? {}\n const base = options.base && options.base !== '/' ? options.base : ''\n\n // Inlined constants — required for VitePress themeConfig function serialization.\n // oxlint-disable-next-line typescript/no-implied-eval -- intentional for VP serializeFunctions\n return new Function(\n 'data',\n 'route',\n 'targetLocale',\n `\n const defaultLocale = ${JSON.stringify(defaultLocale)};\n const localeCodes = ${JSON.stringify(localeCodes)};\n const localeKeyToCode = ${JSON.stringify(localeKeyToCode)};\n const siteBase = ${JSON.stringify(base)};\n const keyFromCode = (code) => {\n for (const key of Object.keys(localeKeyToCode)) {\n if (localeKeyToCode[key] === code) return key;\n }\n return code === defaultLocale ? 'root' : code;\n };\n const prefixes = [];\n for (let i = 0; i < localeCodes.length; i++) {\n const code = localeCodes[i];\n if (code === defaultLocale) continue;\n const key = keyFromCode(code);\n const urlKey = key === 'root' ? code : key;\n prefixes.push(urlKey);\n if (urlKey !== code) prefixes.push(code);\n }\n // VitePress passes locale *keys* (root / fr). URL prefix is the key, not the i18n code.\n const urlPrefix = targetLocale === 'root' ? null : targetLocale;\n let path = (route && route.path) || '/';\n const hash = (route && route.hash) || '';\n const query = (route && route.query) || '';\n const hashIndex = path.indexOf('#');\n const queryIndex = path.indexOf('?');\n let cut = path.length;\n if (hashIndex >= 0) cut = Math.min(cut, hashIndex);\n if (queryIndex >= 0) cut = Math.min(cut, queryIndex);\n let pathname = path.slice(0, cut) || '/';\n const extras = path.slice(cut);\n if (siteBase) {\n const b = siteBase.endsWith('/') ? siteBase.slice(0, -1) : siteBase;\n if (pathname === b) pathname = '/';\n else if (pathname.indexOf(b + '/') === 0) pathname = pathname.slice(b.length) || '/';\n }\n const hadTrailingSlash = pathname === '/' || pathname.endsWith('/');\n const segments = pathname.split('/').filter(Boolean);\n if (segments[0] && prefixes.indexOf(segments[0]) >= 0) segments.shift();\n if (urlPrefix) segments.unshift(urlPrefix);\n let localized = segments.length === 0 ? '/' : '/' + segments.join('/');\n if (localized !== '/' && hadTrailingSlash) localized += '/';\n const q = extras.indexOf('?') >= 0\n ? ''\n : (query ? (query.charAt(0) === '?' ? query : '?' + query) : '');\n const h = hash\n ? (hash.charAt(0) === '#' ? hash : '#' + hash)\n : '';\n return localized + extras + q + h;\n `,\n ) as VitePressI18nRoutingFn\n}\n","import type { Locale } from '@i18n-micro/types'\nimport { resolveHreflangAlternates } from '@i18n-micro/utils/resolve-hreflang'\nimport { resolveOgLocale, warnUnresolvedOgLocale } from '@i18n-micro/utils/resolve-og-locale'\nimport { createI18nRoutingFromAdapter } from '../router/i18n-routing'\nimport { getLocaleFromPath, stripSiteBase } from '../router/adapter'\n\n/** VitePress `HeadConfig` tuple (tag + attrs). */\nexport type VitePressHeadTuple = [string, Record<string, string>]\n\nexport interface VitePressLocaleHeadObject {\n htmlAttrs: {\n lang?: string\n dir?: 'ltr' | 'rtl' | 'auto'\n }\n /** Ready for `transformHead` / `frontmatter.head`. */\n head: VitePressHeadTuple[]\n}\n\nexport interface BuildVitePressLocaleHeadOptions {\n /**\n * Current page path (with or without `site.base`). Query/hash optional.\n * Example: `/docs/fr/guide/` or `/fr/guide`.\n */\n path: string\n locales: Locale[]\n defaultLocale: string\n localeKeyToCode?: Record<string, string>\n /** VitePress `site.base` (e.g. `/docs/`). */\n base?: string\n /**\n * Public site origin **without** trailing slash (e.g. `https://example.com`).\n * Required for absolute `canonical` / `hreflang` / `og:url`.\n * When omitted, only `htmlAttrs` are produced.\n */\n metaBaseUrl?: string\n /** @default false — same as Nuxt / Vue `useLocaleHead`. */\n hreflangBaseLanguage?: boolean\n /** Query keys kept on canonical / alternate URLs. @default [] */\n canonicalQueryWhitelist?: string[]\n /** @default true */\n addDirAttribute?: boolean\n /** @default true */\n addSeoAttributes?: boolean\n /** @default 'id' */\n identifierAttribute?: string\n missingWarn?: boolean\n}\n\nfunction filterQuery(fullPath: string, whitelist: string[]): string {\n const hashIndex = fullPath.indexOf('#')\n const queryIndex = fullPath.indexOf('?')\n let cut = fullPath.length\n if (hashIndex >= 0) cut = Math.min(cut, hashIndex)\n if (queryIndex >= 0) cut = Math.min(cut, queryIndex)\n const pathname = fullPath.slice(0, cut) || '/'\n if (queryIndex < 0 || whitelist.length === 0) return pathname\n\n const params = new URLSearchParams(fullPath.slice(queryIndex, hashIndex >= 0 ? hashIndex : undefined))\n const filtered = new URLSearchParams()\n for (const key of whitelist) {\n if (params.has(key)) filtered.set(key, params.get(key)!)\n }\n const q = filtered.toString()\n return q ? `${pathname}?${q}` : pathname\n}\n\nfunction joinAbsolute(metaBaseUrl: string, siteBase: string | undefined, path: string): string {\n const origin = metaBaseUrl.replace(/\\/$/, '')\n const base = !siteBase || siteBase === '/' ? '' : siteBase.replace(/\\/$/, '')\n const p = path.startsWith('/') ? path : `/${path}`\n return `${origin}${base}${p}`\n}\n\n/**\n * Convert VitePress `pageData.relativePath` to a route path (cleanUrls-style).\n */\nexport function relativePathToRoutePath(relativePath: string): string {\n let path = relativePath.replace(/\\\\/g, '/')\n path = path.replace(/(^|\\/)index\\.md$/, '$1').replace(/\\.md$/, '')\n if (!path.startsWith('/')) path = `/${path}`\n if (path.length > 1 && path.endsWith('/')) path = path.slice(0, -1)\n return path || '/'\n}\n\n/**\n * Build i18n SEO head for VitePress — same tags as Nuxt `useLocaleHead` /\n * plugin `02.meta` (canonical, hreflang, x-default, og:locale / og:url / alternates).\n *\n * Framework-agnostic pure function; wired automatically by `withI18n` when `meta` is on.\n */\nexport function buildVitePressLocaleHead(options: BuildVitePressLocaleHeadOptions): VitePressLocaleHeadObject {\n const {\n locales,\n defaultLocale,\n localeKeyToCode = {},\n base,\n metaBaseUrl,\n hreflangBaseLanguage = false,\n canonicalQueryWhitelist = [],\n addDirAttribute = true,\n addSeoAttributes = true,\n identifierAttribute = 'id',\n missingWarn = true,\n } = options\n\n const path = stripSiteBase(options.path, base)\n const locale = getLocaleFromPath(\n path,\n locales.map((l) => l.code),\n defaultLocale,\n localeKeyToCode,\n undefined,\n )\n const currentLocale = locales.find((l) => l.code === locale)\n if (!currentLocale) {\n return { htmlAttrs: {}, head: [] }\n }\n\n const currentIso = currentLocale.iso || locale\n const currentDir = (currentLocale.dir || 'auto') as 'ltr' | 'rtl' | 'auto'\n const htmlAttrs: VitePressLocaleHeadObject['htmlAttrs'] = {\n lang: currentIso,\n ...(addDirAttribute ? { dir: currentDir } : {}),\n }\n\n if (!addSeoAttributes || !metaBaseUrl) {\n return { htmlAttrs, head: [] }\n }\n\n const switchLocalePath = createI18nRoutingFromAdapter({\n defaultLocale,\n localeCodes: locales.map((l) => l.code),\n localeKeyToCode,\n base,\n })\n\n const filteredPath = filterQuery(path, canonicalQueryWhitelist)\n // VitePress locale keys for i18nRouting: root vs code\n const currentVpKey =\n locale === defaultLocale\n ? 'root'\n : (() => {\n for (const [key, code] of Object.entries(localeKeyToCode)) {\n if (code === locale) return key === 'root' ? 'root' : key\n }\n return locale\n })()\n const canonicalPath = switchLocalePath({}, { path: filteredPath }, currentVpKey)\n const ogUrl = joinAbsolute(metaBaseUrl, base, canonicalPath)\n\n const localesForSeo = locales.filter((loc) => !loc.disabled && loc.seo !== false)\n const currentOg = resolveOgLocale(currentLocale)\n if (!currentOg) {\n warnUnresolvedOgLocale(currentLocale, { missingWarn, tag: 'og:locale' })\n }\n\n const head: VitePressHeadTuple[] = []\n\n head.push(['link', { [identifierAttribute]: 'i18n-can', rel: 'canonical', href: ogUrl }])\n\n if (currentOg) {\n head.push(['meta', { [identifierAttribute]: 'i18n-og', property: 'og:locale', content: currentOg }])\n }\n head.push(['meta', { [identifierAttribute]: 'i18n-og-url', property: 'og:url', content: ogUrl }])\n\n for (const loc of localesForSeo) {\n if (loc.code === locale) continue\n const ogAlt = resolveOgLocale(loc)\n if (!ogAlt) {\n warnUnresolvedOgLocale(loc, { missingWarn, tag: 'og:locale:alternate' })\n continue\n }\n head.push(['meta', { [identifierAttribute]: `i18n-og-alt-${ogAlt}`, property: 'og:locale:alternate', content: ogAlt }])\n }\n\n const hrefByCode = new Map<string, string>()\n for (const loc of localesForSeo) {\n const vpKey =\n loc.code === defaultLocale\n ? 'root'\n : (() => {\n for (const [key, code] of Object.entries(localeKeyToCode)) {\n if (code === loc.code) return key === 'root' ? loc.code : key\n }\n return loc.code\n })()\n const switched = switchLocalePath({}, { path: filteredPath }, vpKey)\n if (!switched) continue\n hrefByCode.set(String(loc.code), joinAbsolute(metaBaseUrl, base, switched))\n }\n\n for (const { hreflang, localeCode } of resolveHreflangAlternates(localesForSeo, { hreflangBaseLanguage })) {\n const href = hrefByCode.get(localeCode)\n if (!href) continue\n head.push(['link', { [identifierAttribute]: `i18n-alternate-${hreflang}`, rel: 'alternate', href, hreflang }])\n }\n\n const defaultLocaleObj = locales.find((l) => l.code === defaultLocale)\n if (defaultLocaleObj && defaultLocaleObj.seo !== false) {\n const xHref = hrefByCode.get(defaultLocale)\n if (xHref) {\n head.push(['link', { [identifierAttribute]: 'i18n-xd', rel: 'alternate', href: xHref, hreflang: 'x-default' }])\n }\n }\n\n return { htmlAttrs, head }\n}\n","import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'\nimport { join, relative, resolve, sep } from 'node:path'\nimport type { Translations } from '@i18n-micro/types'\nimport { storeLoadedTranslationFile, type TranslationFileBuckets } from '@i18n-micro/utils/parse-path'\n\n/** Sync FS walk for the Vite plugin — prefer `@i18n-micro/node` in scripts. */\nexport interface LoadMessagesOptions {\n translationDir: string\n rootDir?: string\n disablePageLocales?: boolean\n}\n\nexport type LoadedTranslations = TranslationFileBuckets<Translations>\n\nexport interface TranslationFileRef {\n relativePath: string\n absolutePath: string\n}\n\nfunction walkTranslationFiles(dir: string, onFile: (fullPath: string) => void): void {\n if (!existsSync(dir)) return\n\n for (const entry of readdirSync(dir)) {\n const fullPath = join(dir, entry)\n const stat = statSync(fullPath)\n if (stat.isDirectory()) {\n walkTranslationFiles(fullPath, onFile)\n continue\n }\n if (entry.endsWith('.json')) onFile(fullPath)\n }\n}\n\nexport function listTranslationFiles(options: LoadMessagesOptions): TranslationFileRef[] {\n const rootDir = options.rootDir ?? process.cwd()\n const dir = resolve(rootDir, options.translationDir)\n const files: TranslationFileRef[] = []\n\n walkTranslationFiles(dir, (fullPath) => {\n files.push({\n absolutePath: fullPath,\n relativePath: relative(dir, fullPath).split(sep).join('/'),\n })\n })\n\n return files.sort((a, b) => a.relativePath.localeCompare(b.relativePath))\n}\n\nexport function loadTranslationBuckets(options: LoadMessagesOptions): LoadedTranslations {\n const rootDir = options.rootDir ?? process.cwd()\n const dir = resolve(rootDir, options.translationDir)\n const buckets: LoadedTranslations = { root: {}, routes: {} }\n const disablePageLocales = options.disablePageLocales === true\n\n if (!existsSync(dir)) return buckets\n\n walkTranslationFiles(dir, (fullPath) => {\n const relativePath = relative(dir, fullPath).split(sep).join('/')\n try {\n const parsed: unknown = JSON.parse(readFileSync(fullPath, 'utf-8'))\n if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {\n console.error(\n `[i18n-micro/vitepress] Skipping ${relativePath}: expected a JSON object, got ${Array.isArray(parsed) ? 'array' : typeof parsed}`,\n )\n return\n }\n storeLoadedTranslationFile(buckets, relativePath, parsed as Translations, disablePageLocales)\n } catch (error) {\n console.error(`[i18n-micro/vitepress] Failed to load ${relativePath}:`, error)\n }\n })\n\n return buckets\n}\n","import { existsSync } from 'node:fs'\nimport { resolve } from 'node:path'\nimport type { Locale, Translations } from '@i18n-micro/types'\nimport { classifyTranslationRelativePath } from '@i18n-micro/utils/parse-path'\nimport type { Plugin } from 'vite'\nimport type { CreateI18nOptions } from '../runtime/create'\nimport { buildVitePressLocaleHead, relativePathToRoutePath } from '../seo/locale-head'\nimport { listTranslationFiles, loadTranslationBuckets } from './load-messages'\nimport { createI18nRoutingFromAdapter } from '../router/i18n-routing'\n\nexport interface WithI18nOptions extends CreateI18nOptions {\n /**\n * Directory with locale JSON (`en.json`, `pages/guide/demo/en.json`, …), relative to Vite root\n * (VitePress content / docs root). Used by `virtual:i18n-micro/messages`.\n * @default 'locales'\n */\n translationDir?: string\n /**\n * When true, treat `pages/**` as root-level dictionaries.\n * @default false\n */\n disablePageLocales?: boolean\n /**\n * When true, logs a warning if VitePress `locales` keys do not align with\n * configured i18n locale codes.\n * @default true\n */\n warnOnLocaleMismatch?: boolean\n /**\n * Inject `themeConfig.i18nRouting` from adapter options + `config.base`.\n * Set `false` to skip. Skipped automatically when `themeConfig.i18nRouting` is already set.\n * @default true\n */\n i18nRouting?: boolean\n /**\n * Emit i18n SEO tags via `transformHead` (canonical, hreflang, og:locale…) —\n * Nuxt `meta` / plugin `02.meta` analogue.\n * Absolute link tags require `metaBaseUrl`.\n * @default true when `metaBaseUrl` is set, otherwise false\n */\n meta?: boolean\n /**\n * Public origin without trailing slash (`https://example.com`).\n * Same role as Nuxt `metaBaseUrl`.\n */\n metaBaseUrl?: string\n /** Also emit bare-language hreflang from `iso` (Nuxt `hreflangBaseLanguage`). @default false */\n hreflangBaseLanguage?: boolean\n /** Query keys kept on canonical / alternate URLs. @default [] */\n canonicalQueryWhitelist?: string[]\n}\n\n/**\n * Minimal VitePress / Vite user config shape we merge into.\n * Avoid importing `vitepress` types so the package stays usable as a pure library dep.\n */\nexport interface VitePressUserConfigLike {\n base?: string\n locales?: Record<string, unknown>\n themeConfig?: Record<string, unknown> | null\n transformHead?: (...args: any[]) => any\n transformPageData?: (...args: any[]) => any\n vite?: {\n plugins?: Plugin[] | Plugin[][]\n ssr?: {\n noExternal?: string | true | Array<string | RegExp>\n [key: string]: unknown\n }\n [key: string]: unknown\n }\n [key: string]: unknown\n}\n\nexport interface VirtualI18nConfig {\n defaultLocale: string\n fallbackLocale: string\n locales: Locale[]\n localeCodes: string[]\n missingWarn: boolean\n syncWithVitePress: boolean\n translationDir: string\n disablePageLocales: boolean\n localeKeyToCode: Record<string, string>\n /** VitePress `site.base` (normalized, trailing slash preserved from config). */\n base?: string\n}\n\nconst VIRTUAL_CONFIG_ID = 'virtual:i18n-micro/config'\nconst RESOLVED_CONFIG_ID = `\\0${VIRTUAL_CONFIG_ID}`\nconst VIRTUAL_MESSAGES_ID = 'virtual:i18n-micro/messages'\nconst RESOLVED_MESSAGES_ID = `\\0${VIRTUAL_MESSAGES_ID}`\n\nfunction toPosix(path: string): string {\n return path.replace(/\\\\/g, '/')\n}\n\nfunction generateImportMessagesModule(rootDir: string, translationDir: string, disablePageLocales: boolean): string {\n const files = listTranslationFiles({ rootDir, translationDir })\n if (files.length === 0) {\n return 'export const messages = {}\\nexport const routeMessages = {}\\n'\n }\n\n const imports: string[] = []\n const rootEntries: string[] = []\n const routeVarNames = new Map<string, Map<string, string>>()\n let i = 0\n\n for (const file of files) {\n const parsed = classifyTranslationRelativePath(file.relativePath, disablePageLocales)\n if (parsed.type === 'ignore') continue\n\n const varName = `__i18n_${i++}`\n imports.push(`import ${varName} from ${JSON.stringify(toPosix(file.absolutePath))}`)\n\n if (parsed.type === 'root') {\n rootEntries.push(` ${JSON.stringify(parsed.locale)}: ${varName}`)\n continue\n }\n\n let byLocale = routeVarNames.get(parsed.pageName)\n if (!byLocale) {\n byLocale = new Map()\n routeVarNames.set(parsed.pageName, byLocale)\n }\n byLocale.set(parsed.locale, varName)\n }\n\n const routeEntries: string[] = []\n for (const [routeName, byLocale] of routeVarNames) {\n const localeEntries = [...byLocale.entries()].map(([locale, varName]) => ` ${JSON.stringify(locale)}: ${varName}`).join(',\\n')\n routeEntries.push(` ${JSON.stringify(routeName)}: {\\n${localeEntries}\\n }`)\n }\n\n return [\n ...imports,\n `export const messages = {\\n${rootEntries.join(',\\n')}\\n}`,\n `export const routeMessages = {\\n${routeEntries.join(',\\n')}\\n}`,\n '',\n ].join('\\n')\n}\n\nfunction generateInlineMessagesModule(messages: Record<string, Translations>, routeMessages: Record<string, Record<string, Translations>>): string {\n return [`export const messages = ${JSON.stringify(messages)}`, `export const routeMessages = ${JSON.stringify(routeMessages)}`, ''].join('\\n')\n}\n\nfunction createI18nVitePlugin(options: WithI18nOptions, siteBase?: string): Plugin {\n const defaultLocale = options.defaultLocale || options.locale\n const translationDir = options.translationDir ?? 'locales'\n const disablePageLocales = options.disablePageLocales === true\n const configData: VirtualI18nConfig = {\n defaultLocale,\n fallbackLocale: options.fallbackLocale || defaultLocale,\n locales: options.locales || [],\n localeCodes: (options.locales || []).map((l) => l.code),\n missingWarn: options.missingWarn ?? true,\n syncWithVitePress: options.syncWithVitePress !== false,\n translationDir,\n disablePageLocales,\n localeKeyToCode: options.localeKeyToCode ?? {},\n base: siteBase && siteBase !== '/' ? siteBase : undefined,\n }\n\n let rootDir = process.cwd()\n let useInline = Boolean(options.messages || options.routeMessages)\n let inlineRoot = options.messages ?? {}\n let inlineRoutes = options.routeMessages ?? {}\n let debounceTimer: ReturnType<typeof setTimeout> | undefined\n const needsDiskReload = () => !options.messages || !options.routeMessages\n\n const reloadInlineFromDisk = () => {\n // Fully inline config: skip disk I/O (and avoid spurious JSON parse errors).\n if (!needsDiskReload()) return\n const loaded = loadTranslationBuckets({\n rootDir,\n translationDir,\n disablePageLocales,\n })\n if (!options.messages) {\n inlineRoot = loaded.root\n }\n if (!options.routeMessages) {\n inlineRoutes = loaded.routes\n }\n }\n\n return {\n name: 'vite-plugin-i18n-vitepress',\n configResolved(config) {\n rootDir = config.root\n // Inline when caller passed messages and/or routeMessages.\n // routeMessages alone still loads root dictionaries from translationDir.\n useInline = Boolean(options.messages || options.routeMessages)\n if (useInline) {\n if (options.messages) inlineRoot = options.messages\n if (options.routeMessages) inlineRoutes = options.routeMessages\n if (needsDiskReload()) {\n reloadInlineFromDisk()\n }\n if (options.messages) inlineRoot = options.messages\n if (options.routeMessages) inlineRoutes = options.routeMessages\n }\n },\n configureServer(server) {\n // Both maps provided inline — nothing to watch on disk.\n if (useInline && !needsDiskReload()) return\n\n const dir = resolve(rootDir, translationDir)\n if (!existsSync(dir)) return\n\n server.watcher.add(dir)\n\n const invalidate = () => {\n if (debounceTimer) clearTimeout(debounceTimer)\n debounceTimer = setTimeout(() => {\n if (useInline) reloadInlineFromDisk()\n const mod = server.moduleGraph.getModuleById(RESOLVED_MESSAGES_ID)\n if (mod) {\n server.moduleGraph.invalidateModule(mod)\n server.ws.send({ type: 'full-reload' })\n }\n }, 50)\n }\n\n // add/unlink need virtual module regen; change is usually handled by JSON import HMR,\n // but we still invalidate when using inline payload that still reads disk.\n server.watcher.on('add', (file) => {\n if (file.startsWith(dir) && file.endsWith('.json')) invalidate()\n })\n server.watcher.on('unlink', (file) => {\n if (file.startsWith(dir) && file.endsWith('.json')) invalidate()\n })\n if (useInline && needsDiskReload()) {\n server.watcher.on('change', (file) => {\n if (file.startsWith(dir) && file.endsWith('.json')) invalidate()\n })\n }\n },\n resolveId(id) {\n if (id === VIRTUAL_CONFIG_ID) return RESOLVED_CONFIG_ID\n if (id === VIRTUAL_MESSAGES_ID) return RESOLVED_MESSAGES_ID\n },\n load(id) {\n if (id === RESOLVED_CONFIG_ID) {\n return `export const config = ${JSON.stringify(configData)}`\n }\n if (id === RESOLVED_MESSAGES_ID) {\n if (useInline) {\n return generateInlineMessagesModule(inlineRoot, inlineRoutes)\n }\n return generateImportMessagesModule(rootDir, translationDir, disablePageLocales)\n }\n },\n }\n}\n\nexport function warnLocaleMismatch(config: VitePressUserConfigLike, options: WithI18nOptions): void {\n if (options.warnOnLocaleMismatch === false) return\n const vpLocales = config.locales\n if (!vpLocales || !options.locales?.length) return\n\n const defaultLocale = options.defaultLocale || options.locale\n const vpKeys = Object.keys(vpLocales)\n const codes = new Set(options.locales.map((l) => l.code))\n\n for (const key of vpKeys) {\n const expectedCode = key === 'root' ? defaultLocale : (options.localeKeyToCode?.[key] ?? key)\n if (!codes.has(expectedCode)) {\n console.warn(\n `[i18n-micro/vitepress] VitePress locale key \"${key}\" maps to \"${expectedCode}\", ` +\n `which is not in i18n locales (${[...codes].join(', ')}).`,\n )\n }\n }\n}\n\n/**\n * VitePress config helper: virtual modules + optional `i18nRouting` / SEO head.\n *\n * Registers:\n * - `virtual:i18n-micro/config`\n * - `virtual:i18n-micro/messages` (from `translationDir`, default `locales/`)\n *\n * By default also sets `themeConfig.i18nRouting` (pass `i18nRouting: false` to skip).\n * Pair with `defineI18nTheme(DefaultTheme)` from `@i18n-micro/vitepress/theme`.\n * Import from `@i18n-micro/vitepress/config` (Node / config files only).\n */\nexport function withI18n<T extends VitePressUserConfigLike>(config: T, options: WithI18nOptions): T {\n warnLocaleMismatch(config, options)\n\n const siteBase = typeof config.base === 'string' ? config.base : undefined\n const existingPlugins = config.vite?.plugins\n const plugins = [...(Array.isArray(existingPlugins) ? existingPlugins.flat() : []), createI18nVitePlugin(options, siteBase)]\n\n const prevSsr = config.vite?.ssr\n const prevNoExternal = prevSsr?.noExternal\n const noExternalList = [\n '@i18n-micro/vitepress',\n ...(Array.isArray(prevNoExternal) ? prevNoExternal : prevNoExternal && prevNoExternal !== true ? [prevNoExternal] : []),\n ]\n\n const defaultLocale = options.defaultLocale || options.locale\n const localeCodes = (options.locales || []).map((l) => l.code)\n const prevTheme = (config.themeConfig && typeof config.themeConfig === 'object' ? config.themeConfig : {}) as Record<string, unknown>\n const shouldInjectRouting = options.i18nRouting !== false && prevTheme.i18nRouting === undefined && localeCodes.length > 0\n\n const metaEnabled = options.meta ?? Boolean(options.metaBaseUrl)\n const locales = options.locales || []\n const prevTransformHead = config.transformHead\n const prevTransformPageData = config.transformPageData\n\n const transformHead = metaEnabled\n ? async (ctx: {\n pageData?: { relativePath?: string; frontmatter?: { i18n?: { disableMeta?: boolean } } }\n siteConfig?: { site?: { base?: string } }\n siteData?: { base?: string }\n }) => {\n const prev = typeof prevTransformHead === 'function' ? await prevTransformHead(ctx) : []\n const prevHead = Array.isArray(prev) ? prev : []\n if (ctx.pageData?.frontmatter?.i18n?.disableMeta === true) return prevHead\n\n const relativePath = ctx.pageData?.relativePath || 'index.md'\n const siteBase = (typeof config.base === 'string' ? config.base : undefined) ?? ctx.siteData?.base ?? ctx.siteConfig?.site?.base\n const built = buildVitePressLocaleHead({\n path: relativePathToRoutePath(relativePath),\n locales,\n defaultLocale,\n localeKeyToCode: options.localeKeyToCode,\n base: siteBase,\n metaBaseUrl: options.metaBaseUrl,\n hreflangBaseLanguage: options.hreflangBaseLanguage,\n canonicalQueryWhitelist: options.canonicalQueryWhitelist,\n missingWarn: options.missingWarn,\n })\n return [...prevHead, ...built.head]\n }\n : prevTransformHead\n\n const transformPageData = metaEnabled\n ? async (\n pageData: {\n relativePath?: string\n frontmatter?: Record<string, unknown> & { i18n?: { disableMeta?: boolean } }\n },\n ctx?: unknown,\n ) => {\n if (typeof prevTransformPageData === 'function') {\n await prevTransformPageData(pageData, ctx)\n }\n if (pageData.frontmatter?.i18n?.disableMeta === true) return\n\n const built = buildVitePressLocaleHead({\n path: relativePathToRoutePath(pageData.relativePath || 'index.md'),\n locales,\n defaultLocale,\n localeKeyToCode: options.localeKeyToCode,\n base: typeof config.base === 'string' ? config.base : undefined,\n metaBaseUrl: options.metaBaseUrl,\n hreflangBaseLanguage: options.hreflangBaseLanguage,\n canonicalQueryWhitelist: options.canonicalQueryWhitelist,\n missingWarn: options.missingWarn,\n addSeoAttributes: false,\n })\n if (built.htmlAttrs.lang) {\n pageData.frontmatter ??= {}\n // VitePress uses frontmatter for per-page lang when set\n if (!pageData.frontmatter.lang) {\n pageData.frontmatter.lang = built.htmlAttrs.lang\n }\n }\n }\n : prevTransformPageData\n\n return {\n ...config,\n ...(shouldInjectRouting\n ? {\n themeConfig: {\n ...prevTheme,\n i18nRouting: createI18nRoutingFromAdapter({\n defaultLocale,\n localeCodes,\n localeKeyToCode: options.localeKeyToCode,\n base: siteBase,\n }),\n },\n }\n : {}),\n ...(metaEnabled\n ? {\n transformHead,\n transformPageData,\n }\n : {}),\n vite: {\n ...config.vite,\n plugins,\n // Theme entry statically imports `virtual:i18n-micro/*`; Vite must bundle\n // the package during SSG so those IDs resolve (not left as bare Node imports).\n ssr: {\n ...prevSsr,\n noExternal: prevNoExternal === true ? true : noExternalList,\n },\n },\n }\n}\n"],"names":["isAdapter","value","createI18nRoutingFromAdapter","adapterOrOptions","options","defaultLocale","localeCodes","localeKeyToCode","base","filterQuery","fullPath","whitelist","hashIndex","queryIndex","cut","pathname","params","filtered","key","q","joinAbsolute","metaBaseUrl","siteBase","path","origin","p","relativePathToRoutePath","relativePath","buildVitePressLocaleHead","locales","hreflangBaseLanguage","canonicalQueryWhitelist","addDirAttribute","addSeoAttributes","identifierAttribute","missingWarn","stripSiteBase","locale","getLocaleFromPath","l","currentLocale","currentIso","currentDir","htmlAttrs","switchLocalePath","filteredPath","currentVpKey","code","canonicalPath","ogUrl","localesForSeo","loc","currentOg","resolveOgLocale","warnUnresolvedOgLocale","head","ogAlt","hrefByCode","vpKey","switched","hreflang","localeCode","resolveHreflangAlternates","href","defaultLocaleObj","xHref","walkTranslationFiles","dir","onFile","existsSync","entry","readdirSync","join","statSync","listTranslationFiles","rootDir","resolve","files","relative","sep","a","b","loadTranslationBuckets","buckets","disablePageLocales","parsed","readFileSync","storeLoadedTranslationFile","error","VIRTUAL_CONFIG_ID","RESOLVED_CONFIG_ID","VIRTUAL_MESSAGES_ID","RESOLVED_MESSAGES_ID","toPosix","generateImportMessagesModule","translationDir","imports","rootEntries","routeVarNames","file","classifyTranslationRelativePath","varName","byLocale","routeEntries","routeName","localeEntries","generateInlineMessagesModule","messages","routeMessages","createI18nVitePlugin","configData","useInline","inlineRoot","inlineRoutes","debounceTimer","needsDiskReload","reloadInlineFromDisk","loaded","config","server","invalidate","mod","id","warnLocaleMismatch","vpLocales","vpKeys","codes","expectedCode","withI18n","existingPlugins","plugins","prevSsr","prevNoExternal","noExternalList","prevTheme","shouldInjectRouting","metaEnabled","prevTransformHead","prevTransformPageData","transformHead","ctx","prev","prevHead","built","transformPageData","pageData"],"mappings":";;;;;;;AAqCA,SAASA,GAAUC,GAAgG;AACjH,SAAO,sBAAsBA,KAAS,OAAQA,EAAiC,oBAAqB;AACtG;AAYO,SAASC,EAA6BC,GAAkG;AAC7I,QAAMC,IAAyCJ,GAAUG,CAAgB,IACrE;AAAA,IACE,eAAeA,EAAiB;AAAA,IAChC,aAAaA,EAAiB;AAAA,IAC9B,iBAAiBA,EAAiB,mBAAmB,CAAA;AAAA,IACrD,MAAMA,EAAiB;AAAA,EAAA,IAEzBA,GAEEE,IAAgBD,EAAQ,eACxBE,IAAcF,EAAQ,aACtBG,IAAkBH,EAAQ,mBAAmB,CAAA,GAC7CI,IAAOJ,EAAQ,QAAQA,EAAQ,SAAS,MAAMA,EAAQ,OAAO;AAInE,SAAO,IAAI;AAAA,IACT;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,8BAC0B,KAAK,UAAUC,CAAa,CAAC;AAAA,4BAC/B,KAAK,UAAUC,CAAW,CAAC;AAAA,gCACvB,KAAK,UAAUC,CAAe,CAAC;AAAA,yBACtC,KAAK,UAAUC,CAAI,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAA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C,eAAAG;AAAA,UACA,aAAAC;AAAA,UACA,iBAAiBF,EAAQ;AAAA,UACzB,MAAMkB;AAAA,QAAA,CACP;AAAA,MAAA;AAAA,IACH,IAEF,CAAA;AAAA,IACJ,GAAIkH,IACA;AAAA,MACE,eAAAG;AAAA,MACA,mBAAAK;AAAA,IAAA,IAEF,CAAA;AAAA,IACJ,MAAM;AAAA,MACJ,GAAG1B,EAAO;AAAA,MACV,SAAAY;AAAA;AAAA;AAAA,MAGA,KAAK;AAAA,QACH,GAAGC;AAAA,QACH,YAAYC,MAAmB,KAAO,KAAOC;AAAA,MAAA;AAAA,IAC/C;AAAA,EACF;AAEJ;"}
@@ -0,0 +1,2 @@
1
+ "use strict";const L=require("@i18n-micro/utils/parse-path"),R=require("@i18n-micro/vue"),P=require("./adapter-BJ-0ltIc.cjs");function v(e,n,l){if(l)for(const[i,a]of Object.entries(l))for(const[c,h]of Object.entries(a))e.global.addRouteTranslations(c,i,L.mergeRouteTranslationsWithRoot(n?.[c],h),!1)}function F(e){const n=e.defaultLocale||e.locale,l=e.locales??[],i=e.syncWithVitePress!==!1,a=R.createI18n({locale:e.locale,fallbackLocale:e.fallbackLocale??n,messages:e.messages,plural:e.plural,missingWarn:e.missingWarn,missingHandler:e.missingHandler,locales:l,defaultLocale:n});v(a,e.messages,e.routeMessages);const c=P.createVitePressRouterAdapter({locales:l,defaultLocale:n,localeKeyToCode:e.localeKeyToCode,base:e.base}),h={localizePath:c.localizePath,switchLocalePath:c.switchLocalePath,getLocaleFromPath:c.getLocaleFromPath,removeLocaleFromPath:c.removeLocaleFromPath,routeNameFromPath:c.routeNameFromPath};a.global.extend(h);const y=new Set(Object.keys(e.routeMessages??{})),f=new WeakMap;return Object.assign(a,h,{get i18n(){return a.global},enhanceApp:p=>{const{app:d,router:u}=p;let t=f.get(d);if(!t){const r=P.createVitePressRouterAdapter({locales:l,defaultLocale:n,localeKeyToCode:e.localeKeyToCode,base:e.base,getPath:()=>{const o=u.route;return`${o.path}${o.query||""}${o.hash||""}`},go:(o,s)=>u.go(o,s)});d.use(a),a.setRoutingStrategy(r),t={adapter:r,boundSyncHandler:null,chainedPrevious:void 0},f.set(d,t)}if(!i)return;const{adapter:m}=t,b=(r=u.route.path)=>{const o=m.getLocaleFromPath(r);a.global.getLocale()!==o&&(a.global.locale=o);const s=m.routeNameFromPath(r);a.global.setRoute(y.has(s)?s:"index")};b();const g=u.onAfterRouteChange;g!==t.boundSyncHandler&&(t.chainedPrevious=typeof g=="function"?g:void 0),t.boundSyncHandler=async r=>{typeof t.chainedPrevious=="function"&&await t.chainedPrevious(r);const o=r.startsWith("http")?(()=>{const s=new URL(r);return s.pathname+s.search+s.hash})():r;b(o)},u.onAfterRouteChange=t.boundSyncHandler}})}exports.createI18n=F;
2
+ //# sourceMappingURL=create-BgMbe0w1.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"create-BgMbe0w1.cjs","sources":["../src/runtime/create.ts"],"sourcesContent":["import type { Locale, PluralFunc, Translations } from '@i18n-micro/types'\nimport { mergeRouteTranslationsWithRoot } from '@i18n-micro/utils/parse-path'\nimport { createI18n as createVueI18n, type I18nPlugin } from '@i18n-micro/vue'\nimport type { App, Ref } from 'vue'\nimport { createVitePressRouterAdapter, type PathMethods, type VitePressRouterAdapter, type VitePressRouterLike } from '../router/adapter'\n\nexport type { PathMethods }\n\nexport interface CreateI18nOptions {\n locale: string\n fallbackLocale?: string\n locales?: Locale[]\n defaultLocale?: string\n messages?: Record<string, Translations>\n /**\n * Page-scoped dictionaries keyed by route name (`guide-demo`), then locale.\n * Loaded from `locales/pages/**` when using `withI18n`.\n */\n routeMessages?: Record<string, Record<string, Translations>>\n plural?: PluralFunc\n missingWarn?: boolean\n missingHandler?: (locale: string, key: string, routeName: string) => void\n /**\n * Sync i18n locale from the VitePress URL path on every navigation.\n * @default true\n */\n syncWithVitePress?: boolean\n /**\n * Map VitePress locale keys to i18n codes (`root` → default locale code).\n */\n localeKeyToCode?: Record<string, string>\n /**\n * VitePress `site.base`. Needed so SSG paths (`withBase`) and lang switcher\n * do not treat the base segment as content / double-prefix links.\n */\n base?: string\n}\n\nexport interface VitePressSiteDataLike {\n locales?: Record<string, { lang?: string; link?: string; label?: string }>\n}\n\nexport type CreateI18nResult = I18nPlugin &\n PathMethods & {\n /** Same as `.global` (VueI18n + path methods). */\n i18n: I18nPlugin['global'] & PathMethods\n enhanceApp: (ctx: { app: App; router: VitePressRouterLike; siteData?: Ref<VitePressSiteDataLike> | VitePressSiteDataLike }) => void\n }\n\nfunction applyRouteMessages(\n plugin: I18nPlugin,\n root: Record<string, Translations> | undefined,\n routeMessages: Record<string, Record<string, Translations>> | undefined,\n): void {\n if (!routeMessages) return\n for (const [routeName, byLocale] of Object.entries(routeMessages)) {\n for (const [locale, translations] of Object.entries(byLocale)) {\n plugin.global.addRouteTranslations(locale, routeName, mergeRouteTranslationsWithRoot(root?.[locale], translations), false)\n }\n }\n}\n\n/**\n * Universal VitePress i18n: Vue plugin + path helpers + `enhanceApp` sync.\n * Path methods are the router adapter’s own functions (no wrapper layer).\n */\nexport function createI18n(options: CreateI18nOptions): CreateI18nResult {\n const defaultLocale = options.defaultLocale || options.locale\n const locales = options.locales ?? []\n const syncWithVitePress = options.syncWithVitePress !== false\n\n const plugin = createVueI18n({\n locale: options.locale,\n fallbackLocale: options.fallbackLocale ?? defaultLocale,\n messages: options.messages,\n plural: options.plural,\n missingWarn: options.missingWarn,\n missingHandler: options.missingHandler,\n locales,\n defaultLocale,\n })\n\n applyRouteMessages(plugin, options.messages, options.routeMessages)\n\n const paths = createVitePressRouterAdapter({\n locales,\n defaultLocale,\n localeKeyToCode: options.localeKeyToCode,\n base: options.base,\n })\n const pathMethods: PathMethods = {\n localizePath: paths.localizePath,\n switchLocalePath: paths.switchLocalePath,\n getLocaleFromPath: paths.getLocaleFromPath,\n removeLocaleFromPath: paths.removeLocaleFromPath,\n routeNameFromPath: paths.routeNameFromPath,\n }\n plugin.global.extend(pathMethods)\n\n const pageRouteNames = new Set(Object.keys(options.routeMessages ?? {}))\n\n const byApp = new WeakMap<\n object,\n {\n adapter: VitePressRouterAdapter\n boundSyncHandler: ((to: string) => unknown) | null\n chainedPrevious: ((to: string) => unknown) | undefined\n }\n >()\n\n const enhanceApp = (ctx: { app: App; router: VitePressRouterLike; siteData?: Ref<VitePressSiteDataLike> | VitePressSiteDataLike }) => {\n const { app, router } = ctx\n\n let state = byApp.get(app)\n if (!state) {\n const adapter = createVitePressRouterAdapter({\n locales,\n defaultLocale,\n localeKeyToCode: options.localeKeyToCode,\n base: options.base,\n getPath: () => {\n const route = router.route\n return `${route.path}${route.query || ''}${route.hash || ''}`\n },\n go: (href, navOptions) => router.go(href, navOptions),\n })\n\n app.use(plugin)\n plugin.setRoutingStrategy(adapter)\n state = { adapter, boundSyncHandler: null, chainedPrevious: undefined }\n byApp.set(app, state)\n }\n\n if (!syncWithVitePress) return\n\n const { adapter } = state\n const sync = (path = router.route.path) => {\n const nextLocale = adapter.getLocaleFromPath(path)\n if (plugin.global.getLocale() !== nextLocale) {\n plugin.global.locale = nextLocale\n }\n const derived = adapter.routeNameFromPath(path)\n plugin.global.setRoute(pageRouteNames.has(derived) ? derived : 'index')\n }\n\n sync()\n\n const current = router.onAfterRouteChange\n if (current !== state.boundSyncHandler) {\n state.chainedPrevious = typeof current === 'function' ? current : undefined\n }\n state.boundSyncHandler = async (to: string) => {\n if (typeof state.chainedPrevious === 'function') {\n await state.chainedPrevious(to)\n }\n const path = to.startsWith('http')\n ? (() => {\n const url = new URL(to)\n return url.pathname + url.search + url.hash\n })()\n : to\n sync(path)\n }\n router.onAfterRouteChange = state.boundSyncHandler\n }\n\n return Object.assign(plugin, pathMethods, {\n get i18n() {\n return plugin.global as I18nPlugin['global'] & PathMethods\n },\n enhanceApp,\n }) as CreateI18nResult\n}\n"],"names":["applyRouteMessages","plugin","root","routeMessages","routeName","byLocale","locale","translations","mergeRouteTranslationsWithRoot","createI18n","options","defaultLocale","locales","syncWithVitePress","createVueI18n","paths","createVitePressRouterAdapter","pathMethods","pageRouteNames","byApp","ctx","app","router","state","adapter","route","href","navOptions","sync","path","nextLocale","derived","current","to","url"],"mappings":"8HAiDA,SAASA,EACPC,EACAC,EACAC,EACM,CACN,GAAKA,EACL,SAAW,CAACC,EAAWC,CAAQ,IAAK,OAAO,QAAQF,CAAa,EAC9D,SAAW,CAACG,EAAQC,CAAY,IAAK,OAAO,QAAQF,CAAQ,EAC1DJ,EAAO,OAAO,qBAAqBK,EAAQF,EAAWI,iCAA+BN,IAAOI,CAAM,EAAGC,CAAY,EAAG,EAAK,CAG/H,CAMO,SAASE,EAAWC,EAA8C,CACvE,MAAMC,EAAgBD,EAAQ,eAAiBA,EAAQ,OACjDE,EAAUF,EAAQ,SAAW,CAAA,EAC7BG,EAAoBH,EAAQ,oBAAsB,GAElDT,EAASa,EAAAA,WAAc,CAC3B,OAAQJ,EAAQ,OAChB,eAAgBA,EAAQ,gBAAkBC,EAC1C,SAAUD,EAAQ,SAClB,OAAQA,EAAQ,OAChB,YAAaA,EAAQ,YACrB,eAAgBA,EAAQ,eACxB,QAAAE,EACA,cAAAD,CAAA,CACD,EAEDX,EAAmBC,EAAQS,EAAQ,SAAUA,EAAQ,aAAa,EAElE,MAAMK,EAAQC,EAAAA,6BAA6B,CACzC,QAAAJ,EACA,cAAAD,EACA,gBAAiBD,EAAQ,gBACzB,KAAMA,EAAQ,IAAA,CACf,EACKO,EAA2B,CAC/B,aAAcF,EAAM,aACpB,iBAAkBA,EAAM,iBACxB,kBAAmBA,EAAM,kBACzB,qBAAsBA,EAAM,qBAC5B,kBAAmBA,EAAM,iBAAA,EAE3Bd,EAAO,OAAO,OAAOgB,CAAW,EAEhC,MAAMC,EAAiB,IAAI,IAAI,OAAO,KAAKR,EAAQ,eAAiB,CAAA,CAAE,CAAC,EAEjES,MAAY,QAiElB,OAAO,OAAO,OAAOlB,EAAQgB,EAAa,CACxC,IAAI,MAAO,CACT,OAAOhB,EAAO,MAChB,EACA,WA5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,OAAOC,EAAI,SAAWA,EAAI,OAASA,EAAI,IACzC,KACAD,EACJL,EAAKC,CAAI,CACX,EACAP,EAAO,mBAAqBC,EAAM,gBACpC,CAME,CACD,CACH"}
@@ -0,0 +1,80 @@
1
+ import { mergeRouteTranslationsWithRoot as L } from "@i18n-micro/utils/parse-path";
2
+ import { createI18n as R } from "@i18n-micro/vue";
3
+ import { c as y } from "./adapter-BnsyIKhp.js";
4
+ function v(e, l, n) {
5
+ if (n)
6
+ for (const [i, a] of Object.entries(n))
7
+ for (const [c, h] of Object.entries(a))
8
+ e.global.addRouteTranslations(c, i, L(l?.[c], h), !1);
9
+ }
10
+ function C(e) {
11
+ const l = e.defaultLocale || e.locale, n = e.locales ?? [], i = e.syncWithVitePress !== !1, a = R({
12
+ locale: e.locale,
13
+ fallbackLocale: e.fallbackLocale ?? l,
14
+ messages: e.messages,
15
+ plural: e.plural,
16
+ missingWarn: e.missingWarn,
17
+ missingHandler: e.missingHandler,
18
+ locales: n,
19
+ defaultLocale: l
20
+ });
21
+ v(a, e.messages, e.routeMessages);
22
+ const c = y({
23
+ locales: n,
24
+ defaultLocale: l,
25
+ localeKeyToCode: e.localeKeyToCode,
26
+ base: e.base
27
+ }), h = {
28
+ localizePath: c.localizePath,
29
+ switchLocalePath: c.switchLocalePath,
30
+ getLocaleFromPath: c.getLocaleFromPath,
31
+ removeLocaleFromPath: c.removeLocaleFromPath,
32
+ routeNameFromPath: c.routeNameFromPath
33
+ };
34
+ a.global.extend(h);
35
+ const P = new Set(Object.keys(e.routeMessages ?? {})), m = /* @__PURE__ */ new WeakMap();
36
+ return Object.assign(a, h, {
37
+ get i18n() {
38
+ return a.global;
39
+ },
40
+ enhanceApp: (p) => {
41
+ const { app: d, router: u } = p;
42
+ let t = m.get(d);
43
+ if (!t) {
44
+ const o = y({
45
+ locales: n,
46
+ defaultLocale: l,
47
+ localeKeyToCode: e.localeKeyToCode,
48
+ base: e.base,
49
+ getPath: () => {
50
+ const r = u.route;
51
+ return `${r.path}${r.query || ""}${r.hash || ""}`;
52
+ },
53
+ go: (r, s) => u.go(r, s)
54
+ });
55
+ d.use(a), a.setRoutingStrategy(o), t = { adapter: o, boundSyncHandler: null, chainedPrevious: void 0 }, m.set(d, t);
56
+ }
57
+ if (!i) return;
58
+ const { adapter: f } = t, b = (o = u.route.path) => {
59
+ const r = f.getLocaleFromPath(o);
60
+ a.global.getLocale() !== r && (a.global.locale = r);
61
+ const s = f.routeNameFromPath(o);
62
+ a.global.setRoute(P.has(s) ? s : "index");
63
+ };
64
+ b();
65
+ const g = u.onAfterRouteChange;
66
+ g !== t.boundSyncHandler && (t.chainedPrevious = typeof g == "function" ? g : void 0), t.boundSyncHandler = async (o) => {
67
+ typeof t.chainedPrevious == "function" && await t.chainedPrevious(o);
68
+ const r = o.startsWith("http") ? (() => {
69
+ const s = new URL(o);
70
+ return s.pathname + s.search + s.hash;
71
+ })() : o;
72
+ b(r);
73
+ }, u.onAfterRouteChange = t.boundSyncHandler;
74
+ }
75
+ });
76
+ }
77
+ export {
78
+ C as c
79
+ };
80
+ //# sourceMappingURL=create-Dev8Q66O.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"create-Dev8Q66O.js","sources":["../src/runtime/create.ts"],"sourcesContent":["import type { Locale, PluralFunc, Translations } from '@i18n-micro/types'\nimport { mergeRouteTranslationsWithRoot } from '@i18n-micro/utils/parse-path'\nimport { createI18n as createVueI18n, type I18nPlugin } from '@i18n-micro/vue'\nimport type { App, Ref } from 'vue'\nimport { createVitePressRouterAdapter, type PathMethods, type VitePressRouterAdapter, type VitePressRouterLike } from '../router/adapter'\n\nexport type { PathMethods }\n\nexport interface CreateI18nOptions {\n locale: string\n fallbackLocale?: string\n locales?: Locale[]\n defaultLocale?: string\n messages?: Record<string, Translations>\n /**\n * Page-scoped dictionaries keyed by route name (`guide-demo`), then locale.\n * Loaded from `locales/pages/**` when using `withI18n`.\n */\n routeMessages?: Record<string, Record<string, Translations>>\n plural?: PluralFunc\n missingWarn?: boolean\n missingHandler?: (locale: string, key: string, routeName: string) => void\n /**\n * Sync i18n locale from the VitePress URL path on every navigation.\n * @default true\n */\n syncWithVitePress?: boolean\n /**\n * Map VitePress locale keys to i18n codes (`root` → default locale code).\n */\n localeKeyToCode?: Record<string, string>\n /**\n * VitePress `site.base`. Needed so SSG paths (`withBase`) and lang switcher\n * do not treat the base segment as content / double-prefix links.\n */\n base?: string\n}\n\nexport interface VitePressSiteDataLike {\n locales?: Record<string, { lang?: string; link?: string; label?: string }>\n}\n\nexport type CreateI18nResult = I18nPlugin &\n PathMethods & {\n /** Same as `.global` (VueI18n + path methods). */\n i18n: I18nPlugin['global'] & PathMethods\n enhanceApp: (ctx: { app: App; router: VitePressRouterLike; siteData?: Ref<VitePressSiteDataLike> | VitePressSiteDataLike }) => void\n }\n\nfunction applyRouteMessages(\n plugin: I18nPlugin,\n root: Record<string, Translations> | undefined,\n routeMessages: Record<string, Record<string, Translations>> | undefined,\n): void {\n if (!routeMessages) return\n for (const [routeName, byLocale] of Object.entries(routeMessages)) {\n for (const [locale, translations] of Object.entries(byLocale)) {\n plugin.global.addRouteTranslations(locale, routeName, mergeRouteTranslationsWithRoot(root?.[locale], translations), false)\n }\n }\n}\n\n/**\n * Universal VitePress i18n: Vue plugin + path helpers + `enhanceApp` sync.\n * Path methods are the router adapter’s own functions (no wrapper layer).\n */\nexport function createI18n(options: CreateI18nOptions): CreateI18nResult {\n const defaultLocale = options.defaultLocale || options.locale\n const locales = options.locales ?? []\n const syncWithVitePress = options.syncWithVitePress !== false\n\n const plugin = createVueI18n({\n locale: options.locale,\n fallbackLocale: options.fallbackLocale ?? defaultLocale,\n messages: options.messages,\n plural: options.plural,\n missingWarn: options.missingWarn,\n missingHandler: options.missingHandler,\n locales,\n defaultLocale,\n })\n\n applyRouteMessages(plugin, options.messages, options.routeMessages)\n\n const paths = createVitePressRouterAdapter({\n locales,\n defaultLocale,\n localeKeyToCode: options.localeKeyToCode,\n base: options.base,\n })\n const pathMethods: PathMethods = {\n localizePath: paths.localizePath,\n switchLocalePath: paths.switchLocalePath,\n getLocaleFromPath: paths.getLocaleFromPath,\n removeLocaleFromPath: paths.removeLocaleFromPath,\n routeNameFromPath: paths.routeNameFromPath,\n }\n plugin.global.extend(pathMethods)\n\n const pageRouteNames = new Set(Object.keys(options.routeMessages ?? {}))\n\n const byApp = new WeakMap<\n object,\n {\n adapter: VitePressRouterAdapter\n boundSyncHandler: ((to: string) => unknown) | null\n chainedPrevious: ((to: string) => unknown) | undefined\n }\n >()\n\n const enhanceApp = (ctx: { app: App; router: VitePressRouterLike; siteData?: Ref<VitePressSiteDataLike> | VitePressSiteDataLike }) => {\n const { app, router } = ctx\n\n let state = byApp.get(app)\n if (!state) {\n const adapter = createVitePressRouterAdapter({\n locales,\n defaultLocale,\n localeKeyToCode: options.localeKeyToCode,\n base: options.base,\n getPath: () => {\n const route = router.route\n return `${route.path}${route.query || ''}${route.hash || ''}`\n },\n go: (href, navOptions) => router.go(href, navOptions),\n })\n\n app.use(plugin)\n plugin.setRoutingStrategy(adapter)\n state = { adapter, boundSyncHandler: null, chainedPrevious: undefined }\n byApp.set(app, state)\n }\n\n if (!syncWithVitePress) return\n\n const { adapter } = state\n const sync = (path = router.route.path) => {\n const nextLocale = adapter.getLocaleFromPath(path)\n if (plugin.global.getLocale() !== nextLocale) {\n plugin.global.locale = nextLocale\n }\n const derived = adapter.routeNameFromPath(path)\n plugin.global.setRoute(pageRouteNames.has(derived) ? derived : 'index')\n }\n\n sync()\n\n const current = router.onAfterRouteChange\n if (current !== state.boundSyncHandler) {\n state.chainedPrevious = typeof current === 'function' ? current : undefined\n }\n state.boundSyncHandler = async (to: string) => {\n if (typeof state.chainedPrevious === 'function') {\n await state.chainedPrevious(to)\n }\n const path = to.startsWith('http')\n ? (() => {\n const url = new URL(to)\n return url.pathname + url.search + url.hash\n })()\n : to\n sync(path)\n }\n router.onAfterRouteChange = state.boundSyncHandler\n }\n\n return Object.assign(plugin, pathMethods, {\n get i18n() {\n return plugin.global as I18nPlugin['global'] & PathMethods\n },\n enhanceApp,\n }) as CreateI18nResult\n}\n"],"names":["applyRouteMessages","plugin","root","routeMessages","routeName","byLocale","locale","translations","mergeRouteTranslationsWithRoot","createI18n","options","defaultLocale","locales","syncWithVitePress","createVueI18n","paths","createVitePressRouterAdapter","pathMethods","pageRouteNames","byApp","ctx","app","router","state","adapter","route","href","navOptions","sync","path","nextLocale","derived","current","to","url"],"mappings":";;;AAiDA,SAASA,EACPC,GACAC,GACAC,GACM;AACN,MAAKA;AACL,eAAW,CAACC,GAAWC,CAAQ,KAAK,OAAO,QAAQF,CAAa;AAC9D,iBAAW,CAACG,GAAQC,CAAY,KAAK,OAAO,QAAQF,CAAQ;AAC1D,QAAAJ,EAAO,OAAO,qBAAqBK,GAAQF,GAAWI,EAA+BN,IAAOI,CAAM,GAAGC,CAAY,GAAG,EAAK;AAG/H;AAMO,SAASE,EAAWC,GAA8C;AACvE,QAAMC,IAAgBD,EAAQ,iBAAiBA,EAAQ,QACjDE,IAAUF,EAAQ,WAAW,CAAA,GAC7BG,IAAoBH,EAAQ,sBAAsB,IAElDT,IAASa,EAAc;AAAA,IAC3B,QAAQJ,EAAQ;AAAA,IAChB,gBAAgBA,EAAQ,kBAAkBC;AAAA,IAC1C,UAAUD,EAAQ;AAAA,IAClB,QAAQA,EAAQ;AAAA,IAChB,aAAaA,EAAQ;AAAA,IACrB,gBAAgBA,EAAQ;AAAA,IACxB,SAAAE;AAAA,IACA,eAAAD;AAAA,EAAA,CACD;AAED,EAAAX,EAAmBC,GAAQS,EAAQ,UAAUA,EAAQ,aAAa;AAElE,QAAMK,IAAQC,EAA6B;AAAA,IACzC,SAAAJ;AAAA,IACA,eAAAD;AAAA,IACA,iBAAiBD,EAAQ;AAAA,IACzB,MAAMA,EAAQ;AAAA,EAAA,CACf,GACKO,IAA2B;AAAA,IAC/B,cAAcF,EAAM;AAAA,IACpB,kBAAkBA,EAAM;AAAA,IACxB,mBAAmBA,EAAM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