vite-bundled-i18n 0.7.2 → 0.8.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 (37) hide show
  1. package/README.md +10 -0
  2. package/dist/{build-stamp-BvP03CCo.js → build-stamp-BgrEayAW.js} +246 -154
  3. package/dist/build-stamp-BgrEayAW.js.map +1 -0
  4. package/dist/cli/commands.d.ts +19 -0
  5. package/dist/cli/index.js +83 -4
  6. package/dist/cli/index.js.map +1 -1
  7. package/dist/core/config.d.ts +21 -1
  8. package/dist/core/i18n-generated.d.ts +2 -0
  9. package/dist/core/types.d.ts +3 -1
  10. package/dist/{data-MH8nzEsb.js → data-Gc1TYVNf.js} +13 -3
  11. package/dist/{data-MH8nzEsb.js.map → data-Gc1TYVNf.js.map} +1 -1
  12. package/dist/eslint.js +1 -1
  13. package/dist/extractor/bundle-generator.d.ts +16 -0
  14. package/dist/extractor/compiler.d.ts +9 -0
  15. package/dist/extractor/locale-store.d.ts +68 -0
  16. package/dist/extractor/reports.d.ts +3 -2
  17. package/dist/index.js +2 -2
  18. package/dist/plugin/buildPlugin.d.ts +25 -2
  19. package/dist/plugin.js +210 -18
  20. package/dist/plugin.js.map +1 -1
  21. package/dist/{server-B6C5KwkP.js → server-ghPdPuC9.js} +2 -2
  22. package/dist/{server-B6C5KwkP.js.map → server-ghPdPuC9.js.map} +1 -1
  23. package/dist/server.js +2 -2
  24. package/dist/testing.js +1 -1
  25. package/dist/vanilla.js +2 -2
  26. package/dist/vue.js +1 -1
  27. package/docs/api.md +1032 -0
  28. package/docs/architecture.md +144 -0
  29. package/docs/getting-started.md +683 -0
  30. package/package.json +7 -3
  31. package/skills/vite-bundled-i18n/SKILL.md +60 -0
  32. package/skills/vite-bundled-i18n/agents/openai.yaml +4 -0
  33. package/skills/vite-bundled-i18n/references/api-reference.md +142 -0
  34. package/skills/vite-bundled-i18n/references/best-practices.md +127 -0
  35. package/skills/vite-bundled-i18n/references/setup.md +174 -0
  36. package/skills/vite-bundled-i18n/references/troubleshooting.md +132 -0
  37. package/dist/build-stamp-BvP03CCo.js.map +0 -1
package/README.md CHANGED
@@ -546,6 +546,16 @@ If after that the key is _still_ missing, the issue is in the source — not the
546
546
 
547
547
  The CLI's `clean` command accepts repeatable `--extra-path` flags for project layouts that emit assets outside `.i18n/` (e.g. `--extra-path public/__i18n --extra-path public/build/__i18n`).
548
548
 
549
+ ### Codex skill for consumer apps
550
+
551
+ The package also ships a Codex skill with setup guidance, best practices, API notes, and troubleshooting for consumer apps. Install it into the current app with:
552
+
553
+ ```bash
554
+ npx vite-bundled-i18n install-skill
555
+ ```
556
+
557
+ By default this copies the skill to `.agents/skills/vite-bundled-i18n`. Use `--global` to install into `${CODEX_HOME:-~/.codex}/skills`, `--target <skills-dir>` for a custom skills directory, and `--force` to refresh an existing copy.
558
+
549
559
  ## ESLint plugin
550
560
 
551
561
  `vite-bundled-i18n/eslint` ships five rules that catch the patterns the extractor cannot see — keys reached through aliases, props, member access, or runtime concatenation. Same package, optional peer dep on `eslint >= 8`, opt in via the subpath:
@@ -1,8 +1,8 @@
1
+ import crypto from "node:crypto";
1
2
  import fs from "node:fs";
2
3
  import path from "node:path";
3
4
  import { globSync } from "tinyglobby";
4
5
  import ts from "typescript";
5
- import crypto from "node:crypto";
6
6
  //#region src/extractor/dictionary-ownership.ts
