@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,147 +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, 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
- };
@@ -1,241 +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
- 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
- };
@@ -1,316 +0,0 @@
1
- import {
2
- clearContext,
3
- compileTranslations,
4
- setContext
5
- } from "./chunk-AYY2YIBQ.js";
6
-
7
- // src/extraction/hash.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
-
34
- // src/server/service.ts
35
- var instance = null;
36
- function createI18nService(config) {
37
- if (instance) {
38
- throw new Error("i18n service already created. Call createI18nService() only once.");
39
- }
40
- instance = new I18nServiceImpl(config);
41
- return instance;
42
- }
43
- function getI18nService() {
44
- if (!instance) {
45
- throw new Error(
46
- "i18n service not initialized. Call createI18nService() before first request (e.g., in your boot file)."
47
- );
48
- }
49
- return instance;
50
- }
51
- function hasI18nService() {
52
- return instance !== null;
53
- }
54
- var I18nServiceImpl = class {
55
- config;
56
- // raw translation cache per locale
57
- rawCache = /* @__PURE__ */ new Map();
58
- // compiled translation cache per locale
59
- compiledCache = /* @__PURE__ */ new Map();
60
- // hash cache per locale (for per-chunk loading)
61
- hashCache = /* @__PURE__ */ new Map();
62
- // chunk manifest from build
63
- chunkManifest;
64
- // track in-progress fetches to avoid duplicate requests
65
- fetchInProgress = /* @__PURE__ */ new Map();
66
- constructor(config) {
67
- this.config = Object.freeze({ ...config });
68
- }
69
- invalidate(locales) {
70
- const targets = this.resolveLocales(locales);
71
- for (const locale of targets) {
72
- this.rawCache.delete(locale);
73
- this.compiledCache.delete(locale);
74
- this.hashCache.delete(locale);
75
- this.fetchInProgress.delete(locale);
76
- }
77
- }
78
- async refresh(locales) {
79
- const targets = this.resolveLocales(locales);
80
- const fetches = targets.map(async (locale) => {
81
- const raw = await this.fetchTranslations(locale);
82
- return { locale, raw };
83
- });
84
- const results = await Promise.all(fetches);
85
- for (const { locale, raw } of results) {
86
- this.rawCache.set(locale, raw);
87
- this.compiledCache.set(locale, compileTranslations(locale, raw));
88
- if (this.chunkManifest) {
89
- this.hashCache.set(locale, computeAllChunkHashes(raw, this.chunkManifest));
90
- }
91
- }
92
- }
93
- async prefetch(locales) {
94
- const targets = this.resolveLocales(locales);
95
- await Promise.all(
96
- targets.map(async (locale) => {
97
- if (this.rawCache.has(locale)) return;
98
- const raw = await this.fetchTranslations(locale);
99
- this.rawCache.set(locale, raw);
100
- this.compiledCache.set(locale, compileTranslations(locale, raw));
101
- if (this.chunkManifest) {
102
- this.hashCache.set(locale, computeAllChunkHashes(raw, this.chunkManifest));
103
- }
104
- })
105
- );
106
- }
107
- async getTranslations(locale) {
108
- const cached = this.compiledCache.get(locale);
109
- if (cached) return cached;
110
- const raw = await this.ensureRawTranslations(locale);
111
- const compiled = compileTranslations(locale, raw);
112
- this.compiledCache.set(locale, compiled);
113
- return compiled;
114
- }
115
- async getRawTranslations(locale) {
116
- return this.ensureRawTranslations(locale);
117
- }
118
- getHashes(locale) {
119
- return this.hashCache.get(locale);
120
- }
121
- setChunkManifest(manifest) {
122
- this.chunkManifest = manifest;
123
- if (manifest) {
124
- for (const [locale, raw] of this.rawCache) {
125
- this.hashCache.set(locale, computeAllChunkHashes(raw, manifest));
126
- }
127
- }
128
- }
129
- getChunkManifest() {
130
- return this.chunkManifest;
131
- }
132
- /**
133
- * Ensure raw translations are cached, fetching if needed
134
- */
135
- async ensureRawTranslations(locale) {
136
- const cached = this.rawCache.get(locale);
137
- if (cached) return cached;
138
- const raw = await this.fetchTranslations(locale);
139
- this.rawCache.set(locale, raw);
140
- if (this.chunkManifest) {
141
- this.hashCache.set(locale, computeAllChunkHashes(raw, this.chunkManifest));
142
- }
143
- return raw;
144
- }
145
- /**
146
- * Fetch translations, deduplicating concurrent requests
147
- */
148
- async fetchTranslations(locale) {
149
- const inProgress = this.fetchInProgress.get(locale);
150
- if (inProgress) return inProgress;
151
- const fetchPromise = this.config.fetch(locale, []).finally(() => {
152
- this.fetchInProgress.delete(locale);
153
- });
154
- this.fetchInProgress.set(locale, fetchPromise);
155
- return fetchPromise;
156
- }
157
- /**
158
- * Resolve locale argument to array of locales
159
- */
160
- resolveLocales(locales) {
161
- if (!locales) return this.config.locales;
162
- if (typeof locales === "string") return [locales];
163
- return locales;
164
- }
165
- };
166
-
167
- // src/server/middleware.ts
168
- var I18N_ENDPOINT_PREFIX = "/_i18n/";
169
- function defaultDetectLocale(request, locales, defaultLocale) {
170
- const url = new URL(request.url);
171
- const localeParam = url.searchParams.get("locale");
172
- if (localeParam && locales.includes(localeParam)) {
173
- return localeParam;
174
- }
175
- const acceptLanguage = request.headers.get("accept-language");
176
- if (acceptLanguage) {
177
- const preferred = acceptLanguage.split(",").map((part) => {
178
- const [lang, q = "q=1"] = part.trim().split(";");
179
- return {
180
- lang: lang.split("-")[0].toLowerCase(),
181
- q: parseFloat(q.replace("q=", ""))
182
- };
183
- }).sort((a, b) => b.q - a.q);
184
- for (const { lang } of preferred) {
185
- if (locales.includes(lang)) {
186
- return lang;
187
- }
188
- }
189
- }
190
- return defaultLocale;
191
- }
192
- function generateI18nHashScript(locale, hashes) {
193
- const state = { locale, hashes, translations: {} };
194
- return `<script>window.__i18n__=${JSON.stringify(state)};</script>`;
195
- }
196
- function generateI18nFullScript(locale, raw) {
197
- const state = { locale, hashes: {}, translations: raw };
198
- return `<script>window.__i18n__=${JSON.stringify(state)};</script>`;
199
- }
200
- async function injectI18nScript(response, script) {
201
- const contentType = response.headers.get("content-type");
202
- if (!contentType?.includes("text/html")) {
203
- return response;
204
- }
205
- const html = await response.text();
206
- let injectedHtml;
207
- if (html.includes("</head>")) {
208
- injectedHtml = html.replace("</head>", `${script}</head>`);
209
- } else if (html.includes("<body")) {
210
- injectedHtml = html.replace(/<body([^>]*)>/, `<body$1>${script}`);
211
- } else {
212
- injectedHtml = script + html;
213
- }
214
- return new Response(injectedHtml, {
215
- status: response.status,
216
- statusText: response.statusText,
217
- headers: response.headers
218
- });
219
- }
220
- function parseI18nEndpointPath(pathname) {
221
- if (!pathname.startsWith(I18N_ENDPOINT_PREFIX)) {
222
- return null;
223
- }
224
- const path = pathname.slice(I18N_ENDPOINT_PREFIX.length);
225
- const match = path.match(/^([^/]+)\/(.+)\.([a-z0-9]+)\.js$/);
226
- if (!match) {
227
- return null;
228
- }
229
- return { locale: match[1], chunkName: match[2], hash: match[3] };
230
- }
231
- function handleI18nEndpoint(chunkName, requestedHash, translations, chunkManifest) {
232
- const keys = chunkManifest[chunkName];
233
- if (!keys) {
234
- return new Response(`/* chunk not found: ${chunkName} */`, {
235
- status: 404,
236
- headers: { "Content-Type": "application/javascript" }
237
- });
238
- }
239
- const actualHash = computeChunkHash(translations, keys);
240
- if (requestedHash !== actualHash) {
241
- console.warn(`[i18n] hash mismatch for ${chunkName}: expected ${actualHash}, got ${requestedHash}`);
242
- }
243
- const chunkTranslations = {};
244
- for (const key of keys) {
245
- if (translations[key]) {
246
- chunkTranslations[key] = translations[key];
247
- }
248
- }
249
- const js = `/* @astroscope/i18n chunk: ${chunkName} */
250
- (function() {
251
- var i = window.__i18n__;
252
- if (i) Object.assign(i.translations, ${JSON.stringify(chunkTranslations)});
253
- })();
254
- `;
255
- return new Response(js, {
256
- status: 200,
257
- headers: {
258
- "Content-Type": "application/javascript",
259
- // immutable cache - hash in URL ensures cache busting
260
- "Cache-Control": "public, max-age=31536000, immutable"
261
- }
262
- });
263
- }
264
- function createI18nMiddleware(options) {
265
- const { locales, defaultLocale, fallback, detectLocale, chunkManifest } = options;
266
- const service = getI18nService();
267
- if (chunkManifest) {
268
- service.setChunkManifest(chunkManifest);
269
- }
270
- return async (ctx, next) => {
271
- const pathname = new URL(ctx.request.url).pathname;
272
- const serviceChunkManifest = service.getChunkManifest();
273
- if (serviceChunkManifest) {
274
- const endpointParams = parseI18nEndpointPath(pathname);
275
- if (endpointParams) {
276
- const { locale: urlLocale, chunkName, hash } = endpointParams;
277
- const endpointRaw = await service.getRawTranslations(urlLocale);
278
- return handleI18nEndpoint(chunkName, hash, endpointRaw, serviceChunkManifest);
279
- }
280
- }
281
- const locale = detectLocale ? detectLocale(ctx.request) : ctx.currentLocale ?? defaultDetectLocale(ctx.request, locales, defaultLocale);
282
- const translations = await service.getTranslations(locale);
283
- const raw = await service.getRawTranslations(locale);
284
- const context = {
285
- locale,
286
- translations,
287
- fallback,
288
- meta: {}
289
- };
290
- setContext(context);
291
- try {
292
- const response = await next();
293
- let script;
294
- const hasChunkManifest = serviceChunkManifest && Object.keys(serviceChunkManifest).length > 0;
295
- if (hasChunkManifest) {
296
- const hashes = service.getHashes(locale) ?? {};
297
- script = generateI18nHashScript(locale, hashes);
298
- } else {
299
- script = generateI18nFullScript(locale, raw);
300
- }
301
- const injectedResponse = await injectI18nScript(response, script);
302
- return injectedResponse;
303
- } finally {
304
- clearContext();
305
- }
306
- };
307
- }
308
-
309
- export {
310
- computeChunkHash,
311
- computeAllChunkHashes,
312
- createI18nService,
313
- getI18nService,
314
- hasI18nService,
315
- createI18nMiddleware
316
- };