@astroscope/i18n 0.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 (194) hide show
  1. package/README.md +262 -0
  2. package/dist/babel-plugin-FUTQRKLT.js +121 -0
  3. package/dist/babel-plugin-K2K4ZPM5.js +118 -0
  4. package/dist/chunk-22ZZFFC2.js +159 -0
  5. package/dist/chunk-2PSXD3JJ.js +144 -0
  6. package/dist/chunk-3VI62RLT.js +176 -0
  7. package/dist/chunk-4A5BKHFN.js +16 -0
  8. package/dist/chunk-4DAQPWXI.js +36 -0
  9. package/dist/chunk-4OGX6AF5.js +10 -0
  10. package/dist/chunk-4PHYKXO3.js +227 -0
  11. package/dist/chunk-4UBFISFY.js +376 -0
  12. package/dist/chunk-5DERF6DV.js +266 -0
  13. package/dist/chunk-5KGNHFTC.js +344 -0
  14. package/dist/chunk-5PP4D2VK.js +23 -0
  15. package/dist/chunk-6BW3PN23.js +14 -0
  16. package/dist/chunk-6ESQ4JQI.js +263 -0
  17. package/dist/chunk-A7MPXMOP.js +202 -0
  18. package/dist/chunk-AWZ2SQDW.js +149 -0
  19. package/dist/chunk-AYY2YIBQ.js +52 -0
  20. package/dist/chunk-BMNEJFTD.js +56 -0
  21. package/dist/chunk-BSXQGEUK.js +16 -0
  22. package/dist/chunk-BSYTJFGF.js +21 -0
  23. package/dist/chunk-BVPXEGTT.js +12 -0
  24. package/dist/chunk-C4DJYWF6.js +193 -0
  25. package/dist/chunk-C5EJYE2P.js +245 -0
  26. package/dist/chunk-CLNOQHMS.js +254 -0
  27. package/dist/chunk-E5MCIRSU.js +144 -0
  28. package/dist/chunk-E7ZJS7WX.js +162 -0
  29. package/dist/chunk-EMM6LRO2.js +8 -0
  30. package/dist/chunk-ESFGCYYH.js +24 -0
  31. package/dist/chunk-FAKBSLNW.js +24 -0
  32. package/dist/chunk-FHBVI3TL.js +372 -0
  33. package/dist/chunk-FI5KZ5IO.js +17 -0
  34. package/dist/chunk-H5R6YMOL.js +233 -0
  35. package/dist/chunk-H62K3FGA.js +236 -0
  36. package/dist/chunk-HDG2R6XT.js +211 -0
  37. package/dist/chunk-HGXU5QAK.js +344 -0
  38. package/dist/chunk-HHRMR3TM.js +17 -0
  39. package/dist/chunk-HS4HVBAD.js +127 -0
  40. package/dist/chunk-IPJWKKHJ.js +324 -0
  41. package/dist/chunk-ITTL4V7J.js +24 -0
  42. package/dist/chunk-IWUBCMOK.js +128 -0
  43. package/dist/chunk-JJBBY2GR.js +14 -0
  44. package/dist/chunk-JJEDOJBR.js +193 -0
  45. package/dist/chunk-JTUKXNIJ.js +23 -0
  46. package/dist/chunk-K7YULG4A.js +14 -0
  47. package/dist/chunk-KNDYKTHE.js +31 -0
  48. package/dist/chunk-KNONI6DP.js +89 -0
  49. package/dist/chunk-LMTEO22Y.js +17 -0
  50. package/dist/chunk-LRLZEX4D.js +147 -0
  51. package/dist/chunk-MFKPLUAN.js +241 -0
  52. package/dist/chunk-MIWXQOO3.js +316 -0
  53. package/dist/chunk-MJRTAWPR.js +261 -0
  54. package/dist/chunk-MZEPQCXX.js +249 -0
  55. package/dist/chunk-NHHTSFA7.js +237 -0
  56. package/dist/chunk-NTTXM7AG.js +23 -0
  57. package/dist/chunk-NZFAVJXR.js +192 -0
  58. package/dist/chunk-OFNFSDW3.js +13 -0
  59. package/dist/chunk-PG3XDNGF.js +227 -0
  60. package/dist/chunk-PVEVTPNK.js +139 -0
  61. package/dist/chunk-QAO4BXS4.js +244 -0
  62. package/dist/chunk-QCTULQQK.js +34 -0
  63. package/dist/chunk-QFAAGCP5.js +177 -0
  64. package/dist/chunk-QKND2KCA.js +163 -0
  65. package/dist/chunk-QZEGY6RJ.js +151 -0
  66. package/dist/chunk-RAE2L6FT.js +193 -0
  67. package/dist/chunk-S3ABJBU3.js +255 -0
  68. package/dist/chunk-SVDVCPCV.js +236 -0
  69. package/dist/chunk-T35ZUWTL.js +153 -0
  70. package/dist/chunk-T6WV5DW6.js +156 -0
  71. package/dist/chunk-TGUXVDA3.js +82 -0
  72. package/dist/chunk-TYMO7K3A.js +173 -0
  73. package/dist/chunk-V4RBFLQL.js +23 -0
  74. package/dist/chunk-V4XWJXXZ.js +23 -0
  75. package/dist/chunk-VQCY3OKK.js +258 -0
  76. package/dist/chunk-WLGOJPDJ.js +15 -0
  77. package/dist/chunk-WUEPDJIL.js +259 -0
  78. package/dist/chunk-X3L7WZLY.js +254 -0
  79. package/dist/chunk-XDD62ZM3.js +255 -0
  80. package/dist/chunk-XFXXEDRD.js +36 -0
  81. package/dist/chunk-XKYOR5UK.js +8 -0
  82. package/dist/chunk-Y26535SI.js +239 -0
  83. package/dist/chunk-Y3PQX5TX.js +152 -0
  84. package/dist/chunk-Y4BE2V6F.js +347 -0
  85. package/dist/chunk-Z4IZYDIA.js +24 -0
  86. package/dist/chunk-Z52G4CYY.js +14 -0
  87. package/dist/chunk-ZGLUYWVM.js +128 -0
  88. package/dist/client/directives/idle.d.ts +9 -0
  89. package/dist/client/directives/idle.js +15 -0
  90. package/dist/client/directives/load.d.ts +9 -0
  91. package/dist/client/directives/load.js +15 -0
  92. package/dist/client/directives/media.d.ts +9 -0
  93. package/dist/client/directives/media.js +15 -0
  94. package/dist/client/directives/only.d.ts +9 -0
  95. package/dist/client/directives/only.js +15 -0
  96. package/dist/client/directives/utils.d.ts +10 -0
  97. package/dist/client/directives/utils.js +7 -0
  98. package/dist/client/directives/visible.d.ts +9 -0
  99. package/dist/client/directives/visible.js +15 -0
  100. package/dist/client/import-with-i18n.d.ts +16 -0
  101. package/dist/client/import-with-i18n.js +8 -0
  102. package/dist/client/t.d.ts +20 -0
  103. package/dist/client/t.js +37 -0
  104. package/dist/client-directives/idle.d.ts +9 -0
  105. package/dist/client-directives/idle.js +15 -0
  106. package/dist/client-directives/load.d.ts +9 -0
  107. package/dist/client-directives/load.js +15 -0
  108. package/dist/client-directives/media.d.ts +9 -0
  109. package/dist/client-directives/media.js +15 -0
  110. package/dist/client-directives/only.d.ts +9 -0
  111. package/dist/client-directives/only.js +15 -0
  112. package/dist/client-directives/utils.d.ts +9 -0
  113. package/dist/client-directives/utils.js +7 -0
  114. package/dist/client-directives/visible.d.ts +9 -0
  115. package/dist/client-directives/visible.js +15 -0
  116. package/dist/extraction/index.d.ts +34 -0
  117. package/dist/extraction/index.js +9 -0
  118. package/dist/i18n-3cZHoHwP.d.ts +86 -0
  119. package/dist/i18n-BGfrSNM8.d.ts +56 -0
  120. package/dist/i18n-BHU81LMA.d.ts +55 -0
  121. package/dist/i18n-BagoeH4_.d.ts +62 -0
  122. package/dist/i18n-BeL84090.d.ts +77 -0
  123. package/dist/i18n-BeRWDfHi.d.ts +55 -0
  124. package/dist/i18n-Bfs2PVcf.d.ts +79 -0
  125. package/dist/i18n-BrL7p3aN.d.ts +99 -0
  126. package/dist/i18n-CNQNCFU0.d.ts +55 -0
  127. package/dist/i18n-CX_uU8V2.d.ts +80 -0
  128. package/dist/i18n-Cr1QZCwe.d.ts +64 -0
  129. package/dist/i18n-CzTRxGeX.d.ts +80 -0
  130. package/dist/i18n-DUOFiC7g.d.ts +77 -0
  131. package/dist/i18n-DcF47BHS.d.ts +77 -0
  132. package/dist/i18n-DifWvtaO.d.ts +60 -0
  133. package/dist/i18n-DumSqX1t.d.ts +55 -0
  134. package/dist/i18n-fWTJw12h.d.ts +80 -0
  135. package/dist/import-with-i18n.d.ts +23 -0
  136. package/dist/import-with-i18n.js +7 -0
  137. package/dist/index.d.ts +68 -0
  138. package/dist/index.js +151 -0
  139. package/dist/init.d.ts +2 -0
  140. package/dist/init.js +8 -0
  141. package/dist/internal.d.ts +11 -0
  142. package/dist/internal.js +9 -0
  143. package/dist/middleware-entrypoint-C0Drh9E_.d.ts +29 -0
  144. package/dist/middleware-entrypoint-mEl66IUy.d.ts +29 -0
  145. package/dist/middleware-entrypoint.d.ts +5 -0
  146. package/dist/middleware-entrypoint.js +30 -0
  147. package/dist/server/middleware-entrypoint.d.ts +2 -0
  148. package/dist/server/middleware-entrypoint.js +28 -0
  149. package/dist/server/t.d.ts +17 -0
  150. package/dist/server/t.js +59 -0
  151. package/dist/t-BY_C9lZ1.d.ts +30 -0
  152. package/dist/t-CG3yDiEa.d.ts +30 -0
  153. package/dist/t-CHsBfrPr.d.ts +30 -0
  154. package/dist/t-DQpXaDhP.d.ts +30 -0
  155. package/dist/t.client.d.ts +11 -0
  156. package/dist/t.client.js +35 -0
  157. package/dist/t.server.d.ts +22 -0
  158. package/dist/t.server.js +12 -0
  159. package/dist/types-8uKCwFda.d.ts +24 -0
  160. package/dist/types-BC6K-pID.d.ts +110 -0
  161. package/dist/types-BUV7BZML.d.ts +55 -0
  162. package/dist/types-BWGB322F.d.ts +46 -0
  163. package/dist/types-B_-RxW4A.d.ts +7 -0
  164. package/dist/types-BaaSiz9n.d.ts +7 -0
  165. package/dist/types-Bgl2V5xo.d.ts +102 -0
  166. package/dist/types-BwhB6IT4.d.ts +111 -0
  167. package/dist/types-Bzp6KxsI.d.ts +50 -0
  168. package/dist/types-C6rOJFY2.d.ts +24 -0
  169. package/dist/types-C7lD-Woj.d.ts +50 -0
  170. package/dist/types-CLWZeQhD.d.ts +54 -0
  171. package/dist/types-COXt613w.d.ts +19 -0
  172. package/dist/types-CUlkbl9-.d.ts +50 -0
  173. package/dist/types-CVv7GGPj.d.ts +46 -0
  174. package/dist/types-CiIDN2sW.d.ts +64 -0
  175. package/dist/types-Cr86qjYl.d.ts +58 -0
  176. package/dist/types-CxnObiEO.d.ts +7 -0
  177. package/dist/types-D44mFUjA.d.ts +97 -0
  178. package/dist/types-D85m9UTC.d.ts +137 -0
  179. package/dist/types-DWhsmSPP.d.ts +102 -0
  180. package/dist/types-DdprXGJ1.d.ts +46 -0
  181. package/dist/types-DhVJ2ZIo.d.ts +43 -0
  182. package/dist/types-DnbOuM1L.d.ts +7 -0
  183. package/dist/types-DsNK_9sI.d.ts +24 -0
  184. package/dist/types-DvWBr9Xp.d.ts +17 -0
  185. package/dist/types-DwkIalh6.d.ts +24 -0
  186. package/dist/types-OYRgjtE_.d.ts +110 -0
  187. package/dist/types-SV8S05GX.d.ts +7 -0
  188. package/dist/types-TYn9WnxY.d.ts +46 -0
  189. package/dist/types-aXCBbdhq.d.ts +55 -0
  190. package/dist/types-gn4aNKGx.d.ts +54 -0
  191. package/dist/types-nippsMkm.d.ts +54 -0
  192. package/package.json +105 -0
  193. package/src/components/I18nScript.astro +37 -0
  194. package/src/components/index.ts +2 -0
