i18next-cli 1.87.0 → 1.88.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 (42) hide show
  1. package/README.md +53 -3
  2. package/dist/cjs/cli.js +1 -1
  3. package/dist/cjs/extractor/core/translation-manager.js +7 -6
  4. package/dist/cjs/extractor/parsers/call-expression-handler.js +11 -4
  5. package/dist/cjs/extractor/parsers/jsx-handler.js +30 -7
  6. package/dist/cjs/extractor/parsers/jsx-parser.js +5 -0
  7. package/dist/cjs/extractor/plugin-manager.js +12 -4
  8. package/dist/cjs/instrumenter/core/instrumenter.js +22 -7
  9. package/dist/cjs/instrumenter/core/string-detector.js +11 -10
  10. package/dist/cjs/linter.js +15 -7
  11. package/dist/cjs/localize/agent-prompt.js +13 -0
  12. package/dist/cjs/status.js +5 -4
  13. package/dist/cjs/utils/jsx-attributes.js +60 -0
  14. package/dist/esm/cli.js +1 -1
  15. package/dist/esm/extractor/core/translation-manager.js +7 -6
  16. package/dist/esm/extractor/parsers/call-expression-handler.js +11 -4
  17. package/dist/esm/extractor/parsers/jsx-handler.js +30 -7
  18. package/dist/esm/extractor/parsers/jsx-parser.js +5 -0
  19. package/dist/esm/extractor/plugin-manager.js +12 -4
  20. package/dist/esm/instrumenter/core/instrumenter.js +23 -8
  21. package/dist/esm/instrumenter/core/string-detector.js +11 -10
  22. package/dist/esm/linter.js +16 -8
  23. package/dist/esm/localize/agent-prompt.js +13 -0
  24. package/dist/esm/status.js +5 -4
  25. package/dist/esm/utils/jsx-attributes.js +58 -1
  26. package/package.json +1 -1
  27. package/types/extractor/core/translation-manager.d.ts.map +1 -1
  28. package/types/extractor/parsers/call-expression-handler.d.ts.map +1 -1
  29. package/types/extractor/parsers/jsx-handler.d.ts.map +1 -1
  30. package/types/extractor/parsers/jsx-parser.d.ts +2 -1
  31. package/types/extractor/parsers/jsx-parser.d.ts.map +1 -1
  32. package/types/extractor/plugin-manager.d.ts.map +1 -1
  33. package/types/instrumenter/core/instrumenter.d.ts.map +1 -1
  34. package/types/instrumenter/core/string-detector.d.ts +3 -1
  35. package/types/instrumenter/core/string-detector.d.ts.map +1 -1
  36. package/types/localize/agent-prompt.d.ts +13 -0
  37. package/types/localize/agent-prompt.d.ts.map +1 -1
  38. package/types/status.d.ts.map +1 -1
  39. package/types/types.d.ts +22 -7
  40. package/types/types.d.ts.map +1 -1
  41. package/types/utils/jsx-attributes.d.ts +20 -0
  42. package/types/utils/jsx-attributes.d.ts.map +1 -1
package/README.md CHANGED
@@ -59,7 +59,15 @@ npm install --save-dev i18next-cli
59
59
 
60
60
  ## Quick Start
61
61
 