7
7
  function getDictionaryIncludePatterns(dict) {
8
8
  return [...(dict.keys ?? []).map((key) => `${key}.*`), ...dict.include ?? []];
@@ -108,6 +108,96 @@ function buildScopePlans(analysis, availableKeys, options = {}) {
108
108
  return [...scopePlans.values()].sort((a, b) => a.scope.localeCompare(b.scope));
109
109
  }
110
110
  //#endregion
111
+ //#region src/extractor/locale-store.ts
112
+ /**
113
+ * Flattens a nested translation object into `target`, prefixing every key
114
+ * with `prefix` (which must already end with a dot, e.g. `'products.'`).
115
+ *
116
+ * Writes straight into one accumulator instead of building a map per
117
+ * nesting level. Insertion order and last-write-wins semantics are the same
118
+ * as building nested maps and copying them into their parent.
119
+ *
120
+ * Only string leaves are kept; arrays recurse by index; other values
121
+ * (numbers, booleans, null) are skipped.
122
+ *
123
+ * @internal
124
+ */
125
+ function flattenNamespaceInto(target, data, prefix) {
126
+ for (const key of Object.keys(data)) {
127
+ const value = data[key];
128
+ const fullKey = `${prefix}${key}`;
129
+ if (typeof value === "string") target.set(fullKey, value);
130
+ else if (typeof value === "object" && value !== null) flattenNamespaceInto(target, value, `${fullKey}.`);
131
+ }
132
+ }
133
+ /**
134
+ * Creates an empty per-run {@link LocaleStore} for `localesDir`.
135
+ *
136
+ * @internal
137
+ */
138
+ function createLocaleStore(localesDir) {
139
+ const namespaceLists = /* @__PURE__ */ new Map();
140
+ const parsed = /* @__PURE__ */ new Map();
141
+ const fullMaps = /* @__PURE__ */ new Map();
142
+ const fullMapIndexes = /* @__PURE__ */ new Map();
143
+ function namespaces(locale) {
144
+ let list = namespaceLists.get(locale);
145
+ if (!list) {
146
+ const localeDir = path.join(localesDir, locale);
147
+ list = fs.existsSync(localeDir) ? fs.readdirSync(localeDir).filter((file) => file.endsWith(".json")).map((file) => file.replace(/\.json$/, "")) : [];
148
+ namespaceLists.set(locale, list);
149
+ }
150
+ return list;
151
+ }
152
+ function namespace(locale, ns) {
153
+ const cacheKey = `${locale}\0${ns}`;
154
+ if (parsed.has(cacheKey)) return parsed.get(cacheKey);
155
+ const filePath = path.join(localesDir, locale, `${ns}.json`);
156
+ const data = fs.existsSync(filePath) ? JSON.parse(fs.readFileSync(filePath, "utf-8")) : null;
157
+ parsed.set(cacheKey, data);
158
+ return data;
159
+ }
160
+ function fullMap(locale) {
161
+ let map = fullMaps.get(locale);
162
+ if (!map) {
163
+ map = /* @__PURE__ */ new Map();
164
+ for (const ns of namespaces(locale)) {
165
+ const data = namespace(locale, ns);
166
+ if (!data) continue;
167
+ flattenNamespaceInto(map, data, `${ns}.`);
168
+ }
169
+ fullMaps.set(locale, map);
170
+ }
171
+ return map;
172
+ }
173
+ function fullMapIndex(locale) {
174
+ let index = fullMapIndexes.get(locale);
175
+ if (!index) {
176
+ index = /* @__PURE__ */ new Map();
177
+ let position = 0;
178
+ for (const key of fullMap(locale).keys()) index.set(key, position++);
179
+ fullMapIndexes.set(locale, index);
180
+ }
181
+ return index;
182
+ }
183
+ return {
184
+ localesDir,
185
+ namespaces,
186
+ namespace,
187
+ fullMap,
188
+ fullMapIndex
189
+ };
190
+ }
191
+ /**
192
+ * Returns `store` when it reads from `localesDir`, otherwise a fresh store.
193
+ * Guards against a caller passing a store built for a different directory.
194
+ *
195
+ * @internal
196
+ */
197
+ function localeStoreFor(localesDir, store) {
198
+ return store && store.localesDir === localesDir ? store : createLocaleStore(localesDir);
199
+ }
200
+ //#endregion
111
201
  //#region src/extractor/bundle-generator.ts
112
202
  /**
113
203
  * Flatten a nested object into dot-separated key paths. Null/undefined at
@@ -115,26 +205,52 @@ function buildScopePlans(analysis, availableKeys, options = {}) {
115
205
  * namespace contributes no keys, never throws.
116
206
  */
117
207
  function flattenKeys(data, prefix) {
118
- if (data == null) return [];
119
208
  const keys = [];
209
+ flattenKeysInto(keys, data, prefix);
210
+ return keys;
211
+ }
212
+ /** {@link flattenKeys} into one accumulator instead of an array per level. */
213
+ function flattenKeysInto(out, data, prefix) {
214
+ if (data == null) return;
120
215
  for (const [k, v] of Object.entries(data)) {
121
216
  const fullKey = prefix ? `${prefix}.${k}` : k;
122
- if (v !== null && typeof v === "object" && !Array.isArray(v)) keys.push(...flattenKeys(v, fullKey));
123
- else keys.push(fullKey);
217
+ if (v !== null && typeof v === "object" && !Array.isArray(v)) flattenKeysInto(out, v, fullKey);
218
+ else out.push(fullKey);
124
219
  }
125
- return keys;
220
+ }
221
+ /**
222
+ * Number of entries {@link flattenKeys} would return, without building the
223
+ * array.
224
+ */
225
+ function countFlatKeys(data) {
226
+ if (data == null) return 0;
227
+ let count = 0;
228
+ for (const v of Object.values(data)) if (v !== null && typeof v === "object" && !Array.isArray(v)) count += countFlatKeys(v);
229
+ else count++;
230
+ return count;
126
231
  }
127
232
  /**
128
233
  * Set a value at a dot-separated path in a nested object, creating
129
234
  * intermediate objects as needed.
235
+ *
236
+ * `owned` holds the containers this prune created. When the path runs into
237
+ * a container that isn't owned, a whole subtree of the input already sits
238
+ * at that path and holds this exact value, so there is nothing to write.
239
+ * Stopping there keeps the input untouched: parsed locale files are shared
240
+ * between scopes for the whole build.
130
241
  */
131
- function setNestedValue(obj, keyPath, value) {
242
+ function setNestedValue(obj, keyPath, value, owned) {
132
243
  const parts = keyPath.split(".");
133
244
  let current = obj;
134
245
  for (let i = 0; i < parts.length - 1; i++) {
135
246
  const part = parts[i];
136
- if (!(part in current) || typeof current[part] !== "object" || current[part] === null) current[part] = {};
247
+ if (!(part in current) || typeof current[part] !== "object" || current[part] === null) {
248
+ const created = {};
249
+ owned.add(created);
250
+ current[part] = created;
251
+ }
137
252
  current = current[part];
253
+ if (!owned.has(current)) return;
138
254
  }
139
255
  current[parts[parts.length - 1]] = value;
140
256
  }
@@ -160,27 +276,40 @@ function getNestedValue(obj, keyPath) {
160
276
  */
161
277
  function pruneNamespace(fullData, usedKeyPaths) {
162
278
  const result = {};
279
+ const owned = new WeakSet([result]);
163
280
  for (const keyPath of usedKeyPaths) {
164
281
  const value = getNestedValue(fullData, keyPath);
165
- if (value !== void 0) setNestedValue(result, keyPath, value);
282
+ if (value !== void 0) setNestedValue(result, keyPath, value, owned);
166
283
  }
167
284
  return result;
168
285
  }
169
286
  /**
170
- * Read a namespace JSON file for a given locale.
171
- */
172
- function readNamespaceFile(localesDir, locale, namespace) {
173
- const filePath = path.join(localesDir, locale, `${namespace}.json`);
174
- if (!fs.existsSync(filePath)) return null;
175
- const content = fs.readFileSync(filePath, "utf-8");
176
- return JSON.parse(content);
177
- }
178
- /**
179
287
  * Generate tree-shaken per-route translation bundles from project analysis.
180
288
  */
181
289
  function generateBundles(analysis, options) {
182
290
  const { localesDir, locales, outDir, dictionaries, crossNamespacePacking } = options;
183
291
  const bundles = [];
292
+ const serialize = options.pretty === false ? (data) => JSON.stringify(data) : (data) => JSON.stringify(data, null, 2);
293
+ const store = localeStoreFor(localesDir, options.localeStore);
294
+ const readNamespaceFile = (locale, namespace) => store.namespace(locale, namespace);
295
+ const flatKeysCache = /* @__PURE__ */ new WeakMap();
296
+ const flatKeysOf = (data) => {
297
+ let keys = flatKeysCache.get(data);
298
+ if (!keys) {
299
+ keys = flattenKeys(data);
300
+ flatKeysCache.set(data, keys);
301
+ }
302
+ return keys;
303
+ };
304
+ const keyCountCache = /* @__PURE__ */ new WeakMap();
305
+ const keyCountOf = (data) => {
306
+ let count = keyCountCache.get(data);
307
+ if (count === void 0) {
308
+ count = flatKeysCache.get(data)?.length ?? countFlatKeys(data);
309
+ keyCountCache.set(data, count);
310
+ }
311
+ return count;
312
+ };
184
313
  const availableKeys = /* @__PURE__ */ new Set();
185
314
  for (const route of analysis.routes) for (const key of route.keys) if (!key.dynamic) availableKeys.add(key.key);
186
315
  const ownership = resolveDictionaryOwnership(availableKeys, dictionaries);
@@ -194,12 +323,12 @@ function generateBundles(analysis, options) {
194
323
  if (ownership.keyOwner.has(key)) return false;
195
324
  return !(!hasNamedDictionaries && sharedNsSet.has(plan.namespace));
196
325
  }).filter((key) => key.startsWith(`${plan.namespace}.`)).map((key) => key.slice(plan.namespace.length + 1));
197
- const fullData = readNamespaceFile(localesDir, locale, plan.namespace);
326
+ const fullData = readNamespaceFile(locale, plan.namespace);
198
327
  if (fullData && subKeys.length > 0) {
199
328
  const pruned = pruneNamespace(fullData, [...new Set(subKeys)]);
200
329
  bundleData[plan.namespace] = pruned;
201
- const availableCount = flattenKeys(fullData).length;
202
- const keptCount = flattenKeys(pruned).length;
330
+ const availableCount = keyCountOf(fullData);
331
+ const keptCount = countFlatKeys(pruned);
203
332
  totalKeyCount += keptCount;
204
333
  totalPrunedCount += availableCount - keptCount;
205
334
  }
@@ -209,15 +338,15 @@ function generateBundles(analysis, options) {
209
338
  if (!hasNamedDictionaries && sharedNsSet.has(extraNs)) continue;
210
339
  const extraSubKeys = retained.filter((key) => key.startsWith(`${extraNs}.`)).map((key) => key.slice(extraNs.length + 1));
211
340
  if (extraSubKeys.length === 0) continue;
212
- const extraFullData = readNamespaceFile(localesDir, locale, extraNs);
341
+ const extraFullData = readNamespaceFile(locale, extraNs);
213
342
  if (!extraFullData) continue;
214
343
  const pruned = pruneNamespace(extraFullData, [...new Set(extraSubKeys)]);
215
344
  bundleData[extraNs] = pruned;
216
- totalKeyCount += flattenKeys(pruned).length;
345
+ totalKeyCount += countFlatKeys(pruned);
217
346
  }
218
347
  const filePath = path.join(outDir, locale, `${plan.scope}.json`);
219
348
  fs.mkdirSync(path.dirname(filePath), { recursive: true });
220
- fs.writeFileSync(filePath, JSON.stringify(bundleData, null, 2));
349
+ fs.writeFileSync(filePath, serialize(bundleData));
221
350
  bundles.push({
222
351
  name: plan.scope,
223
352
  locale,
@@ -247,9 +376,9 @@ function generateBundles(analysis, options) {
247
376
  const bundleData = {};
248
377
  let totalKeyCount = 0;
249
378
  for (const ns of matchedNamespaces) {
250
- const fullData = readNamespaceFile(localesDir, locale, ns);
379
+ const fullData = readNamespaceFile(locale, ns);
251
380
  if (!fullData) continue;
252
- const includedKeys = flattenKeys(fullData).filter((subKey) => {
381
+ const includedKeys = flatKeysOf(fullData).filter((subKey) => {
253
382
  const fullKey = `${ns}.${subKey}`;
254
383
  const included = rule.include.some((pattern) => keyMatchesPattern(fullKey, pattern));
255
384
  const excluded = rule.exclude.length > 0 && rule.exclude.some((pattern) => keyMatchesPattern(fullKey, pattern));
@@ -258,11 +387,11 @@ function generateBundles(analysis, options) {
258
387
  if (includedKeys.length === 0) continue;
259
388
  const pruned = pruneNamespace(fullData, includedKeys);
260
389
  bundleData[ns] = pruned;
261
- totalKeyCount += flattenKeys(pruned).length;
390
+ totalKeyCount += countFlatKeys(pruned);
262
391
  }
263
392
  const filePath = path.join(outDir, locale, "_dict", `${rule.name}.json`);
264
393
  fs.mkdirSync(path.dirname(filePath), { recursive: true });
265
- fs.writeFileSync(filePath, JSON.stringify(bundleData, null, 2));
394
+ fs.writeFileSync(filePath, serialize(bundleData));
266
395
  bundles.push({
267
396
  name: `_dict/${rule.name}`,
268
397
  locale,
@@ -285,14 +414,14 @@ function generateBundles(analysis, options) {
285
414
  }
286
415
  }
287
416
  for (const locale of locales) {
288
- const fullData = readNamespaceFile(localesDir, locale, sharedNs);
417
+ const fullData = readNamespaceFile(locale, sharedNs);
289
418
  if (!fullData) continue;
290
419
  const pruned = pruneNamespace(fullData, [...allSubKeys]);
291
420
  const filePath = path.join(outDir, locale, "_dict", `${sharedNs}.json`);
292
421
  fs.mkdirSync(path.dirname(filePath), { recursive: true });
293
- fs.writeFileSync(filePath, JSON.stringify(pruned, null, 2));
294
- const availableCount = flattenKeys(fullData).length;
295
- const keptCount = flattenKeys(pruned).length;
422
+ fs.writeFileSync(filePath, serialize(pruned));
423
+ const availableCount = keyCountOf(fullData);
424
+ const keptCount = countFlatKeys(pruned);
296
425
  bundles.push({
297
426
  name: `_dict/${sharedNs}`,
298
427
  locale,
@@ -538,8 +667,14 @@ function runtimePathFromTypesPath(typesOutPath) {
538
667
  * Read all namespace JSON files for the default locale and return a map of
539
668
  * namespace → flattened dot-path key arrays.
540
669
  */
541
- function flattenLocaleKeys(localesDir, defaultLocale) {
670
+ function flattenLocaleKeys(localesDir, defaultLocale, localeStore) {
542
671
  const result = /* @__PURE__ */ new Map();
672
+ if (localeStore && localeStore.localesDir === localesDir) {
673
+ for (const namespace of localeStore.namespaces(defaultLocale)) try {
674
+ result.set(namespace, flattenKeys(localeStore.namespace(defaultLocale, namespace)));
675
+ } catch {}
676
+ return result;
677
+ }
543
678
  const localeDir = path.join(localesDir, defaultLocale);
544
679
  if (!fs.existsSync(localeDir)) return result;
545
680
  const entries = fs.readdirSync(localeDir);
@@ -732,8 +867,8 @@ function generateDictionaryOwnershipReport(availableKeys, dictionaries) {
732
867
  * Orchestrate report generation: flatten locale keys, generate all four
733
868
  * reports, and write them as JSON files to outDir.
734
869
  */
735
- function generateReports(analysis, localesDir, defaultLocale, outDir, dictionaries) {
736
- const availableKeys = flattenLocaleKeys(localesDir, defaultLocale);
870
+ function generateReports(analysis, localesDir, defaultLocale, outDir, dictionaries, localeStore) {
871
+ const availableKeys = flattenLocaleKeys(localesDir, defaultLocale, localeStore);
737
872
  const manifest = generateManifest$1(analysis);
738
873
  const missing = generateMissing(analysis, availableKeys);
739
874
  const unused = generateUnused(analysis, availableKeys);
@@ -925,6 +1060,33 @@ function findTranslationCalls(sourceFile, options) {
925
1060
  }
926
1061
  });
927
1062
  const keyFields = getKeyFields(options);
1063
+ function resolveStaticKeys(keyArg) {
1064
+ const direct = getStringValue(keyArg) ?? (ts.isIdentifier(keyArg) ? literalConstants.get(keyArg.text) : void 0);
1065
+ if (direct !== void 0) return [direct];
1066
+ if (ts.isPropertyAccessExpression(keyArg) && ts.isIdentifier(keyArg.expression)) {
1067
+ const value = constObjectMaps.get(keyArg.expression.text)?.get(keyArg.name.text);
1068
+ return value === void 0 ? void 0 : [value];
1069
+ }
1070
+ if (ts.isElementAccessExpression(keyArg) && ts.isIdentifier(keyArg.expression)) {
1071
+ const objMap = constObjectMaps.get(keyArg.expression.text);
1072
+ if (!objMap) return void 0;
1073
+ const staticMember = keyArg.argumentExpression ? getStringValue(keyArg.argumentExpression) : void 0;
1074
+ if (staticMember !== void 0) {
1075
+ const value = objMap.get(staticMember);
1076
+ return value === void 0 ? void 0 : [value];
1077
+ }
1078
+ return [...objMap.values()];
1079
+ }
1080
+ }
1081
+ function pushStaticKeys(keys, line, character, fallback) {
1082
+ for (const key of keys) results.push({
1083
+ key,
1084
+ fallback,
1085
+ dynamic: false,
1086
+ line: line + 1,
1087
+ column: character
1088
+ });
1089
+ }
928
1090
  function visit(node) {
929
1091
  if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.initializer && getStringValue(node.initializer) !== void 0) literalConstants.set(node.name.text, getStringValue(node.initializer));
930
1092
  if (ts.isVariableDeclaration(node) && node.initializer && ts.isCallExpression(node.initializer) && ts.isIdentifier(node.initializer.expression) && useI18nNames.has(node.initializer.expression.text) && node.name && ts.isObjectBindingPattern(node.name)) for (const element of node.name.elements) {
@@ -941,35 +1103,9 @@ function findTranslationCalls(sourceFile, options) {
941
1103
  return;
942
1104
  }
943
1105
  const keyArg = args[0];
944
- let staticKey = getStringValue(keyArg) ?? (ts.isIdentifier(keyArg) ? literalConstants.get(keyArg.text) : void 0);
945
- if (staticKey === void 0 && ts.isPropertyAccessExpression(keyArg) && ts.isIdentifier(keyArg.expression)) {
946
- const objMap = constObjectMaps.get(keyArg.expression.text);
947
- if (objMap) {
948
- const value = objMap.get(keyArg.name.text);
949
- if (value !== void 0) staticKey = value;
950
- }
951
- }
1106
+ const staticKeys = resolveStaticKeys(keyArg);
952
1107
  const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
953
- if (staticKey === void 0 && ts.isElementAccessExpression(keyArg) && ts.isIdentifier(keyArg.expression)) {
954
- const objMap = constObjectMaps.get(keyArg.expression.text);
955
- if (objMap) {
956
- for (const value of objMap.values()) results.push({
957
- key: value,
958
- dynamic: false,
959
- line: line + 1,
960
- column: character
961
- });
962
- ts.forEachChild(node, visit);
963
- return;
964
- }
965
- }
966
- if (staticKey !== void 0) results.push({
967
- key: staticKey,
968
- fallback: extractFallback(args),
969
- dynamic: false,
970
- line: line + 1,
971
- column: character
972
- });
1108
+ if (staticKeys !== void 0) pushStaticKeys(staticKeys, line, character, extractFallback(args));
973
1109
  else {
974
1110
  const prefix = getStaticPrefix(keyArg);
975
1111
  results.push({
@@ -983,34 +1119,9 @@ function findTranslationCalls(sourceFile, options) {
983
1119
  }
984
1120
  if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && i18nKeyNames.has(node.expression.text) && node.arguments.length > 0) {
985
1121
  const keyArg = node.arguments[0];
986
- let staticKey = getStringValue(keyArg) ?? (ts.isIdentifier(keyArg) ? literalConstants.get(keyArg.text) : void 0);
987
- if (staticKey === void 0 && ts.isPropertyAccessExpression(keyArg) && ts.isIdentifier(keyArg.expression)) {
988
- const objMap = constObjectMaps.get(keyArg.expression.text);
989
- if (objMap) {
990
- const value = objMap.get(keyArg.name.text);
991
- if (value !== void 0) staticKey = value;
992
- }
993
- }
1122
+ const staticKeys = resolveStaticKeys(keyArg);
994
1123
  const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
995
- if (staticKey === void 0 && ts.isElementAccessExpression(keyArg) && ts.isIdentifier(keyArg.expression)) {
996
- const objMap = constObjectMaps.get(keyArg.expression.text);
997
- if (objMap) {
998
- for (const value of objMap.values()) results.push({
999
- key: value,
1000
- dynamic: false,
1001
- line: line + 1,
1002
- column: character
1003
- });
1004
- ts.forEachChild(node, visit);
1005
- return;
1006
- }
1007
- }
1008
- if (staticKey !== void 0) results.push({
1009
- key: staticKey,
1010
- dynamic: false,
1011
- line: line + 1,
1012
- column: character
1013
- });
1124
+ if (staticKeys !== void 0) pushStaticKeys(staticKeys, line, character);
1014
1125
  else {
1015
1126
  const prefix = getStaticPrefix(keyArg);
1016
1127
  results.push({
@@ -1024,15 +1135,10 @@ function findTranslationCalls(sourceFile, options) {
1024
1135
  }
1025
1136
  if (options.scope !== "scoped" && ts.isCallExpression(node) && ts.isIdentifier(node.expression) && !trackedNames.has(node.expression.text) && !i18nKeyNames.has(node.expression.text) && TRANSLATION_CALLEE_NAMES.has(node.expression.text) && node.arguments.length > 0) {
1026
1137
  const keyArg = node.arguments[0];
1027
- const staticKey = getStringValue(keyArg) ?? (ts.isIdentifier(keyArg) ? literalConstants.get(keyArg.text) : void 0);
1028
- if (staticKey !== void 0 && staticKey.includes(".")) {
1138
+ const staticKeys = resolveStaticKeys(keyArg);
1139
+ if (staticKeys !== void 0) {
1029
1140
  const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
1030
- results.push({
1031
- key: staticKey,
1032
- dynamic: false,
1033
- line: line + 1,
1034
- column: character
1035
- });
1141
+ pushStaticKeys(staticKeys.filter((key) => key.includes(".")), line, character);
1036
1142
  }
1037
1143
  }
1038
1144
  if (ts.isPropertyAssignment(node) && (ts.isIdentifier(node.name) && keyFields.has(node.name.text) || ts.isStringLiteral(node.name) && keyFields.has(node.name.text))) {
@@ -1588,7 +1694,7 @@ function resolveCacheConfig(input, context) {
1588
1694
  * back to a development placeholder during tests and direct imports before
1589
1695
  * the build step runs.
1590
1696
  */
1591
- var PLUGIN_VERSION = "0.7.2";
1697
+ var PLUGIN_VERSION = "0.8.0";
1592
1698
  //#endregion
1593
1699
  //#region src/extractor/scope-map.ts
1594
1700
  var COMPOSITE_PAGE_SUFFIXES = [
@@ -1766,27 +1872,6 @@ function escapeValue(value) {
1766
1872
  return value.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
1767
1873
  }
1768
1874
  /**
1769
- * Flattens a nested translation object into a flat Map with fully qualified keys.
1770
- *
1771
- * @param namespace - The namespace prefix (e.g., 'products')
1772
- * @param data - The nested translation object
1773
- * @param prefix - Internal prefix for recursion
1774
- * @returns A Map of fully qualified keys to string values
1775
- */
1776
- function flattenNamespace(namespace, data, prefix) {
1777
- const result = /* @__PURE__ */ new Map();
1778
- const currentPrefix = prefix ? `${prefix}.` : `${namespace}.`;
1779
- for (const [key, value] of Object.entries(data)) {
1780
- const fullKey = `${currentPrefix}${key}`;
1781
- if (typeof value === "string") result.set(fullKey, value);
1782
- else if (typeof value === "object" && value !== null) {
1783
- const nested = flattenNamespace(namespace, value, fullKey);
1784
- for (const [k, v] of nested) result.set(k, v);
1785
- }
1786
- }
1787
- return result;
1788
- }
1789
- /**
1790
1875
  * Creates a new map with all keys from primary, plus any missing keys filled from fallback.
1791
1876
  */
1792
1877
  function preResolveFallbacks(primary, fallback) {
@@ -1808,42 +1893,42 @@ function generateCompiledModule(entries) {
1808
1893
  return lines.join("\n");
1809
1894
  }
1810
1895
  /**
1811
- * Reads namespace JSON files for a locale and returns a combined flattened Map.
1896
+ * Picks `keys` out of `map`, keeping `map`'s insertion order.
1897
+ *
1898
+ * Same result as scanning `map` and keeping the entries whose key is in
1899
+ * `keys`, but costs O(|keys| log |keys|) instead of O(|map|): scope plans
1900
+ * use a few dozen keys out of tens of thousands.
1812
1901
  */
1813
- function buildLocaleMap(localesDir, locale, namespaces) {
1814
- const combined = /* @__PURE__ */ new Map();
1815
- for (const ns of namespaces) {
1816
- const filePath = path.join(localesDir, locale, `${ns}.json`);
1817
- if (!fs.existsSync(filePath)) continue;
1818
- const flat = flattenNamespace(ns, JSON.parse(fs.readFileSync(filePath, "utf-8")));
1819
- for (const [k, v] of flat) combined.set(k, v);
1902
+ function pickInMapOrder(map, index, keys) {
1903
+ const positions = [];
1904
+ const byPosition = /* @__PURE__ */ new Map();
1905
+ for (const key of keys) {
1906
+ const position = index.get(key);
1907
+ if (position === void 0 || byPosition.has(position)) continue;
1908
+ positions.push(position);
1909
+ byPosition.set(position, key);
1820
1910
  }
1821
- return combined;
1822
- }
1823
- /**
1824
- * Reads ALL namespace JSON files for a locale directory.
1825
- */
1826
- function buildFullLocaleMap(localesDir, locale) {
1827
- const localeDir = path.join(localesDir, locale);
1828
- if (!fs.existsSync(localeDir)) return /* @__PURE__ */ new Map();
1829
- return buildLocaleMap(localesDir, locale, fs.readdirSync(localeDir).filter((f) => f.endsWith(".json")).map((f) => f.replace(/\.json$/, "")));
1830
- }
1831
- /**
1832
- * Filters a map to only include entries whose keys are in the given set.
1833
- */
1834
- function filterMap(map, keys) {
1911
+ positions.sort((a, b) => a - b);
1835
1912
  const result = /* @__PURE__ */ new Map();
1836
- for (const [k, v] of map) if (keys.has(k)) result.set(k, v);
1913
+ for (const position of positions) {
1914
+ const key = byPosition.get(position);
1915
+ result.set(key, map.get(key));
1916
+ }
1837
1917
  return result;
1838
1918
  }
1919
+ /** {@link pickInMapOrder} over a locale's full map from the store. */
1920
+ function pickFromLocale(store, locale, keys) {
1921
+ return pickInMapOrder(store.fullMap(locale), store.fullMapIndex(locale), keys);
1922
+ }
1839
1923
  /**
1840
- * Generates a dictionary module for a locale by reading all dictionary namespace files,
1841
- * flattening them, and pre-resolving fallbacks against the default locale.
1924
+ * Builds one dictionary module from already-loaded locale maps and an
1925
+ * already-resolved ownership. Shared by {@link compileAll} and the public
1926
+ * {@link generateDictionaryModule} wrapper so both emit the same bytes.
1842
1927
  */
1843
- function generateDictionaryModule(localesDir, locale, defaultLocale, dictionaries, dictionaryName) {
1844
- const ownedKeys = resolveDictionaryOwnership(buildFullLocaleMap(localesDir, defaultLocale).keys(), dictionaries).dictionaryKeys.get(dictionaryName) ?? /* @__PURE__ */ new Set();
1845
- const localeMap = filterMap(buildFullLocaleMap(localesDir, locale), ownedKeys);
1846
- if (locale !== defaultLocale) return generateCompiledModule(preResolveFallbacks(localeMap, filterMap(buildFullLocaleMap(localesDir, defaultLocale), ownedKeys)));
1928
+ function generateDictionaryModuleFrom(store, ownership, locale, defaultLocale, dictionaryName) {
1929
+ const ownedKeys = ownership.dictionaryKeys.get(dictionaryName) ?? /* @__PURE__ */ new Set();
1930
+ const localeMap = pickFromLocale(store, locale, ownedKeys);
1931
+ if (locale !== defaultLocale) return generateCompiledModule(preResolveFallbacks(localeMap, pickFromLocale(store, defaultLocale, ownedKeys)));
1847
1932
  return generateCompiledModule(localeMap);
1848
1933
  }
1849
1934
  /**
@@ -1879,8 +1964,9 @@ function generateManifest(scopeIds, locales, dictionaryNames) {
1879
1964
  */
1880
1965
  function compileAll(analysis, options) {
1881
1966
  const { localesDir, locales, defaultLocale, outDir, dictionaries, crossNamespacePacking } = options;
1967
+ const store = localeStoreFor(localesDir, options.localeStore);
1882
1968
  fs.mkdirSync(outDir, { recursive: true });
1883
- const defaultFullMap = buildFullLocaleMap(localesDir, defaultLocale);
1969
+ const defaultFullMap = store.fullMap(defaultLocale);
1884
1970
  const ownership = resolveDictionaryOwnership(defaultFullMap.keys(), dictionaries);
1885
1971
  const scopePlans = buildScopePlans(analysis, defaultFullMap.keys(), { crossNamespacePacking });
1886
1972
  for (const plan of scopePlans) {
@@ -1889,11 +1975,17 @@ function compileAll(analysis, options) {
1889
1975
  if (ownership.keyOwner.has(key)) continue;
1890
1976
  usedKeys.add(key);
1891
1977
  }
1978
+ let defaultFiltered;
1892
1979
  for (const locale of locales) {
1893
1980
  const localeDir = path.join(outDir, locale);
1894
1981
  fs.mkdirSync(localeDir, { recursive: true });
1895
- const filtered = filterMap(buildFullLocaleMap(localesDir, locale), usedKeys);
1896
- const moduleSource = generateCompiledModule(locale !== defaultLocale ? preResolveFallbacks(filtered, filterMap(defaultFullMap, usedKeys)) : filtered);
1982
+ const filtered = pickFromLocale(store, locale, usedKeys);
1983
+ let resolved = filtered;
1984
+ if (locale !== defaultLocale) {
1985
+ defaultFiltered ??= pickFromLocale(store, defaultLocale, usedKeys);
1986
+ resolved = preResolveFallbacks(filtered, defaultFiltered);
1987
+ }
1988
+ const moduleSource = generateCompiledModule(resolved);
1897
1989
  fs.writeFileSync(path.join(localeDir, `${plan.scope}.js`), moduleSource);
1898
1990
  }
1899
1991
  }
@@ -1902,7 +1994,7 @@ function compileAll(analysis, options) {
1902
1994
  const dictDir = path.join(localeDir, "_dict");
1903
1995
  fs.mkdirSync(dictDir, { recursive: true });
1904
1996
  for (const dictionaryName of Object.keys(dictionaries)) {
1905
- const dictModule = generateDictionaryModule(localesDir, locale, defaultLocale, dictionaries, dictionaryName);
1997
+ const dictModule = generateDictionaryModuleFrom(store, ownership, locale, defaultLocale, dictionaryName);
1906
1998
  fs.writeFileSync(path.join(dictDir, `${dictionaryName}.js`), dictModule);
1907
1999
  }
1908
2000
  }
@@ -2267,6 +2359,6 @@ function formatDuration(ms) {
2267
2359
  return `${Math.round(ms / 864e5)}d`;
2268
2360
  }
2269
2361
  //#endregion
2270
- export { keyMatchesPattern as A, writeRuntimeConst as C, pruneNamespace as D, generateBundles as E, resolveDictionaryOwnership as M, buildScopePlans as O, runtimePathFromTypesPath as S, flattenKeys as T, extractKeys as _, runStrictExtraction as a, generateReports as b, applyDynamicKeys as c, resolveCacheConfig as d, CACHE_FILE_NAME as f, walkAll as g, resolveImport as h, assertNoStrictExtractionErrors as i, normalizeDictionaries as j, inferScopeNamespace as k, buildScopeMap as l, createExtractionCache as m, detectStaleness as n, writeStrictExtractionReport as o, computeConfigHash as p, writeBuildStamp as r, compileAll as s, computeAnalysisFingerprint as t, PLUGIN_VERSION as u, flattenLocaleKeys as v, writeTypes as w, generateTypes as x, generateDictionaryOwnershipReport as y };
2362
+ export { pruneNamespace as A, flattenToLeafValues as C, writeTypes as D, writeRuntimeConst as E, normalizeDictionaries as F, resolveDictionaryOwnership as I, buildScopePlans as M, inferScopeNamespace as N, flattenKeys as O, keyMatchesPattern as P, flattenToKeyPaths as S, runtimePathFromTypesPath as T, extractKeys as _, runStrictExtraction as a, generateReports as b, applyDynamicKeys as c, resolveCacheConfig as d, CACHE_FILE_NAME as f, walkAll as g, resolveImport as h, assertNoStrictExtractionErrors as i, createLocaleStore as j, generateBundles as k, buildScopeMap as l, createExtractionCache as m, detectStaleness as n, writeStrictExtractionReport as o, computeConfigHash as p, writeBuildStamp as r, compileAll as s, computeAnalysisFingerprint as t, PLUGIN_VERSION as u, flattenLocaleKeys as v, generateTypes as w, extractPlaceholders as x, generateDictionaryOwnershipReport as y };
2271
2363
 
2272
- //# sourceMappingURL=build-stamp-BvP03CCo.js.map
2364
+ //# sourceMappingURL=build-stamp-BgrEayAW.js.map