@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,236 +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
- setTranslations(locale, raw) {
52
- this.rawCache.set(locale, raw);
53
- this.compiledCache.set(locale, compileTranslations(locale, raw));
54
- this.hashCache.delete(locale);
55
- if (this.chunkManifest) {
56
- this.hashCache.set(locale, computeAllChunkHashes(raw, this.chunkManifest));
57
- }
58
- }
59
- getTranslations(locale) {
60
- return this.rawCache.get(locale);
61
- }
62
- getCompiledTranslations(locale) {
63
- return this.compiledCache.get(locale);
64
- }
65
- setChunkManifest(manifest) {
66
- this.chunkManifest = manifest;
67
- for (const [locale, raw] of this.rawCache) {
68
- this.hashCache.set(locale, computeAllChunkHashes(raw, manifest));
69
- }
70
- }
71
- getChunkManifest() {
72
- return this.chunkManifest;
73
- }
74
- getHashes(locale) {
75
- return this.hashCache.get(locale);
76
- }
77
- /**
78
- * Clear translations for specified locale(s).
79
- * @param locales - Locale(s) to clear, or all if not specified
80
- */
81
- clear(locales) {
82
- const targets = this.resolveLocales(locales);
83
- for (const locale of targets) {
84
- this.rawCache.delete(locale);
85
- this.compiledCache.delete(locale);
86
- this.hashCache.delete(locale);
87
- }
88
- }
89
- resolveLocales(locales) {
90
- if (!locales) return this.config?.locales ?? [];
91
- if (typeof locales === "string") return [locales];
92
- return locales;
93
- }
94
- };
95
- var i18n = new I18nSingleton();
96
-
97
- // src/server/middleware.ts
98
- var I18N_ENDPOINT_PREFIX = "/_i18n/";
99
- function detectLocale(request) {
100
- const config = i18n.getConfig();
101
- if (!config) return void 0;
102
- const { locales } = config;
103
- const acceptLanguage = request.headers.get("accept-language");
104
- if (!acceptLanguage) return void 0;
105
- const preferred = acceptLanguage.split(",").map((part) => {
106
- const [lang, q = "q=1"] = part.trim().split(";");
107
- return {
108
- lang: lang.split("-")[0].toLowerCase(),
109
- q: parseFloat(q.replace("q=", ""))
110
- };
111
- }).sort((a, b) => b.q - a.q);
112
- for (const { lang } of preferred) {
113
- if (locales.includes(lang)) {
114
- return lang;
115
- }
116
- }
117
- return void 0;
118
- }
119
- function generateI18nHashScript(locale, hashes) {
120
- const state = { locale, hashes, translations: {} };
121
- return `<script>window.__i18n__=${JSON.stringify(state)};</script>`;
122
- }
123
- function generateI18nFullScript(locale, raw) {
124
- const state = { locale, hashes: {}, translations: raw };
125
- return `<script>window.__i18n__=${JSON.stringify(state)};</script>`;
126
- }
127
- async function injectI18nScript(response, script) {
128
- const contentType = response.headers.get("content-type");
129
- if (!contentType?.includes("text/html")) {
130
- return response;
131
- }
132
- const html = await response.text();
133
- let injectedHtml;
134
- if (html.includes("</head>")) {
135
- injectedHtml = html.replace("</head>", `${script}</head>`);
136
- } else if (html.includes("<body")) {
137
- injectedHtml = html.replace(/<body([^>]*)>/, `<body$1>${script}`);
138
- } else {
139
- injectedHtml = script + html;
140
- }
141
- return new Response(injectedHtml, {
142
- status: response.status,
143
- statusText: response.statusText,
144
- headers: response.headers
145
- });
146
- }
147
- function parseI18nEndpointPath(pathname) {
148
- if (!pathname.startsWith(I18N_ENDPOINT_PREFIX)) {
149
- return null;
150
- }
151
- const path = pathname.slice(I18N_ENDPOINT_PREFIX.length);
152
- const match = path.match(/^([^/]+)\/(.+)\.([a-z0-9]+)\.js$/);
153
- if (!match) {
154
- return null;
155
- }
156
- return { locale: match[1], chunkName: match[2], hash: match[3] };
157
- }
158
- function handleI18nEndpoint(chunkName, requestedHash, translations, chunkManifest) {
159
- const keys = chunkManifest[chunkName];
160
- if (!keys) {
161
- return new Response(`/* chunk not found: ${chunkName} */`, {
162
- status: 404,
163
- headers: { "Content-Type": "application/javascript" }
164
- });
165
- }
166
- const actualHash = computeChunkHash(translations, keys);
167
- if (requestedHash !== actualHash) {
168
- console.warn(`[i18n] hash mismatch for ${chunkName}: expected ${actualHash}, got ${requestedHash}`);
169
- }
170
- const chunkTranslations = {};
171
- for (const key of keys) {
172
- if (translations[key]) {
173
- chunkTranslations[key] = translations[key];
174
- }
175
- }
176
- const js = `/* @astroscope/i18n chunk: ${chunkName} */
177
- (function() {
178
- var i = window.__i18n__;
179
- if (i) Object.assign(i.translations, ${JSON.stringify(chunkTranslations)});
180
- })();
181
- `;
182
- return new Response(js, {
183
- status: 200,
184
- headers: {
185
- "Content-Type": "application/javascript",
186
- "Cache-Control": "public, max-age=31536000, immutable"
187
- }
188
- });
189
- }
190
- function createI18nMiddleware(options) {
191
- return async (ctx, next) => {
192
- const config = i18n.getConfig();
193
- if (!config) {
194
- throw new Error("i18n not configured. Call i18n.configure() before using i18nMiddleware.");
195
- }
196
- const pathname = new URL(ctx.request.url).pathname;
197
- const chunkManifest = i18n.getChunkManifest();
198
- if (chunkManifest) {
199
- const endpointParams = parseI18nEndpointPath(pathname);
200
- if (endpointParams) {
201
- const { locale: urlLocale, chunkName, hash } = endpointParams;
202
- const endpointRaw = i18n.getTranslations(urlLocale) ?? {};
203
- return handleI18nEndpoint(chunkName, hash, endpointRaw, chunkManifest);
204
- }
205
- }
206
- const locale = options.locale(ctx);
207
- const compiled = i18n.getCompiledTranslations(locale) ?? {};
208
- const raw = i18n.getTranslations(locale) ?? {};
209
- const context = {
210
- locale,
211
- translations: compiled,
212
- fallback: config.fallback,
213
- meta: {}
214
- };
215
- return runWithContext(context, async () => {
216
- const response = await next();
217
- let script;
218
- const hasChunkManifest = chunkManifest && Object.keys(chunkManifest).length > 0;
219
- if (hasChunkManifest) {
220
- const hashes = i18n.getHashes(locale) ?? {};
221
- script = generateI18nHashScript(locale, hashes);
222
- } else {
223
- script = generateI18nFullScript(locale, raw);
224
- }
225
- return injectI18nScript(response, script);
226
- });
227
- };
228
- }
229
-
230
- export {
231
- computeChunkHash,
232
- computeAllChunkHashes,
233
- i18n,
234
- detectLocale,
235
- createI18nMiddleware
236
- };
@@ -1,153 +0,0 @@
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, manifest2) {
20
- const hashes = {};
21
- for (const [chunkId, keys] of Object.entries(manifest2)) {
22
- hashes[chunkId] = computeChunkHash(translations, keys);
23
- }
24
- return hashes;
25
- }
26
-
27
- // src/server/i18n.ts
28
- import { manifest } from "virtual:@astroscope/i18n/manifest";
29
- var I18nSingleton = class {
30
- // normalized user config with defaults applied
31
- config = null;
32
- // locale -> raw translation strings (before ICU compilation)
33
- rawCache = /* @__PURE__ */ new Map();
34
- // locale -> compiled ICU MessageFormat functions
35
- compiledCache = /* @__PURE__ */ new Map();
36
- // locale -> chunk name -> content hash (for cache busting)
37
- hashCache = /* @__PURE__ */ new Map();
38
- configure(config) {
39
- if (!config.locales?.length) {
40
- throw new Error("i18n.configure(): locales array is required and must not be empty");
41
- }
42
- for (const locale of config.locales) {
43
- if (!locale) {
44
- throw new Error("i18n.configure(): locale cannot be empty");
45
- }
46
- if (locale !== locale.trim()) {
47
- throw new Error(`i18n.configure(): locale "${locale}" has leading or trailing whitespace`);
48
- }
49
- }
50
- if (new Set(config.locales).size !== config.locales.length) {
51
- throw new Error("i18n.configure(): locales array contains duplicates");
52
- }
53
- if (config.defaultLocale !== void 0) {
54
- if (!config.defaultLocale) {
55
- throw new Error("i18n.configure(): defaultLocale cannot be empty");
56
- }
57
- if (config.defaultLocale !== config.defaultLocale.trim()) {
58
- throw new Error(`i18n.configure(): defaultLocale "${config.defaultLocale}" has leading or trailing whitespace`);
59
- }
60
- if (!config.locales.includes(config.defaultLocale)) {
61
- throw new Error(`i18n.configure(): defaultLocale "${config.defaultLocale}" is not in locales array`);
62
- }
63
- }
64
- this.config = {
65
- locales: config.locales,
66
- defaultLocale: config.defaultLocale ?? config.locales[0],
67
- fallback: config.fallback ?? "fallback"
68
- };
69
- }
70
- isConfigured() {
71
- return this.config !== null;
72
- }
73
- getConfig() {
74
- if (!this.config) {
75
- throw new Error("i18n not configured. Call i18n.configure() first.");
76
- }
77
- return this.config;
78
- }
79
- setTranslations(locale, raw) {
80
- this.rawCache.set(locale, raw);
81
- this.compiledCache.set(locale, compileTranslations(locale, raw));
82
- this.hashCache.delete(locale);
83
- const chunks = this.getChunkManifest();
84
- if (Object.keys(chunks).length > 0) {
85
- this.hashCache.set(locale, computeAllChunkHashes(raw, chunks));
86
- }
87
- }
88
- getTranslations(locale) {
89
- return this.rawCache.get(locale) ?? {};
90
- }
91
- getCompiledTranslations(locale) {
92
- return this.compiledCache.get(locale) ?? {};
93
- }
94
- getChunkManifest() {
95
- return this.getExtractionManifest().chunks;
96
- }
97
- /**
98
- * Get extracted translation keys with metadata.
99
- * Use this to populate your translation provider with keys extracted from the codebase.
100
- */
101
- getExtractedKeys() {
102
- return this.getExtractionManifest().keys;
103
- }
104
- /**
105
- * Get the full extraction manifest (keys + chunks).
106
- * In dev mode, keys are available live but chunks are empty.
107
- * In build mode, both keys and chunk mappings are populated.
108
- */
109
- getExtractionManifest() {
110
- return manifest;
111
- }
112
- getHashes(locale) {
113
- return this.hashCache.get(locale) ?? {};
114
- }
115
- /**
116
- * Clear translations for specified locale(s).
117
- * @param locales - Locale(s) to clear, or all if not specified
118
- */
119
- clear(locales) {
120
- const targets = this.resolveLocales(locales);
121
- for (const locale of targets) {
122
- this.rawCache.delete(locale);
123
- this.compiledCache.delete(locale);
124
- this.hashCache.delete(locale);
125
- }
126
- }
127
- resolveLocales(locales) {
128
- if (!locales) {
129
- return this.config?.locales ?? [];
130
- }
131
- if (typeof locales === "string") {
132
- return [locales];
133
- }
134
- return locales;
135
- }
136
- };
137
- var i18n = new I18nSingleton();
138
-
139
- // src/server/context.ts
140
- import { AsyncLocalStorage } from "async_hooks";
141
- var als = new AsyncLocalStorage();
142
- function runWithContext(context, fn) {
143
- return als.run(context, fn);
144
- }
145
- function getContext() {
146
- return als.getStore() ?? null;
147
- }
148
-
149
- export {
150
- i18n,
151
- runWithContext,
152
- getContext
153
- };
@@ -1,156 +0,0 @@
1
- import {
2
- compileTranslations
3
- } from "./chunk-KNDYKTHE.js";
4
-
5
- // src/server/i18n.ts
6
- import fs from "fs";
7
-
8
- // src/extraction/hash.ts
9
- import { createHash } from "crypto";
10
- function hashString(str) {
11
- return createHash("sha256").update(str).digest("hex").substring(0, 8);
12
- }
13
- function computeChunkHash(translations, keys) {
14
- const relevantTranslations = {};
15
- for (const key of keys.sort()) {
16
- if (translations[key]) {
17
- relevantTranslations[key] = translations[key];
18
- }
19
- }
20
- return hashString(JSON.stringify(relevantTranslations));
21
- }
22
- function computeAllChunkHashes(translations, manifest) {
23
- const hashes = {};
24
- for (const [chunkId, keys] of Object.entries(manifest)) {
25
- hashes[chunkId] = computeChunkHash(translations, keys);
26
- }
27
- return hashes;
28
- }
29
-
30
- // src/server/i18n.ts
31
- function loadExtractionManifest() {
32
- const candidates = [
33
- "./i18n-manifest.json",
34
- // same directory
35
- "../i18n-manifest.json"
36
- // parent (when code is in chunks/)
37
- ];
38
- for (const candidate of candidates) {
39
- try {
40
- const manifestPath = new URL(candidate, import.meta.url);
41
- const content = fs.readFileSync(manifestPath, "utf-8");
42
- return JSON.parse(content);
43
- } catch {
44
- }
45
- }
46
- return void 0;
47
- }
48
- var I18nSingleton = class {
49
- config = null;
50
- rawCache = /* @__PURE__ */ new Map();
51
- compiledCache = /* @__PURE__ */ new Map();
52
- extractionManifest = void 0;
53
- // undefined = not loaded yet
54
- hashCache = /* @__PURE__ */ new Map();
55
- configure(config) {
56
- if (!config.locales?.length) {
57
- throw new Error("i18n.configure(): locales array is required and must not be empty");
58
- }
59
- for (const locale of config.locales) {
60
- if (!locale) {
61
- throw new Error("i18n.configure(): locale cannot be empty");
62
- }
63
- if (locale !== locale.trim()) {
64
- throw new Error(`i18n.configure(): locale "${locale}" has leading or trailing whitespace`);
65
- }
66
- }
67
- if (new Set(config.locales).size !== config.locales.length) {
68
- throw new Error("i18n.configure(): locales array contains duplicates");
69
- }
70
- if (config.defaultLocale !== void 0) {
71
- if (!config.defaultLocale) {
72
- throw new Error("i18n.configure(): defaultLocale cannot be empty");
73
- }
74
- if (config.defaultLocale !== config.defaultLocale.trim()) {
75
- throw new Error(`i18n.configure(): defaultLocale "${config.defaultLocale}" has leading or trailing whitespace`);
76
- }
77
- if (!config.locales.includes(config.defaultLocale)) {
78
- throw new Error(`i18n.configure(): defaultLocale "${config.defaultLocale}" is not in locales array`);
79
- }
80
- }
81
- this.config = {
82
- locales: config.locales,
83
- defaultLocale: config.defaultLocale ?? config.locales[0],
84
- fallback: config.fallback ?? "fallback"
85
- };
86
- }
87
- isConfigured() {
88
- return this.config !== null;
89
- }
90
- getConfig() {
91
- if (!this.config) {
92
- throw new Error("i18n not configured. Call i18n.configure() first.");
93
- }
94
- return this.config;
95
- }
96
- setTranslations(locale, raw) {
97
- this.rawCache.set(locale, raw);
98
- this.compiledCache.set(locale, compileTranslations(locale, raw));
99
- this.hashCache.delete(locale);
100
- const chunks = this.getChunkManifest();
101
- if (chunks) {
102
- this.hashCache.set(locale, computeAllChunkHashes(raw, chunks));
103
- }
104
- }
105
- getTranslations(locale) {
106
- return this.rawCache.get(locale) ?? {};
107
- }
108
- getCompiledTranslations(locale) {
109
- return this.compiledCache.get(locale) ?? {};
110
- }
111
- getChunkManifest() {
112
- return this.getExtractionManifest()?.chunks ?? {};
113
- }
114
- /**
115
- * Get extracted translation keys with metadata.
116
- * Use this to populate your CMS with keys extracted from the codebase.
117
- */
118
- getExtractedKeys() {
119
- return this.getExtractionManifest()?.keys ?? null;
120
- }
121
- /**
122
- * Get the full extraction manifest (keys + chunks).
123
- * Returns null in dev mode (manifest doesn't exist).
124
- */
125
- getExtractionManifest() {
126
- if (this.extractionManifest === void 0) {
127
- this.extractionManifest = loadExtractionManifest() ?? null;
128
- }
129
- return this.extractionManifest;
130
- }
131
- getHashes(locale) {
132
- return this.hashCache.get(locale) ?? {};
133
- }
134
- /**
135
- * Clear translations for specified locale(s).
136
- * @param locales - Locale(s) to clear, or all if not specified
137
- */
138
- clear(locales) {
139
- const targets = this.resolveLocales(locales);
140
- for (const locale of targets) {
141
- this.rawCache.delete(locale);
142
- this.compiledCache.delete(locale);
143
- this.hashCache.delete(locale);
144
- }
145
- }
146
- resolveLocales(locales) {
147
- if (!locales) return this.config?.locales ?? [];
148
- if (typeof locales === "string") return [locales];
149
- return locales;
150
- }
151
- };
152
- var i18n = new I18nSingleton();
153
-
154
- export {
155
- i18n
156
- };
@@ -1,82 +0,0 @@
1
- import {
2
- clearContext,
3
- compileTranslations,
4
- setContext
5
- } from "./chunk-KNONI6DP.js";
6
-
7
- // src/middleware.ts
8
- function defaultDetectLocale(request, locales, defaultLocale) {
9
- const acceptLanguage = request.headers.get("accept-language");
10
- if (!acceptLanguage) {
11
- return defaultLocale;
12
- }
13
- const preferred = acceptLanguage.split(",").map((part) => {
14
- const [lang, q = "q=1"] = part.trim().split(";");
15
- return {
16
- lang: lang.split("-")[0].toLowerCase(),
17
- q: parseFloat(q.replace("q=", ""))
18
- };
19
- }).sort((a, b) => b.q - a.q);
20
- for (const { lang } of preferred) {
21
- if (locales.includes(lang)) {
22
- return lang;
23
- }
24
- }
25
- return defaultLocale;
26
- }
27
- var translationCache = /* @__PURE__ */ new Map();
28
- function generateI18nScript(locale, raw, fallback) {
29
- const fallbackValue = typeof fallback === "function" ? "example" : fallback;
30
- return `<script>window.__i18n_locale__=${JSON.stringify(locale)};window.__i18n_fallback__=${JSON.stringify(fallbackValue)};window.__i18n__=${JSON.stringify(raw)};</script>`;
31
- }
32
- async function injectI18nScript(response, script) {
33
- const contentType = response.headers.get("content-type");
34
- if (!contentType?.includes("text/html")) {
35
- return response;
36
- }
37
- const html = await response.text();
38
- let injectedHtml;
39
- if (html.includes("</head>")) {
40
- injectedHtml = html.replace("</head>", `${script}</head>`);
41
- } else if (html.includes("<body")) {
42
- injectedHtml = html.replace(/<body([^>]*)>/, `<body$1>${script}`);
43
- } else {
44
- injectedHtml = script + html;
45
- }
46
- return new Response(injectedHtml, {
47
- status: response.status,
48
- statusText: response.statusText,
49
- headers: response.headers
50
- });
51
- }
52
- function createI18nMiddleware(options) {
53
- const { locales, defaultLocale, fallback, cms, detectLocale } = options;
54
- return async (ctx, next) => {
55
- const locale = detectLocale ? detectLocale(ctx.request) : ctx.currentLocale ?? defaultDetectLocale(ctx.request, locales, defaultLocale);
56
- let raw = translationCache.get(locale);
57
- if (!raw) {
58
- raw = await cms.fetch(locale, []);
59
- translationCache.set(locale, raw);
60
- }
61
- const translations = compileTranslations(locale, raw);
62
- const context = {
63
- locale,
64
- translations,
65
- fallback,
66
- meta: {}
67
- };
68
- setContext(context);
69
- try {
70
- const response = await next();
71
- const script = generateI18nScript(locale, raw, fallback);
72
- const injectedResponse = await injectI18nScript(response, script);
73
- return injectedResponse;
74
- } finally {
75
- clearContext();
76
- }
77
- };
78
- }
79
-
80
- export {
81
- createI18nMiddleware
82
- };