i18next-cli 1.88.0 → 1.89.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 (53) hide show
  1. package/README.md +62 -9
  2. package/dist/cjs/cli.js +18 -3
  3. package/dist/cjs/extractor/core/translation-manager.js +9 -2
  4. package/dist/cjs/extractor/parsers/expression-resolver.js +9 -0
  5. package/dist/cjs/index.js +2 -1
  6. package/dist/cjs/init.js +3 -11
  7. package/dist/cjs/instrumenter/core/instrumenter.js +1114 -209
  8. package/dist/cjs/instrumenter/core/key-generator.js +19 -9
  9. package/dist/cjs/instrumenter/core/string-detector.js +106 -29
  10. package/dist/cjs/instrumenter/core/transformer.js +89 -31
  11. package/dist/cjs/localize/agent-prompt.js +3 -2
  12. package/dist/cjs/localize/detect.js +2 -11
  13. package/dist/cjs/localize/localize.js +2 -1
  14. package/dist/cjs/utils/file-utils.js +48 -0
  15. package/dist/cjs/utils/jsx-attributes.js +3 -1
  16. package/dist/esm/cli.js +18 -3
  17. package/dist/esm/extractor/core/translation-manager.js +9 -2
  18. package/dist/esm/extractor/parsers/expression-resolver.js +9 -0
  19. package/dist/esm/index.js +2 -1
  20. package/dist/esm/init.js +3 -11
  21. package/dist/esm/instrumenter/core/instrumenter.js +1117 -212
  22. package/dist/esm/instrumenter/core/key-generator.js +19 -9
  23. package/dist/esm/instrumenter/core/string-detector.js +107 -31
  24. package/dist/esm/instrumenter/core/transformer.js +89 -31
  25. package/dist/esm/localize/agent-prompt.js +3 -2
  26. package/dist/esm/localize/detect.js +3 -12
  27. package/dist/esm/localize/localize.js +2 -1
  28. package/dist/esm/utils/file-utils.js +49 -2
  29. package/dist/esm/utils/jsx-attributes.js +3 -1
  30. package/package.json +1 -1
  31. package/types/cli.d.ts.map +1 -1
  32. package/types/extractor/core/translation-manager.d.ts.map +1 -1
  33. package/types/extractor/parsers/expression-resolver.d.ts.map +1 -1
  34. package/types/index.d.ts +1 -1
  35. package/types/index.d.ts.map +1 -1
  36. package/types/init.d.ts.map +1 -1
  37. package/types/instrumenter/core/instrumenter.d.ts.map +1 -1
  38. package/types/instrumenter/core/key-generator.d.ts +2 -0
  39. package/types/instrumenter/core/key-generator.d.ts.map +1 -1
  40. package/types/instrumenter/core/string-detector.d.ts +5 -1
  41. package/types/instrumenter/core/string-detector.d.ts.map +1 -1
  42. package/types/instrumenter/core/transformer.d.ts +10 -1
  43. package/types/instrumenter/core/transformer.d.ts.map +1 -1
  44. package/types/instrumenter/index.d.ts +1 -1
  45. package/types/instrumenter/index.d.ts.map +1 -1
  46. package/types/localize/agent-prompt.d.ts +3 -2
  47. package/types/localize/agent-prompt.d.ts.map +1 -1
  48. package/types/localize/detect.d.ts.map +1 -1
  49. package/types/types.d.ts +48 -1
  50. package/types/types.d.ts.map +1 -1
  51. package/types/utils/file-utils.d.ts +7 -0
  52. package/types/utils/file-utils.d.ts.map +1 -1
  53. package/types/utils/jsx-attributes.d.ts.map +1 -1
@@ -14,6 +14,8 @@ var logger = require('../../utils/logger.js');
14
14
  var jsxAttributes = require('../../utils/jsx-attributes.js');
15
15
  var astUtils = require('../../extractor/parsers/ast-utils.js');
16
16
  var fileUtils = require('../../utils/file-utils.js');
17
+ var keyFinder = require('../../extractor/core/key-finder.js');
18
+ var functionMatcher = require('../../extractor/utils/function-matcher.js');
17
19
  var messageFormat = require('../../utils/message-format.js');
18
20
 
19
21
  /**
@@ -41,6 +43,27 @@ async function runInstrumenter(config, options, logger$1 = new logger.ConsoleLog
41
43
  let totalSkipped = 0;
42
44
  let totalLanguageChanges = 0;
43
45
  let usesI18nextT = false;
46
+ // The same warning for many files is printed once, with the files below it
47
+ const warnings = new Map();
48
+ const warnFor = (where, message) => {
49
+ warnings.set(message, [...(warnings.get(message) ?? []), where]);
50
+ };
51
+ let moduleScopeTotal = 0;
52
+ // The code imports i18next before it is instrumented: it is set up already, here or in a shared package
53
+ let i18nextInUse = false;
54
+ // Keys the code uses already: a new text gets another key, unless it is the same text, and no new key is
55
+ // the parent of nested ones (`tenants` beside `tenants.title` is a nesting conflict at extract)
56
+ // Best effort, without plugins (their hooks are for extract): a file it cannot read reserves nothing
57
+ const separator = config.extract.keySeparator ?? '.';
58
+ const existingKeys = await keyFinder.findKeys({ ...config, plugins: [] }, { info() { }, warn() { }, error() { } })
59
+ .then(found => found.allKeys, () => new Map());
60
+ for (const { key, defaultValue } of existingKeys.values()) {
61
+ const parent = separator ? key.split(separator)[0] : key;
62
+ if (parent !== key)
63
+ keyRegistry.reserve(parent);
64
+ else
65
+ keyRegistry.reserve(key, defaultValue ?? key);
66
+ }
44
67
  // Detect framework and language
45
68
  const hasReact = await isProjectUsingReact();
46
69
  const hasTypeScript = await isProjectUsingTypeScript();
@@ -71,18 +94,22 @@ async function runInstrumenter(config, options, logger$1 = new logger.ConsoleLog
71
94
  if (loadResult === null)
72
95
  continue; // plugin says skip this file
73
96
  content = loadResult;
97
+ i18nextInUse ||= I18NEXT_IMPORT_RE.test(content);
74
98
  const scanResult = await scanFileForCandidates(content, file, config);
75
99
  let { candidates } = scanResult;
76
- const { components, languageChangeSites } = scanResult;
100
+ const { components, languageChangeSites, imports, memoHooks, pluralHelperImports } = scanResult;
77
101
  // Run instrumentOnResult plugin pipeline
78
102
  candidates = await runInstrumentOnResultPipeline(file, candidates, plugins, logger$1);
103
+ if (scanResult.ownTSkipped) {
104
+ totalCandidates += scanResult.ownTSkipped;
105
+ totalSkipped += scanResult.ownTSkipped;
106
+ warnFor(`${file} (${scanResult.ownTSkipped})`, 'Skipped the texts of components that declare a `t` of their own (not a translation function): rename it, then run instrument again.');
107
+ }
79
108
  if (scanResult.moduleScopeSkipped > 0) {
80
109
  totalCandidates += scanResult.moduleScopeSkipped;
81
110
  totalSkipped += scanResult.moduleScopeSkipped;
82
- logger$1.warn(`${file}: skipped ${scanResult.moduleScopeSkipped} module-scope string(s). ` +
83
- 'A t() call there runs once at import time — before i18next may be initialized — and never updates on language change. ' +
84
- 'Move the text into a component/hook (e.g. a useSections() hook calling useTranslation()), or read the key at render time. ' +
85
- 'See: https://www.locize.com/blog/how-to-use-i18next-t-outside-react-components/');
111
+ moduleScopeTotal += scanResult.moduleScopeSkipped;
112
+ warnFor(`${file} (${scanResult.moduleScopeSkipped})`, MODULE_SCOPE_WARNING);
86
113
  }
87
114
  if (candidates.length === 0 && languageChangeSites.length === 0) {
88
115
  continue;
@@ -107,7 +134,7 @@ async function runInstrumenter(config, options, logger$1 = new logger.ConsoleLog
107
134
  ]);
108
135
  switch (action) {
109
136
  case 'approve':
110
- candidate.key = keyGenerator.generateKeyFromContent(candidate.content);
137
+ candidate.key = keyRegistry.add(keyGenerator.generateKeyFromContent(keySourceOf(candidate)), candidate.content);
111
138
  break;
112
139
  case 'skip':
113
140
  candidate.skipReason = 'User skipped';
@@ -118,10 +145,11 @@ async function runInstrumenter(config, options, logger$1 = new logger.ConsoleLog
118
145
  type: 'input',
119
146
  name: 'key',
120
147
  message: 'New key:',
121
- default: keyGenerator.generateKeyFromContent(candidate.content)
148
+ default: keyGenerator.generateKeyFromContent(keySourceOf(candidate))
122
149
  }
123
150
  ]);
124
151
  candidate.key = key;
152
+ keyRegistry.reserve(key, candidate.content);
125
153
  break;
126
154
  }
127
155
  case 'edit-value': {
@@ -134,7 +162,7 @@ async function runInstrumenter(config, options, logger$1 = new logger.ConsoleLog
134
162
  }
135
163
  ]);
136
164
  candidate.content = value;
137
- candidate.key = keyGenerator.generateKeyFromContent(value);
165
+ candidate.key = keyRegistry.add(keyGenerator.generateKeyFromContent(value), value);
138
166
  break;
139
167
  }
140
168
  }
@@ -146,7 +174,7 @@ async function runInstrumenter(config, options, logger$1 = new logger.ConsoleLog
146
174
  // Generate keys for approved candidates
147
175
  for (const candidate of approvedCandidates) {
148
176
  if (!candidate.key) {
149
- candidate.key = keyRegistry.add(keyGenerator.generateKeyFromContent(candidate.content), candidate.content);
177
+ candidate.key = keyRegistry.add(keyGenerator.generateKeyFromContent(keySourceOf(candidate)), candidate.content);
150
178
  }
151
179
  }
152
180
  // After key generation, so ICU/MF2 syntax does not end up in generated keys
@@ -160,7 +188,10 @@ async function runInstrumenter(config, options, logger$1 = new logger.ConsoleLog
160
188
  config,
161
189
  components,
162
190
  namespace: targetNamespace,
163
- languageChangeSites
191
+ languageChangeSites,
192
+ imports,
193
+ memoHooks,
194
+ pluralHelperImports
164
195
  });
165
196
  if (!options.isDryRun && transformResult.modified) {
166
197
  // Write the transformed file
@@ -174,16 +205,15 @@ async function runInstrumenter(config, options, logger$1 = new logger.ConsoleLog
174
205
  if (!usesI18nextT && approvedCandidates.some(c => !c.insideComponent && c.confidence >= 0.7)) {
175
206
  usesI18nextT = true;
176
207
  }
177
- // Log any warnings (e.g. i18next.t() in React files)
178
- if (transformResult.warnings?.length) {
179
- for (const warning of transformResult.warnings) {
180
- logger$1.warn(warning);
181
- }
208
+ // Collect warnings (e.g. i18next.t() in React files) and candidates that could not be rewritten
209
+ for (const warning of [...(transformResult.warnings ?? []), ...transformResult.errors]) {
210
+ warnFor(file, warning.startsWith(`${file}: `) ? warning.slice(file.length + 2) : warning);
182
211
  }
183
212
  results.push({
184
213
  file,
185
214
  candidates: approvedCandidates,
186
- result: transformResult
215
+ result: transformResult,
216
+ languageChangeSites
187
217
  });
188
218
  }
189
219
  else {
@@ -196,8 +226,15 @@ async function runInstrumenter(config, options, logger$1 = new logger.ConsoleLog
196
226
  }
197
227
  const langChangeSuffix = totalLanguageChanges > 0 ? `, ${totalLanguageChanges} language-change site(s)` : '';
198
228
  spinner.succeed(node_util.styleText('bold', `Scanned complete: ${totalCandidates} candidates, ${totalTransformed} approved${langChangeSuffix}`));
229
+ for (const [message, where] of warnings) {
230
+ const head = message === MODULE_SCOPE_WARNING ? `Skipped ${moduleScopeTotal} module-scope string(s). ${message}` : message;
231
+ logger$1.warn(`${head}\n${where.map(w => ` ${w}`).join('\n')}`);
232
+ }
199
233
  // Generate i18n init file if needed and any transformations were made
200
- if ((totalTransformed > 0 || totalLanguageChanges > 0) && !options.isDryRun) {
234
+ if ((totalTransformed > 0 || totalLanguageChanges > 0) && !options.isDryRun && i18nextInUse) {
235
+ logger$1.info('Your code imports i18next already, so it is set up somewhere: no i18n init file generated.');
236
+ }
237
+ if ((totalTransformed > 0 || totalLanguageChanges > 0) && !options.isDryRun && !i18nextInUse) {
201
238
  const initFilePath = await ensureI18nInitFile(hasReact, hasTypeScript, config, logger$1, usesI18nextT);
202
239
  if (initFilePath) {
203
240
  await injectI18nImportIntoEntryFile(initFilePath, logger$1);
@@ -218,6 +255,15 @@ async function runInstrumenter(config, options, logger$1 = new logger.ConsoleLog
218
255
  throw error;
219
256
  }
220
257
  }
258
+ /** The text a key is made from: a <Trans> candidate's words, not its JSX source (`<a href=…>`). */
259
+ function keySourceOf(candidate) {
260
+ return candidate.transValue?.replace(/<\/?\d+>/g, '') ?? candidate.content;
261
+ }
262
+ /** An import of i18next or react-i18next (`.init()` alone is any library's: `Sentry.init()`). */
263
+ const I18NEXT_IMPORT_RE = /\bfrom\s*['"](?:i18next|react-i18next)['"]|\brequire\(\s*['"](?:i18next|react-i18next)['"]\s*\)/;
264
+ const MODULE_SCOPE_WARNING = 'A t() call there runs once at import time — before i18next may be initialized — and never updates on language change. ' +
265
+ 'Move the text into a component/hook (e.g. a useSections() hook calling useTranslation()), or read the key at render time. ' +
266
+ 'See: https://www.locize.com/blog/how-to-use-i18next-t-outside-react-components/';
221
267
  /**
222
268
  * Scans a source file for hardcoded string candidates and React component boundaries.
223
269
  */
@@ -226,6 +272,10 @@ async function scanFileForCandidates(content, file, config) {
226
272
  const components = [];
227
273
  const languageChangeSites = [];
228
274
  let moduleScopeSkipped = 0;
275
+ let ownTSkipped = 0;
276
+ let imports;
277
+ const memoHooks = [];
278
+ let pluralHelperImports;
229
279
  const fileExt = node_path.extname(file).toLowerCase();
230
280
  const isTypeScriptFile = ['.ts', '.tsx', '.mts', '.cts'].includes(fileExt);
231
281
  const isTSX = fileExt === '.tsx';
@@ -273,6 +323,15 @@ async function scanFileForCandidates(content, file, config) {
273
323
  // indices — without the conversion every emoji / accented char / CJK char
274
324
  // shifts all subsequent offsets.
275
325
  astUtils.normalizeSpansToCharIndices(ast, content);
326
+ imports = ast.body
327
+ .filter((item) => item.type === 'ImportDeclaration')
328
+ .map((item) => ({
329
+ source: item.source.value,
330
+ start: item.span.start,
331
+ end: item.span.end,
332
+ locals: (item.specifiers ?? []).map((spec) => spec.local?.value).filter(Boolean)
333
+ }));
334
+ collectMemoHooks(ast, memoHooks);
276
335
  // Detect React function component boundaries
277
336
  detectComponentBoundaries(ast, content, components);
278
337
  // Collect function spans so module-scope strings can be excluded below
@@ -284,11 +343,19 @@ async function scanFileForCandidates(content, file, config) {
284
343
  const jsx = attributeRules && !Array.isArray(attributeRules)
285
344
  ? { rules: attributeRules, aliases: jsxAttributes.importAliases(ast) }
286
345
  : undefined;
287
- visitNodeForStrings(ast, content, file, config, candidates, jsx);
288
- // Detect JSX interpolation patterns (merge adjacent text + expression children)
289
- detectJSXInterpolation(ast, content, file, config, candidates);
290
- // Detect plural conditional patterns (ternary chains checking count === 0/1/other)
291
- detectPluralPatterns(ast, content, file, config, candidates);
346
+ consoleOnlyNames.set(file, collectConsoleOnlyNames(ast));
347
+ fileDataStrings.set(file, collectDataStrings(ast));
348
+ try {
349
+ visitNodeForStrings(ast, content, file, config, candidates, jsx);
350
+ // Detect JSX interpolation patterns (merge adjacent text + expression children)
351
+ detectJSXInterpolation(ast, content, file, config, candidates);
352
+ // Detect plural conditional patterns (ternary chains checking count === 0/1/other)
353
+ detectPluralPatterns(ast, content, file, config, candidates);
354
+ }
355
+ finally {
356
+ consoleOnlyNames.delete(file);
357
+ fileDataStrings.delete(file);
358
+ }
292
359
  // Detect language-change call sites (e.g. updateSettings({ language: code }))
293
360
  detectLanguageChangeSites(ast, content, languageChangeSites);
294
361
  // Annotate candidates with their enclosing component (if any)
@@ -300,6 +367,15 @@ async function scanFileForCandidates(content, file, config) {
300
367
  }
301
368
  }
302
369
  }
370
+ // A component whose `t` is something else (`const [t, setT] = useState(0)`) keeps its texts: a t() call
371
+ // there would call that `t`
372
+ const ownT = new Set(components.filter(c => c.ownT).map(c => c.name));
373
+ if (ownT.size) {
374
+ const keep = candidates.filter(c => !c.insideComponent || !ownT.has(c.insideComponent));
375
+ ownTSkipped = candidates.length - keep.length;
376
+ candidates.length = 0;
377
+ candidates.push(...keep);
378
+ }
303
379
  // Drop module-scope candidates: wrapping them yields a t() call evaluated
304
380
  // once at import time — possibly before i18next is initialized, and never
305
381
  // re-evaluated on language change. See issue #278.
@@ -339,11 +415,27 @@ async function scanFileForCandidates(content, file, config) {
339
415
  candidates.length = 0;
340
416
  candidates.push(...keep);
341
417
  }
418
+ const helperNames = new Set(candidates.map(c => c.pluralHelper).filter((n) => !!n));
419
+ if (helperNames.size)
420
+ pluralHelperImports = findPluralHelperImports(ast, content, helperNames);
421
+ // Two candidates whose spans overlap cannot both be rewritten (a template literal in another one's `${}`):
422
+ // the outer one wins, the inner text stays in its interpolation value as written
423
+ const bySize = [...candidates].sort((a, b) => (b.endOffset - b.offset) - (a.endOffset - a.offset));
424
+ const kept = new Set();
425
+ for (const c of bySize) {
426
+ if (![...kept].some(k => c.offset < k.endOffset && k.offset < c.endOffset))
427
+ kept.add(c);
428
+ }
429
+ if (kept.size < candidates.length) {
430
+ const keep = candidates.filter(c => kept.has(c));
431
+ candidates.length = 0;
432
+ candidates.push(...keep);
433
+ }
342
434
  }
343
435
  catch (err) {
344
436
  // Silently skip files that can't be parsed
345
437
  }
346
- return { candidates, components, languageChangeSites, moduleScopeSkipped };
438
+ return { candidates, components, languageChangeSites, moduleScopeSkipped, ownTSkipped, imports, memoHooks, pluralHelperImports };
347
439
  }