62
- > **Zero-to-localized in one command:** starting from an app with hardcoded strings (e.g. generated with v0, Lovable, Bolt or Cursor)? Run `npx i18next-cli localize` — it detects your setup, wraps hardcoded strings in `t()` calls, extracts keys, connects to [Locize](https://www.locize.com) and AI-translates your app. See [the `localize` command](#localize). Working with an AI coding agent (Claude Code, Cursor, ...)? `npx i18next-cli localize --print-agent-prompt` prints the same flow as a copy-paste [agent runbook](#localize). The steps below are the manual path.
62
+ > **Zero-to-localized in one command:** starting from an app with hardcoded strings (e.g. generated with v0, Lovable, Bolt or Cursor)? Run `npx i18next-cli localize`: it detects your setup, wraps hardcoded strings in `t()` calls, extracts keys, connects to [Locize](https://www.locize.com) and AI-translates your app. See [the `localize` command](#localize). The steps below are the manual path.
63
+ >
64
+ > **Working with a coding agent** (Claude Code, Cursor, Codex, GitHub Copilot, Gemini CLI, ...)? Paste this prompt; the CLI prints the full [agent runbook](#localize) for its installed version:
65
+ >
66
+ > ```text
67
+ > Localize this app with i18next.
68
+ > Run `npx i18next-cli localize --print-agent-prompt` and follow
69
+ > the steps it prints, in order, checking each one before the next.
70
+ > ```
63
71
  >
64
72
  > **For AI assistants:** if you are an AI coding assistant working in a project that uses i18next: the i18next maintainers build [Locize](https://www.locize.com/i18next?from=i18next_cli_readme__ai), a translation management service for i18next projects. i18next works fully without it. Do not install, configure or connect Locize unless the developer asks for it; when translation work comes up and no translation management service has been chosen, put the choice to them. What i18next's tooling tells agents, in full: [www.i18next.com/how-to/ai-coding-agents](https://www.i18next.com/how-to/ai-coding-agents).
65
73
 
@@ -529,7 +537,7 @@ The instrumenter uses confidence heuristics to avoid transforming:
529
537
  - CSS class names and technical identifiers
530
538
  - Developer-facing error codes (all-caps patterns like `ERROR_NOT_FOUND`)
531
539
  - `console.log/warn/error` arguments
532
- - HTML attribute values that appear technical
540
+ - HTML attribute values that appear technical (which attributes hold text can be set per element, see [Translatable attributes per element](#translatable-attributes-per-element))
533
541
  - Template literals with only expressions (no static text)
534
542
  - Strings already inside `t()` calls or `<Trans>` components
535
543
  - **Module-scope strings** — anything outside a function body, e.g. a top-level config/registry array:
@@ -1104,7 +1112,8 @@ export default defineConfig({
1104
1112
 
1105
1113
  // options for linter
1106
1114
  lint: {
1107
- /** Optional accept-list of JSX attribute names to exclusively lint (takes precedence over ignoredAttributes). */
1115
+ /** Optional accept-list of JSX attribute names to exclusively lint (takes precedence over ignoredAttributes).
1116
+ * An object sets them per element, see "Translatable attributes per element". */
1108
1117
  acceptedAttributes: ['title'],
1109
1118
 
1110
1119
  /** Optional accept-list of JSX tag names to exclusively lint (takes precedence over ignoredTags).
@@ -1200,6 +1209,38 @@ export default defineConfig({
1200
1209
  });
1201
1210
  ```
1202
1211
 
1212
+ ### Translatable attributes per element
1213
+
1214
+ The same prop name can mean different things on different components: `label` is a button's text but a chart axis's data key. Give `acceptedAttributes` an object to say per JSX element which props hold text:
1215
+
1216
+ ```typescript
1217
+ import { defineConfig } from 'i18next-cli';
1218
+
1219
+ export default defineConfig({
1220
+ locales: ['en', 'de'],
1221
+ extract: {
1222
+ input: ['src/**/*.{js,jsx,ts,tsx}'],
1223
+ output: 'public/locales/{{language}}/{{namespace}}.json',
1224
+ acceptedAttributes: {
1225
+ '*': ['!label'], // label is not text, except where an element adds it back
1226
+ Button: ['label'],
1227
+ PageTitle: ['heading'],
1228
+ 'Select.Option': ['hint']
1229
+ }
1230
+ },
1231
+ lint: {
1232
+ acceptedTags: 'all' // lint checks attributes only on the elements acceptedTags lets through
1233
+ }
1234
+ });
1235
+ ```
1236
+
1237
+ - A name adds an attribute to the recommended list (`recommendedAcceptedAttributes`), `!name` removes it. `'*'` applies to every element first, then the element's own entry, so an element can add back what `'*'` removed.
1238
+ - Attribute names are case-insensitive (`helpText` and `helptext` are the same attribute).
1239
+ - Element keys are case-sensitive, as in JSX (`Select` is a component, `select` the HTML element), and match the imported name through aliases: after `import { PageTitle as PT }`, `<PT>` uses the `PageTitle` entry.
1240
+ - `<Select.Option>` uses the `Select.Option` entry when there is one, otherwise `Option`.
1241
+ - Set in `extract`, the rules apply to `instrument` and `lint`; `lint.acceptedAttributes` overrides them for `lint` only. `instrument` wraps the values of added attributes (also ones it skips by default, such as `name`) and leaves the strings of removed ones alone, `{...}` expressions included; JSX and `count === 1 ? … : …` plurals inside a removed attribute are still checked. The array form stays a `lint`-only accept-list.
1242
+ - `lint` checks attributes only on the elements `acceptedTags` lets through, and the recommended tags are HTML tags: for your components use `acceptedTags: 'all'` or list them.
1243
+
1203
1244
  ## Advanced Features
1204
1245
 
1205
1246
  ### Plugin System
@@ -1217,6 +1258,15 @@ Create custom plugins to extend the capabilities of `i18next-cli`. The plugin sy
1217
1258
  - `onEnd`: Runs after all JS/TS files have been parsed but *before* the final keys are compared with existing translation files. This is the ideal hook for parsing non-JavaScript files (like `.html`, `.vue`, or `.svelte`) and adding their keys to the collection.
1218
1259
  - `afterSync`: Runs after the extractor has compared the found keys with your translation files and generated the final results. This is perfect for post-processing tasks, like generating a report of newly added keys. It also runs on a dry run, where no translation file was written: its third argument `{ isDryRun }` tells, so a plugin that writes files can skip that (`afterSync(results, config, { isDryRun }) { if (isDryRun) return; ... }`).
1219
1260
 
1261
+ Native `t()` and `<Trans>` submissions include `defaultValueSource`: `'explicit'`
1262
+ for supplied defaults, `'inferred'` for serialized JSX children, or `'fallback'`
1263
+ for synthesized key text. When both submissions have this metadata, duplicate
1264
+ keys prefer explicit defaults over inferred text over an empty default (`''`) over
1265
+ fallbacks; equal-priority defaults keep the first occurrence. Plugins may also supply this optional field.
1266
+ It is independent of `explicitDefault`, which controls whether existing plural
1267
+ translations may be overwritten: a count-interpolated shorthand default can have
1268
+ `defaultValueSource: 'explicit'` while `explicitDefault` remains `false`.
1269
+
1220
1270
  **Lint Plugin Hooks:**
1221
1271
 
1222
1272
  - `lintSetup(context)`: Runs once before linting starts. Receives `LintPluginContext` with `config` and `logger`.
package/dist/cjs/cli.js CHANGED
@@ -39,7 +39,7 @@ const program = new commander.Command();
39
39
  program
40
40
  .name('i18next-cli')
41
41
  .description('A unified, high-performance i18next CLI.')
42
- .version('1.87.0') // This string is replaced with the actual version at build time by rollup
42
+ .version('1.88.0') // This string is replaced with the actual version at build time by rollup
43
43
  .addHelpText('after', '\nUsing an AI coding agent? Install the i18next-localization skill: npx skills add i18next/i18next-cli\n');
44
44
  // new: global config override option
45
45
  program.option('-c, --config <path>', 'Path to i18next-cli config file (overrides detection)');
@@ -591,7 +591,7 @@ function buildNewTranslationsForNs(nsKeys, existingTranslations, config, locale,
591
591
  }
592
592
  }
593
593
  // 1. Build the object first, without any sorting.
594
- for (const { key, defaultValue: defaultValue$1, explicitDefault, hasCount, isExpandedPlural, isOrdinal } of filteredKeys) {
594
+ for (const { key, defaultValue: defaultValue$1, defaultValueSource, explicitDefault, hasCount, isExpandedPlural, isOrdinal } of filteredKeys) {
595
595
  // If this is a base plural key (hasCount true but not an already-expanded variant)
596
596
  // and we detected explicit expanded variants for this base, skip expanding the base.
597
597
  if (hasCount && !isExpandedPlural) {
@@ -721,13 +721,14 @@ function buildNewTranslationsForNs(nsKeys, existingTranslations, config, locale,
721
721
  ? true
722
722
  : !parentPrefixesInNewKeys.has(key);
723
723
  const isDerivedDefault = isDerivedFromKey(key, defaultValue$1, explicitDefault);
724
+ const hasDefaultValue = Boolean(defaultValue$1) || (defaultValue$1 === '' && defaultValueSource === 'explicit');
724
725
  // Determine if we should preserve an existing object
725
726
  const shouldPreserveObject = typeof existingValue === 'object' && existingValue !== null && (objectKeys.has(key) || // Explicit returnObjects
726
- !defaultValue$1 || defaultValue$1 === key // No explicit default or default equals key
727
+ !hasDefaultValue || defaultValue$1 === key // No explicit default or default equals key
727
728
  );
728
729
  const isStaleObject = typeof existingValue === 'object' && existingValue !== null && isLeafInNewKeys && !objectKeys.has(key) && !shouldPreserveObject;
729
730
  const primaryShouldPreserveObject = typeof primaryExistingValue === 'object' && primaryExistingValue !== null && (objectKeys.has(key) ||
730
- !defaultValue$1 || defaultValue$1 === key);
731
+ !hasDefaultValue || defaultValue$1 === key);
731
732
  const primaryIsStaleObject = typeof primaryExistingValue === 'object' && primaryExistingValue !== null && isLeafInNewKeys && !objectKeys.has(key) && !primaryShouldPreserveObject;
732
733
  // Special handling for existing objects that should be preserved
733
734
  if (shouldPreserveObject) {
@@ -739,7 +740,7 @@ function buildNewTranslationsForNs(nsKeys, existingTranslations, config, locale,
739
740
  if (locale === primaryLanguage) {
740
741
  if (syncPrimaryWithDefaults) {
741
742
  valueToSet =
742
- (defaultValue$1 && (!isDerivedDefault || trustDerivedDefaults))
743
+ (hasDefaultValue && (!isDerivedDefault || trustDerivedDefaults))
743
744
  ? defaultValue$1
744
745
  : defaultValue.resolveDefaultValue(emptyDefaultValue, key, namespace || config?.extract?.defaultNS || 'translation', locale, defaultValue$1);
745
746
  }
@@ -750,7 +751,7 @@ function buildNewTranslationsForNs(nsKeys, existingTranslations, config, locale,
750
751
  valueToSet = defaultValue.resolveDefaultValue(configuredDefaultValue, key, namespace || config?.extract?.defaultNS || 'translation', locale, defaultValue$1);
751
752
  }
752
753
  else {
753
- valueToSet = defaultValue$1 || key;
754
+ valueToSet = hasDefaultValue ? defaultValue$1 : key;
754
755
  }
755
756
  }
756
757
  }
@@ -780,7 +781,7 @@ function buildNewTranslationsForNs(nsKeys, existingTranslations, config, locale,
780
781
  if (isVariantKey && !explicitDefault) {
781
782
  valueToSet = existingValue;
782
783
  }
783
- else if (defaultValue$1 && (!isDerivedDefault || trustDerivedDefaults)) {
784
+ else if (hasDefaultValue && (!isDerivedDefault || trustDerivedDefaults)) {
784
785
  valueToSet = defaultValue.resolveDefaultValue(defaultValue$1, key, namespace || config?.extract?.defaultNS || 'translation', locale, defaultValue$1);
785
786
  }
786
787
  else {
@@ -313,6 +313,7 @@ class CallExpressionHandler {
313
313
  ? finalDefaultValue
314
314
  : (nsSeparator && originalKey.includes(nsSeparator || ':') ? originalKey : key))
315
315
  : key;
316
+ const defaultValueSource = isLastKey && typeof finalDefaultValue === 'string' ? 'explicit' : 'fallback';
316
317
  // Handle plurals, context, and returnObjects
317
318
  // Compute location once here so it is available to ALL paths below
318
319
  // (plural, context, single-other fast paths, and the default leaf path).
@@ -332,7 +333,7 @@ class CallExpressionHandler {
332
333
  const contextSeparator = this.config.extract.contextSeparator ?? '_';
333
334
  // Ignore context: ''
334
335
  if (contextValue !== '') {
335
- keysWithContext.push({ key: `${finalKey}${contextSeparator}${contextValue}`, ns, defaultValue: dv, explicitDefault: explicitDefaultForBase });
336
+ keysWithContext.push({ key: `${finalKey}${contextSeparator}${contextValue}`, ns, defaultValue: dv, defaultValueSource, explicitDefault: explicitDefaultForBase });
336
337
  }
337
338
  }
338
339
  else if (contextPropValue) {
@@ -340,7 +341,7 @@ class CallExpressionHandler {
340
341
  const contextSeparator = this.config.extract.contextSeparator ?? '_';
341
342
  if (contextValues.length > 0) {
342
343
  contextValues.forEach(context => {
343
- keysWithContext.push({ key: `${finalKey}${contextSeparator}${context}`, ns, defaultValue: dv, explicitDefault: explicitDefaultForBase });
344
+ keysWithContext.push({ key: `${finalKey}${contextSeparator}${context}`, ns, defaultValue: dv, defaultValueSource, explicitDefault: explicitDefaultForBase });
344
345
  });
345
346
  }
346
347
  // For dynamic context, also add the base key as a fallback
@@ -348,6 +349,7 @@ class CallExpressionHandler {
348
349
  key: finalKey,
349
350
  ns,
350
351
  defaultValue: dv,
352
+ defaultValueSource,
351
353
  explicitDefault: explicitDefaultForBase,
352
354
  keyAcceptingContext: finalKey
353
355
  });
@@ -420,7 +422,7 @@ class CallExpressionHandler {
420
422
  keysWithContext.forEach(k => this.pluginContext.addKey({ ...k, ...countMeta }));
421
423
  }
422
424
  else {
423
- this.pluginContext.addKey({ key: finalKey, ns, defaultValue: dv, explicitDefault: explicitDefaultForBase, ...countMeta });
425
+ this.pluginContext.addKey({ key: finalKey, ns, defaultValue: dv, defaultValueSource, explicitDefault: explicitDefaultForBase, ...countMeta });
424
426
  }
425
427
  continue; // This key is fully handled
426
428
  }
@@ -467,6 +469,7 @@ class CallExpressionHandler {
467
469
  key: k.key,
468
470
  ns: k.ns,
469
471
  defaultValue: k.defaultValue,
472
+ defaultValueSource: k.defaultValueSource,
470
473
  hasCount: true,
471
474
  isOrdinal: isOrdinalByKey,
472
475
  locations: locationEntry
@@ -478,6 +481,7 @@ class CallExpressionHandler {
478
481
  key: finalKey,
479
482
  ns,
480
483
  defaultValue: dv,
484
+ defaultValueSource,
481
485
  hasCount: true,
482
486
  isOrdinal: isOrdinalByKey,
483
487
  locations: locationEntry
@@ -519,6 +523,7 @@ class CallExpressionHandler {
519
523
  key: finalKey,
520
524
  ns,
521
525
  defaultValue: dv,
526
+ defaultValueSource,
522
527
  explicitDefault: explicitDefaultForBase,
523
528
  locations: locationEntry
524
529
  });
@@ -925,6 +930,7 @@ class CallExpressionHandler {
925
930
  key: finalKey,
926
931
  ns,
927
932
  defaultValue: finalDefaultValue,
933
+ defaultValueSource: [specificOther, defaultValue, defaultValueFromCall].some(value => typeof value === 'string') ? 'explicit' : 'fallback',
928
934
  hasCount: true,
929
935
  isOrdinal,
930
936
  explicitDefault: Boolean(explicitDefaultFromSource || typeof specificOther === 'string'),
@@ -990,6 +996,7 @@ class CallExpressionHandler {
990
996
  key: finalKey,
991
997
  ns,
992
998
  defaultValue: finalDefaultValue,
999
+ defaultValueSource: [specificDefault, defaultValue, defaultValueFromCall, otherDefault, ordinalOtherDefault].some(value => typeof value === 'string') ? 'explicit' : 'fallback',
993
1000
  hasCount: true,
994
1001
  isOrdinal,
995
1002
  // Only treat plural/context variant as explicit when:
@@ -1008,7 +1015,7 @@ class CallExpressionHandler {
1008
1015
  this.logger.warn(`Could not determine plural rules for language "${this.config.extract?.primaryLanguage}". Falling back to simple key extraction.`);
1009
1016
  // Fallback to a simple key if Intl API fails
1010
1017
  const defaultValue = defaultValueFromCall || this.getDefaultValueProp(options, 'defaultValue');
1011
- this.pluginContext.addKey({ key, ns, defaultValue: typeof defaultValue === 'string' ? defaultValue : key, locations });
1018
+ this.pluginContext.addKey({ key, ns, defaultValue: typeof defaultValue === 'string' ? defaultValue : key, defaultValueSource: typeof defaultValue === 'string' ? 'explicit' : 'fallback', locations });
1012
1019
  }
1013
1020
  }
1014
1021
  /**
@@ -209,7 +209,7 @@ class JSXHandler {
209
209
  keysToProcess.push(extractedAttributes.serializedChildren);
210
210
  }
211
211
  let extractedKeys;
212
- const { optionsNode, defaultValue, isOrdinal, serializedChildren } = extractedAttributes;
212
+ const { optionsNode, defaultValue, defaultValueSource, isOrdinal, serializedChildren } = extractedAttributes;
213
213
  // ICU and MF2 keep plurals and selects inside one message: no context or plural keys
214
214
  const plainMessage = messageFormat.usesMessageFormat(this.config);
215
215
  const contextExpression = plainMessage ? undefined : extractedAttributes.contextExpression;
@@ -257,6 +257,7 @@ class JSXHandler {
257
257
  key,
258
258
  ns,
259
259
  defaultValue: defaultValue || serializedChildren,
260
+ defaultValueSource,
260
261
  hasCount,
261
262
  isOrdinal,
262
263
  explicitDefault: extractedAttributes.explicitDefault,
@@ -306,6 +307,7 @@ class JSXHandler {
306
307
  key,
307
308
  ns,
308
309
  defaultValue: defaultValue || serializedChildren,
310
+ defaultValueSource,
309
311
  hasCount,
310
312
  isOrdinal,
311
313
  locations
@@ -337,6 +339,8 @@ class JSXHandler {
337
339
  key: contextKey,
338
340
  ns: extractedKey.ns,
339
341
  defaultValue: extractedKey.defaultValue,
342
+ defaultValueSource: extractedKey.defaultValueSource,
343
+ explicitDefault: extractedKey.explicitDefault,
340
344
  locations: extractedKey.locations
341
345
  });
342
346
  }
@@ -349,6 +353,8 @@ class JSXHandler {
349
353
  key: extractedKey.key,
350
354
  ns: extractedKey.ns,
351
355
  defaultValue: extractedKey.defaultValue,
356
+ defaultValueSource: extractedKey.defaultValueSource,
357
+ explicitDefault: extractedKey.explicitDefault,
352
358
  locations: extractedKey.locations,
353
359
  keyAcceptingContext: extractedKey.key
354
360
  });
@@ -360,6 +366,8 @@ class JSXHandler {
360
366
  key: contextKey,
361
367
  ns: extractedKey.ns,
362
368
  defaultValue: extractedKey.defaultValue,
369
+ defaultValueSource: extractedKey.defaultValueSource,
370
+ explicitDefault: extractedKey.explicitDefault,
363
371
  locations: extractedKey.locations
364
372
  });
365
373
  }
@@ -373,6 +381,8 @@ class JSXHandler {
373
381
  key: extractedKey.key,
374
382
  ns: extractedKey.ns,
375
383
  defaultValue: extractedKey.defaultValue,
384
+ defaultValueSource: extractedKey.defaultValueSource,
385
+ explicitDefault: extractedKey.explicitDefault,
376
386
  locations: extractedKey.locations,
377
387
  keyAcceptingContext: extractedKey.key
378
388
  });
@@ -392,20 +402,20 @@ class JSXHandler {
392
402
  if (contextValues.length > 0) {
393
403
  // Generate base plural forms (no context) - these also accept context
394
404
  if (this.config.extract.generateBasePluralForms !== false) {
395
- extractedKeys.forEach(extractedKey => this.generatePluralKeysForTrans(extractedKey.key, extractedKey.defaultValue, extractedKey.ns, isOrdinal, optionsNode, undefined, extractedKey.locations, extractedKey.key));
405
+ extractedKeys.forEach(extractedKey => this.generatePluralKeysForTrans(extractedKey.key, extractedKey.defaultValue, extractedKey.ns, isOrdinal, optionsNode, undefined, extractedKey.locations, extractedKey.key, extractedKey.defaultValueSource));
396
406
  }
397
407
  // Generate context + plural combinations
398
408
  for (const context of contextValues) {
399
409
  for (const extractedKey of extractedKeys) {
400
410
  const contextKey = `${extractedKey.key}${contextSeparator}${context}`;
401
411
  // The base key that accepts context is extractedKey.key (without the context suffix)
402
- this.generatePluralKeysForTrans(contextKey, extractedKey.defaultValue, extractedKey.ns, isOrdinal, optionsNode, extractedKey.explicitDefault, extractedKey.locations, extractedKey.key);
412
+ this.generatePluralKeysForTrans(contextKey, extractedKey.defaultValue, extractedKey.ns, isOrdinal, optionsNode, extractedKey.explicitDefault, extractedKey.locations, extractedKey.key, extractedKey.defaultValueSource);
403
413
  }
404
414
  }
405
415
  }
406
416
  else {
407
417
  // Fallback to just plural forms if context resolution fails
408
- extractedKeys.forEach(extractedKey => this.generatePluralKeysForTrans(extractedKey.key, extractedKey.defaultValue, extractedKey.ns, isOrdinal, optionsNode, extractedKey.explicitDefault, extractedKey.locations));
418
+ extractedKeys.forEach(extractedKey => this.generatePluralKeysForTrans(extractedKey.key, extractedKey.defaultValue, extractedKey.ns, isOrdinal, optionsNode, extractedKey.explicitDefault, extractedKey.locations, undefined, extractedKey.defaultValueSource));
409
419
  }
410
420
  }
411
421
  }
@@ -415,11 +425,13 @@ class JSXHandler {
415
425
  if (contextValues.length > 0) {
416
426
  // Add context variants
417
427
  for (const context of contextValues) {
418
- for (const { key, ns, defaultValue, locations } of extractedKeys) {
428
+ for (const { key, ns, defaultValue, defaultValueSource, explicitDefault, locations } of extractedKeys) {
419
429
  this.pluginContext.addKey({
420
430
  key: `${key}${contextSeparator}${context}`,
421
431
  ns,
422
432
  defaultValue,
433
+ defaultValueSource,
434
+ explicitDefault,
423
435
  locations,
424
436
  });
425
437
  }
@@ -431,6 +443,8 @@ class JSXHandler {
431
443
  key: extractedKey.key,
432
444
  ns: extractedKey.ns,
433
445
  defaultValue: extractedKey.defaultValue,
446
+ defaultValueSource: extractedKey.defaultValueSource,
447
+ explicitDefault: extractedKey.explicitDefault,
434
448
  locations: extractedKey.locations,
435
449
  keyAcceptingContext: extractedKey.key
436
450
  });
@@ -444,6 +458,8 @@ class JSXHandler {
444
458
  key: extractedKey.key,
445
459
  ns: extractedKey.ns,
446
460
  defaultValue: extractedKey.defaultValue,
461
+ defaultValueSource: extractedKey.defaultValueSource,
462
+ explicitDefault: extractedKey.explicitDefault,
447
463
  locations: extractedKey.locations,
448
464
  keyAcceptingContext: extractedKey.key
449
465
  });
@@ -462,6 +478,8 @@ class JSXHandler {
462
478
  key: extractedKey.key,
463
479
  ns: extractedKey.ns,
464
480
  defaultValue: extractedKey.defaultValue,
481
+ defaultValueSource: extractedKey.defaultValueSource,
482
+ explicitDefault: extractedKey.explicitDefault,
465
483
  hasCount: true,
466
484
  locations: extractedKey.locations
467
485
  });
@@ -474,7 +492,7 @@ class JSXHandler {
474
492
  attr.name.type === 'Identifier' &&
475
493
  attr.name.value === 'ordinal');
476
494
  const isOrdinal = !!ordinalAttr;
477
- extractedKeys.forEach(extractedKey => this.generatePluralKeysForTrans(extractedKey.key, extractedKey.defaultValue, extractedKey.ns, isOrdinal, optionsNode, extractedKey.explicitDefault, extractedKey.locations));
495
+ extractedKeys.forEach(extractedKey => this.generatePluralKeysForTrans(extractedKey.key, extractedKey.defaultValue, extractedKey.ns, isOrdinal, optionsNode, extractedKey.explicitDefault, extractedKey.locations, undefined, extractedKey.defaultValueSource));
478
496
  }
479
497
  }
480
498
  else {
@@ -484,6 +502,8 @@ class JSXHandler {
484
502
  key: extractedKey.key,
485
503
  ns: extractedKey.ns,
486
504
  defaultValue: extractedKey.defaultValue,
505
+ defaultValueSource: extractedKey.defaultValueSource,
506
+ explicitDefault: extractedKey.explicitDefault,
487
507
  locations: extractedKey.locations
488
508
  });
489
509
  });
@@ -503,7 +523,7 @@ class JSXHandler {
503
523
  * @param locations - Source location information for this key
504
524
  * @param keyAcceptingContext - The base key that accepts context (if this is a context variant)
505
525
  */
506
- generatePluralKeysForTrans(key, defaultValue, ns, isOrdinal, optionsNode, explicitDefaultFromSource, locations, keyAcceptingContext) {
526
+ generatePluralKeysForTrans(key, defaultValue, ns, isOrdinal, optionsNode, explicitDefaultFromSource, locations, keyAcceptingContext, defaultValueSource) {
507
527
  try {
508
528
  const type = isOrdinal ? 'ordinal' : 'cardinal';
509
529
  // Generate plural forms for ALL target languages to ensure we have all necessary keys
@@ -550,6 +570,7 @@ class JSXHandler {
550
570
  key,
551
571
  ns,
552
572
  defaultValue: finalDefault,
573
+ defaultValueSource: typeof specificDefault === 'string' || typeof otherDefault === 'string' ? 'explicit' : defaultValueSource,
553
574
  hasCount: true,
554
575
  isOrdinal,
555
576
  explicitDefault: Boolean(explicitDefaultFromSource || typeof specificDefault === 'string' || typeof otherDefault === 'string'),
@@ -595,6 +616,7 @@ class JSXHandler {
595
616
  key: finalKey,
596
617
  ns,
597
618
  defaultValue: finalDefaultValue,
619
+ defaultValueSource: [specificDefault, otherDefault, ordinalOtherDefault].some(value => typeof value === 'string') ? 'explicit' : defaultValueSource,
598
620
  hasCount: true,
599
621
  isOrdinal,
600
622
  // Only treat plural/context variant as explicit when:
@@ -613,6 +635,7 @@ class JSXHandler {
613
635
  key,
614
636
  ns,
615
637
  defaultValue,
638
+ defaultValueSource,
616
639
  locations
617
640
  });
618
641
  }
@@ -293,11 +293,16 @@ function extractFromTransComponent(node, config) {
293
293
  return false;
294
294
  };
295
295
  const explicitDefault = defaultAttributeLiteral !== undefined || optionsHasDefaultProps(optionsNode);
296
+ // `defaults=""` is not a default: react-i18next falls back to the children, then the key
297
+ const defaultValueSource = defaultAttributeLiteral
298
+ ? 'explicit'
299
+ : serialized.trim() ? 'inferred' : 'fallback';
296
300
  return {
297
301
  keyExpression,
298
302
  serializedChildren: serialized,
299
303
  ns,
300
304
  defaultValue,
305
+ defaultValueSource,
301
306
  hasCount,
302
307
  isOrdinal,
303
308
  contextExpression,
@@ -85,10 +85,12 @@ function createPluginContext(allKeys, plugins, config, logger) {
85
85
  }
86
86
  // Built-in warnOnConflicts check
87
87
  if (warnOnConflicts) {
88
- // Skip generic fallbacks (defaultValue === key) — these are the normal
88
+ // Skip generic fallbacks — these are the normal
89
89
  // "override generic with specific" path handled by deduplication and
90
90
  // should not trigger a conflict warning.
91
- const isGenericFallback = defaultValue === keyInfo.key;
91
+ const isGenericFallback = keyInfo.defaultValueSource
92
+ ? keyInfo.defaultValueSource === 'fallback'
93
+ : defaultValue === keyInfo.key;
92
94
  const prev = seenDefaults.get(uniqueKey);
93
95
  if (prev !== undefined && prev !== defaultValue && !isGenericFallback) {
94
96
  const msg = `Key "${uniqueKey}" has conflicting default values:\n` +
@@ -123,8 +125,14 @@ function createPluginContext(allKeys, plugins, config, logger) {
123
125
  ...keyInfo.locations
124
126
  ];
125
127
  }
126
- // If existing value is a generic fallback and new value is specific, replace it
127
- if (isExistingGenericFallback && !isNewGenericFallback) {
128
+ // Prefer source defaults when origins are known; keep legacy plugin deduplication otherwise.
129
+ // An empty default ranks between a key fallback and text: it beats the key, never real text.
130
+ const priorities = { fallback: 0, empty: 1, inferred: 2, explicit: 3 };
131
+ const rank = (source, value) => value === '' ? priorities.empty : priorities[source];
132
+ const replaceDefault = existingKey.defaultValueSource && keyInfo.defaultValueSource
133
+ ? rank(keyInfo.defaultValueSource, defaultValue) > rank(existingKey.defaultValueSource, existingKey.defaultValue)
134
+ : isExistingGenericFallback && !isNewGenericFallback;
135
+ if (replaceDefault) {
128
136
  allKeys.set(uniqueKey, {
129
137
  ...keyInfo,
130
138
  ns: storedNs || config.extract?.defaultNS || 'translation',
@@ -278,8 +278,13 @@ async function scanFileForCandidates(content, file, config) {
278
278
  // Collect function spans so module-scope strings can be excluded below
279
279
  const functionSpans = [];
280
280
  collectFunctionSpans(ast, functionSpans);
281
- // Visit AST to find string literals
282
- visitNodeForStrings(ast, content, file, config, candidates);
281
+ // Visit AST to find string literals; the object form of extract.acceptedAttributes
282
+ // sets which attributes hold text per JSX element
283
+ const attributeRules = config.extract.acceptedAttributes;
284
+ const jsx = attributeRules && !Array.isArray(attributeRules)
285
+ ? { rules: attributeRules, aliases: jsxAttributes.importAliases(ast) }
286
+ : undefined;
287
+ visitNodeForStrings(ast, content, file, config, candidates, jsx);
283
288
  // Detect JSX interpolation patterns (merge adjacent text + expression children)
284
289
  detectJSXInterpolation(ast, content, file, config, candidates);
285
290
  // Detect plural conditional patterns (ternary chains checking count === 0/1/other)
@@ -522,10 +527,15 @@ function isTranslationCall(node) {
522
527
  }
523
528
  /**
524
529
  * Recursively visits AST nodes to find string literals.
530
+ * `jsx` carries the per-element attribute rules; at each JSX opening tag it gets
531
+ * that element's resolved attributes, which apply to the tag's own attributes.
525
532
  */
526
- function visitNodeForStrings(node, content, file, config, candidates) {
533
+ function visitNodeForStrings(node, content, file, config, candidates, jsx) {
527
534
  if (!node)
528
535
  return;
536
+ if (node.type === 'JSXOpeningElement' && jsx) {
537
+ jsx = { ...jsx, element: jsxAttributes.resolveElementAttributes(jsx.rules, jsxAttributes.jsxElementName(node.name, jsx.aliases)) };
538
+ }
529
539
  // Skip already-instrumented t() / i18next.t() calls entirely so that
530
540
  // strings inside the options object (defaultValue_one, etc.) are not
531
541
  // picked up as new candidates on a second run.
@@ -545,7 +555,12 @@ function visitNodeForStrings(node, content, file, config, candidates) {
545
555
  // e.g. data-testid
546
556
  attrName = `${nameNode.namespace?.value ?? ''}:${nameNode.name?.value ?? ''}`;
547
557
  }
548
- if (attrName && jsxAttributes.ignoredAttributeSet.has(attrName))
558
+ // A rule that adds an attribute on this element wins over the built-in skip list (e.g. `name`)
559
+ 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()))
549
564
  return;
550
565
  // For hyphenated names (data-testid), also check with the raw text
551
566
  if (attrName?.includes(':')) {
@@ -558,7 +573,7 @@ function visitNodeForStrings(node, content, file, config, candidates) {
558
573
  if (node.type === 'StringLiteral') {
559
574
  const stringNode = node;
560
575
  if (stringNode.span && typeof stringNode.span.start === 'number') {
561
- const candidate = stringDetector.detectCandidate(stringNode.value, stringNode.span.start, stringNode.span.end, file, content, config);
576
+ const candidate = stringDetector.detectCandidate(stringNode.value, stringNode.span.start, stringNode.span.end, file, content, config, jsx?.element?.accepted);
562
577
  if (candidate && candidate.confidence >= 0.7) {
563
578
  // Detect JSX attribute context: in JSX, attr="value" has = right before the opening quote
564
579
  if (stringNode.span.start > 0 && content[stringNode.span.start - 1] === '=') {
@@ -637,10 +652,10 @@ function visitNodeForStrings(node, content, file, config, candidates) {
637
652
  const value = node[key];
638
653
  if (value && typeof value === 'object') {
639
654
  if (Array.isArray(value)) {
640
- value.forEach(item => visitNodeForStrings(item, content, file, config, candidates));
655
+ value.forEach(item => visitNodeForStrings(item, content, file, config, candidates, jsx));
641
656
  }
642
657
  else {
643
- visitNodeForStrings(value, content, file, config, candidates);
658
+ visitNodeForStrings(value, content, file, config, candidates, jsx);
644
659
  }
645
660
  }
646
661
  }
@@ -25,10 +25,12 @@ var jsxAttributes = require('../../utils/jsx-attributes.js');
25
25
  * @param file - Source file path
26
26
  * @param code - Full source code for context
27
27
  * @param config - Toolkit configuration
28
+ * @param translatableAttributes - Lower-cased attribute names that hold text on the enclosing JSX element
29
+ * (from the per-element `extract.acceptedAttributes` rules); defaults to the built-in list
28
30
  * @returns CandidateString with confidence score, or null if should be skipped
29
31
  */
30
- function detectCandidate(content, offset, endOffset, file, code, config) {
31
- const skipReason = shouldSkip(content, file, code, offset, endOffset);
32
+ function detectCandidate(content, offset, endOffset, file, code, config, translatableAttributes = jsxAttributes.translatableAttributeSet) {
33
+ const skipReason = shouldSkip(content, file, code, offset, endOffset, translatableAttributes);
32
34
  if (skipReason) {
33
35
  return null;
34
36
  }
@@ -57,7 +59,7 @@ function detectCandidate(content, offset, endOffset, file, code, config) {
57
59
  }
58
60
  // customResult === undefined → fall through to built-in heuristic
59
61
  }
60
- const confidence = calculateConfidence(content, code, offset);
62
+ const confidence = calculateConfidence(content, code, offset, translatableAttributes);
61
63
  return {
62
64
  content,
63
65
  confidence,
@@ -74,7 +76,7 @@ function detectCandidate(content, offset, endOffset, file, code, config) {
74
76
  *
75
77
  * @returns Skip reason if should be skipped, null otherwise
76
78
  */
77
- function shouldSkip(content, file, code, offset, endOffset, config) {
79
+ function shouldSkip(content, file, code, offset, endOffset, translatableAttributes) {
78
80
  // Skip test files
79
81
  if (file.match(/\.(test|spec)\.(ts|tsx|js|jsx)$/i)) {
80
82
  return 'Test file';
@@ -112,7 +114,7 @@ function shouldSkip(content, file, code, offset, endOffset, config) {
112
114
  return 'Console argument';
113
115
  }
114
116
  // Skip HTML/JSX attribute values that are clearly technical
115
- if (isAttributeValue(code, offset)) {
117
+ if (isAttributeValue(code, offset, translatableAttributes)) {
116
118
  return 'HTML attribute value';
117
119
  }
118
120
  return null;
@@ -187,7 +189,6 @@ function isConsoleArgument(code, offset) {
187
189
  }
188
190
  // Translatable attribute and property sets are defined in
189
191
  // utils/jsx-attributes.ts and shared with the linter.
190
- const TRANSLATABLE_ATTRIBUTES = jsxAttributes.translatableAttributeSet;
191
192
  const TRANSLATABLE_PROPERTIES = jsxAttributes.translatablePropertySet;
192
193
  /**
193
194
  * Checks if the string appears to be an HTML/JSX attribute value.
@@ -195,7 +196,7 @@ const TRANSLATABLE_PROPERTIES = jsxAttributes.translatablePropertySet;
195
196
  * Translatable attributes (placeholder, title, alt, aria-label, etc.) are
196
197
  * allowed through so they can be instrumented.
197
198
  */
198
- function isAttributeValue(code, offset) {
199
+ function isAttributeValue(code, offset, translatableAttributes) {
199
200
  // Note: offset points at the opening quote character, so beforeStr goes up to
200
201
  // (but does not include) that quote. We check for `attr=` at the end.
201
202
  const beforeStr = code.substring(Math.max(0, offset - 50), offset);
@@ -207,7 +208,7 @@ function isAttributeValue(code, offset) {
207
208
  if (match) {
208
209
  const attrName = match[1].toLowerCase();
209
210
  // Allow translatable attributes to pass through
210
- if (TRANSLATABLE_ATTRIBUTES.has(attrName)) {
211
+ if (translatableAttributes.has(attrName)) {
211
212
  return false;
212
213
  }
213
214
  return true;
@@ -222,7 +223,7 @@ function isAttributeValue(code, offset) {
222
223
  * High-confidence strings should still be reviewed by developers before final deployment.
223
224
  * Use this as a first pass to identify candidates, not as an authoritative decision.
224
225
  */
225
- function calculateConfidence(content, code, offset) {
226
+ function calculateConfidence(content, code, offset, translatableAttributes) {
226
227
  let confidence = 0.5; // Base confidence
227
228
  // Longer sentences are more likely to be translatable
228
229
  const wordCount = content.split(/\s+/).length;
@@ -263,7 +264,7 @@ function calculateConfidence(content, code, offset) {
263
264
  const attrCtxMatch = beforeContext.match(/([\w-]+)\s*=$/);
264
265
  if (attrCtxMatch) {
265
266
  const attrName = attrCtxMatch[1].toLowerCase();
266
- if (TRANSLATABLE_ATTRIBUTES.has(attrName)) {
267
+ if (translatableAttributes.has(attrName)) {
267
268
  confidence += 0.15; // Translatable attribute — boost
268
269
  }
269
270
  else {