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