@@ -0,0 +1,14 @@
1
+ // src/shared/meta.ts
2
+ function isMeta(arg) {
3
+ if (typeof arg === "string") return true;
4
+ if (typeof arg === "object" && arg !== null && "fallback" in arg) return true;
5
+ return false;
6
+ }
7
+ function normalizeMeta(meta) {
8
+ return typeof meta === "string" ? { fallback: meta } : meta;
9
+ }
10
+
11
+ export {
12
+ isMeta,
13
+ normalizeMeta
14
+ };
@@ -0,0 +1,31 @@
1
+ // src/shared/compiler.ts
2
+ import MessageFormat from "@messageformat/core";
3
+ var cache = /* @__PURE__ */ new Map();
4
+ function getMessageFormat(locale) {
5
+ let mf = cache.get(locale);
6
+ if (!mf) {
7
+ mf = new MessageFormat(locale);
8
+ cache.set(locale, mf);
9
+ }
10
+ return mf;
11
+ }
12
+ function compileMessage(locale, message) {
13
+ const mf = getMessageFormat(locale);
14
+ try {
15
+ return mf.compile(message);
16
+ } catch {
17
+ return () => message;
18
+ }
19
+ }
20
+ function compileTranslations(locale, raw) {
21
+ const compiled = {};
22
+ for (const [key, message] of Object.entries(raw)) {
23
+ compiled[key] = compileMessage(locale, message);
24
+ }
25
+ return compiled;
26
+ }
27
+
28
+ export {
29
+ compileMessage,
30
+ compileTranslations
31
+ };
@@ -0,0 +1,89 @@
1
+ // src/messageformat.ts
2
+ import MessageFormat from "@messageformat/core";
3
+ var mfCache = /* @__PURE__ */ new Map();
4
+ function getMessageFormat(locale) {
5
+ let mf = mfCache.get(locale);
6
+ if (!mf) {
7
+ mf = new MessageFormat(locale);
8
+ mfCache.set(locale, mf);
9
+ }
10
+ return mf;
11
+ }
12
+ function compileMessage(locale, message) {
13
+ const mf = getMessageFormat(locale);
14
+ try {
15
+ return mf.compile(message);
16
+ } catch {
17
+ return (values) => {
18
+ if (!values) return message;
19
+ return Object.entries(values).reduce(
20
+ (result, [key, value]) => result.replace(new RegExp(`\\{${key}\\}`, "g"), String(value)),
21
+ message
22
+ );
23
+ };
24
+ }
25
+ }
26
+ function compileTranslations(locale, raw) {
27
+ const compiled = {};
28
+ for (const [key, message] of Object.entries(raw)) {
29
+ compiled[key] = compileMessage(locale, message);
30
+ }
31
+ return compiled;
32
+ }
33
+
34
+ // src/t.server.ts
35
+ var currentContext = null;
36
+ function setContext(context) {
37
+ currentContext = context;
38
+ }
39
+ function getContext() {
40
+ return currentContext;
41
+ }
42
+ function clearContext() {
43
+ currentContext = null;
44
+ }
45
+ function applyFallback(key, meta, fallback) {
46
+ if (typeof fallback === "function") {
47
+ return fallback(key, meta);
48
+ }
49
+ switch (fallback) {
50
+ case "key":
51
+ return key;
52
+ case "example":
53
+ return meta.example;
54
+ case "throw":
55
+ throw new Error(`Missing translation for key: ${key}`);
56
+ default:
57
+ return meta.example;
58
+ }
59
+ }
60
+ var t = (key, meta, values) => {
61
+ const ctx = currentContext;
62
+ if (!ctx) {
63
+ return interpolateExample(meta.example, values);
64
+ }
65
+ ctx.meta[key] = meta;
66
+ const compiled = ctx.translations[key];
67
+ if (!compiled) {
68
+ const fallbackValue = applyFallback(key, meta, ctx.fallback);
69
+ const compiledFallback = compileMessage(ctx.locale, fallbackValue);
70
+ ctx.translations[key] = compiledFallback;
71
+ return compiledFallback(values);
72
+ }
73
+ return compiled(values);
74
+ };
75
+ function interpolateExample(example, values) {
76
+ if (!values) return example;
77
+ return Object.entries(values).reduce(
78
+ (result, [key, value]) => result.replace(new RegExp(`\\{${key}\\}`, "g"), String(value)),
79
+ example
80
+ );
81
+ }
82
+
83
+ export {
84
+ compileTranslations,
85
+ setContext,
86
+ getContext,
87
+ clearContext,
88
+ t
89
+ };
@@ -0,0 +1,17 @@
1
+ // src/extraction/url.ts
2
+ function chunkIdToName(chunkId) {
3
+ return chunkId.replace(/^_astro\//, "");
4
+ }
5
+ function componentUrlToChunkName(componentUrl) {
6
+ return componentUrl.replace(/^\/_astro\//, "").replace(/\.js$/, "");
7
+ }
8
+ function buildI18nChunkUrl(locale, chunkId, hash) {
9
+ const chunkName = chunkIdToName(chunkId);
10
+ return `/_i18n/${locale}/${chunkName}.${hash}.js`;
11
+ }
12
+
13
+ export {
14
+ chunkIdToName,
15
+ componentUrlToChunkName,
16
+ buildI18nChunkUrl
17
+ };
@@ -0,0 +1,147 @@
1
+ import {
2
+ compileTranslations
3
+ } from "./chunk-KNDYKTHE.js";
4
+
5
+ // src/extraction/hash.ts
6
+ import { createHash } from "crypto";
7
+ function hashString(str) {
8
+ return createHash("sha256").update(str).digest("hex").substring(0, 8);
9
+ }
10
+ function computeChunkHash(translations, keys) {
11
+ const relevantTranslations = {};
12
+ for (const key of keys.sort()) {
13
+ if (translations[key]) {
14
+ relevantTranslations[key] = translations[key];
15
+ }
16
+ }
17
+ return hashString(JSON.stringify(relevantTranslations));
18
+ }
19
+ function computeAllChunkHashes(translations, manifest) {
20
+ const hashes = {};
21
+ for (const [chunkId, keys] of Object.entries(manifest)) {
22
+ hashes[chunkId] = computeChunkHash(translations, keys);
23
+ }
24
+ return hashes;
25
+ }
26
+
27
+ // src/server/i18n.ts
28
+ var I18nSingleton = class {
29
+ // normalized user config with defaults applied
30
+ config = null;
31
+ // locale -> raw translation strings (before ICU compilation)
32
+ rawCache = /* @__PURE__ */ new Map();
33
+ // locale -> compiled ICU MessageFormat functions
34
+ compiledCache = /* @__PURE__ */ new Map();
35
+ // locale -> chunk name -> content hash (for cache busting)
36
+ hashCache = /* @__PURE__ */ new Map();
37
+ // extraction manifest (loaded from virtual module at init time)
38
+ manifest = { keys: [], chunks: {} };
39
+ configure(config) {
40
+ if (!config.locales?.length) {
41
+ throw new Error("i18n.configure(): locales array is required and must not be empty");
42
+ }
43
+ for (const locale of config.locales) {
44
+ if (!locale) {
45
+ throw new Error("i18n.configure(): locale cannot be empty");
46
+ }
47
+ if (locale !== locale.trim()) {
48
+ throw new Error(`i18n.configure(): locale "${locale}" has leading or trailing whitespace`);
49
+ }
50
+ }
51
+ if (new Set(config.locales).size !== config.locales.length) {
52
+ throw new Error("i18n.configure(): locales array contains duplicates");
53
+ }
54
+ if (config.defaultLocale !== void 0) {
55
+ if (!config.defaultLocale) {
56
+ throw new Error("i18n.configure(): defaultLocale cannot be empty");
57
+ }
58
+ if (config.defaultLocale !== config.defaultLocale.trim()) {
59
+ throw new Error(`i18n.configure(): defaultLocale "${config.defaultLocale}" has leading or trailing whitespace`);
60
+ }
61
+ if (!config.locales.includes(config.defaultLocale)) {
62
+ throw new Error(`i18n.configure(): defaultLocale "${config.defaultLocale}" is not in locales array`);
63
+ }
64
+ }
65
+ this.config = {
66
+ locales: config.locales,
67
+ defaultLocale: config.defaultLocale ?? config.locales[0],
68
+ fallback: config.fallback ?? "fallback"
69
+ };
70
+ }
71
+ isConfigured() {
72
+ return this.config !== null;
73
+ }
74
+ getConfig() {
75
+ if (!this.config) {
76
+ throw new Error("i18n not configured. Call i18n.configure() first.");
77
+ }
78
+ return this.config;
79
+ }
80
+ setTranslations(locale, raw) {
81
+ this.rawCache.set(locale, raw);
82
+ this.compiledCache.set(locale, compileTranslations(locale, raw));
83
+ this.hashCache.delete(locale);
84
+ const chunks = this.getChunkManifest();
85
+ if (Object.keys(chunks).length > 0) {
86
+ this.hashCache.set(locale, computeAllChunkHashes(raw, chunks));
87
+ }
88
+ }
89
+ getTranslations(locale) {
90
+ return this.rawCache.get(locale) ?? {};
91
+ }
92
+ getCompiledTranslations(locale) {
93
+ return this.compiledCache.get(locale) ?? {};
94
+ }
95
+ getChunkManifest() {
96
+ return this.manifest.chunks;
97
+ }
98
+ /**
99
+ * Get extracted translation keys with metadata.
100
+ * Use this to populate your translation provider with keys extracted from the codebase.
101
+ */
102
+ getExtractedKeys() {
103
+ return this.manifest.keys;
104
+ }
105
+ /**
106
+ * Get the full extraction manifest (keys + chunks).
107
+ */
108
+ getExtractionManifest() {
109
+ return this.manifest;
110
+ }
111
+ /**
112
+ * Set the extraction manifest (called by init module).
113
+ * @internal
114
+ */
115
+ setManifest(manifest) {
116
+ this.manifest = manifest;
117
+ }
118
+ getHashes(locale) {
119
+ return this.hashCache.get(locale) ?? {};
120
+ }
121
+ /**
122
+ * Clear translations for specified locale(s).
123
+ * @param locales - Locale(s) to clear, or all if not specified
124
+ */
125
+ clear(locales) {
126
+ const targets = this.resolveLocales(locales);
127
+ for (const locale of targets) {
128
+ this.rawCache.delete(locale);
129
+ this.compiledCache.delete(locale);
130
+ this.hashCache.delete(locale);
131
+ }
132
+ }
133
+ resolveLocales(locales) {
134
+ if (!locales) {
135
+ return this.config?.locales ?? [];
136
+ }
137
+ if (typeof locales === "string") {
138
+ return [locales];
139
+ }
140
+ return locales;
141
+ }
142
+ };
143
+ var i18n = new I18nSingleton();
144
+
145
+ export {
146
+ i18n
147
+ };
@@ -0,0 +1,241 @@
1
+ import {
2
+ chunkIdToName
3
+ } from "./chunk-4A5BKHFN.js";
4
+
5
+ // src/extraction/vite-plugin.ts
6
+ import path from "path";
7
+ var VIRTUAL_MODULE_ID = "virtual:@astroscope/i18n/manifest";
8
+ var RESOLVED_VIRTUAL_MODULE_ID = `\0${VIRTUAL_MODULE_ID}`;
9
+ var MANIFEST_FILE_NAME = "i18n-manifest.json";
10
+ var globalExtractedKeys = [];
11
+ var globalChunkManifest = {};
12
+ var globalProjectRoot = "";
13
+ function getManifest() {
14
+ const keysWithRelativePaths = globalExtractedKeys.map((key) => ({
15
+ ...key,
16
+ file: globalProjectRoot ? path.relative(globalProjectRoot, key.file) : key.file
17
+ }));
18
+ return {
19
+ keys: keysWithRelativePaths,
20
+ chunks: globalChunkManifest
21
+ };
22
+ }
23
+ function extractBalancedBraces(code, startIndex) {
24
+ if (code[startIndex] !== "{") return null;
25
+ let depth = 0;
26
+ let i = startIndex;
27
+ while (i < code.length) {
28
+ if (code[i] === "{") depth++;
29
+ else if (code[i] === "}") {
30
+ depth--;
31
+ if (depth === 0) return code.slice(startIndex, i + 1);
32
+ }
33
+ i++;
34
+ }
35
+ return null;
36
+ }
37
+ function extractTranslationCalls(code, filename) {
38
+ const keys = [];
39
+ const regex = /\bt\s*\(\s*['"`]([^'"`]+)['"`]\s*,\s*/g;
40
+ let match;
41
+ while ((match = regex.exec(code)) !== null) {
42
+ const key = match[1];
43
+ const afterKey = code.slice(match.index + match[0].length);
44
+ const upToMatch = code.slice(0, match.index);
45
+ const lineNumber = (upToMatch.match(/\n/g) || []).length + 1;
46
+ try {
47
+ const stringMatch = afterKey.match(/^['"`]([^'"`]*)['"`]/);
48
+ if (stringMatch) {
49
+ keys.push({
50
+ key,
51
+ meta: { fallback: stringMatch[1] },
52
+ file: filename,
53
+ line: lineNumber
54
+ });
55
+ } else if (afterKey.startsWith("{")) {
56
+ const metaStr = extractBalancedBraces(afterKey, 0);
57
+ if (metaStr) {
58
+ const fallbackMatch = metaStr.match(/fallback\s*:\s*['"`]([^'"`]+)['"`]/);
59
+ const descMatch = metaStr.match(/description\s*:\s*['"`]([^'"`]+)['"`]/);
60
+ const fallback = fallbackMatch ? fallbackMatch[1] : "";
61
+ const description = descMatch ? descMatch[1] : void 0;
62
+ const varsBlockMatch = metaStr.match(/variables\s*:\s*\{/);
63
+ let variables;
64
+ if (varsBlockMatch) {
65
+ const varsStart = metaStr.indexOf("{", varsBlockMatch.index + varsBlockMatch[0].length - 1);
66
+ const varsStr = extractBalancedBraces(metaStr, varsStart);
67
+ if (varsStr) {
68
+ variables = parseVariables(varsStr);
69
+ }
70
+ }
71
+ keys.push({
72
+ key,
73
+ meta: { fallback, description, variables },
74
+ file: filename,
75
+ line: lineNumber
76
+ });
77
+ }
78
+ }
79
+ } catch {
80
+ }
81
+ }
82
+ return keys;
83
+ }
84
+ function parseVariables(str) {
85
+ const result = {};
86
+ const varNameRegex = /(\w+)\s*:\s*\{/g;
87
+ let nameMatch;
88
+ while ((nameMatch = varNameRegex.exec(str)) !== null) {
89
+ const varName = nameMatch[1];
90
+ const varStart = str.indexOf("{", nameMatch.index + nameMatch[0].length - 1);
91
+ const varObj = extractBalancedBraces(str, varStart);
92
+ if (varObj) {
93
+ const fallbackMatch = varObj.match(/fallback\s*:\s*['"`]([^'"`]*)['"`]/);
94
+ const descMatch = varObj.match(/description\s*:\s*['"`]([^'"`]*)['"`]/);
95
+ result[varName] = {
96
+ fallback: fallbackMatch ? fallbackMatch[1] : void 0,
97
+ description: descMatch ? descMatch[1] : void 0
98
+ };
99
+ }
100
+ }
101
+ return Object.keys(result).length > 0 ? result : void 0;
102
+ }
103
+ function hasI18nImport(code) {
104
+ return /@astroscope\/i18n\/t/.test(code);
105
+ }
106
+ function i18nVitePlugin(options) {
107
+ const { include = [".ts", ".tsx", ".js", ".jsx", ".astro"], logger } = options;
108
+ const extractedKeys = [];
109
+ const fileToKeys = /* @__PURE__ */ new Map();
110
+ const filesWithI18n = /* @__PURE__ */ new Set();
111
+ let chunkManifest = {};
112
+ let projectRoot = "";
113
+ let isBuild = false;
114
+ return {
115
+ name: "@astroscope/i18n/extract",
116
+ enforce: "pre",
117
+ configResolved(config) {
118
+ projectRoot = config.root;
119
+ globalProjectRoot = config.root;
120
+ isBuild = config.command === "build";
121
+ },
122
+ resolveId(id) {
123
+ if (id === VIRTUAL_MODULE_ID) {
124
+ return RESOLVED_VIRTUAL_MODULE_ID;
125
+ }
126
+ if (id.startsWith(`${VIRTUAL_MODULE_ID}?`)) {
127
+ return `\0${id}`;
128
+ }
129
+ },
130
+ load(id) {
131
+ if (id === RESOLVED_VIRTUAL_MODULE_ID || id.startsWith(`\0${VIRTUAL_MODULE_ID}?`)) {
132
+ if (isBuild) {
133
+ return `
134
+ import { readFileSync } from 'node:fs';
135
+ import { fileURLToPath } from 'node:url';
136
+ import { dirname, join } from 'node:path';
137
+
138
+ const __dirname = dirname(fileURLToPath(import.meta.url));
139
+ const manifestPath = join(__dirname, '${MANIFEST_FILE_NAME}');
140
+ const manifestJson = JSON.parse(readFileSync(manifestPath, 'utf-8'));
141
+
142
+ export const manifest = manifestJson;
143
+ export function getManifest() { return manifestJson; }
144
+ `;
145
+ }
146
+ const keysWithRelativePaths = extractedKeys.map((key) => ({
147
+ ...key,
148
+ file: projectRoot ? path.relative(projectRoot, key.file) : key.file
149
+ }));
150
+ const manifest = {
151
+ keys: keysWithRelativePaths,
152
+ chunks: chunkManifest
153
+ };
154
+ return `
155
+ export const manifest = ${JSON.stringify(manifest)};
156
+ export function getManifest() { return ${JSON.stringify(manifest)}; }
157
+ `;
158
+ }
159
+ },
160
+ transform(code, id) {
161
+ if (!include.some((ext) => id.endsWith(ext))) {
162
+ return null;
163
+ }
164
+ if (id.includes("node_modules")) {
165
+ return null;
166
+ }
167
+ if (hasI18nImport(code)) {
168
+ filesWithI18n.add(id);
169
+ }
170
+ const keys = extractTranslationCalls(code, id);
171
+ if (keys.length > 0) {
172
+ extractedKeys.push(...keys);
173
+ globalExtractedKeys = extractedKeys;
174
+ fileToKeys.set(
175
+ id,
176
+ keys.map((k) => k.key)
177
+ );
178
+ }
179
+ return null;
180
+ },
181
+ generateBundle(_, bundle) {
182
+ chunkManifest = {};
183
+ for (const [fileName, chunk] of Object.entries(bundle)) {
184
+ if (chunk.type === "chunk" && chunk.moduleIds) {
185
+ const keys = /* @__PURE__ */ new Set();
186
+ let hasI18nModule = false;
187
+ for (const moduleId of chunk.moduleIds) {
188
+ const moduleKeys = fileToKeys.get(moduleId);
189
+ if (moduleKeys) {
190
+ moduleKeys.forEach((k) => keys.add(k));
191
+ }
192
+ if (filesWithI18n.has(moduleId)) {
193
+ hasI18nModule = true;
194
+ }
195
+ }
196
+ if (keys.size > 0) {
197
+ const chunkName = chunkIdToName(fileName.replace(/\.js$/, ""));
198
+ chunkManifest[chunkName] = Array.from(keys);
199
+ }
200
+ if (hasI18nModule && chunk.type === "chunk") {
201
+ const chunkName = chunkIdToName(fileName.replace(/\.js$/, ""));
202
+ const loaderCode = `
203
+ /* @astroscope/i18n loader */
204
+ if (typeof window !== 'undefined' && window.__i18n__) {
205
+ const __i18n__ = window.__i18n__;
206
+ const __i18n_hash__ = __i18n__.hashes[${JSON.stringify(chunkName)}];
207
+ if (__i18n_hash__) {
208
+ await import(\`/_i18n/\${__i18n__.locale}/${chunkName}.\${__i18n_hash__}.js\`);
209
+ }
210
+ }
211
+ /* end @astroscope/i18n loader */
212
+ `;
213
+ chunk.code = loaderCode + chunk.code;
214
+ }
215
+ }
216
+ }
217
+ globalChunkManifest = chunkManifest;
218
+ const keysWithRelativePaths = extractedKeys.map((key) => ({
219
+ ...key,
220
+ file: projectRoot ? path.relative(projectRoot, key.file) : key.file
221
+ }));
222
+ const manifest = {
223
+ keys: keysWithRelativePaths,
224
+ chunks: chunkManifest
225
+ };
226
+ this.emitFile({
227
+ type: "asset",
228
+ fileName: MANIFEST_FILE_NAME,
229
+ source: JSON.stringify(manifest)
230
+ });
231
+ const chunkCount = Object.keys(chunkManifest).length;
232
+ const keyCount = extractedKeys.length;
233
+ logger?.info(`manifest: ${chunkCount} chunks, ${keyCount} keys`);
234
+ }
235
+ };
236
+ }
237
+
238
+ export {
239
+ getManifest,
240
+ i18nVitePlugin
241
+ };