@astroscope/i18n 0.1.0 → 0.2.1

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 (188) hide show
  1. package/README.md +23 -1
  2. package/dist/{chunk-FAKBSLNW.js → chunk-7MSGHEST.js} +14 -7
  3. package/dist/{chunk-JJEDOJBR.js → chunk-EO4FUQXR.js} +49 -18
  4. package/dist/{chunk-QFAAGCP5.js → chunk-RHWEV4L2.js} +58 -1
  5. package/dist/client/directives/idle.d.ts +4 -1
  6. package/dist/client/directives/idle.js +13 -6
  7. package/dist/client/directives/load.d.ts +4 -1
  8. package/dist/client/directives/load.js +6 -6
  9. package/dist/client/directives/media.d.ts +4 -1
  10. package/dist/client/directives/media.js +16 -6
  11. package/dist/client/directives/only.d.ts +6 -1
  12. package/dist/client/directives/only.js +6 -6
  13. package/dist/client/directives/utils.d.ts +6 -5
  14. package/dist/client/directives/utils.js +3 -3
  15. package/dist/client/directives/visible.d.ts +4 -1
  16. package/dist/client/directives/visible.js +23 -6
  17. package/dist/client/t.d.ts +2 -2
  18. package/dist/extraction/index.d.ts +3 -3
  19. package/dist/extraction/index.js +1 -1
  20. package/dist/{i18n-BGfrSNM8.d.ts → i18n-mTHTcD8K.d.ts} +9 -2
  21. package/dist/index.d.ts +26 -3
  22. package/dist/index.js +6 -2
  23. package/dist/internal.d.ts +4 -4
  24. package/dist/internal.js +1 -1
  25. package/dist/server/t.d.ts +1 -1
  26. package/dist/server/t.js +1 -1
  27. package/dist/{types-BaaSiz9n.d.ts → types-BeDFfFIL.d.ts} +1 -1
  28. package/dist/{types-Bzp6KxsI.d.ts → types-DNRFj1XA.d.ts} +1 -0
  29. package/dist/{types-DsNK_9sI.d.ts → types-DTUho6gi.d.ts} +7 -1
  30. package/package.json +8 -7
  31. package/src/components/I18nScript.astro +2 -23
  32. package/dist/babel-plugin-FUTQRKLT.js +0 -121
  33. package/dist/chunk-22ZZFFC2.js +0 -159
  34. package/dist/chunk-2PSXD3JJ.js +0 -144
  35. package/dist/chunk-3VI62RLT.js +0 -176
  36. package/dist/chunk-4DAQPWXI.js +0 -36
  37. package/dist/chunk-4OGX6AF5.js +0 -10
  38. package/dist/chunk-4PHYKXO3.js +0 -227
  39. package/dist/chunk-4UBFISFY.js +0 -376
  40. package/dist/chunk-5DERF6DV.js +0 -266
  41. package/dist/chunk-5KGNHFTC.js +0 -344
  42. package/dist/chunk-5PP4D2VK.js +0 -23
  43. package/dist/chunk-6BW3PN23.js +0 -14
  44. package/dist/chunk-6ESQ4JQI.js +0 -263
  45. package/dist/chunk-A7MPXMOP.js +0 -202
  46. package/dist/chunk-AWZ2SQDW.js +0 -149
  47. package/dist/chunk-AYY2YIBQ.js +0 -52
  48. package/dist/chunk-BMNEJFTD.js +0 -56
  49. package/dist/chunk-BSXQGEUK.js +0 -16
  50. package/dist/chunk-BSYTJFGF.js +0 -21
  51. package/dist/chunk-BVPXEGTT.js +0 -12
  52. package/dist/chunk-C4DJYWF6.js +0 -193
  53. package/dist/chunk-C5EJYE2P.js +0 -245
  54. package/dist/chunk-CLNOQHMS.js +0 -254
  55. package/dist/chunk-E5MCIRSU.js +0 -144
  56. package/dist/chunk-E7ZJS7WX.js +0 -162
  57. package/dist/chunk-ESFGCYYH.js +0 -24
  58. package/dist/chunk-FHBVI3TL.js +0 -372
  59. package/dist/chunk-FI5KZ5IO.js +0 -17
  60. package/dist/chunk-H5R6YMOL.js +0 -233
  61. package/dist/chunk-H62K3FGA.js +0 -236
  62. package/dist/chunk-HDG2R6XT.js +0 -211
  63. package/dist/chunk-HGXU5QAK.js +0 -344
  64. package/dist/chunk-HHRMR3TM.js +0 -17
  65. package/dist/chunk-HS4HVBAD.js +0 -127
  66. package/dist/chunk-IPJWKKHJ.js +0 -324
  67. package/dist/chunk-ITTL4V7J.js +0 -24
  68. package/dist/chunk-IWUBCMOK.js +0 -128
  69. package/dist/chunk-JJBBY2GR.js +0 -14
  70. package/dist/chunk-JTUKXNIJ.js +0 -23
  71. package/dist/chunk-K7YULG4A.js +0 -14
  72. package/dist/chunk-KNONI6DP.js +0 -89
  73. package/dist/chunk-LMTEO22Y.js +0 -17
  74. package/dist/chunk-LRLZEX4D.js +0 -147
  75. package/dist/chunk-MFKPLUAN.js +0 -241
  76. package/dist/chunk-MIWXQOO3.js +0 -316
  77. package/dist/chunk-MJRTAWPR.js +0 -261
  78. package/dist/chunk-MZEPQCXX.js +0 -249
  79. package/dist/chunk-NHHTSFA7.js +0 -237
  80. package/dist/chunk-NTTXM7AG.js +0 -23
  81. package/dist/chunk-NZFAVJXR.js +0 -192
  82. package/dist/chunk-OFNFSDW3.js +0 -13
  83. package/dist/chunk-PG3XDNGF.js +0 -227
  84. package/dist/chunk-PVEVTPNK.js +0 -139
  85. package/dist/chunk-QAO4BXS4.js +0 -244
  86. package/dist/chunk-QCTULQQK.js +0 -34
  87. package/dist/chunk-QKND2KCA.js +0 -163
  88. package/dist/chunk-QZEGY6RJ.js +0 -151
  89. package/dist/chunk-RAE2L6FT.js +0 -193
  90. package/dist/chunk-S3ABJBU3.js +0 -255
  91. package/dist/chunk-SVDVCPCV.js +0 -236
  92. package/dist/chunk-T35ZUWTL.js +0 -153
  93. package/dist/chunk-T6WV5DW6.js +0 -156
  94. package/dist/chunk-TGUXVDA3.js +0 -82
  95. package/dist/chunk-TYMO7K3A.js +0 -173
  96. package/dist/chunk-V4RBFLQL.js +0 -23
  97. package/dist/chunk-V4XWJXXZ.js +0 -23
  98. package/dist/chunk-VQCY3OKK.js +0 -258
  99. package/dist/chunk-WLGOJPDJ.js +0 -15
  100. package/dist/chunk-WUEPDJIL.js +0 -259
  101. package/dist/chunk-X3L7WZLY.js +0 -254
  102. package/dist/chunk-XDD62ZM3.js +0 -255
  103. package/dist/chunk-XFXXEDRD.js +0 -36
  104. package/dist/chunk-XKYOR5UK.js +0 -8
  105. package/dist/chunk-Y26535SI.js +0 -239
  106. package/dist/chunk-Y3PQX5TX.js +0 -152
  107. package/dist/chunk-Y4BE2V6F.js +0 -347
  108. package/dist/chunk-Z4IZYDIA.js +0 -24
  109. package/dist/chunk-Z52G4CYY.js +0 -14
  110. package/dist/chunk-ZGLUYWVM.js +0 -128
  111. package/dist/client/import-with-i18n.d.ts +0 -16
  112. package/dist/client/import-with-i18n.js +0 -8
  113. package/dist/client-directives/idle.d.ts +0 -9
  114. package/dist/client-directives/idle.js +0 -15
  115. package/dist/client-directives/load.d.ts +0 -9
  116. package/dist/client-directives/load.js +0 -15
  117. package/dist/client-directives/media.d.ts +0 -9
  118. package/dist/client-directives/media.js +0 -15
  119. package/dist/client-directives/only.d.ts +0 -9
  120. package/dist/client-directives/only.js +0 -15
  121. package/dist/client-directives/utils.d.ts +0 -9
  122. package/dist/client-directives/utils.js +0 -7
  123. package/dist/client-directives/visible.d.ts +0 -9
  124. package/dist/client-directives/visible.js +0 -15
  125. package/dist/i18n-3cZHoHwP.d.ts +0 -86
  126. package/dist/i18n-BHU81LMA.d.ts +0 -55
  127. package/dist/i18n-BagoeH4_.d.ts +0 -62
  128. package/dist/i18n-BeL84090.d.ts +0 -77
  129. package/dist/i18n-BeRWDfHi.d.ts +0 -55
  130. package/dist/i18n-Bfs2PVcf.d.ts +0 -79
  131. package/dist/i18n-BrL7p3aN.d.ts +0 -99
  132. package/dist/i18n-CNQNCFU0.d.ts +0 -55
  133. package/dist/i18n-CX_uU8V2.d.ts +0 -80
  134. package/dist/i18n-Cr1QZCwe.d.ts +0 -64
  135. package/dist/i18n-CzTRxGeX.d.ts +0 -80
  136. package/dist/i18n-DUOFiC7g.d.ts +0 -77
  137. package/dist/i18n-DcF47BHS.d.ts +0 -77
  138. package/dist/i18n-DifWvtaO.d.ts +0 -60
  139. package/dist/i18n-DumSqX1t.d.ts +0 -55
  140. package/dist/i18n-fWTJw12h.d.ts +0 -80
  141. package/dist/import-with-i18n.d.ts +0 -23
  142. package/dist/import-with-i18n.js +0 -7
  143. package/dist/init.d.ts +0 -2
  144. package/dist/init.js +0 -8
  145. package/dist/middleware-entrypoint-C0Drh9E_.d.ts +0 -29
  146. package/dist/middleware-entrypoint-mEl66IUy.d.ts +0 -29
  147. package/dist/middleware-entrypoint.d.ts +0 -5
  148. package/dist/middleware-entrypoint.js +0 -30
  149. package/dist/server/middleware-entrypoint.d.ts +0 -2
  150. package/dist/server/middleware-entrypoint.js +0 -28
  151. package/dist/t-BY_C9lZ1.d.ts +0 -30
  152. package/dist/t-CG3yDiEa.d.ts +0 -30
  153. package/dist/t-CHsBfrPr.d.ts +0 -30
  154. package/dist/t-DQpXaDhP.d.ts +0 -30
  155. package/dist/t.client.d.ts +0 -11
  156. package/dist/t.client.js +0 -35
  157. package/dist/t.server.d.ts +0 -22
  158. package/dist/t.server.js +0 -12
  159. package/dist/types-8uKCwFda.d.ts +0 -24
  160. package/dist/types-BC6K-pID.d.ts +0 -110
  161. package/dist/types-BUV7BZML.d.ts +0 -55
  162. package/dist/types-BWGB322F.d.ts +0 -46
  163. package/dist/types-B_-RxW4A.d.ts +0 -7
  164. package/dist/types-Bgl2V5xo.d.ts +0 -102
  165. package/dist/types-BwhB6IT4.d.ts +0 -111
  166. package/dist/types-C6rOJFY2.d.ts +0 -24
  167. package/dist/types-C7lD-Woj.d.ts +0 -50
  168. package/dist/types-CLWZeQhD.d.ts +0 -54
  169. package/dist/types-COXt613w.d.ts +0 -19
  170. package/dist/types-CUlkbl9-.d.ts +0 -50
  171. package/dist/types-CVv7GGPj.d.ts +0 -46
  172. package/dist/types-CiIDN2sW.d.ts +0 -64
  173. package/dist/types-Cr86qjYl.d.ts +0 -58
  174. package/dist/types-CxnObiEO.d.ts +0 -7
  175. package/dist/types-D44mFUjA.d.ts +0 -97
  176. package/dist/types-D85m9UTC.d.ts +0 -137
  177. package/dist/types-DWhsmSPP.d.ts +0 -102
  178. package/dist/types-DdprXGJ1.d.ts +0 -46
  179. package/dist/types-DhVJ2ZIo.d.ts +0 -43
  180. package/dist/types-DnbOuM1L.d.ts +0 -7
  181. package/dist/types-DvWBr9Xp.d.ts +0 -17
  182. package/dist/types-DwkIalh6.d.ts +0 -24
  183. package/dist/types-OYRgjtE_.d.ts +0 -110
  184. package/dist/types-SV8S05GX.d.ts +0 -7
  185. package/dist/types-TYn9WnxY.d.ts +0 -46
  186. package/dist/types-aXCBbdhq.d.ts +0 -55
  187. package/dist/types-gn4aNKGx.d.ts +0 -54
  188. package/dist/types-nippsMkm.d.ts +0 -54