348
440
  /**
349
441
  * Node types whose span delimits deferred (call-time) evaluation. A string
@@ -417,7 +509,7 @@ function detectComponentBoundaries(node, content, components) {
417
509
  name: node.identifier.value,
418
510
  bodyStart: body.span.start,
419
511
  bodyEnd: body.span.end,
420
- hasUseTranslation: content.slice(body.span.start, body.span.end).includes('useTranslation')
512
+ ...tBinding(node, body)
421
513
  });
422
514
  }
423
515
  }
@@ -435,7 +527,7 @@ function detectComponentBoundaries(node, content, components) {
435
527
  name: node.identifier.value,
436
528
  bodyStart: body.span.start,
437
529
  bodyEnd: body.span.end,
438
- hasUseTranslation: content.slice(body.span.start, body.span.end).includes('useTranslation')
530
+ ...tBinding(node, body)
439
531
  });
440
532
  }
441
533
  }
@@ -492,14 +584,74 @@ function isBlockBody(body) {
492
584
  */
493
585
  function addComponentFromFunctionNode(name, fnNode, content, components) {
494
586
  const body = fnNode.body;
495
- if (body?.type === 'BlockStatement' && body.span) {
587
+ if (isBlockBody(body) && body.span) {
496
588
  components.push({
497
589
  name,
498
590
  bodyStart: body.span.start,
499
591
  bodyEnd: body.span.end,
500
- hasUseTranslation: content.slice(body.span.start, body.span.end).includes('useTranslation')
592
+ ...tBinding(fnNode, body)
501
593
  });
502
594
  }
595
+ else if (isJSXExpression(body) && body.span) {
596
+ // `const Hint = () => <p>…</p>`: a component too; its body becomes a block when it needs the hook
597
+ components.push({
598
+ name,
599
+ bodyStart: body.span.start,
600
+ bodyEnd: body.span.end,
601
+ ...tBinding(fnNode, {}),
602
+ expressionBody: true
603
+ });
604
+ }
605
+ }
606
+ /** JSX, possibly in parentheses. */
607
+ function isJSXExpression(expr) {
608
+ if (expr?.type === 'ParenthesisExpression')
609
+ return isJSXExpression(expr.expression);
610
+ return expr?.type === 'JSXElement' || expr?.type === 'JSXFragment';
611
+ }
612
+ /**
613
+ * The `t` a component has already: `'translation'` for a parameter (`({ t })`, a prop passed down) or one
614
+ * destructured from a translation hook (`const { t } = useTranslation('ns')`, also re-exported or renamed:
615
+ * `useT`, `useAppTranslation`, `getTranslations`), `'other'` for any other `t` in its body
616
+ * (`const [t, setT] = useState(0)`), null for none. Another `const { t }` would be a redeclaration, and the
617
+ * `t()` calls would call the other `t`.
618
+ */
619
+ function bindsT(fnNode, body) {
620
+ if ((fnNode.params ?? []).some((p) => patternBinds(p, 't')))
621
+ return 'translation';
622
+ for (const stmt of body.stmts ?? []) {
623
+ if (stmt.type === 'FunctionDeclaration' && stmt.identifier?.value === 't')
624
+ return 'other';
625
+ for (const d of stmt.type === 'VariableDeclaration' ? stmt.declarations ?? [] : []) {
626
+ if (!patternBinds(d.id, 't'))
627
+ continue;
628
+ const call = d.init?.type === 'AwaitExpression' ? d.init.argument : d.init;
629
+ const hook = call?.type === 'CallExpression' ? dottedName(call.callee)?.split('.').pop() : null;
630
+ return d.id.type === 'ObjectPattern' && hook && TRANSLATION_HOOK_RE.test(hook) ? 'translation' : 'other';
631
+ }
632
+ }
633
+ return null;
634
+ }
635
+ /** Names of the hooks and functions that give a translation `t`. */
636
+ const TRANSLATION_HOOK_RE = /^(?:use|get)\w*(?:Translation|T|I18n|Intl)\w*$/;
637
+ /** A component's `hasUseTranslation`, and `ownT` when its `t` is something else (see `bindsT`). */
638
+ function tBinding(fnNode, body) {
639
+ const kind = bindsT(fnNode, body);
640
+ return kind === 'other' ? { hasUseTranslation: true, ownT: true } : { hasUseTranslation: kind === 'translation' };
641
+ }
642
+ /** Whether a binding pattern (a parameter, a destructuring) binds `name`; defaults and renamed keys aside. */
643
+ function patternBinds(pat, name) {
644
+ switch (pat?.type) {
645
+ case 'Identifier': return pat.value === name;
646
+ case 'Parameter': return patternBinds(pat.pat, name);
647
+ case 'AssignmentPattern': return patternBinds(pat.left, name);
648
+ case 'RestElement': return patternBinds(pat.argument, name);
649
+ case 'ArrayPattern': return (pat.elements ?? []).some((e) => patternBinds(e, name));
650
+ case 'ObjectPattern': return (pat.properties ?? []).some((p) => p.type === 'KeyValuePatternProperty'
651
+ ? patternBinds(p.value, name)
652
+ : p.type === 'AssignmentPatternProperty' ? p.key?.value === name : patternBinds(p.argument, name));
653
+ default: return false;
654
+ }
503
655
  }
504
656
  // Non-translatable JSX attributes are defined in utils/jsx-attributes.ts
505
657
  // and shared with the linter. The instrumenter uses `ignoredAttributeSet`
@@ -508,22 +660,183 @@ function addComponentFromFunctionNode(name, fnNode, content, components) {
508
660
  * Returns true when the AST node is a `t(...)` or `i18next.t(...)` call
509
661
  * expression — i.e. code that was already instrumented.
510
662
  */
511
- function isTranslationCall(node) {
663
+ function isTranslationCall(node, functions = []) {
664
+ const name = dottedName(node.callee);
665
+ if (!name)
666
+ return false;
667
+ // t(...), $t(...), i18next.t(...), props.t(...), this.$t(...), and the project's own (`extract.functions`)
668
+ return name === 't' || name === '$t' || /\.\$?t$/.test(name) || functions.some(fn => functionMatcher.matchesFunctionPattern(name, fn));
669
+ }
670
+ /** A callee as a dotted name (`this.props.t`, `i18n.t`), or null for a computed one. */
671
+ function dottedName(callee) {
672
+ if (callee?.type === 'Identifier')
673
+ return callee.value;
674
+ if (callee?.type === 'ThisExpression')
675
+ return 'this';
676
+ if (callee?.type !== 'MemberExpression' || callee.property?.type !== 'Identifier')
677
+ return null;
678
+ const object = dottedName(callee.object);
679
+ return object && `${object}.${callee.property.value}`;
680
+ }
681
+ /**
682
+ * Methods whose string arguments are never text shown to a user: selectors, attribute and storage names,
683
+ * and the strings a text is searched for or compared with (translating `msg.includes('not found')` breaks it).
684
+ */
685
+ const NON_TEXT_METHODS = new Set([
686
+ 'querySelector', 'querySelectorAll', 'closest', 'matches', 'getElementById', 'getElementsByClassName',
687
+ 'getElementsByTagName', 'getElementsByName', 'addEventListener', 'removeEventListener',
688
+ 'getAttribute', 'hasAttribute', 'removeAttribute', 'getPropertyValue', 'setProperty', 'removeProperty',
689
+ 'getItem', 'setItem', 'removeItem',
690
+ // analytics event and user names: a translated one splits the data by language
691
+ 'track', 'trackEvent', 'logEvent', 'capture', 'captureMessage', 'captureException', 'identify',
692
+ // event names, and format patterns (`dayjs(d).format('DD MMM YYYY')`)
693
+ 'emit', 'on', 'once', 'off', 'addListener', 'removeListener', 'format',
694
+ 'indexOf', 'lastIndexOf', 'includes', 'startsWith', 'endsWith', 'match', 'matchAll', 'search', 'replace',
695
+ 'replaceAll', 'split', 'localeCompare'
696
+ ]);
697
+ /**
698
+ * Functions whose string arguments are never text: `gtag('event', 'Sign Up Completed')`, `require('x')`,
699
+ * `RegExp('…')`, `format(date, 'yyyy-MM-dd')`.
700
+ */
701
+ const NON_TEXT_FUNCTIONS = new Set(['gtag', 'require', 'RegExp', 'format']);
702
+ /** Objects whose method calls are logs or error reports, for developers whatever they say. */
703
+ const LOG_OBJECTS = /^(?:logger|log|Sentry|sentry|Bugsnag|bugsnag|Rollbar|rollbar|winston|pino)$/;
704
+ /** A call to one of `NON_TEXT_METHODS` or `NON_TEXT_FUNCTIONS` (`el.closest('button, a')`, `gtag(…)`). */
705
+ function isNonTextMethodCall(node) {
512
706
  const callee = node.callee;
513
- if (!callee)
707
+ if (callee?.type === 'Identifier')
708
+ return NON_TEXT_FUNCTIONS.has(callee.value);
709
+ if (callee?.type !== 'MemberExpression' || callee.property?.type !== 'Identifier')
514
710
  return false;
515
- // t(...)
516
- if (callee.type === 'Identifier' && callee.value === 't')
517
- return true;
518
- // i18next.t(...)
519
- if (callee.type === 'MemberExpression' &&
520
- !callee.computed &&
521
- callee.property?.type === 'Identifier' &&
522
- callee.property.value === 't' &&
523
- callee.object?.type === 'Identifier' &&
524
- callee.object.value === 'i18next')
525
- return true;
526
- return false;
711
+ return NON_TEXT_METHODS.has(callee.property.value) || (callee.object?.type === 'Identifier' && LOG_OBJECTS.test(callee.object.value));
712
+ }
713
+ /**
714
+ * The names of a file's variables whose every use is inside a `console.*` call: a variable declared twice
715
+ * counts as one name, and any use elsewhere takes it out.
716
+ */
717
+ function collectConsoleOnlyNames(ast) {
718
+ const declared = new Set();
719
+ const inConsole = new Set();
720
+ const elsewhere = new Set();
721
+ const walk = (node, inLog) => {
722
+ if (!node || typeof node !== 'object')
723
+ return;
724
+ if (Array.isArray(node)) {
725
+ node.forEach(n => walk(n, inLog));
726
+ return;
727
+ }
728
+ if (node.type === 'VariableDeclarator') {
729
+ if (node.id?.type === 'Identifier')
730
+ declared.add(node.id.value);
731
+ else
732
+ walk(node.id, inLog);
733
+ walk(node.init, inLog);
734
+ return;
735
+ }
736
+ if (node.type === 'MemberExpression') {
737
+ walk(node.object, inLog);
738
+ if (node.property?.type === 'Computed')
739
+ walk(node.property, inLog);
740
+ return;
741
+ }
742
+ if (node.type === 'KeyValueProperty') {
743
+ walk(node.value, inLog);
744
+ return;
745
+ }
746
+ if (node.type === 'Identifier')
747
+ (inLog ? inConsole : elsewhere).add(node.value);
748
+ const log = inLog || (node.type === 'CallExpression' && isConsoleCall(node));
749
+ for (const key in node)
750
+ if (key !== 'span')
751
+ walk(node[key], log);
752
+ };
753
+ walk(ast, false);
754
+ return new Set([...declared].filter(n => inConsole.has(n) && !elsewhere.has(n)));
755
+ }
756
+ /** Per file, the names `collectConsoleOnlyNames` found for its content (set by the scan, read by the visit). */
757
+ const consoleOnlyNames = new Map();
758
+ /** The property names whose value is text (`label`, `title`, …), lower-cased. */
759
+ const translatablePropertyLowerSet = new Set([...jsxAttributes.translatablePropertySet].map(p => p.toLowerCase()));
760
+ /** String literals a JSX element renders (see `markRendered`): text whatever their words. */
761
+ const renderedStrings = new WeakSet();
762
+ /** Marks the strings an expression rendered as a JSX child can produce: itself, a branch, a fallback. */
763
+ function markRendered(expr) {
764
+ if (!expr)
765
+ return;
766
+ if (expr.type === 'StringLiteral')
767
+ renderedStrings.add(expr);
768
+ else if (expr.type === 'ConditionalExpression') {
769
+ markRendered(expr.consequent);
770
+ markRendered(expr.alternate);
771
+ }
772
+ else if (expr.type === 'BinaryExpression' && LOGICAL_OPERATORS.has(expr.operator)) {
773
+ // swc types `&&`, `||` and `??` as a BinaryExpression
774
+ markRendered(expr.right);
775
+ }
776
+ else if (expr.type === 'ParenthesisExpression')
777
+ markRendered(expr.expression);
778
+ }
779
+ /** Per file, the strings `collectDataStrings` found (set by the scan, read by the visit). */
780
+ const fileDataStrings = new Map();
781
+ /** Property and attribute names whose string value is data the code matches against. */
782
+ const DATA_KEYS = new Set(['id', 'key', 'value', 'type', 'code', 'kind']);
783
+ /** Names of lists whose strings are values to match (`order: ['2FA', 'no 2FA']`). */
784
+ const DATA_LISTS = /^(?:order|ids|keys|values|types|kinds|codes)$/i;
785
+ /**
786
+ * The strings a file uses as data: compared (`=== 'no 2FA'`), a `case`, an object key, the value of an `id`,
787
+ * `key`, `value`, `type`, `code` or `kind`, an entry of an `order`/`ids`/`values` list, or an argument of a
788
+ * method that compares (`includes`). The same string as text elsewhere in that file is then data too: a
789
+ * facet's `of()` returning `'no 2FA'` must keep matching `order: ['2FA', 'no 2FA']`.
790
+ */
791
+ function collectDataStrings(ast) {
792
+ const found = new Set();
793
+ const add = (node) => { if (node?.type === 'StringLiteral')
794
+ found.add(node.value); };
795
+ const addList = (node) => { if (node?.type === 'ArrayExpression')
796
+ for (const e of node.elements ?? [])
797
+ add(e?.expression); };
798
+ const walk = (node) => {
799
+ if (!node || typeof node !== 'object')
800
+ return;
801
+ if (Array.isArray(node)) {
802
+ node.forEach(walk);
803
+ return;
804
+ }
805
+ if (node.type === 'BinaryExpression' && COMPARISON_OPERATORS.has(node.operator)) {
806
+ add(node.left);
807
+ add(node.right);
808
+ }
809
+ if (node.type === 'SwitchCase')
810
+ add(node.test);
811
+ if (node.type === 'KeyValueProperty') {
812
+ add(node.key);
813
+ const name = propertyName(node.key);
814
+ if (name && DATA_KEYS.has(name))
815
+ add(node.value);
816
+ if (name && DATA_LISTS.test(name))
817
+ addList(node.value);
818
+ }
819
+ if (node.type === 'VariableDeclarator' && DATA_LISTS.test(node.id?.value ?? ''))
820
+ addList(node.init);
821
+ if (node.type === 'JSXAttribute' && DATA_KEYS.has(node.name?.value) && node.value?.type === 'StringLiteral')
822
+ add(node.value);
823
+ if (node.type === 'CallExpression' && isNonTextMethodCall(node)) {
824
+ for (const arg of node.arguments ?? [])
825
+ add(arg.expression);
826
+ if (node.callee?.type === 'MemberExpression')
827
+ addList(node.callee.object);
828
+ }
829
+ for (const key in node)
830
+ if (key !== 'span')
831
+ walk(node[key]);
832
+ };
833
+ walk(ast);
834
+ return found;
835
+ }
836
+ /** `console.log(...)`, `console.warn(...)`: their arguments are for developers, however they are built. */
837
+ function isConsoleCall(node) {
838
+ const callee = node.callee;
839
+ return callee?.type === 'MemberExpression' && callee.object?.type === 'Identifier' && callee.object.value === 'console';
527
840
  }
528
841
  /**
529
842
  * Recursively visits AST nodes to find string literals.
@@ -536,14 +849,22 @@ function visitNodeForStrings(node, content, file, config, candidates, jsx) {
536
849
  if (node.type === 'JSXOpeningElement' && jsx) {
537
850
  jsx = { ...jsx, element: jsxAttributes.resolveElementAttributes(jsx.rules, jsxAttributes.jsxElementName(node.name, jsx.aliases)) };
538
851
  }
539
- // Skip already-instrumented t() / i18next.t() calls entirely so that
540
- // strings inside the options object (defaultValue_one, etc.) are not
541
- // picked up as new candidates on a second run.
542
- if (node.type === 'CallExpression' && isTranslationCall(node))
852
+ const visit = (child) => visitNodeForStrings(child, content, file, config, candidates, jsx);
853
+ // Its string arguments are not text; what it is called on and the functions it gets may hold some
854
+ // (`el.addEventListener('click', () => { status.textContent = 'Copied to clipboard' })`)
855
+ if (node.type === 'CallExpression' && isNonTextMethodCall(node)) {
856
+ visit(node.callee);
857
+ for (const arg of node.arguments ?? [])
858
+ visitTextHolders(arg.expression, content, file, config, candidates, jsx);
543
859
  return;
544
- // Skip <Trans> elements (already instrumented)
545
- if (node.type === 'JSXElement' && isTransComponent(node))
860
+ }
861
+ const parts = nonTextParts(node, file, config, true);
862
+ if (parts === 'all')
863
+ return;
864
+ if (parts) {
865
+ forEachChild(node, parts, visit);
546
866
  return;
867
+ }
547
868
  // Skip non-translatable JSX attributes entirely (e.g. className={...})
548
869
  if (node.type === 'JSXAttribute') {
549
870
  const nameNode = node.name;
@@ -557,31 +878,47 @@ function visitNodeForStrings(node, content, file, config, candidates, jsx) {
557
878
  }
558
879
  // A rule that adds an attribute on this element wins over the built-in skip list (e.g. `name`)
559
880
  const added = attrName != null && jsx?.element?.accepted.has(attrName.toLowerCase());
560
- if (attrName && jsxAttributes.ignoredAttributeSet.has(attrName) && !added)
561
- return;
562
- // A rule removed this attribute on this element: its value is not text, skip it entirely
563
- if (attrName && jsx?.element?.removed.has(attrName.toLowerCase()))
881
+ // The value of an ignored attribute, or one a rule removed on this element, is not text; but the
882
+ // elements and functions in it hold text as anywhere else (`action={<Button>change</Button>}`,
883
+ // `onClick={() => setMessage('Copied')}`)
884
+ const notText = !!attrName && ((jsxAttributes.ignoredAttributeSet.has(attrName) && !added) ||
885
+ !!jsx?.element?.removed.has(attrName.toLowerCase()) ||
886
+ // For hyphenated names (data-testid), also check with the raw text
887
+ (attrName.includes(':') && jsxAttributes.ignoredAttributeSet.has(attrName.replace(':', '-'))));
888
+ if (notText) {
889
+ visitTextHolders(node.value, content, file, config, candidates, jsx);
564
890
  return;
565
- // For hyphenated names (data-testid), also check with the raw text
566
- if (attrName?.includes(':')) {
567
- const hyphenated = attrName.replace(':', '-');
568
- if (jsxAttributes.ignoredAttributeSet.has(hyphenated))
569
- return;
570
891
  }
571
892
  }
893
+ // What a JSX element renders from an expression is text, a single word too: `{used ? <>…</> : 'Never used'}`,
894
+ // `{busy && 'saving'}`, `{name || 'the organization'}`
895
+ if (node.type === 'JSXElement' || node.type === 'JSXFragment') {
896
+ for (const child of node.children ?? [])
897
+ if (child.type === 'JSXExpressionContainer')
898
+ markRendered(child.expression);
899
+ }
900
+ // The two branches of a ternary are alternatives of one text: when one is text, a string on the other side
901
+ // is too (`running ? 'Confirm all reviews' : 'stop'`, `n ? \`Pay invoice ${n}\` : 'Pay invoice'`)
902
+ if (node.type === 'ConditionalExpression') {
903
+ visit(node.test);
904
+ visit(node.consequent);
905
+ visit(node.alternate);
906
+ const branches = [node.consequent, node.alternate];
907
+ const found = (b) => candidates.some(c => c.offset === b?.span?.start && c.endOffset === b?.span?.end);
908
+ branches.forEach((b, i) => {
909
+ if (b?.type !== 'StringLiteral' || found(b) || !found(branches[1 - i]))
910
+ return;
911
+ const candidate = stringCandidate(b, content, file, config, jsx?.element?.accepted, true);
912
+ if (candidate)
913
+ candidates.push(candidate);
914
+ });
915
+ return;
916
+ }
572
917
  // Check if this is a string literal
573
918
  if (node.type === 'StringLiteral') {
574
- const stringNode = node;
575
- if (stringNode.span && typeof stringNode.span.start === 'number') {
576
- const candidate = stringDetector.detectCandidate(stringNode.value, stringNode.span.start, stringNode.span.end, file, content, config, jsx?.element?.accepted);
577
- if (candidate && candidate.confidence >= 0.7) {
578
- // Detect JSX attribute context: in JSX, attr="value" has = right before the opening quote
579
- if (stringNode.span.start > 0 && content[stringNode.span.start - 1] === '=') {
580
- candidate.type = 'jsx-attribute';
581
- }
582
- candidates.push(candidate);
583
- }
584
- }
919
+ const candidate = stringCandidate(node, content, file, config, jsx?.element?.accepted, renderedStrings.has(node));
920
+ if (candidate)
921
+ candidates.push(candidate);
585
922
  }
586
923
  // Template literals
587
924
  if (node.type === 'TemplateLiteral') {
@@ -603,18 +940,26 @@ function visitNodeForStrings(node, content, file, config, candidates, jsx) {
603
940
  }
604
941
  }
605
942
  else if (quasis?.length > 1 && expressions?.length > 0 && node.span) {
606
- // Template literal with interpolation, e.g. `${count}-day streak`
607
- const result = buildInterpolatedTemplate(quasis, expressions, content);
608
- if (result) {
943
+ // Template literal with interpolation, e.g. `${count}-day streak`, possibly with a plural in it
944
+ const plural = buildPluralTemplate(quasis, expressions, content);
945
+ const result = plural
946
+ ? { text: plural.pluralForms.other, interpolations: plural.interpolations }
947
+ : buildInterpolatedTemplate(quasis, expressions, content);
948
+ if (result && hasWordsBesidePlaceholders(result.text)) {
609
949
  const trimmed = result.text.trim();
610
950
  if (trimmed) {
611
951
  const candidate = stringDetector.detectCandidate(trimmed, node.span.start, node.span.end, file, content, config);
612
952
  if (candidate) {
613
953
  candidate.content = trimmed;
614
954
  candidate.type = 'template-literal';
615
- candidate.interpolations = result.interpolations;
616
- // Template literals mixing text + expressions are likely user-facing
617
- candidate.confidence = Math.min(1, candidate.confidence + 0.15);
955
+ if (result.interpolations.length)
956
+ candidate.interpolations = result.interpolations;
957
+ if (plural) {
958
+ candidate.pluralForms = plural.pluralForms;
959
+ candidate.pluralHelper = plural.pluralHelper;
960
+ }
961
+ // Template literals mixing text + expressions are likely user-facing, plurals always
962
+ candidate.confidence = Math.min(1, candidate.confidence + (plural ? 0.3 : 0.15));
618
963
  if (node.span.start > 0 && content[node.span.start - 1] === '=') {
619
964
  candidate.type = 'jsx-attribute';
620
965
  }
@@ -635,7 +980,7 @@ function visitNodeForStrings(node, content, file, config, candidates, jsx) {
635
980
  const trimmedStart = raw.indexOf(trimmed);
636
981
  const offset = node.span.start + trimmedStart;
637
982
  const endOffset = offset + trimmed.length;
638
- const candidate = stringDetector.detectCandidate(trimmed, offset, endOffset, file, content, config);
983
+ const candidate = stringDetector.detectCandidate(jsxTextValue(trimmed), offset, endOffset, file, content, config, undefined, true);
639
984
  if (candidate) {
640
985
  candidate.type = 'jsx-text';
641
986
  // JSXText is almost always user-visible content; boost confidence
@@ -660,6 +1005,183 @@ function visitNodeForStrings(node, content, file, config, candidates, jsx) {
660
1005
  }
661
1006
  }
662
1007
  }
1008
+ /**
1009
+ * Whether a name says it holds a language model's input: a function or variable (not a component) whose
1010
+ * camelCase words include `prompt` and one of system, user, ai, llm, gpt, assistant, chat, model
1011
+ * (`getSystemPrompt`, `aiFixPrompt`, `userPromptBatch`). A bare `prompt` may ask the user something
1012
+ * (`deletePrompt`), and `EmailPrompt` or `UserPromptDialog` are components.
1013
+ */
1014
+ function isModelPromptName(name) {
1015
+ if (!name || !/^[a-z]/.test(name))
1016
+ return false;
1017
+ const words = name.split(/(?=[A-Z])|_/).map(w => w.toLowerCase());
1018
+ return words.includes('prompt') && words.some(w => MODEL_WORDS.has(w));
1019
+ }
1020
+ const MODEL_WORDS = new Set(['system', 'user', 'ai', 'llm', 'gpt', 'assistant', 'chat', 'model']);
1021
+ /**
1022
+ * JSX text as React renders it: each line trimmed where it meets a line break, the lines joined by one space,
1023
+ * entities decoded (`can&apos;t` → `can't`). In a `t()` default the source form would show as written.
1024
+ */
1025
+ function jsxTextValue(raw) {
1026
+ const lines = raw.split(/\r\n|\n|\r/);
1027
+ let lastNonEmpty = 0;
1028
+ lines.forEach((line, i) => { if (/[^ \t]/.test(line))
1029
+ lastNonEmpty = i; });
1030
+ let text = '';
1031
+ lines.forEach((line, i) => {
1032
+ let part = line.replace(/\t/g, ' ');
1033
+ if (i > 0)
1034
+ part = part.replace(/^ +/, '');
1035
+ if (i < lines.length - 1)
1036
+ part = part.replace(/ +$/, '');
1037
+ if (part)
1038
+ text += i < lastNonEmpty ? `${part} ` : part;
1039
+ });
1040
+ return text.replace(stringDetector.HTML_ENTITY_RE, entity => decodeEntity(entity));
1041
+ }
1042
+ const NAMED_ENTITIES = {
1043
+ amp: '&',
1044
+ lt: '<',
1045
+ gt: '>',
1046
+ quot: '"',
1047
+ apos: "'",
1048
+ nbsp: '\u00a0',
1049
+ ndash: '–',
1050
+ mdash: '—',
1051
+ hellip: '…',
1052
+ lsquo: '‘',
1053
+ rsquo: '’',
1054
+ ldquo: '“',
1055
+ rdquo: '”',
1056
+ laquo: '«',
1057
+ raquo: '»',
1058
+ middot: '·',
1059
+ bull: '•',
1060
+ times: '×',
1061
+ copy: '©',
1062
+ reg: '®',
1063
+ trade: '™',
1064
+ euro: '€',
1065
+ deg: '°'
1066
+ };
1067
+ /** One HTML character reference as its character; an unknown name stays as written. */
1068
+ function decodeEntity(entity) {
1069
+ const body = entity.slice(1, -1);
1070
+ if (body[0] === '#') {
1071
+ const code = body[1] === 'x' || body[1] === 'X' ? parseInt(body.slice(2), 16) : parseInt(body.slice(1), 10);
1072
+ return Number.isFinite(code) && code <= 0x10FFFF ? String.fromCodePoint(code) : entity;
1073
+ }
1074
+ return NAMED_ENTITIES[body] ?? NAMED_ENTITIES[body.toLowerCase()] ?? entity;
1075
+ }
1076
+ /**
1077
+ * What of a node is never text, the same for every walker looking for text: `'all'` (a t() call, a console
1078
+ * call, a <Trans>, an icon, code, a prompt for a language model, a log line, an error or a pattern), the
1079
+ * child keys that are not (an object key, a member property, a compared operand, a `case` value, the strings
1080
+ * of a non-text call), or null (all of it may be). `withTextHolders` is for the walker that visits the
1081
+ * functions and elements passed to a non-text call itself.
1082
+ */
1083
+ function nonTextParts(node, file, config, withTextHolders) {
1084
+ switch (node.type) {
1085
+ case 'CallExpression':
1086
+ // already instrumented (also its options on a second run), or for developers however it is built
1087
+ if (isTranslationCall(node, config.extract.functions) || isConsoleCall(node))
1088
+ return 'all';
1089
+ return !withTextHolders && isNonTextMethodCall(node) ? ['arguments'] : null;
1090
+ case 'NewExpression':
1091
+ // `new Error('…')` is for developers, `new RegExp('…')` a pattern
1092
+ return node.callee?.type === 'Identifier' && /^RegExp$|Error$/.test(node.callee.value) ? 'all' : null;
1093
+ case 'JSXElement': {
1094
+ if (isTransComponent(node, config.extract.transComponents) || isIconElement(node))
1095
+ return 'all';
1096
+ // what code, scripts and styles show (`ignoredTags`, as for lint); inside a sentence it stays in its <Trans>
1097
+ const tag = node.opening?.name?.type === 'Identifier' ? node.opening.name.value.toLowerCase() : null;
1098
+ return tag && (jsxAttributes.ignoredTags.includes(tag) || config.extract.ignoredTags?.some(t => t.toLowerCase() === tag)) ? 'all' : null;
1099
+ }
1100
+ case 'KeyValueProperty':
1101
+ // a key names something and is never text; a call there is even a syntax error (`{ 'a b': 1 }`)
1102
+ return isModelPromptName(propertyName(node.key)) ? 'all' : ['key'];
1103
+ case 'MemberExpression':
1104
+ return ['property'];
1105
+ case 'BinaryExpression':
1106
+ // the strings a value is compared with are data (`status === 'Active'`)
1107
+ if (!COMPARISON_OPERATORS.has(node.operator))
1108
+ return null;
1109
+ return ['left', 'right'].filter(k => node[k]?.type === 'StringLiteral' || node[k]?.type === 'TemplateLiteral');
1110
+ case 'SwitchCase':
1111
+ return ['test'];
1112
+ case 'FunctionDeclaration':
1113
+ // a prompt is the input of a language model: translating it changes what the model does
1114
+ return isModelPromptName(node.identifier?.value) ? 'all' : null;
1115
+ case 'VariableDeclarator':
1116
+ // a prompt, or a variable used only in console calls (a log line: `const took = …; console.log(took)`)
1117
+ return isModelPromptName(node.id?.value) ||
1118
+ (node.id?.type === 'Identifier' && consoleOnlyNames.get(file)?.has(node.id.value))
1119
+ ? 'all'
1120
+ : null;
1121
+ default:
1122
+ return null;
1123
+ }
1124
+ }
1125
+ /** Calls `visit` for each child node, but not those under the keys `except`. */
1126
+ function forEachChild(node, except, visit) {
1127
+ if (except === 'all')
1128
+ return;
1129
+ for (const key in node) {
1130
+ if (key === 'span' || except?.includes(key))
1131
+ continue;
1132
+ const value = node[key];
1133
+ if (Array.isArray(value))
1134
+ value.forEach(item => item && typeof item === 'object' && visit(item));
1135
+ else if (value && typeof value === 'object')
1136
+ visit(value);
1137
+ }
1138
+ }
1139
+ /** A string literal as a candidate of enough confidence, or null; `textSlot` takes a single word as text. */
1140
+ function stringCandidate(stringNode, content, file, config, accepted, textSlot) {
1141
+ if (!stringNode.span || typeof stringNode.span.start !== 'number')
1142
+ return null;
1143
+ // the same string as data elsewhere in the file: translating it here breaks the match there (what a JSX
1144
+ // element renders and an attribute's value, `data-tip='overridden'`, are shown, never matched)
1145
+ // nor a text property's (`{ value: 'Weekly', label: 'Weekly' }`)
1146
+ const attributeValue = stringNode.span.start > 0 && content[stringNode.span.start - 1] === '=';
1147
+ const property = /([\w]+)\s*:\s*$/.exec(content.slice(Math.max(0, stringNode.span.start - 40), stringNode.span.start))?.[1];
1148
+ const textProperty = !!property && translatablePropertyLowerSet.has(property.toLowerCase());
1149
+ if (fileDataStrings.get(file)?.has(stringNode.value) && !renderedStrings.has(stringNode) && !attributeValue && !textProperty)
1150
+ return null;
1151
+ const candidate = stringDetector.detectCandidate(stringNode.value, stringNode.span.start, stringNode.span.end, file, content, config, accepted, textSlot);
1152
+ // in a text slot the place says it is text, whatever the words score
1153
+ if (candidate && textSlot)
1154
+ candidate.confidence = Math.max(candidate.confidence, 0.7);
1155
+ if (!candidate || candidate.confidence < 0.7)
1156
+ return null;
1157
+ // Detect JSX attribute context: in JSX, attr="value" has = right before the opening quote
1158
+ if (stringNode.span.start > 0 && content[stringNode.span.start - 1] === '=')
1159
+ candidate.type = 'jsx-attribute';
1160
+ return candidate;
1161
+ }
1162
+ const LOGICAL_OPERATORS = new Set(['&&', '||', '??']);
1163
+ const COMPARISON_OPERATORS = new Set(['===', '!==', '==', '!=', 'in', 'instanceof']);
1164
+ /** The name of an object property's key (`label`, `'aria-label'`), or null for a computed one. */
1165
+ function propertyName(key) {
1166
+ return key?.type === 'Identifier' || key?.type === 'StringLiteral' ? key.value : null;
1167
+ }
1168
+ /** Visits the JSX elements and functions inside a value that is not text itself, and nothing else of it. */
1169
+ function visitTextHolders(node, ...rest) {
1170
+ if (!node || typeof node !== 'object')
1171
+ return;
1172
+ if (TEXT_HOLDERS.has(node.type)) {
1173
+ visitNodeForStrings(node, ...rest);
1174
+ return;
1175
+ }
1176
+ for (const key in node) {
1177
+ const value = node[key];
1178
+ if (Array.isArray(value))
1179
+ value.forEach(item => visitTextHolders(item, ...rest));
1180
+ else
1181
+ visitTextHolders(value, ...rest);
1182
+ }
1183
+ }
1184
+ const TEXT_HOLDERS = new Set(['JSXElement', 'JSXFragment', 'ArrowFunctionExpression', 'FunctionExpression']);
663
1185
  // ─── Template-literal interpolation helpers ──────────────────────────────────
664
1186
  /**
665
1187
  * Builds a merged text with `{{var}}` placeholders from a template literal's
@@ -667,7 +1189,7 @@ function visitNodeForStrings(node, content, file, config, candidates, jsx) {
667
1189
  */
668
1190
  function buildInterpolatedTemplate(quasis, expressions, content) {
669
1191
  const interpolations = [];
670
- const usedNames = new Set();
1192
+ const usedNames = new Map();
671
1193
  let text = '';
672
1194
  for (let i = 0; i < quasis.length; i++) {
673
1195
  const quasi = quasis[i];
@@ -677,38 +1199,168 @@ function buildInterpolatedTemplate(quasis, expressions, content) {
677
1199
  if (!info)
678
1200
  return null; // un-resolvable expression — bail
679
1201
  text += `{{${info.name}}}`;
680
- interpolations.push(info);
1202
+ if (!info.reused)
1203
+ interpolations.push(info);
681
1204
  }
682
1205
  }
683
1206
  return interpolations.length > 0 ? { text, interpolations } : null;
684
1207
  }
685
1208
  /**
686
- * Resolves a human-friendly interpolation name from an AST expression node.
687
- *
688
- * - `Identifier` → uses the identifier value (`count`)
689
- * - `MemberExpression` → uses the deepest property name (`profile.name` → `name`)
690
- * - anything else → generated placeholder (`val`, `val2`, ...)
1209
+ * Whether a text with `{{placeholders}}` holds at least one word standing on its own, and is not a
1210
+ * kebab-case name. A word: two letters or more, not camelCase, punctuation around it, a placeholder only
1211
+ * after it (`review{{suffix}}.`), not before it nor joined by `_`, `.` or `-`. Ids, paths, keys, flags and
1212
+ * class names built in a template literal have none: `{{projectId}}-{{version}}`, `weight_{{code}}`,
1213
+ * `{{baseUrl}}/api/{{id}}`, `{{id}}.collapsed`, `{{metric}}Avg`, `nameField{{i}}`, `--ct {{cdnType}}`,
1214
+ * `locize-dropzone {{state}}`.
1215
+ */
1216
+ function hasWordsBesidePlaceholders(text) {
1217
+ // a placeholder becomes one private-use character, neither letter nor punctuation
1218
+ const bare = text.replace(stringDetector.HTML_ENTITY_RE, ' ').replace(/\{\{[^}]*\}\}/g, '\uE000');
1219
+ if (/^[a-z0-9]+(?:-[a-z0-9]+)+$/.test(bare.replace(/\uE000/g, ' ').trim()))
1220
+ return false;
1221
+ return bare.split(/\s+/).some(token => {
1222
+ const word = /^[^\p{L}\p{N}\uE000_.-]*(\p{L}{2,}(?:['’-]\p{L}+)*)[^\p{L}\p{N}_]*$/u.exec(token)?.[1];
1223
+ // `zh-{{country}}`, `{{a}}/{{b}}`: a placeholder joined to the word by a separator makes an id, not a phrase
1224
+ if (/[-_./:#@=&?|\\]\uE000/.test(token))
1225
+ return false;
1226
+ // one Han, Kana or Hangul character is a word of its own (`共 {{n}} 条`)
1227
+ return (!!word && !/\p{Ll}\p{Lu}/u.test(word)) || /[\p{sc=Han}\p{sc=Hiragana}\p{sc=Katakana}\p{sc=Hangul}]/u.test(token);
1228
+ });
1229
+ }
1230
+ /**
1231
+ * A template literal one of whose expressions is a plural (a plural helper call or a `count === 1` ternary),
1232
+ * as one text per plural form: `${n(keys)} ${plural(keys, 'key', 'keys')} unused` → one: '{{keys}} key unused',
1233
+ * other: '{{keys}} keys unused', count: keys. An expression that is the count itself becomes `{{count}}`.
1234
+ */
1235
+ function buildPluralTemplate(quasis, expressions, content) {
1236
+ const pluralIndex = expressions.findIndex(e => parsePluralExpression(e, content));
1237
+ if (pluralIndex < 0)
1238
+ return null;
1239
+ const plural = parsePluralExpression(expressions[pluralIndex], content);
1240
+ const usedNames = new Map();
1241
+ const interpolations = [];
1242
+ const formText = (form) => {
1243
+ let text = '';
1244
+ for (let i = 0; i < quasis.length; i++) {
1245
+ text += quasis[i].cooked ?? quasis[i].raw ?? '';
1246
+ if (i >= expressions.length)
1247
+ continue;
1248
+ if (i === pluralIndex) {
1249
+ text += form;
1250
+ continue;
1251
+ }
1252
+ const expression = content.slice(expressions[i].span.start, expressions[i].span.end);
1253
+ if (expression === plural.countExpression) {
1254
+ text += '{{count}}';
1255
+ continue;
1256
+ }
1257
+ const info = resolveExpressionName(expressions[i], content, usedNames);
1258
+ if (!info)
1259
+ return null;
1260
+ text += `{{${info.name}}}`;
1261
+ if (!info.reused)
1262
+ interpolations.push(info);
1263
+ }
1264
+ return text.trim();
1265
+ };
1266
+ const other = formText(plural.other);
1267
+ const one = plural.one !== undefined ? formText(plural.one) : undefined;
1268
+ const zero = plural.zero !== undefined ? formText(plural.zero) : undefined;
1269
+ if (!other || one === null || zero === null)
1270
+ return null;
1271
+ if (!mergeInterpolations(interpolations, plural.interpolations))
1272
+ return null;
1273
+ return { pluralForms: { countExpression: plural.countExpression, zero, one, other }, interpolations, pluralHelper: pluralHelperOf(expressions[pluralIndex]) };
1274
+ }
1275
+ /** The name of the plural helper a call expression calls (`plural(n, …)` → `plural`), or undefined. */
1276
+ function pluralHelperOf(expr) {
1277
+ return expr?.type === 'CallExpression' && expr.callee?.type === 'Identifier' ? expr.callee.value : undefined;
1278
+ }
1279
+ /**
1280
+ * Adds a plural's own placeholders (from its forms) to the text's; false when a name stands for two
1281
+ * different expressions.
1282
+ */
1283
+ function mergeInterpolations(into, from = []) {
1284
+ for (const item of from) {
1285
+ const same = into.find(i => i.name === item.name);
1286
+ if (same && same.expression !== item.expression)
1287
+ return false;
1288
+ if (!same)
1289
+ into.push(item);
1290
+ }
1291
+ return true;
1292
+ }
1293
+ /**
1294
+ * The name an expression's value says best what it is, or null:
1295
+ * - `Identifier` → itself (`count`); `MemberExpression` → its last property (`profile.name` → `name`)
1296
+ * - a formatter's call, by its argument: `format.date(user.lastLogin)` → `lastLogin`, `n(queue)` → `queue`,
1297
+ * `Math.floor(m / 60)` → `m` (a namespace or a formatter keeps the meaning of what it gets)
1298
+ * - a string method's call, by what it is called on: `input.value.trim()` → `value`
1299
+ * - any other call, by the function: `price(plan)` → `price`, `api.calculatePercentage(stats)` → `calculatePercentage`
1300
+ * - `a - b`, `a || b`, `(a)`, `a as T`, `a!` → the name of `a`
1301
+ */
1302
+ function nameOfExpression(expr) {
1303
+ switch (expr?.type) {
1304
+ case 'Identifier': return expr.value;
1305
+ case 'MemberExpression':
1306
+ return !expr.computed && expr.property?.type === 'Identifier' ? expr.property.value : null;
1307
+ case 'CallExpression': {
1308
+ const callee = expr.callee;
1309
+ const argument = () => nameOfExpression(expr.arguments?.[0]?.expression);
1310
+ if (callee?.type === 'Identifier')
1311
+ return FORMATTER_RE.test(callee.value) ? argument() : callee.value;
1312
+ if (callee?.type !== 'MemberExpression' || callee.property?.type !== 'Identifier')
1313
+ return null;
1314
+ const object = callee.object;
1315
+ const method = callee.property.value;
1316
+ if (object?.type === 'Identifier' && (/^[A-Z]/.test(object.value) || FORMATTER_NAMESPACE_RE.test(object.value)))
1317
+ return argument();
1318
+ // `date.toLocaleDateString()`, `terms.map(…).join(', ')`: still the value it is called on
1319
+ if (STRING_METHODS.has(method) || ARRAY_METHODS.has(method))
1320
+ return nameOfExpression(object);
1321
+ return method;
1322
+ }
1323
+ case 'BinaryExpression':
1324
+ // `name || email` (swc types `||`, `&&`, `??` as a BinaryExpression), `i + 1`: the value meant; any other
1325
+ // arithmetic is a new quantity (`segments * tokensPerSegment`), which no operand names
1326
+ if (LOGICAL_OPERATORS.has(expr.operator))
1327
+ return nameOfExpression(expr.left);
1328
+ if ((expr.operator === '+' || expr.operator === '-') && expr.right?.type === 'NumericLiteral')
1329
+ return nameOfExpression(expr.left);
1330
+ return null;
1331
+ case 'ParenthesisExpression':
1332
+ case 'TsAsExpression':
1333
+ case 'TsNonNullExpression':
1334
+ case 'TsSatisfiesExpression': return nameOfExpression(expr.expression);
1335
+ default: return null;
1336
+ }
1337
+ }
1338
+ /** Names of formatter functions: their call shows the value they get (`n(queue)`, `formatDate(createdAt)`). */
1339
+ const FORMATTER_RE = /^(?:format\w*|fmt|formatter|n|num|number|money|percent)$/i;
1340
+ /** Names of formatting namespaces (`format.date(x)`); a capitalized one (`Math`, `Intl`) is one too. */
1341
+ const FORMATTER_NAMESPACE_RE = /^(?:format\w*|fmt|formatter|intl)$/i;
1342
+ /** Array methods whose result still holds what they are called on. */
1343
+ const ARRAY_METHODS = new Set(['map', 'filter', 'sort', 'slice', 'flat', 'flatMap', 'concat', 'reverse']);
1344
+ /**
1345
+ * Resolves a human-friendly interpolation name from an AST expression node (see `nameOfExpression`;
1346
+ * `val`, `val2`, ... when none). The same expression twice in one text gets one name (`reused`), so the
1347
+ * options name it once.
691
1348
  */
692
1349
  function resolveExpressionName(expr, content, usedNames) {
693
1350
  if (!expr?.span)
694
1351
  return null;
695
1352
  const expression = content.slice(expr.span.start, expr.span.end);
696
- let baseName;
697
- if (expr.type === 'Identifier') {
698
- baseName = expr.value;
699
- }
700
- else if (expr.type === 'MemberExpression' && !expr.computed && expr.property?.type === 'Identifier') {
701
- baseName = expr.property.value;
702
- }
703
- else {
704
- baseName = 'val';
1353
+ for (const [name, expr] of usedNames) {
1354
+ if (expr === expression)
1355
+ return { name, expression, reused: true };
705
1356
  }
1357
+ const baseName = nameOfExpression(expr) ?? 'val';
706
1358
  let name = baseName;
707
1359
  let counter = 2;
708
1360
  while (usedNames.has(name)) {
709
1361
  name = `${baseName}${counter++}`;
710
1362
  }
711
- usedNames.add(name);
1363
+ usedNames.set(name, expression);
712
1364
  return { name, expression };
713
1365
  }
714
1366
  // ─── JSX sibling interpolation merging ───────────────────────────────────────
@@ -722,8 +1374,9 @@ function resolveExpressionName(expr, content, usedNames) {
722
1374
  function detectJSXInterpolation(node, content, file, config, candidates) {
723
1375
  if (!node)
724
1376
  return;
725
- // Skip <Trans> elements (already instrumented)
726
- if (node.type === 'JSXElement' && isTransComponent(node))
1377
+ // Not text (a <Trans>, code, an icon, a prompt, a log line, a key, …): nothing to merge in it
1378
+ const parts = nonTextParts(node, file, config, false);
1379
+ if (parts === 'all')
727
1380
  return;
728
1381
  const children = (node.type === 'JSXElement' || node.type === 'JSXFragment') ? node.children : null;
729
1382
  if (children?.length > 1) {
@@ -734,13 +1387,12 @@ function detectJSXInterpolation(node, content, file, config, candidates) {
734
1387
  if (child.type === 'JSXText') {
735
1388
  currentRun.push(child);
736
1389
  }
737
- else if (child.type === 'JSXExpressionContainer' && isSimpleJSXExpression(child.expression)) {
1390
+ else if (child.type === 'JSXExpressionContainer' && (isSimpleJSXExpression(child.expression) || child.expression?.type === 'StringLiteral')) {
1391
+ // a simple expression, or literal text such as {' '}
738
1392
  currentRun.push(child);
739
1393
  }
740
- else if (child.type === 'JSXExpressionContainer' &&
741
- child.expression?.type === 'ConditionalExpression' &&
742
- tryParsePluralTernary(child.expression, content)) {
743
- // Plural ternary expression — include in the run for merged handling
1394
+ else if (child.type === 'JSXExpressionContainer' && parsePluralExpression(child.expression, content)) {
1395
+ // Plural ternary or plural helper call: part of the run, merged with it
744
1396
  currentRun.push(child);
745
1397
  }
746
1398
  else if (child.type === 'JSXElement' && isSimpleJSXElement(child)) {
@@ -758,7 +1410,12 @@ function detectJSXInterpolation(node, content, file, config, candidates) {
758
1410
  if (currentRun.length > 0) {
759
1411
  runs.push(currentRun);
760
1412
  }
761
- for (const run of runs) {
1413
+ for (const fullRun of runs) {
1414
+ // Whitespace at a run's edges stays in the source: a rewrite of it would drop a space the page shows
1415
+ // (`provider:{' '}<strong>…`)
1416
+ const run = trimRun(fullRun);
1417
+ if (!run.length)
1418
+ continue;
762
1419
  const hasText = run.some(c => c.type === 'JSXText' && c.value?.trim());
763
1420
  const hasExpr = run.some(c => c.type === 'JSXExpressionContainer');
764
1421
  const hasElement = run.some(c => c.type === 'JSXElement');
@@ -771,9 +1428,8 @@ function detectJSXInterpolation(node, content, file, config, candidates) {
771
1428
  let pluralChild = null;
772
1429
  let pluralData = null;
773
1430
  for (const child of run) {
774
- if (child.type === 'JSXExpressionContainer' &&
775
- child.expression?.type === 'ConditionalExpression') {
776
- const p = tryParsePluralTernary(child.expression, content);
1431
+ if (child.type === 'JSXExpressionContainer') {
1432
+ const p = parsePluralExpression(child.expression, content);
777
1433
  if (p) {
778
1434
  pluralChild = child;
779
1435
  pluralData = p;
@@ -781,12 +1437,15 @@ function detectJSXInterpolation(node, content, file, config, candidates) {
781
1437
  }
782
1438
  }
783
1439
  }
1440
+ // A sentence with both an element and a plural stays in its parts: in a <Trans> the plural's forms would
1441
+ // end up untranslated in an interpolation, and a plural t() cannot hold the element
1442
+ if (hasElement && pluralChild)
1443
+ continue;
784
1444
  if (hasElement) {
785
1445
  // ── JSX sibling run with nested HTML elements → <Trans> ──
786
- const spanStart = run[0].span.start;
787
- const spanEnd = run[run.length - 1].span.end;
1446
+ const [spanStart, spanEnd] = runSpan(run, content);
788
1447
  // Build the translation string (with indexed tags) and text-only version (for scoring)
789
- const usedNames = new Set();
1448
+ const usedNames = new Map();
790
1449
  const interpolations = [];
791
1450
  let transValue = '';
792
1451
  let textOnly = '';
@@ -796,9 +1455,19 @@ function detectJSXInterpolation(node, content, file, config, candidates) {
796
1455
  for (const child of run) {
797
1456
  if (child.type === 'JSXText') {
798
1457
  const raw = content.slice(child.span.start, child.span.end);
799
- transValue += raw;
800
- textOnly += raw;
1458
+ const text = jsxTextValue(raw);
1459
+ transValue += text;
1460
+ textOnly += text;
801
1461
  transContent += raw;
1462
+ // whitespace with a line break is no child of the element at all
1463
+ if (text)
1464
+ childIndex++;
1465
+ }
1466
+ else if (child.type === 'JSXExpressionContainer' && child.expression?.type === 'StringLiteral') {
1467
+ // {' '} and other literal text: part of the sentence, kept as written
1468
+ transValue += child.expression.value;
1469
+ textOnly += child.expression.value;
1470
+ transContent += content.slice(child.span.start, child.span.end);
802
1471
  childIndex++;
803
1472
  }
804
1473
  else if (child.type === 'JSXExpressionContainer') {
@@ -812,7 +1481,8 @@ function detectJSXInterpolation(node, content, file, config, candidates) {
812
1481
  // In <Trans> children, simple expressions become {{ obj }} syntax
813
1482
  const objExpr = info.name === info.expression ? info.name : `${info.name}: ${info.expression}`;
814
1483
  transContent += `{{ ${objExpr} }}`;
815
- interpolations.push(info);
1484
+ if (!info.reused)
1485
+ interpolations.push(info);
816
1486
  childIndex++;
817
1487
  }
818
1488
  else if (child.type === 'JSXElement') {
@@ -855,12 +1525,12 @@ function detectJSXInterpolation(node, content, file, config, candidates) {
855
1525
  // ── JSX sibling run with embedded plural ternary ──
856
1526
  const countExpr = pluralData.countExpression;
857
1527
  // Resolve names for non-count, non-plural expressions
858
- const usedNames = new Set();
1528
+ const usedNames = new Map();
859
1529
  const extraInterpolations = [];
860
1530
  const exprNameMap = new Map();
861
1531
  let valid = true;
862
1532
  for (const child of run) {
863
- if (child.type === 'JSXExpressionContainer' && child !== pluralChild) {
1533
+ if (child.type === 'JSXExpressionContainer' && child !== pluralChild && child.expression?.type !== 'StringLiteral') {
864
1534
  const exprText = content.slice(child.expression.span.start, child.expression.span.end);
865
1535
  if (exprText === countExpr) {
866
1536
  exprNameMap.set(child, 'count');
@@ -872,11 +1542,12 @@ function detectJSXInterpolation(node, content, file, config, candidates) {
872
1542
  break;
873
1543
  }
874
1544
  exprNameMap.set(child, info.name);
875
- extraInterpolations.push(info);
1545
+ if (!info.reused)
1546
+ extraInterpolations.push(info);
876
1547
  }
877
1548
  }
878
1549
  }
879
- if (!valid)
1550
+ if (!valid || !mergeInterpolations(extraInterpolations, pluralData.interpolations))
880
1551
  continue;
881
1552
  // Build merged text for each plural form
882
1553
  const forms = [
@@ -889,7 +1560,10 @@ function detectJSXInterpolation(node, content, file, config, candidates) {
889
1560
  let text = '';
890
1561
  for (const child of run) {
891
1562
  if (child.type === 'JSXText') {
892
- text += content.slice(child.span.start, child.span.end);
1563
+ text += jsxTextValue(content.slice(child.span.start, child.span.end));
1564
+ }
1565
+ else if (child.expression?.type === 'StringLiteral') {
1566
+ text += child.expression.value;
893
1567
  }
894
1568
  else if (child === pluralChild) {
895
1569
  const formText = form === 'zero'
@@ -906,8 +1580,7 @@ function detectJSXInterpolation(node, content, file, config, candidates) {
906
1580
  }
907
1581
  formTexts[form] = text.trim();
908
1582
  }
909
- const spanStart = run[0].span.start;
910
- const spanEnd = run[run.length - 1].span.end;
1583
+ const [spanStart, spanEnd] = runSpan(run, content);
911
1584
  const otherText = formTexts.other;
912
1585
  if (!otherText)
913
1586
  continue;
@@ -924,6 +1597,7 @@ function detectJSXInterpolation(node, content, file, config, candidates) {
924
1597
  if (extraInterpolations.length > 0) {
925
1598
  candidate.interpolations = extraInterpolations;
926
1599
  }
1600
+ candidate.pluralHelper = pluralHelperOf(pluralChild.expression);
927
1601
  // Plural + JSX merge is always user-facing
928
1602
  candidate.confidence = Math.min(1, candidate.confidence + 0.3);
929
1603
  if (candidate.confidence >= 0.7) {
@@ -940,13 +1614,16 @@ function detectJSXInterpolation(node, content, file, config, candidates) {
940
1614
  else {
941
1615
  // ── Original JSX sibling merging (text + expressions, no elements) ──
942
1616
  // Build the interpolated text from the run
943
- const usedNames = new Set();
1617
+ const usedNames = new Map();
944
1618
  const interpolations = [];
945
1619
  let text = '';
946
1620
  let valid = true;
947
1621
  for (const child of run) {
948
1622
  if (child.type === 'JSXText') {
949
- text += content.slice(child.span.start, child.span.end);
1623
+ text += jsxTextValue(content.slice(child.span.start, child.span.end));
1624
+ }
1625
+ else if (child.expression?.type === 'StringLiteral') {
1626
+ text += child.expression.value;
950
1627
  }
951
1628
  else {
952
1629
  const info = resolveExpressionName(child.expression, content, usedNames);
@@ -955,21 +1632,23 @@ function detectJSXInterpolation(node, content, file, config, candidates) {
955
1632
  break;
956
1633
  }
957
1634
  text += `{{${info.name}}}`;
958
- interpolations.push(info);
1635
+ if (!info.reused)
1636
+ interpolations.push(info);
959
1637
  }
960
1638
  }
961
1639
  if (!valid)
962
1640
  continue;
963
1641
  const trimmed = text.trim();
964
- if (!trimmed || interpolations.length === 0)
1642
+ const literalPiece = run.some(c => c.expression?.type === 'StringLiteral');
1643
+ if (!trimmed || (interpolations.length === 0 && !literalPiece) || !hasWordsBesidePlaceholders(trimmed))
965
1644
  continue;
966
- const spanStart = run[0].span.start;
967
- const spanEnd = run[run.length - 1].span.end;
1645
+ const [spanStart, spanEnd] = runSpan(run, content);
968
1646
  const candidate = stringDetector.detectCandidate(trimmed, spanStart, spanEnd, file, content, config);
969
1647
  if (candidate) {
970
1648
  candidate.type = 'jsx-text';
971
1649
  candidate.content = trimmed;
972
- candidate.interpolations = interpolations;
1650
+ if (interpolations.length)
1651
+ candidate.interpolations = interpolations;
973
1652
  // Mixed text + expressions in JSX is almost always user-facing
974
1653
  candidate.confidence = Math.min(1, candidate.confidence + 0.2);
975
1654
  if (candidate.confidence >= 0.7) {
@@ -986,17 +1665,35 @@ function detectJSXInterpolation(node, content, file, config, candidates) {
986
1665
  }
987
1666
  }
988
1667
  // Recurse into children
989
- for (const key in node) {
990
- const value = node[key];
991
- if (value && typeof value === 'object') {
992
- if (Array.isArray(value)) {
993
- value.forEach(item => detectJSXInterpolation(item, content, file, config, candidates));
994
- }
995
- else {
996
- detectJSXInterpolation(value, content, file, config, candidates);
997
- }
998
- }
999
- }
1668
+ forEachChild(node, parts, child => detectJSXInterpolation(child, content, file, config, candidates));
1669
+ }
1670
+ /** A run without the whitespace-only text and `{' '}` pieces at its two ends. */
1671
+ function trimRun(run) {
1672
+ const blank = (c) => (c.type === 'JSXText' && !c.value?.trim()) ||
1673
+ (c.type === 'JSXExpressionContainer' && c.expression?.type === 'StringLiteral' && !c.expression.value.trim());
1674
+ let start = 0;
1675
+ let end = run.length;
1676
+ while (start < end && blank(run[start]))
1677
+ start++;
1678
+ while (end > start && blank(run[end - 1]))
1679
+ end--;
1680
+ return run.slice(start, end);
1681
+ }
1682
+ /** Where a run's rewrite starts and ends: inside the whitespace of its first and last text. */
1683
+ function runSpan(run, content) {
1684
+ const first = run[0];
1685
+ const last = run[run.length - 1];
1686
+ let start = first.span.start;
1687
+ let end = last.span.end;
1688
+ if (first.type === 'JSXText') {
1689
+ const raw = content.slice(first.span.start, first.span.end);
1690
+ start += raw.length - raw.trimStart().length;
1691
+ }
1692
+ if (last.type === 'JSXText') {
1693
+ const raw = content.slice(last.span.start, last.span.end);
1694
+ end -= raw.length - raw.trimEnd().length;
1695
+ }
1696
+ return [start, end];
1000
1697
  }
1001
1698
  /**
1002
1699
  * Returns true when the expression is a simple Identifier or non-computed
@@ -1009,36 +1706,77 @@ function isSimpleJSXExpression(expr) {
1009
1706
  return true;
1010
1707
  if (expr.type === 'MemberExpression' && !expr.computed && expr.property?.type === 'Identifier')
1011
1708
  return true;
1709
+ // A string or number made from one, inside a sentence as a placeholder (`up to {n.toLocaleString()} segments`,
1710
+ // `{Math.round(score * 100)}%`, `+ {total - shown} more`); any other call may return elements
1711
+ if (expr.type === 'ParenthesisExpression')
1712
+ return isSimpleJSXExpression(expr.expression);
1713
+ if (expr.type === 'NumericLiteral')
1714
+ return true;
1715
+ if (expr.type === 'BinaryExpression' && ARITHMETIC_OPERATORS.has(expr.operator)) {
1716
+ return isSimpleJSXExpression(expr.left) && isSimpleJSXExpression(expr.right);
1717
+ }
1718
+ // a choice between such values (`{young ? 3 : 2}`); a choice between strings is text of its own, which a
1719
+ // placeholder would leave untranslated
1720
+ if (expr.type === 'ConditionalExpression') {
1721
+ return [expr.consequent, expr.alternate].every(b => b?.type !== 'StringLiteral' && b?.type !== 'TemplateLiteral' && isSimpleJSXExpression(b));
1722
+ }
1723
+ // `format.date(x)`, `formatPrice(x)`: a formatter returns a string
1724
+ if (expr.type === 'CallExpression' && expr.callee?.type === 'Identifier')
1725
+ return /^format[A-Z]/.test(expr.callee.value);
1726
+ if (expr.type === 'CallExpression' && expr.callee?.type === 'MemberExpression' && expr.callee.property?.type === 'Identifier') {
1727
+ const object = expr.callee.object;
1728
+ const method = expr.callee.property.value;
1729
+ return STRING_METHODS.has(method) || /^format/.test(method) ||
1730
+ (object?.type === 'Identifier' && (object.value === 'Math' || object.value === 'Number' || /^(?:format|formatter|fmt|intl)$/i.test(object.value)));
1731
+ }
1012
1732
  return false;
1013
1733
  }
1734
+ const ARITHMETIC_OPERATORS = new Set(['-', '*', '/', '%']);
1735
+ /**
1736
+ * Methods that return a string whatever they are called on (`list.map(…).join(', ')`), so their call in JSX
1737
+ * text is a placeholder like a variable; not `slice`, which keeps an array of elements.
1738
+ */
1739
+ const STRING_METHODS = new Set([
1740
+ 'join', 'toString', 'toLocaleString', 'toLocaleDateString', 'toLocaleTimeString', 'toFixed', 'toPrecision',
1741
+ 'trim', 'toUpperCase', 'toLowerCase', 'padStart', 'padEnd', 'substring', 'replace', 'replaceAll'
1742
+ ]);
1014
1743
  /**
1015
1744
  * Returns true when a JSXElement is "simple" enough to be included in a
1016
1745
  * `<Trans>` JSX sibling run. Accepts:
1017
- * - Self-closing elements (`<br />`, `<img />`)
1018
- * - Elements whose only children are `JSXText` nodes
1019
- * Only HTML-like elements (lowercase tag name) are accepted; React
1020
- * components (uppercase, e.g. `<Button />`) break the run.
1746
+ * - Self-closing HTML elements (`<br />`, `<img />`)
1747
+ * - HTML elements whose only children are `JSXText` nodes
1748
+ * - Components whose only children are text, a link in a sentence
1749
+ * (`Leave your <DialogLink to='/'>projects</DialogLink> first.`); a component
1750
+ * without text (`<Icon />`) breaks the run
1021
1751
  */
1022
1752
  function isSimpleJSXElement(node) {
1023
- if (node.type !== 'JSXElement')
1753
+ if (node.type !== 'JSXElement' || isIconElement(node))
1024
1754
  return false;
1025
1755
  const namePart = node.opening?.name;
1026
1756
  if (!namePart)
1027
1757
  return false;
1028
- // Only include HTML-like elements (lowercase first char)
1029
- let tagName = null;
1030
- if (namePart.type === 'Identifier') {
1031
- tagName = namePart.value;
1758
+ const children = node.children || [];
1759
+ const textOnly = children.every((c) => c.type === 'JSXText');
1760
+ if (namePart.type === 'JSXMemberExpression') {
1761
+ const name = `${namePart.object?.value ?? ''}.${namePart.property?.value ?? ''}`;
1762
+ return INLINE_COMPONENT_RE.test(name) && children.length > 0 && textOnly;
1032
1763
  }
1033
- if (!tagName || tagName[0] !== tagName[0].toLowerCase())
1764
+ if (namePart.type !== 'Identifier')
1034
1765
  return false;
1766
+ const tagName = namePart.value;
1767
+ if (tagName[0] !== tagName[0].toLowerCase())
1768
+ return INLINE_COMPONENT_RE.test(tagName) && children.some((c) => c.value?.trim()) && textOnly;
1035
1769
  // Self-closing elements are simple
1036
1770
  if (node.opening?.selfClosing)
1037
1771
  return true;
1038
1772
  // Elements with only text children (or empty) are simple
1039
- const children = node.children || [];
1040
- return children.length === 0 || children.every((c) => c.type === 'JSXText');
1773
+ return children.length === 0 || textOnly;
1041
1774
  }
1775
+ /**
1776
+ * Components that stand inside a sentence: links and text styles (`DialogLink`, `Text.Strong`). A button or a
1777
+ * card next to a text is a piece of its own, not part of the sentence.
1778
+ */
1779
+ const INLINE_COMPONENT_RE = /Link$|^Text\b|Text$|^(?:Strong|Em|B|I|Code|Mark|Highlight)$/;
1042
1780
  /**
1043
1781
  * Returns the text content of a simple JSXElement's children.
1044
1782
  */
@@ -1053,17 +1791,30 @@ function getJSXElementTextContent(node, content) {
1053
1791
  * Returns true when a JSXElement is a `<Trans>` component
1054
1792
  * (already instrumented content).
1055
1793
  */
1056
- function isTransComponent(node) {
1794
+ function isTransComponent(node, transComponents = []) {
1057
1795
  const opening = node.opening;
1058
1796
  if (!opening)
1059
1797
  return false;
1060
1798
  const name = opening.name;
1061
- if (name?.type === 'Identifier' && name.value === 'Trans')
1062
- return true;
1063
- if (name?.type === 'JSXMemberExpression' && name.property?.type === 'Identifier' && name.property.value === 'Trans')
1064
- return true;
1799
+ if (name?.type === 'Identifier')
1800
+ return name.value === 'Trans' || transComponents.includes(name.value);
1801
+ if (name?.type === 'JSXMemberExpression' && name.property?.type === 'Identifier') {
1802
+ const object = name.object?.type === 'Identifier' ? name.object.value : '';
1803
+ return name.property.value === 'Trans' || transComponents.includes(`${object}.${name.property.value}`);
1804
+ }
1065
1805
  return false;
1066
1806
  }
1807
+ /**
1808
+ * An icon: an element whose name ends in `Icon`, or one with a Material icon class. Its text is a ligature
1809
+ * (`<Icon>delete</Icon>`, `<span className='material-icons'>search</span>`) that a translation would break.
1810
+ */
1811
+ function isIconElement(node) {
1812
+ const name = node.opening?.name;
1813
+ const tag = name?.type === 'Identifier' ? name.value : name?.type === 'JSXMemberExpression' ? name.property?.value : '';
1814
+ if (/Icon$/.test(tag ?? ''))
1815
+ return true;
1816
+ return (node.opening?.attributes ?? []).some((a) => a.name?.value === 'className' && a.value?.type === 'StringLiteral' && /\bmaterial-(?:icons|symbols)/.test(a.value.value));
1817
+ }
1067
1818
  // ─── Plural conditional pattern detection ────────────────────────────────────
1068
1819
  /**
1069
1820
  * Extracts the text value from a string literal or static template literal node.
@@ -1164,8 +1915,11 @@ function parseCountTest(test, content) {
1164
1915
  function detectPluralPatterns(node, content, file, config, candidates) {
1165
1916
  if (!node)
1166
1917
  return;
1167
- if (node.type === 'ConditionalExpression') {
1168
- const plural = tryParsePluralTernary(node, content);
1918
+ const parts = nonTextParts(node, file, config, false);
1919
+ if (parts === 'all')
1920
+ return;
1921
+ if (node.type === 'ConditionalExpression' || node.type === 'CallExpression') {
1922
+ const plural = parsePluralExpression(node, content);
1169
1923
  if (plural) {
1170
1924
  // Use the "other" form as the candidate content (with {{count}})
1171
1925
  const spanStart = node.span.start;
@@ -1185,6 +1939,9 @@ function detectPluralPatterns(node, content, file, config, candidates) {
1185
1939
  one: plural.one,
1186
1940
  other: plural.other
1187
1941
  };
1942
+ if (plural.interpolations)
1943
+ candidate.interpolations = plural.interpolations;
1944
+ candidate.pluralHelper = pluralHelperOf(node);
1188
1945
  // Plural patterns are always user-facing text — boost confidence
1189
1946
  candidate.confidence = Math.min(1, candidate.confidence + 0.3);
1190
1947
  if (candidate.confidence >= 0.7) {
@@ -1202,20 +1959,77 @@ function detectPluralPatterns(node, content, file, config, candidates) {
1202
1959
  }
1203
1960
  }
1204
1961
  // Recurse into children
1205
- for (const key in node) {
1206
- const value = node[key];
1207
- if (value && typeof value === 'object') {
1208
- if (Array.isArray(value)) {
1209
- value.forEach(item => detectPluralPatterns(item, content, file, config, candidates));
1210
- }
1211
- else {
1212
- detectPluralPatterns(value, content, file, config, candidates);
1962
+ forEachChild(node, parts, child => detectPluralPatterns(child, content, file, config, candidates));
1963
+ }
1964
+ /** A plural helper call or a `count === 1` ternary as its plural forms, or null. */
1965
+ function parsePluralExpression(expr, content) {
1966
+ if (expr?.type === 'ConditionalExpression')
1967
+ return tryParsePluralTernary(expr, content);
1968
+ if (expr?.type === 'CallExpression')
1969
+ return tryParsePluralCall(expr, content);
1970
+ return null;
1971
+ }
1972
+ /** Names of plural helpers whose call reads `(count, one, other)`. */
1973
+ const PLURAL_HELPER_RE = /^(?:plural|pluralize|pluralise)$/i;
1974
+ /**
1975
+ * Attempts to parse a plural helper call into a plural pattern:
1976
+ * plural(count, '# file', '# files') → one: '{{count}} file', other: '{{count}} files'
1977
+ * pluralize(n, 'item', `${n} items`) → one: 'item', other: '{{count}} items'
1978
+ * `#` in a form stands for the number, as in ICU. Only a call whose two forms are text (a string, or a
1979
+ * template literal whose only expression is the count) and whose count is not a string.
1980
+ */
1981
+ function tryParsePluralCall(node, content) {
1982
+ const callee = node.callee;
1983
+ const name = callee?.type === 'Identifier'
1984
+ ? callee.value
1985
+ : callee?.type === 'MemberExpression' && !callee.computed && callee.property?.type === 'Identifier' ? callee.property.value : null;
1986
+ if (!name || !PLURAL_HELPER_RE.test(name))
1987
+ return null;
1988
+ const [count, one, other] = (node.arguments ?? []).map((a) => a?.spread ? null : a?.expression);
1989
+ if (!count?.span || !one || !other || count.type === 'StringLiteral' || count.type === 'TemplateLiteral')
1990
+ return null;
1991
+ const countExpression = content.slice(count.span.start, count.span.end);
1992
+ // A form's other expressions become placeholders, named once for both forms (`showing ${shown} of # user`)
1993
+ const usedNames = new Map();
1994
+ const interpolations = [];
1995
+ const formText = (form) => {
1996
+ const text = extractStaticText(form);
1997
+ if (text !== null)
1998
+ return text;
1999
+ if (form?.type !== 'TemplateLiteral')
2000
+ return null;
2001
+ let result = '';
2002
+ for (let i = 0; i < form.quasis.length; i++) {
2003
+ result += form.quasis[i].cooked ?? form.quasis[i].raw ?? '';
2004
+ const expr = form.expressions?.[i];
2005
+ if (!expr)
2006
+ continue;
2007
+ if (content.slice(expr.span.start, expr.span.end) === countExpression) {
2008
+ result += '{{count}}';
2009
+ continue;
1213
2010
  }
2011
+ const info = resolveExpressionName(expr, content, usedNames);
2012
+ if (!info)
2013
+ return null;
2014
+ result += `{{${info.name}}}`;
2015
+ if (!info.reused)
2016
+ interpolations.push(info);
1214
2017
  }
1215
- }
2018
+ return result;
2019
+ };
2020
+ const oneText = formText(one);
2021
+ const otherText = formText(other);
2022
+ if (oneText === null || otherText === null)
2023
+ return null;
2024
+ return {
2025
+ countExpression,
2026
+ one: oneText.replace(/#/g, '{{count}}'),
2027
+ other: otherText.replace(/#/g, '{{count}}'),
2028
+ ...(interpolations.length ? { interpolations } : {})
2029
+ };
1216
2030
  }
1217
2031
  /**
1218
- * Attempts to parse a `ConditionalExpression` tree into a plural pattern.
2032
+ * Parses the shape of a `ConditionalExpression` tree into a plural pattern (see `tryParsePluralTernary`).
1219
2033
  *
1220
2034
  * Supported shapes:
1221
2035
  * count === 0 ? zeroText : count === 1 ? oneText : otherText (3-way)
@@ -1223,7 +2037,7 @@ function detectPluralPatterns(node, content, file, config, candidates) {
1223
2037
  *
1224
2038
  * Returns `null` when the node doesn't match any recognised plural shape.
1225
2039
  */
1226
- function tryParsePluralTernary(node, content) {
2040
+ function parsePluralTernaryShape(node, content) {
1227
2041
  if (node?.type !== 'ConditionalExpression')
1228
2042
  return null;
1229
2043
  const outerTest = parseCountTest(node.test, content);
@@ -1262,6 +2076,23 @@ function tryParsePluralTernary(node, content) {
1262
2076
  }
1263
2077
  return null;
1264
2078
  }
2079
+ /**
2080
+ * A ternary on `count === 1` is a plural only when its branches are text: `score === 1 ? 'var(--ok)' :
2081
+ * 'var(--warn)'` and `score === 1 ? 'item-full' : 'item-low'` pick a style.
2082
+ */
2083
+ function tryParsePluralTernary(node, content) {
2084
+ const plural = parsePluralTernaryShape(node, content);
2085
+ if (!plural)
2086
+ return null;
2087
+ // Fragments merged with the text around them (`''`, `'s'`, `${n}`) are fine; a technical form is not
2088
+ const forms = [plural.zero, plural.one, plural.other].filter((f) => f !== undefined);
2089
+ const technical = forms.some(f => f.trim().length > 1 && detectsAsTechnical(f));
2090
+ return !technical && forms.some(f => /\p{L}/u.test(f.replace(/\{\{[^}]*\}\}/g, ''))) ? plural : null;
2091
+ }
2092
+ /** A form that the string detector skips as technical (a CSS value, a class name); a single word is text here. */
2093
+ function detectsAsTechnical(text) {
2094
+ return stringDetector.detectCandidate(text, 0, text.length, 'plural.js', text, { extract: { input: [], output: '' } }, undefined, true) === null;
2095
+ }
1265
2096
  // ─── Language-change detection ───────────────────────────────────────────────
1266
2097
  /**
1267
2098
  * Property names that indicate a "language" value in an object literal.
@@ -1276,6 +2107,24 @@ const LANGUAGE_PROP_NAMES = new Set(['language', 'lang', 'locale', 'lng']);
1276
2107
  * Examples: `setLanguage(code)`, `setLocale(lng)`, `changeLanguage(x)`
1277
2108
  */
1278
2109
  const LANGUAGE_SETTER_RE = /^(?:set|change|update|select)(?:Language|Lang|Locale|Lng)$/i;
2110
+ /**
2111
+ * A variable or a property (`code`, `lang.code`, `e.target.value`): the injected `changeLanguage()` repeats
2112
+ * the expression, which must then give the same value without doing anything (`getDefault(…)` would run twice).
2113
+ */
2114
+ function isPlainValue(expr) {
2115
+ if (expr?.type === 'Identifier')
2116
+ return true;
2117
+ return expr?.type === 'MemberExpression' && expr.property?.type === 'Identifier' && isPlainValue(expr.object);
2118
+ }
2119
+ /** Nodes whose statements are a list, where one more statement can go before another. */
2120
+ const STATEMENT_LISTS = new Set(['FunctionBody', 'BlockStatement', 'Module', 'Script', 'SwitchCase']);
2121
+ /**
2122
+ * Callees whose object argument holds the user's settings, so a language property there is the app's
2123
+ * language (`updateSettings({ language })`, `saveProfile({ locale })`, `setState({ locale })`). Elsewhere a
2124
+ * `language`/`lng` property is data (`fetchTranslations({ lng })`, `list.push({ lng })`), and hooks
2125
+ * (`useState({ lng: [] })`) never are.
2126
+ */
2127
+ const SETTINGS_CALLEE_RE = /settings|preferences|prefs|profile|user|account|state|locale|language/i;
1279
2128
  /**
1280
2129
  * Walks the AST looking for call expressions that appear to change the
1281
2130
  * application language. Detected sites will later be augmented with an
@@ -1291,11 +2140,18 @@ const LANGUAGE_SETTER_RE = /^(?:set|change|update|select)(?:Language|Lang|Locale
1291
2140
  * `setLanguage(code)`
1292
2141
  * `setLocale(lng)`
1293
2142
  * `changeLanguage(selectedLng)`
2143
+ *
2144
+ * Only a call that is a statement of its own in a block or an arrow function's expression body: the
2145
+ * injected call goes before it, which would change any other place (`const x = setLocale(l)`,
2146
+ * `return save({ locale })`, `if (ok) setLocale(l)`).
1294
2147
  */
1295
- function detectLanguageChangeSites(node, content, sites) {
2148
+ function detectLanguageChangeSites(node, content, sites, parent, grandparent) {
1296
2149
  if (!node)
1297
2150
  return;
1298
- if (node.type === 'CallExpression' && node.span) {
2151
+ const standsAlone = (parent?.type === 'ExpressionStatement' && parent.expression === node &&
2152
+ STATEMENT_LISTS.has(grandparent?.type)) ||
2153
+ (parent?.type === 'ArrowFunctionExpression' && parent.body === node);
2154
+ if (node.type === 'CallExpression' && node.span && standsAlone) {
1299
2155
  const detected = tryParseLanguageChangeCall(node, content);
1300
2156
  if (detected) {
1301
2157
  // Check if changeLanguage() already exists nearby (e.g. same arrow body)
@@ -1326,14 +2182,89 @@ function detectLanguageChangeSites(node, content, sites) {
1326
2182
  const value = node[key];
1327
2183
  if (value && typeof value === 'object') {
1328
2184
  if (Array.isArray(value)) {
1329
- value.forEach(item => detectLanguageChangeSites(item, content, sites));
2185
+ value.forEach(item => detectLanguageChangeSites(item, content, sites, node, parent));
1330
2186
  }
1331
2187
  else {
1332
- detectLanguageChangeSites(value, content, sites);
2188
+ detectLanguageChangeSites(value, content, sites, node, parent);
1333
2189
  }
1334
2190
  }
1335
2191
  }
1336
2192
  }
2193
+ /**
2194
+ * The imports of the plural helpers `names` (`import { plural, number } from './format'`), each with the
2195
+ * number of other identifiers naming it in the file and the text that removes its import.
2196
+ */
2197
+ function findPluralHelperImports(ast, content, names) {
2198
+ const found = [];
2199
+ for (const decl of ast.body ?? []) {
2200
+ if (decl.type !== 'ImportDeclaration')
2201
+ continue;
2202
+ const specifiers = decl.specifiers ?? [];
2203
+ // `import fmt, { plural } from …` mixes a default with the braces: removing one of them takes more than a
2204
+ // specifier and a comma, so such an import stays
2205
+ const named = specifiers.every((spec) => spec.type === 'ImportSpecifier');
2206
+ specifiers.forEach((spec, i) => {
2207
+ const name = spec.local?.value;
2208
+ if (!names.has(name) || (!named && specifiers.length > 1))
2209
+ return;
2210
+ let [removeStart, removeEnd] = specifiers.length === 1
2211
+ ? [decl.span.start, decl.span.end]
2212
+ : i < specifiers.length - 1
2213
+ ? [spec.span.start, specifiers[i + 1].span.start]
2214
+ : [specifiers[i - 1].span.end, spec.span.end];
2215
+ if (specifiers.length === 1)
2216
+ removeEnd += /^\r?\n/.exec(content.slice(removeEnd))?.[0].length ?? 0;
2217
+ found.push({ name, references: 0, removeStart, removeEnd });
2218
+ });
2219
+ }
2220
+ const count = (node) => {
2221
+ if (!node || typeof node !== 'object')
2222
+ return;
2223
+ if (node.type === 'ImportDeclaration')
2224
+ return;
2225
+ if (node.type === 'Identifier') {
2226
+ const helper = found.find(h => h.name === node.value);
2227
+ if (helper)
2228
+ helper.references++;
2229
+ }
2230
+ for (const key in node) {
2231
+ const value = node[key];
2232
+ if (Array.isArray(value))
2233
+ value.forEach(count);
2234
+ else if (value && typeof value === 'object')
2235
+ count(value);
2236
+ }
2237
+ };
2238
+ count(ast);
2239
+ return found;
2240
+ }
2241
+ /** The `useMemo`/`useCallback` calls with a callback and a dependency array (see `MemoHookSpan`). */
2242
+ function collectMemoHooks(node, hooks) {
2243
+ if (!node || typeof node !== 'object')
2244
+ return;
2245
+ if (node.type === 'CallExpression' && ['useMemo', 'useCallback'].includes(getCalleeName(node.callee) ?? '')) {
2246
+ const [callback, deps] = (node.arguments ?? []).map((a) => a?.expression);
2247
+ if (callback?.span && deps?.type === 'ArrayExpression' && deps.span) {
2248
+ const elements = (deps.elements ?? []).filter(Boolean).map((e) => e.expression);
2249
+ hooks.push({
2250
+ callbackStart: callback.span.start,
2251
+ callbackEnd: callback.span.end,
2252
+ insertAt: elements.length ? elements[elements.length - 1].span.end : deps.span.start + 1,
2253
+ hasDeps: elements.length > 0,
2254
+ hasT: elements.some((e) => e.type === 'Identifier' && e.value === 't')
2255
+ });
2256
+ }
2257
+ }
2258
+ for (const key in node) {
2259
+ const value = node[key];
2260
+ if (value && typeof value === 'object') {
2261
+ if (Array.isArray(value))
2262
+ value.forEach(item => collectMemoHooks(item, hooks));
2263
+ else
2264
+ collectMemoHooks(value, hooks);
2265
+ }
2266
+ }
2267
+ }
1337
2268
  /**
1338
2269
  * Inspects a single CallExpression node to determine if it is a language-change
1339
2270
  * call. Returns the detected site data (without line/column) or `null`.
@@ -1350,10 +2281,10 @@ function tryParseLanguageChangeCall(node, content) {
1350
2281
  if (objName === 'i18n' || objName === 'i18next')
1351
2282
  return null;
1352
2283
  }
1353
- // ── Pattern 1: direct setter — setLanguage(expr), changeLocale(expr) etc. ──
2284
+ // ── Pattern 1: direct setter, setLanguage(expr), changeLocale(expr) etc. ──
1354
2285
  if (calleeName && LANGUAGE_SETTER_RE.test(calleeName)) {
1355
2286
  const firstArg = node.arguments[0]?.expression;
1356
- if (firstArg?.span) {
2287
+ if (firstArg?.span && isPlainValue(firstArg)) {
1357
2288
  const langExpr = content.slice(firstArg.span.start, firstArg.span.end);
1358
2289
  // Skip if the argument is already an i18next.changeLanguage call
1359
2290
  if (langExpr.includes('changeLanguage'))
@@ -1365,7 +2296,9 @@ function tryParseLanguageChangeCall(node, content) {
1365
2296
  };
1366
2297
  }
1367
2298
  }
1368
- // ── Pattern 2: object with language property — fn({ language: expr }) ──
2299
+ // ── Pattern 2: object with language property, updateSettings({ language: expr }) ──
2300
+ if (!calleeName || /^use[A-Z]/.test(calleeName) || !SETTINGS_CALLEE_RE.test(calleeName))
2301
+ return null;
1369
2302
  for (const arg of node.arguments) {
1370
2303
  const expr = arg.expression ?? arg;
1371
2304
  if (expr?.type !== 'ObjectExpression')
@@ -1385,8 +2318,8 @@ function tryParseLanguageChangeCall(node, content) {
1385
2318
  const valNode = prop.value;
1386
2319
  if (valNode?.span) {
1387
2320
  const langExpr = content.slice(valNode.span.start, valNode.span.end);
1388
- // Skip if value is a static string (e.g. `{ language: 'en' }` in a config)
1389
- if (valNode.type === 'StringLiteral')
2321
+ // Skip if value is a static string (e.g. `{ language: 'en' }` in a config), or not a plain value
2322
+ if (valNode.type === 'StringLiteral' || !isPlainValue(valNode))
1390
2323
  continue;
1391
2324
  // Skip if already contains changeLanguage
1392
2325
  if (langExpr.includes('changeLanguage'))
@@ -1420,7 +2353,11 @@ function getCalleeName(callee) {
1420
2353
  * Gets the list of source files to instrument.
1421
2354
  */
1422
2355
  async function getSourceFilesForInstrumentation(config) {
1423
- const defaultIgnore = ['node_modules/**', 'dist/**', 'build/**', '.next/**'];
2356
+ // Stories, mocks and fixtures hold sample data, not the app's texts
2357
+ const defaultIgnore = [
2358
+ 'node_modules/**', 'dist/**', 'build/**', '.next/**',
2359
+ '**/*.{stories,story,storybook}.*', '**/__mocks__/**', '**/__fixtures__/**', '**/__tests__/**'
2360
+ ];
1424
2361
  const userIgnore = Array.isArray(config.extract.ignore)
1425
2362
  ? config.extract.ignore
1426
2363
  : config.extract.ignore ? [config.extract.ignore] : [];
@@ -1435,16 +2372,8 @@ async function getSourceFilesForInstrumentation(config) {
1435
2372
  * Checks if the project uses React.
1436
2373
  */
1437
2374
  async function isProjectUsingReact() {
1438
- try {
1439
- const packageJsonPath = process.cwd() + '/package.json';
1440
- const content = await promises.readFile(packageJsonPath, 'utf-8');
1441
- const packageJson = JSON.parse(content);
1442
- const deps = { ...packageJson.dependencies, ...packageJson.devDependencies };
1443
- return !!deps.react || !!deps['react-i18next'];
1444
- }
1445
- catch {
1446
- return false;
1447
- }
2375
+ const deps = await fileUtils.readProjectDeps();
2376
+ return !!deps.react || !!deps['react-i18next'];
1448
2377
  }
1449
2378
  /** Well-known frontend framework packages (presence → browser environment). */
1450
2379
  const FRONTEND_FRAMEWORKS = [
@@ -1481,13 +2410,7 @@ const SERVER_FRAMEWORKS = [
1481
2410
  */
1482
2411
  async function detectProjectEnvironment() {
1483
2412
  try {
1484
- const packageJsonPath = process.cwd() + '/package.json';
1485
- const raw = await promises.readFile(packageJsonPath, 'utf-8');
1486
- const packageJson = JSON.parse(raw);
1487
- const allDeps = {
1488
- ...packageJson.dependencies,
1489
- ...packageJson.devDependencies
1490
- };
2413
+ const allDeps = await fileUtils.readProjectDeps();
1491
2414
  const has = (list) => list.some(dep => !!allDeps[dep]);
1492
2415
  // 1. Edge / serverless (check first — these projects may also list a
1493
2416
  // bundler or even a framework, but they have no filesystem)
@@ -1586,28 +2509,10 @@ function buildDynamicImportPath(outputTemplate, initDir) {
1586
2509
  */
1587
2510
  async function ensureI18nInitFile(hasReact, hasTypeScript, config, logger, usesI18nextT) {
1588
2511
  const cwd = process.cwd();
1589
- // Check for existing init files in common locations
2512
+ // Check for existing init files in common locations (an init elsewhere imports i18next, see runInstrumenter)
1590
2513
  if (await findExistingI18nInitFile()) {
1591
2514
  return null; // Init file already exists
1592
2515
  }
1593
- // Check if i18next.init() is called anywhere in the source
1594
- try {
1595
- const sourceFiles = await getSourceFilesForInstrumentation(config);
1596
- for (const file of sourceFiles) {
1597
- try {
1598
- const content = await promises.readFile(file, 'utf-8');
1599
- if (content.includes('i18next.init') || content.includes('.init(') || content.includes('i18n.init')) {
1600
- return null; // Init is already present somewhere
1601
- }
1602
- }
1603
- catch {
1604
- // Skip unreadable files
1605
- }
1606
- }
1607
- }
1608
- catch {
1609
- // Skip if file scanning fails
1610
- }
1611
2516
  // Determine output location — prefer src/ if it exists
1612
2517
  const srcExists = await fileExists(node_path.join(cwd, 'src'));
1613
2518
  const initDir = srcExists ? node_path.join(cwd, 'src') : cwd;