@@ -1,237 +0,0 @@
1
- import {
2
- runWithContext
3
- } from "./chunk-JJBBY2GR.js";
4
- import {
5
- compileTranslations
6
- } from "./chunk-KNDYKTHE.js";
7
-
8
- // src/extraction/hash.ts
9
- function hashString(str) {
10
- let hash = 0;
11
- for (let i = 0; i < str.length; i++) {
12
- const char = str.charCodeAt(i);
13
- hash = (hash << 5) - hash + char;
14
- hash = hash & hash;
15
- }
16
- return Math.abs(hash).toString(36).substring(0, 8);
17
- }
18
- function computeChunkHash(translations, keys) {
19
- const relevantTranslations = {};
20
- for (const key of keys.sort()) {
21
- if (translations[key]) {
22
- relevantTranslations[key] = translations[key];
23
- }
24
- }
25
- return hashString(JSON.stringify(relevantTranslations));
26
- }
27
- function computeAllChunkHashes(translations, manifest) {
28
- const hashes = {};
29
- for (const [chunkId, keys] of Object.entries(manifest)) {
30
- hashes[chunkId] = computeChunkHash(translations, keys);
31
- }
32
- return hashes;
33
- }
34
-
35
- // src/server/i18n.ts
36
- var I18nSingleton = class {
37
- config = null;
38
- rawCache = /* @__PURE__ */ new Map();
39
- compiledCache = /* @__PURE__ */ new Map();
40
- chunkManifest = null;
41
- hashCache = /* @__PURE__ */ new Map();
42
- configure(config) {
43
- this.config = config;
44
- }
45
- getConfig() {
46
- return this.config;
47
- }
48
- getDefaultLocale() {
49
- return this.config?.defaultLocale ?? this.config?.locales[0];
50
- }
51
- getFallbackBehavior() {
52
- return this.config?.fallback ?? "fallback";
53
- }
54
- setTranslations(locale, raw) {
55
- this.rawCache.set(locale, raw);
56
- this.compiledCache.set(locale, compileTranslations(locale, raw));
57
- this.hashCache.delete(locale);
58
- if (this.chunkManifest) {
59
- this.hashCache.set(locale, computeAllChunkHashes(raw, this.chunkManifest));
60
- }
61
- }
62
- getTranslations(locale) {
63
- return this.rawCache.get(locale);
64
- }
65
- getCompiledTranslations(locale) {
66
- return this.compiledCache.get(locale);
67
- }
68
- setChunkManifest(manifest) {
69
- this.chunkManifest = manifest;
70
- for (const [locale, raw] of this.rawCache) {
71
- this.hashCache.set(locale, computeAllChunkHashes(raw, manifest));
72
- }
73
- }
74
- getChunkManifest() {
75
- return this.chunkManifest;
76
- }
77
- getHashes(locale) {
78
- return this.hashCache.get(locale);
79
- }
80
- /**
81
- * Clear translations for specified locale(s).
82
- * @param locales - Locale(s) to clear, or all if not specified
83
- */
84
- clear(locales) {
85
- const targets = this.resolveLocales(locales);
86
- for (const locale of targets) {
87
- this.rawCache.delete(locale);
88
- this.compiledCache.delete(locale);
89
- this.hashCache.delete(locale);
90
- }
91
- }
92
- resolveLocales(locales) {
93
- if (!locales) return this.config?.locales ?? [];
94
- if (typeof locales === "string") return [locales];
95
- return locales;
96
- }
97
- };
98
- var i18n = new I18nSingleton();
99
-
100
- // src/server/middleware.ts
101
- var I18N_ENDPOINT_PREFIX = "/_i18n/";
102
- function detectLocale(request) {
103
- const config = i18n.getConfig();
104
- if (!config) return void 0;
105
- const { locales } = config;
106
- const acceptLanguage = request.headers.get("accept-language");
107
- if (!acceptLanguage) return void 0;
108
- const preferred = acceptLanguage.split(",").map((part) => {
109
- const [lang, q = "q=1"] = part.trim().split(";");
110
- return {
111
- lang: lang.split("-")[0].toLowerCase(),
112
- q: parseFloat(q.replace("q=", ""))
113
- };
114
- }).sort((a, b) => b.q - a.q);
115
- for (const { lang } of preferred) {
116
- if (locales.includes(lang)) {
117
- return lang;
118
- }
119
- }
120
- return void 0;
121
- }
122
- function generateI18nHashScript(locale, hashes) {
123
- const state = { locale, hashes, translations: {} };
124
- return `<script>window.__i18n__=${JSON.stringify(state)};</script>`;
125
- }
126
- function generateI18nFullScript(locale, raw) {
127
- const state = { locale, hashes: {}, translations: raw };
128
- return `<script>window.__i18n__=${JSON.stringify(state)};</script>`;
129
- }
130
- async function injectI18nScript(response, script) {
131
- const contentType = response.headers.get("content-type");
132
- if (!contentType?.includes("text/html")) {
133
- return response;
134
- }
135
- const html = await response.text();
136
- let injectedHtml;
137
- if (html.includes("</head>")) {
138
- injectedHtml = html.replace("</head>", `${script}</head>`);
139
- } else if (html.includes("<body")) {
140
- injectedHtml = html.replace(/<body([^>]*)>/, `<body$1>${script}`);
141
- } else {
142
- injectedHtml = script + html;
143
- }
144
- return new Response(injectedHtml, {
145
- status: response.status,
146
- statusText: response.statusText,
147
- headers: response.headers
148
- });
149
- }
150
- function parseI18nEndpointPath(pathname) {
151
- if (!pathname.startsWith(I18N_ENDPOINT_PREFIX)) {
152
- return null;
153
- }
154
- const path = pathname.slice(I18N_ENDPOINT_PREFIX.length);
155
- const match = path.match(/^([^/]+)\/(.+)\.([a-z0-9]+)\.js$/);
156
- if (!match) {
157
- return null;
158
- }
159
- return { locale: match[1], chunkName: match[2], hash: match[3] };
160
- }
161
- function handleI18nEndpoint(chunkName, requestedHash, translations, chunkManifest) {
162
- const keys = chunkManifest[chunkName];
163
- if (!keys) {
164
- return new Response(`/* chunk not found: ${chunkName} */`, {
165
- status: 404,
166
- headers: { "Content-Type": "application/javascript" }
167
- });
168
- }
169
- const actualHash = computeChunkHash(translations, keys);
170
- if (requestedHash !== actualHash) {
171
- console.warn(`[i18n] hash mismatch for ${chunkName}: expected ${actualHash}, got ${requestedHash}`);
172
- }
173
- const chunkTranslations = {};
174
- for (const key of keys) {
175
- if (translations[key]) {
176
- chunkTranslations[key] = translations[key];
177
- }
178
- }
179
- const js = `/* @astroscope/i18n chunk: ${chunkName} */
180
- (function() {
181
- var i = window.__i18n__;
182
- if (i) Object.assign(i.translations, ${JSON.stringify(chunkTranslations)});
183
- })();
184
- `;
185
- return new Response(js, {
186
- status: 200,
187
- headers: {
188
- "Content-Type": "application/javascript",
189
- "Cache-Control": "public, max-age=31536000, immutable"
190
- }
191
- });
192
- }
193
- function createI18nMiddleware(options) {
194
- return async (ctx, next) => {
195
- const config = i18n.getConfig();
196
- if (!config) {
197
- throw new Error("i18n not configured. Call i18n.configure() before using i18nMiddleware.");
198
- }
199
- const pathname = new URL(ctx.request.url).pathname;
200
- const chunkManifest = i18n.getChunkManifest();
201
- if (chunkManifest) {
202
- const endpointParams = parseI18nEndpointPath(pathname);
203
- if (endpointParams) {
204
- const { locale: urlLocale, chunkName, hash } = endpointParams;
205
- const endpointRaw = i18n.getTranslations(urlLocale) ?? {};
206
- return handleI18nEndpoint(chunkName, hash, endpointRaw, chunkManifest);
207
- }
208
- }
209
- const locale = options.locale(ctx);
210
- const compiled = i18n.getCompiledTranslations(locale) ?? {};
211
- const raw = i18n.getTranslations(locale) ?? {};
212
- const context = {
213
- locale,
214
- translations: compiled,
215
- fallback: i18n.getFallbackBehavior(),
216
- meta: {}
217
- };
218
- return runWithContext(context, async () => {
219
- const response = await next();
220
- let script;
221
- const hasChunkManifest = chunkManifest && Object.keys(chunkManifest).length > 0;
222
- if (hasChunkManifest) {
223
- const hashes = i18n.getHashes(locale) ?? {};
224
- script = generateI18nHashScript(locale, hashes);
225
- } else {
226
- script = generateI18nFullScript(locale, raw);
227
- }
228
- return injectI18nScript(response, script);
229
- });
230
- };
231
- }
232
-
233
- export {
234
- i18n,
235
- detectLocale,
236
- createI18nMiddleware
237
- };
@@ -1,23 +0,0 @@
1
- import {
2
- buildI18nChunkUrl
3
- } from "./chunk-OFNFSDW3.js";
4
-
5
- // src/client-directives/utils.ts
6
- async function loadI18nForChunk(el) {
7
- const componentUrl = el.getAttribute("component-url");
8
- if (!componentUrl) return;
9
- const chunkId = componentUrl.replace(/^\//, "").replace(/\.js$/, "");
10
- const hash = window.__i18n_hashes__?.[chunkId];
11
- const locale = window.__i18n_locale__ || "en";
12
- if (hash) {
13
- const url = buildI18nChunkUrl(locale, chunkId, hash);
14
- await import(
15
- /* @vite-ignore */
16
- url
17
- );
18
- }
19
- }
20
-
21
- export {
22
- loadI18nForChunk
23
- };
@@ -1,192 +0,0 @@
1
- import {
2
- clearContext,
3
- compileTranslations,
4
- setContext
5
- } from "./chunk-KNONI6DP.js";
6
-
7
- // src/i18n-endpoint.ts
8
- function hashString(str) {
9
- let hash = 0;
10
- for (let i = 0; i < str.length; i++) {
11
- const char = str.charCodeAt(i);
12
- hash = (hash << 5) - hash + char;
13
- hash = hash & hash;
14
- }
15
- return Math.abs(hash).toString(36).substring(0, 8);
16
- }
17
- function computeChunkHash(translations, keys) {
18
- const relevantTranslations = {};
19
- for (const key of keys.sort()) {
20
- if (translations[key]) {
21
- relevantTranslations[key] = translations[key];
22
- }
23
- }
24
- return hashString(JSON.stringify(relevantTranslations));
25
- }
26
- function computeAllChunkHashes(translations, manifest) {
27
- const hashes = {};
28
- for (const [chunkId, keys] of Object.entries(manifest)) {
29
- hashes[chunkId] = computeChunkHash(translations, keys);
30
- }
31
- return hashes;
32
- }
33
- function createI18nEndpoint(options) {
34
- const { cms, manifest } = options;
35
- const translationCache2 = /* @__PURE__ */ new Map();
36
- return async ({ params }) => {
37
- const { path } = params;
38
- if (!path) {
39
- return new Response("Not found", { status: 404 });
40
- }
41
- const match = path.match(/^([^/]+)\/(.+)\.([a-z0-9]+)\.js$/);
42
- if (!match) {
43
- return new Response("Invalid path", { status: 400 });
44
- }
45
- const [, locale, chunkId, requestedHash] = match;
46
- const keys = manifest[chunkId];
47
- if (!keys) {
48
- return new Response(`/* chunk not found: ${chunkId} */`, {
49
- status: 404,
50
- headers: { "Content-Type": "application/javascript" }
51
- });
52
- }
53
- let translations = translationCache2.get(locale);
54
- if (!translations) {
55
- translations = await cms.fetch(locale, []);
56
- translationCache2.set(locale, translations);
57
- }
58
- const actualHash = computeChunkHash(translations, keys);
59
- if (requestedHash !== actualHash) {
60
- console.warn(`[i18n] hash mismatch for ${chunkId}: expected ${actualHash}, got ${requestedHash}`);
61
- }
62
- const chunkTranslations = {};
63
- for (const key of keys) {
64
- if (translations[key]) {
65
- chunkTranslations[key] = translations[key];
66
- }
67
- }
68
- const js = `/* @astroscope/i18n chunk: ${chunkId} */
69
- (function() {
70
- window.__i18n__ = window.__i18n__ || {};
71
- Object.assign(window.__i18n__, ${JSON.stringify(chunkTranslations)});
72
- })();
73
- `;
74
- return new Response(js, {
75
- status: 200,
76
- headers: {
77
- "Content-Type": "application/javascript",
78
- // immutable cache - hash in URL ensures cache busting
79
- "Cache-Control": "public, max-age=31536000, immutable"
80
- }
81
- });
82
- };
83
- }
84
-
85
- // src/middleware.ts
86
- function defaultDetectLocale(request, locales, defaultLocale) {
87
- const acceptLanguage = request.headers.get("accept-language");
88
- if (!acceptLanguage) {
89
- return defaultLocale;
90
- }
91
- const preferred = acceptLanguage.split(",").map((part) => {
92
- const [lang, q = "q=1"] = part.trim().split(";");
93
- return {
94
- lang: lang.split("-")[0].toLowerCase(),
95
- q: parseFloat(q.replace("q=", ""))
96
- };
97
- }).sort((a, b) => b.q - a.q);
98
- for (const { lang } of preferred) {
99
- if (locales.includes(lang)) {
100
- return lang;
101
- }
102
- }
103
- return defaultLocale;
104
- }
105
- var translationCache = /* @__PURE__ */ new Map();
106
- var hashCache = /* @__PURE__ */ new Map();
107
- function generateI18nHashScript(locale, hashes, fallback) {
108
- const fallbackValue = typeof fallback === "function" ? "example" : fallback;
109
- return `<script>window.__i18n_locale__=${JSON.stringify(locale)};window.__i18n_fallback__=${JSON.stringify(fallbackValue)};window.__i18n_hashes__=${JSON.stringify(hashes)};window.__i18n__=window.__i18n__||{};</script>`;
110
- }
111
- function generateI18nFullScript(locale, raw, fallback) {
112
- const fallbackValue = typeof fallback === "function" ? "example" : fallback;
113
- return `<script>window.__i18n_locale__=${JSON.stringify(locale)};window.__i18n_fallback__=${JSON.stringify(fallbackValue)};window.__i18n__=${JSON.stringify(raw)};</script>`;
114
- }
115
- async function injectI18nScript(response, script) {
116
- const contentType = response.headers.get("content-type");
117
- if (!contentType?.includes("text/html")) {
118
- return response;
119
- }
120
- const html = await response.text();
121
- let injectedHtml;
122
- if (html.includes("</head>")) {
123
- injectedHtml = html.replace("</head>", `${script}</head>`);
124
- } else if (html.includes("<body")) {
125
- injectedHtml = html.replace(/<body([^>]*)>/, `<body$1>${script}`);
126
- } else {
127
- injectedHtml = script + html;
128
- }
129
- return new Response(injectedHtml, {
130
- status: response.status,
131
- statusText: response.statusText,
132
- headers: response.headers
133
- });
134
- }
135
- function createI18nMiddleware(options) {
136
- const { locales, defaultLocale, fallback, cms, detectLocale, chunkManifest } = options;
137
- return async (ctx, next) => {
138
- const locale = detectLocale ? detectLocale(ctx.request) : ctx.currentLocale ?? defaultDetectLocale(ctx.request, locales, defaultLocale);
139
- let raw = translationCache.get(locale);
140
- if (!raw) {
141
- raw = await cms.fetch(locale, []);
142
- translationCache.set(locale, raw);
143
- if (chunkManifest) {
144
- const hashes = computeAllChunkHashes(raw, chunkManifest);
145
- hashCache.set(locale, hashes);
146
- }
147
- }
148
- const translations = compileTranslations(locale, raw);
149
- const context = {
150
- locale,
151
- translations,
152
- fallback,
153
- meta: {}
154
- };
155
- setContext(context);
156
- try {
157
- const response = await next();
158
- let script;
159
- if (chunkManifest) {
160
- const hashes = hashCache.get(locale) || {};
161
- script = generateI18nHashScript(locale, hashes, fallback);
162
- } else {
163
- script = generateI18nFullScript(locale, raw, fallback);
164
- }
165
- const injectedResponse = await injectI18nScript(response, script);
166
- return injectedResponse;
167
- } finally {
168
- clearContext();
169
- }
170
- };
171
- }
172
- function getCachedTranslations(locale) {
173
- return translationCache.get(locale);
174
- }
175
- function clearTranslationCache(locale) {
176
- if (locale) {
177
- translationCache.delete(locale);
178
- hashCache.delete(locale);
179
- } else {
180
- translationCache.clear();
181
- hashCache.clear();
182
- }
183
- }
184
-
185
- export {
186
- computeChunkHash,
187
- computeAllChunkHashes,
188
- createI18nEndpoint,
189
- createI18nMiddleware,
190
- getCachedTranslations,
191
- clearTranslationCache
192
- };
@@ -1,13 +0,0 @@
1
- // src/i18n-url.ts
2
- function chunkIdToName(chunkId) {
3
- return chunkId.replace(/^_astro\//, "");
4
- }
5
- function buildI18nChunkUrl(locale, chunkId, hash) {
6
- const chunkName = chunkIdToName(chunkId);
7
- return `/_i18n/${locale}/${chunkName}.${hash}.js`;
8
- }
9
-
10
- export {
11
- chunkIdToName,
12
- buildI18nChunkUrl
13
- };
@@ -1,227 +0,0 @@
1
- import {
2
- chunkIdToName
3
- } from "./chunk-4A5BKHFN.js";
4
-
5
- // src/extraction/manifest.ts
6
- import path from "path";
7
- var I18N_GLOBAL_KEY = "__astroscope_i18n_manifest__";
8
- function getGlobalState() {
9
- const g = globalThis;
10
- if (!g[I18N_GLOBAL_KEY]) {
11
- g[I18N_GLOBAL_KEY] = {
12
- extractedKeys: [],
13
- chunkManifest: {},
14
- projectRoot: ""
15
- };
16
- }
17
- return g[I18N_GLOBAL_KEY];
18
- }
19
- function getManifest() {
20
- const state = getGlobalState();
21
- const keysWithRelativePaths = state.extractedKeys.map((key) => ({
22
- ...key,
23
- file: state.projectRoot ? path.relative(state.projectRoot, key.file) : key.file
24
- }));
25
- return {
26
- keys: keysWithRelativePaths,
27
- chunks: state.chunkManifest
28
- };
29
- }
30
-
31
- // src/extraction/vite-plugin.ts
32
- import fs from "fs";
33
- import path2 from "path";
34
- var VIRTUAL_MODULE_ID = "virtual:@astroscope/i18n/manifest";
35
- var RESOLVED_VIRTUAL_MODULE_ID = `\0${VIRTUAL_MODULE_ID}`;
36
- var MANIFEST_FILE_NAME = "i18n-manifest.json";
37
- function hasI18nImport(code) {
38
- return /@astroscope\/i18n\/t/.test(code);
39
- }
40
- function getParserPlugins(filename) {
41
- const plugins = [];
42
- if (/\.tsx?$/.test(filename)) {
43
- plugins.push("typescript");
44
- }
45
- if (/\.(jsx|tsx)$/.test(filename)) {
46
- plugins.push("jsx");
47
- }
48
- return plugins;
49
- }
50
- function i18nVitePlugin(options) {
51
- const { include = [".ts", ".tsx", ".js", ".jsx", ".astro"], logger } = options;
52
- const extractedKeys = [];
53
- const fileToKeys = /* @__PURE__ */ new Map();
54
- const filesWithI18n = /* @__PURE__ */ new Set();
55
- let chunkManifest = {};
56
- let projectRoot = "";
57
- let isBuild = false;
58
- let isSSR = false;
59
- return {
60
- name: "@astroscope/i18n/extract",
61
- enforce: "pre",
62
- configResolved(config) {
63
- projectRoot = config.root;
64
- getGlobalState().projectRoot = config.root;
65
- isBuild = config.command === "build";
66
- isSSR = !!config.build.ssr;
67
- },
68
- resolveId(id) {
69
- if (id === VIRTUAL_MODULE_ID) {
70
- return RESOLVED_VIRTUAL_MODULE_ID;
71
- }
72
- if (id.startsWith(`${VIRTUAL_MODULE_ID}?`)) {
73
- return `\0${id}`;
74
- }
75
- },
76
- load(id) {
77
- if (id === RESOLVED_VIRTUAL_MODULE_ID || id.startsWith(`\0${VIRTUAL_MODULE_ID}?`)) {
78
- if (isBuild) {
79
- return `
80
- import { readFileSync, existsSync } from 'node:fs';
81
- import { fileURLToPath } from 'node:url';
82
- import { dirname, join } from 'node:path';
83
-
84
- const __dirname = dirname(fileURLToPath(import.meta.url));
85
- const manifestName = '${MANIFEST_FILE_NAME}';
86
-
87
- // manifest is emitted to server directory (not publicly accessible)
88
- const searchPaths = [
89
- join(__dirname, manifestName), // same dir (server/)
90
- join(__dirname, '..', manifestName), // parent dir (from chunks/)
91
- ];
92
-
93
- let manifestPath = searchPaths.find(p => existsSync(p));
94
- if (!manifestPath) {
95
- console.warn('[i18n] manifest not found, using empty manifest');
96
- manifestPath = null;
97
- }
98
-
99
- const manifestJson = manifestPath
100
- ? JSON.parse(readFileSync(manifestPath, 'utf-8'))
101
- : { keys: [], chunks: {} };
102
-
103
- export const manifest = manifestJson;
104
- export function getManifest() { return manifestJson; }
105
- `;
106
- }
107
- return `
108
- import { getManifest as _getManifest } from '@astroscope/i18n/extraction';
109
- export const manifest = { keys: [], chunks: {} }; // placeholder, use getManifest()
110
- export function getManifest() { return _getManifest(); }
111
- `;
112
- }
113
- },
114
- async transform(code, id) {
115
- if (!include.some((ext) => id.endsWith(ext))) {
116
- return null;
117
- }
118
- if (id.includes("node_modules")) {
119
- return null;
120
- }
121
- if (!hasI18nImport(code)) {
122
- return null;
123
- }
124
- filesWithI18n.add(id);
125
- const fileKeys = [];
126
- const { transformAsync } = await import("@babel/core");
127
- const { default: i18nExtractPlugin } = await import("./babel-plugin-FUTQRKLT.js");
128
- const result = await transformAsync(code, {
129
- filename: id,
130
- sourceMaps: true,
131
- babelrc: false,
132
- configFile: false,
133
- parserOpts: {
134
- plugins: getParserPlugins(id)
135
- },
136
- plugins: [
137
- [
138
- i18nExtractPlugin,
139
- {
140
- onKeyExtracted: (key) => fileKeys.push(key),
141
- stripFallbacks: isBuild
142
- // only strip in production
143
- }
144
- ]
145
- ]
146
- });
147
- if (fileKeys.length > 0) {
148
- extractedKeys.push(...fileKeys);
149
- getGlobalState().extractedKeys = extractedKeys;
150
- fileToKeys.set(
151
- id,
152
- fileKeys.map((k) => k.key)
153
- );
154
- }
155
- if (isBuild && result?.code) {
156
- return {
157
- code: result.code,
158
- map: result.map
159
- };
160
- }
161
- return null;
162
- },
163
- generateBundle(_, bundle) {
164
- chunkManifest = {};
165
- for (const [fileName, chunk] of Object.entries(bundle)) {
166
- if (chunk.type === "chunk" && chunk.moduleIds) {
167
- const keys = /* @__PURE__ */ new Set();
168
- let hasI18nModule = false;
169
- for (const moduleId of chunk.moduleIds) {
170
- const moduleKeys = fileToKeys.get(moduleId);
171
- if (moduleKeys) {
172
- moduleKeys.forEach((k) => keys.add(k));
173
- }
174
- if (filesWithI18n.has(moduleId)) {
175
- hasI18nModule = true;
176
- }
177
- }
178
- if (keys.size > 0) {
179
- const chunkName = chunkIdToName(fileName.replace(/\.js$/, ""));
180
- chunkManifest[chunkName] = Array.from(keys);
181
- }
182
- if (hasI18nModule && chunk.type === "chunk") {
183
- const chunkName = chunkIdToName(fileName.replace(/\.js$/, ""));
184
- const loaderCode = `
185
- /* @astroscope/i18n loader */
186
- if (typeof window !== 'undefined' && window.__i18n__) {
187
- const __i18n__ = window.__i18n__;
188
- const __i18n_hash__ = __i18n__.hashes[${JSON.stringify(chunkName)}];
189
- if (__i18n_hash__) {
190
- await import(\`/_i18n/\${__i18n__.locale}/${chunkName}.\${__i18n_hash__}.js\`);
191
- }
192
- }
193
- /* end @astroscope/i18n loader */
194
- `;
195
- chunk.code = loaderCode + chunk.code;
196
- }
197
- }
198
- }
199
- getGlobalState().chunkManifest = chunkManifest;
200
- const chunkCount = Object.keys(chunkManifest).length;
201
- const keyCount = extractedKeys.length;
202
- logger?.info(`manifest: ${chunkCount} chunks, ${keyCount} keys`);
203
- },
204
- writeBundle(outputOptions) {
205
- if (!isSSR && outputOptions.dir) {
206
- const keysWithRelativePaths = extractedKeys.map((key) => ({
207
- ...key,
208
- file: projectRoot ? path2.relative(projectRoot, key.file) : key.file
209
- }));
210
- const manifest = {
211
- keys: keysWithRelativePaths,
212
- chunks: chunkManifest
213
- };
214
- const serverDir = path2.resolve(outputOptions.dir, "..", "server");
215
- const manifestPath = path2.join(serverDir, MANIFEST_FILE_NAME);
216
- if (fs.existsSync(serverDir)) {
217
- fs.writeFileSync(manifestPath, JSON.stringify(manifest));
218
- }
219
- }
220
- }
221
- };
222
- }
223
-
224
- export {
225
- getManifest,
226
- i18nVitePlugin
227
- };