i18next-cli 1.80.2 → 1.80.4
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.
- package/dist/cjs/cli.js +1 -1
- package/dist/cjs/extractor/core/translation-manager.js +14 -53
- package/dist/cjs/rename-key.js +28 -17
- package/dist/cjs/syncer.js +1 -1
- package/dist/cjs/utils/nested-object.js +32 -1
- package/dist/esm/cli.js +1 -1
- package/dist/esm/extractor/core/translation-manager.js +15 -54
- package/dist/esm/rename-key.js +29 -18
- package/dist/esm/syncer.js +1 -1
- package/dist/esm/utils/nested-object.js +31 -2
- package/package.json +1 -1
- package/types/extractor/core/translation-manager.d.ts.map +1 -1
- package/types/utils/nested-object.d.ts +11 -0
- package/types/utils/nested-object.d.ts.map +1 -1
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.80.
|
|
42
|
+
.version('1.80.4') // 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)');
|
|
@@ -11,8 +11,6 @@ var nesting = require('../../utils/nesting.js');
|
|
|
11
11
|
var messageFormat = require('../../utils/message-format.js');
|
|
12
12
|
var contextVariants = require('../../utils/context-variants.js');
|
|
13
13
|
|
|
14
|
-
// used for natural language check
|
|
15
|
-
const chars = [' ', ',', '?', '!', ';'];
|
|
16
14
|
const pluralForms = ['zero', 'one', 'two', 'few', 'many', 'other'];
|
|
17
15
|
/**
|
|
18
16
|
* Converts a glob pattern to a regular expression for matching keys
|
|
@@ -24,31 +22,6 @@ function globToRegex(glob) {
|
|
|
24
22
|
const regexString = `^${escaped.replace(/\*/g, '.*')}$`;
|
|
25
23
|
return new RegExp(regexString);
|
|
26
24
|
}
|
|
27
|
-
/**
|
|
28
|
-
* Checks if a key looks like an object path or natural language.
|
|
29
|
-
* (like in i18next)
|
|
30
|
-
*/
|
|
31
|
-
function looksLikeObjectPath(key, separator, regex) {
|
|
32
|
-
if (!regex)
|
|
33
|
-
return true;
|
|
34
|
-
let matched = !regex.test(key);
|
|
35
|
-
if (!matched) {
|
|
36
|
-
const ki = key.indexOf(separator);
|
|
37
|
-
if (ki > 0 && !regex.test(key.substring(0, ki))) {
|
|
38
|
-
matched = true;
|
|
39
|
-
}
|
|
40
|
-
}
|
|
41
|
-
return matched;
|
|
42
|
-
}
|
|
43
|
-
/**
|
|
44
|
-
* Returns true when splitting `key` by `separator` would produce at least one
|
|
45
|
-
* empty string segment (e.g. "Loading..." split by "." → ["Loading","","",""]).
|
|
46
|
-
* Keys with empty segments must be treated as flat keys, not nested paths,
|
|
47
|
-
* otherwise they create `{ "": { "": "..." } }` entries in the JSON output.
|
|
48
|
-
*/
|
|
49
|
-
function hasEmptySegments(key, separator) {
|
|
50
|
-
return key.split(separator).some(s => s === '');
|
|
51
|
-
}
|
|
52
25
|
/**
|
|
53
26
|
* Detects a nesting conflict for `key` against the object being built.
|
|
54
27
|
* Returns the conflicting ancestor/descendant key path as a string when a
|
|
@@ -208,10 +181,11 @@ function buildNewTranslationsForNs(nsKeys, existingTranslations, config, locale,
|
|
|
208
181
|
return false;
|
|
209
182
|
};
|
|
210
183
|
// Prepare regex for natural language detection
|
|
211
|
-
const
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
184
|
+
const naturalLanguageRegex = nestedObject.naturalLanguageRegexFor(nsSep, keySeparator ?? '.');
|
|
185
|
+
// Serialized Trans components, natural-language keys and keys with empty segments
|
|
186
|
+
// (e.g. "Loading..." would become { "Loading": { "": { "": "…" } } }) are stored flat.
|
|
187
|
+
// Every write goes through this, so plural and context variants land next to their base key.
|
|
188
|
+
const separatorFor = (key) => nestedObject.storedKeySeparator(key, keySeparator ?? '.', naturalLanguageRegex);
|
|
215
189
|
// Build a set of base keys that accept context (only if preserveContextVariants is enabled)
|
|
216
190
|
// These are keys that were called with a context parameter in the source code
|
|
217
191
|
const keysAcceptingContext = new Set();
|
|
@@ -510,7 +484,7 @@ function buildNewTranslationsForNs(nsKeys, existingTranslations, config, locale,
|
|
|
510
484
|
const isContextVariant = !shouldPreserve && contextVariants.isContextVariantOfAcceptingKey(existingKey, keysAcceptingContext, pluralSeparator, contextSeparator);
|
|
511
485
|
if (shouldPreserve || (preserveContextVariants && isContextVariant)) {
|
|
512
486
|
const value = nestedObject.getNestedValue(existingTranslations, existingKey, keySeparator ?? '.');
|
|
513
|
-
nestedObject.setNestedValue(newTranslations, existingKey, value,
|
|
487
|
+
nestedObject.setNestedValue(newTranslations, existingKey, value, separatorFor(existingKey));
|
|
514
488
|
}
|
|
515
489
|
}
|
|
516
490
|
// PROPAGATE CONTEXT VARIANTS FROM PRIMARY TO SECONDARY (issue #242):
|
|
@@ -529,7 +503,7 @@ function buildNewTranslationsForNs(nsKeys, existingTranslations, config, locale,
|
|
|
529
503
|
const isContextVariant = contextVariants.isContextVariantOfAcceptingKey(primaryKey, keysAcceptingContext, pluralSeparator, contextSeparator);
|
|
530
504
|
if (!isContextVariant)
|
|
531
505
|
continue;
|
|
532
|
-
const separator = primaryKey
|
|
506
|
+
const separator = separatorFor(primaryKey);
|
|
533
507
|
const alreadySet = nestedObject.getNestedValue(newTranslations, primaryKey, separator);
|
|
534
508
|
if (alreadySet !== undefined)
|
|
535
509
|
continue;
|
|
@@ -579,7 +553,7 @@ function buildNewTranslationsForNs(nsKeys, existingTranslations, config, locale,
|
|
|
579
553
|
if (!isAlreadySet) {
|
|
580
554
|
// This plural form is NOT being generated by our code, so preserve it
|
|
581
555
|
const value = nestedObject.getNestedValue(existingTranslations, existingKey, keySeparator ?? '.');
|
|
582
|
-
nestedObject.setNestedValue(newTranslations, existingKey, value,
|
|
556
|
+
nestedObject.setNestedValue(newTranslations, existingKey, value, separatorFor(existingKey));
|
|
583
557
|
}
|
|
584
558
|
}
|
|
585
559
|
}
|
|
@@ -604,7 +578,7 @@ function buildNewTranslationsForNs(nsKeys, existingTranslations, config, locale,
|
|
|
604
578
|
if (hasBaseInExtracted) {
|
|
605
579
|
// Preserve the existing _zero form
|
|
606
580
|
const value = nestedObject.getNestedValue(existingTranslations, existingKey, keySeparator ?? '.');
|
|
607
|
-
nestedObject.setNestedValue(newTranslations, existingKey, value,
|
|
581
|
+
nestedObject.setNestedValue(newTranslations, existingKey, value, separatorFor(existingKey));
|
|
608
582
|
}
|
|
609
583
|
}
|
|
610
584
|
}
|
|
@@ -667,7 +641,7 @@ function buildNewTranslationsForNs(nsKeys, existingTranslations, config, locale,
|
|
|
667
641
|
const finalKey = isOrdinal
|
|
668
642
|
? `${base}${pluralSeparator}${form}`
|
|
669
643
|
: `${base}${pluralSeparator}${form}`;
|
|
670
|
-
const separator = finalKey
|
|
644
|
+
const separator = separatorFor(finalKey);
|
|
671
645
|
const existingVariantValue = nestedObject.getNestedValue(existingTranslations, finalKey, separator);
|
|
672
646
|
if (existingVariantValue === undefined) {
|
|
673
647
|
// Use the default value for secondary locale forms
|
|
@@ -690,7 +664,7 @@ function buildNewTranslationsForNs(nsKeys, existingTranslations, config, locale,
|
|
|
690
664
|
const finalKey = isOrdinal
|
|
691
665
|
? `${base}${pluralSeparator}${form}`
|
|
692
666
|
: `${base}${pluralSeparator}${form}`;
|
|
693
|
-
const separator = finalKey
|
|
667
|
+
const separator = separatorFor(finalKey);
|
|
694
668
|
const existingVariantValue = nestedObject.getNestedValue(existingTranslations, finalKey, separator);
|
|
695
669
|
if (existingVariantValue !== undefined) {
|
|
696
670
|
// Preserve manually-added forms
|
|
@@ -713,7 +687,7 @@ function buildNewTranslationsForNs(nsKeys, existingTranslations, config, locale,
|
|
|
713
687
|
const finalKey = isOrdinal
|
|
714
688
|
? `${base}${pluralSeparator}${form}`
|
|
715
689
|
: `${base}${pluralSeparator}${form}`;
|
|
716
|
-
const separator = finalKey
|
|
690
|
+
const separator = separatorFor(finalKey);
|
|
717
691
|
const existingVariantValue = nestedObject.getNestedValue(existingTranslations, finalKey, separator);
|
|
718
692
|
if (existingVariantValue === undefined) {
|
|
719
693
|
// Prefer explicit defaultValue extracted for this key; fall back to configured defaultValue
|
|
@@ -741,20 +715,7 @@ function buildNewTranslationsForNs(nsKeys, existingTranslations, config, locale,
|
|
|
741
715
|
}
|
|
742
716
|
}
|
|
743
717
|
}
|
|
744
|
-
|
|
745
|
-
let separator = key.startsWith('<') ? false : (keySeparator ?? '.');
|
|
746
|
-
if (separator && typeof separator === 'string') {
|
|
747
|
-
if (!looksLikeObjectPath(key, separator, naturalLanguageRegex)) {
|
|
748
|
-
// Natural-language key — treat as flat
|
|
749
|
-
separator = false;
|
|
750
|
-
}
|
|
751
|
-
else if (hasEmptySegments(key, separator)) {
|
|
752
|
-
// Splitting would produce empty-string segments (e.g. "Loading..." split by "."
|
|
753
|
-
// yields ["Loading","","",""]). Storing those creates { "": { "": "…" } }
|
|
754
|
-
// noise in the JSON, so treat the whole key as a flat leaf instead.
|
|
755
|
-
separator = false;
|
|
756
|
-
}
|
|
757
|
-
}
|
|
718
|
+
const separator = separatorFor(key);
|
|
758
719
|
const existingValue = nestedObject.getNestedValue(existingTranslations, key, separator);
|
|
759
720
|
const primaryExistingValue = locale === primaryLanguage
|
|
760
721
|
? existingValue
|
|
@@ -905,7 +866,7 @@ function buildNewTranslationsForNs(nsKeys, existingTranslations, config, locale,
|
|
|
905
866
|
for (const base of expandedBases) {
|
|
906
867
|
for (const form of allLocalesCardinalCategories) {
|
|
907
868
|
const finalKey = `${base}${pluralSeparator}${form}`;
|
|
908
|
-
const separator = finalKey
|
|
869
|
+
const separator = separatorFor(finalKey);
|
|
909
870
|
const existingInNew = nestedObject.getNestedValue(newTranslations, finalKey, separator);
|
|
910
871
|
if (existingInNew === undefined) {
|
|
911
872
|
const existingVariantValue = nestedObject.getNestedValue(existingTranslations, finalKey, separator);
|
package/dist/cjs/rename-key.js
CHANGED
|
@@ -291,6 +291,9 @@ function replaceKeyWithRegex(code, oldParts, newParts, config, namespaceKeyMap)
|
|
|
291
291
|
let newCode = code;
|
|
292
292
|
const nsSeparator = config.extract.nsSeparator ?? ':';
|
|
293
293
|
const configuredFunctions = config.extract.functions || ['t', '*.t'];
|
|
294
|
+
// An optional string default value after the key: t('key', 'Default') or t('key', 'Default', { ... })
|
|
295
|
+
const stringLiteral = ['\'', '"', '`'].map(q => `${q}(?:[^${q}\\\\]|\\\\.)*${q}`).join('|');
|
|
296
|
+
const defaultValueArg = `(?:\\s*,\\s*(?:${stringLiteral}))?`;
|
|
294
297
|
// Helper to create function-prefix regex fragment
|
|
295
298
|
const fnPrefixToRegex = (fnPattern) => {
|
|
296
299
|
if (fnPattern.startsWith('*.')) {
|
|
@@ -338,16 +341,16 @@ function replaceKeyWithRegex(code, oldParts, newParts, config, namespaceKeyMap)
|
|
|
338
341
|
oldParts.namespace !== newParts.namespace &&
|
|
339
342
|
config.extract.defaultNS === newParts.namespace &&
|
|
340
343
|
hasKeyInNamespace(oldParts.namespace)) {
|
|
341
|
-
const nsRegexToDefault = new RegExp(`${prefix}\\s*\\(\\s*(['"\`])${escapeRegex(oldParts.key)}\\1\\s*,\\s*\\{([^}]*)\\bns\\s*:\\s*(['"\`])${escapeRegex(oldParts.namespace)}\\3([^}]*)\\}\\s*\\)`, 'g');
|
|
344
|
+
const nsRegexToDefault = new RegExp(`${prefix}\\s*\\(\\s*(['"\`])${escapeRegex(oldParts.key)}\\1${defaultValueArg}\\s*,\\s*\\{([^}]*)\\bns\\s*:\\s*(['"\`])${escapeRegex(oldParts.namespace)}\\3([^}]*)\\}\\s*\\)`, 'g');
|
|
342
345
|
newCode = newCode.replace(nsRegexToDefault, (match, keyQ, beforeNs, nsQ, afterNs) => {
|
|
343
346
|
changes++;
|
|
344
347
|
const obj = (beforeNs + afterNs).replace(/,?\s*$/, '').replace(/^\s*,?/, '').trim();
|
|
345
348
|
let updated = match.replace(new RegExp(`(['"\`])${escapeRegex(oldParts.key)}\\1`), `${keyQ}${newParts.key}${keyQ}`);
|
|
346
349
|
if (obj) {
|
|
347
|
-
updated = updated.replace(/\{
|
|
350
|
+
updated = updated.replace(/\{[^}]*\}(?=\s*\)$)/, `{${obj}}`);
|
|
348
351
|
}
|
|
349
352
|
else {
|
|
350
|
-
updated = updated.replace(/\s*,\s*\{[^}]*\}\s*\)
|
|
353
|
+
updated = updated.replace(/\s*,\s*\{[^}]*\}\s*\)$/, ')');
|
|
351
354
|
}
|
|
352
355
|
return updated;
|
|
353
356
|
});
|
|
@@ -360,7 +363,7 @@ function replaceKeyWithRegex(code, oldParts, newParts, config, namespaceKeyMap)
|
|
|
360
363
|
// Only run if old namespace actually contains the key (to avoid touching unrelated ns calls).
|
|
361
364
|
//
|
|
362
365
|
if (oldParts.namespace && newParts.namespace && hasKeyInNamespace(oldParts.namespace)) {
|
|
363
|
-
const nsRegexFullKey = new RegExp(`${prefix}\\s*\\(\\s*(['"\`])${escapeRegex(oldParts.key)}\\1\\s*,\\s*\\{([^}]*)\\bns\\s*:\\s*(['"\`])${escapeRegex(oldParts.namespace)}\\3([^}]*)\\}\\s*\\)`, 'g');
|
|
366
|
+
const nsRegexFullKey = new RegExp(`${prefix}\\s*\\(\\s*(['"\`])${escapeRegex(oldParts.key)}\\1${defaultValueArg}\\s*,\\s*\\{([^}]*)\\bns\\s*:\\s*(['"\`])${escapeRegex(oldParts.namespace)}\\3([^}]*)\\}\\s*\\)`, 'g');
|
|
364
367
|
newCode = newCode.replace(nsRegexFullKey, (match, keyQ, beforeNs, nsQ, afterNs) => {
|
|
365
368
|
changes++;
|
|
366
369
|
// remaining props except ns
|
|
@@ -370,7 +373,7 @@ function replaceKeyWithRegex(code, oldParts, newParts, config, namespaceKeyMap)
|
|
|
370
373
|
if (oldParts.namespace === newParts.namespace) {
|
|
371
374
|
// same namespace: keep ns value untouched, but keep other props
|
|
372
375
|
if (obj) {
|
|
373
|
-
updated = updated.replace(/\{
|
|
376
|
+
updated = updated.replace(/\{[^}]*\}(?=\s*\)$)/, `{${obj}}`);
|
|
374
377
|
}
|
|
375
378
|
}
|
|
376
379
|
else {
|
|
@@ -378,10 +381,10 @@ function replaceKeyWithRegex(code, oldParts, newParts, config, namespaceKeyMap)
|
|
|
378
381
|
if (config.extract.defaultNS === newParts.namespace) {
|
|
379
382
|
// moving INTO the default namespace -> remove the ns property
|
|
380
383
|
if (obj) {
|
|
381
|
-
updated = updated.replace(/\{
|
|
384
|
+
updated = updated.replace(/\{[^}]*\}(?=\s*\)$)/, `{${obj}}`);
|
|
382
385
|
}
|
|
383
386
|
else {
|
|
384
|
-
updated = updated.replace(/\s*,\s*\{[^}]*\}\s*\)
|
|
387
|
+
updated = updated.replace(/\s*,\s*\{[^}]*\}\s*\)$/, ')');
|
|
385
388
|
}
|
|
386
389
|
}
|
|
387
390
|
else {
|
|
@@ -464,7 +467,7 @@ function replaceKeyWithRegex(code, oldParts, newParts, config, namespaceKeyMap)
|
|
|
464
467
|
oldParts.namespace !== newParts.namespace &&
|
|
465
468
|
config.extract.defaultNS === oldParts.namespace &&
|
|
466
469
|
hasKeyInNamespace(oldParts.namespace)) {
|
|
467
|
-
const regexOptionsNoNs = new RegExp(`${prefix}\\s*\\(\\s*(['"\`])${escapeRegex(oldParts.key)}\\1\\s*,\\s*\\{([^}]*)\\}\\s*\\)`, 'g');
|
|
470
|
+
const regexOptionsNoNs = new RegExp(`${prefix}\\s*\\(\\s*(['"\`])${escapeRegex(oldParts.key)}\\1${defaultValueArg}\\s*,\\s*\\{([^}]*)\\}\\s*\\)`, 'g');
|
|
468
471
|
newCode = newCode.replace(regexOptionsNoNs, (match, q, objContents) => {
|
|
469
472
|
// If object already contains ns, skip (other branches handle it).
|
|
470
473
|
if (/\bns\s*:\s*['"`]/.test(objContents))
|
|
@@ -475,13 +478,13 @@ function replaceKeyWithRegex(code, oldParts, newParts, config, namespaceKeyMap)
|
|
|
475
478
|
// replace the key and the object contents (preserve spacing minimally)
|
|
476
479
|
return match
|
|
477
480
|
.replace(new RegExp(`(['"\`])${escapeRegex(oldParts.key)}\\1`), `${q}${newParts.key}${q}`)
|
|
478
|
-
.replace(/\{
|
|
481
|
+
.replace(/\{[^}]*\}(?=\s*\)$)/, `{ ${newObj} }`);
|
|
479
482
|
});
|
|
480
483
|
}
|
|
481
484
|
// 4.5b) Same-namespace rename where call already has options object (no ns):
|
|
482
485
|
// t('key', { user: 'name' }) -> t('key2', { user: 'name' })
|
|
483
486
|
if (oldParts.namespace === newParts.namespace && oldParts.namespace === effectiveDefaultNS) {
|
|
484
|
-
const regexKeyWithOptions = new RegExp(`${prefix}\\s*\\(\\s*(['"\`])${escapeRegex(oldParts.key)}\\1\\s*,\\s*\\{([^}]*)\\}\\s*\\)`, 'g');
|
|
487
|
+
const regexKeyWithOptions = new RegExp(`${prefix}\\s*\\(\\s*(['"\`])${escapeRegex(oldParts.key)}\\1${defaultValueArg}\\s*,\\s*\\{([^}]*)\\}\\s*\\)`, 'g');
|
|
485
488
|
newCode = newCode.replace(regexKeyWithOptions, (match, q, objContents) => {
|
|
486
489
|
// don't touch objects that already explicitly set ns (handled elsewhere)
|
|
487
490
|
if (/\bns\s*:\s*['"`]/.test(objContents))
|
|
@@ -500,10 +503,12 @@ function replaceKeyWithRegex(code, oldParts, newParts, config, namespaceKeyMap)
|
|
|
500
503
|
oldParts.namespace !== newParts.namespace &&
|
|
501
504
|
config.extract.defaultNS === oldParts.namespace &&
|
|
502
505
|
hasKeyInNamespace(oldParts.namespace)) {
|
|
503
|
-
const regexKeyWithParen = new RegExp(`${prefix}\\s*\\(\\s*(['"\`])${escapeRegex(oldParts.key)}\\1\\s*\\)`, 'g');
|
|
506
|
+
const regexKeyWithParen = new RegExp(`${prefix}\\s*\\(\\s*(['"\`])${escapeRegex(oldParts.key)}\\1${defaultValueArg}\\s*\\)`, 'g');
|
|
504
507
|
newCode = newCode.replace(regexKeyWithParen, (match, quote) => {
|
|
505
508
|
changes++;
|
|
506
|
-
return match
|
|
509
|
+
return match
|
|
510
|
+
.replace(new RegExp(`(['"\`])${escapeRegex(oldParts.key)}\\1`), `${quote}${newParts.key}${quote}`)
|
|
511
|
+
.replace(/\s*\)$/, `, { ns: '${newParts.namespace}' })`);
|
|
507
512
|
});
|
|
508
513
|
}
|
|
509
514
|
//
|
|
@@ -517,7 +522,7 @@ function replaceKeyWithRegex(code, oldParts, newParts, config, namespaceKeyMap)
|
|
|
517
522
|
{
|
|
518
523
|
const effectiveDefaultNS = config.extract.defaultNS ?? 'translation';
|
|
519
524
|
if (oldParts.namespace === effectiveDefaultNS) {
|
|
520
|
-
const regexKeyNoOptions = new RegExp(`${prefix}\\s*\\(\\s*(['"\`])${escapeRegex(oldParts.key)}\\1\\s*\\)`, 'g');
|
|
525
|
+
const regexKeyNoOptions = new RegExp(`${prefix}\\s*\\(\\s*(['"\`])${escapeRegex(oldParts.key)}\\1${defaultValueArg}\\s*\\)`, 'g');
|
|
521
526
|
newCode = newCode.replace(regexKeyNoOptions, (match, q) => {
|
|
522
527
|
changes++;
|
|
523
528
|
const replacementKey = newParts.key;
|
|
@@ -551,6 +556,12 @@ function escapeRegex(str) {
|
|
|
551
556
|
async function updateTranslationFiles(oldParts, newParts, config, dryRun, namespaceKeyMap, logger) {
|
|
552
557
|
const results = [];
|
|
553
558
|
const keySeparator = config.extract.keySeparator ?? '.';
|
|
559
|
+
// Write the new key the way the extractor would store it (flat for "Loading..." or
|
|
560
|
+
// natural-language keys), and remove the old one the way it is actually stored.
|
|
561
|
+
const nsSeparator = config.extract.nsSeparator;
|
|
562
|
+
const naturalLanguageRegex = nestedObject.naturalLanguageRegexFor(typeof nsSeparator === 'string' ? nsSeparator : ':', keySeparator);
|
|
563
|
+
const newKeySeparator = nestedObject.storedKeySeparator(newParts.key, keySeparator, naturalLanguageRegex);
|
|
564
|
+
const oldKeySeparatorIn = (translations) => Object.prototype.hasOwnProperty.call(translations, oldParts.key) ? false : keySeparator;
|
|
554
565
|
// Helper: determine whether a flattened key-set indicates presence of `baseKey`.
|
|
555
566
|
const namespaceHasKey = (set, baseKey) => {
|
|
556
567
|
if (!set)
|
|
@@ -677,8 +688,8 @@ async function updateTranslationFiles(oldParts, newParts, config, dryRun, namesp
|
|
|
677
688
|
if (oldValue !== undefined) {
|
|
678
689
|
if (ns === targetNamespace) {
|
|
679
690
|
// rename within same file (nested)
|
|
680
|
-
deleteNestedValue(oldTranslations, oldParts.key,
|
|
681
|
-
nestedObject.setNestedValue(oldTranslations, newParts.key, oldValue,
|
|
691
|
+
deleteNestedValue(oldTranslations, oldParts.key, oldKeySeparatorIn(oldTranslations));
|
|
692
|
+
nestedObject.setNestedValue(oldTranslations, newParts.key, oldValue, newKeySeparator);
|
|
682
693
|
if (!dryRun) {
|
|
683
694
|
const content = fileUtils.serializeTranslationFile(oldTranslations, config.extract.outputFormat, config.extract.indentation);
|
|
684
695
|
await promises.writeFile(oldFullPath, content, 'utf-8');
|
|
@@ -691,7 +702,7 @@ async function updateTranslationFiles(oldParts, newParts, config, dryRun, namesp
|
|
|
691
702
|
else {
|
|
692
703
|
// move nested value across namespaces
|
|
693
704
|
const updatedOld = { ...oldTranslations };
|
|
694
|
-
deleteNestedValue(updatedOld, oldParts.key,
|
|
705
|
+
deleteNestedValue(updatedOld, oldParts.key, oldKeySeparatorIn(updatedOld));
|
|
695
706
|
if (!dryRun) {
|
|
696
707
|
const contentOld = fileUtils.serializeTranslationFile(updatedOld, config.extract.outputFormat, config.extract.indentation);
|
|
697
708
|
await promises.writeFile(oldFullPath, contentOld, 'utf-8');
|
|
@@ -706,7 +717,7 @@ async function updateTranslationFiles(oldParts, newParts, config, dryRun, namesp
|
|
|
706
717
|
catch { }
|
|
707
718
|
if (!newTranslations)
|
|
708
719
|
newTranslations = {};
|
|
709
|
-
nestedObject.setNestedValue(newTranslations, newParts.key, oldValue,
|
|
720
|
+
nestedObject.setNestedValue(newTranslations, newParts.key, oldValue, newKeySeparator);
|
|
710
721
|
if (!dryRun) {
|
|
711
722
|
const contentNew = fileUtils.serializeTranslationFile(newTranslations, config.extract.outputFormat, config.extract.indentation);
|
|
712
723
|
await promises.writeFile(newFullPath, contentNew, 'utf-8');
|
package/dist/cjs/syncer.js
CHANGED
|
@@ -183,7 +183,7 @@ async function runSyncer(config, options = {}) {
|
|
|
183
183
|
const existingSecondaryKeys = nestedObject.getNestedKeys(existingSecondaryTranslations, keySeparator ?? '.');
|
|
184
184
|
// Keep a key flat when the primary or the existing secondary file has it as one flat
|
|
185
185
|
// top-level key, which is how the extractor writes keys like "Loading..." or
|
|
186
|
-
// "Hello.
|
|
186
|
+
// "Hello world. Bye". Splitting them on the separator would nest them under new parents.
|
|
187
187
|
const keySeparatorFor = (key) => Object.prototype.hasOwnProperty.call(primaryTranslations, key) ||
|
|
188
188
|
Object.prototype.hasOwnProperty.call(existingSecondaryTranslations, key)
|
|
189
189
|
? false
|
|
@@ -76,7 +76,7 @@ function getNestedValue(obj, path, keySeparator) {
|
|
|
76
76
|
}
|
|
77
77
|
const value = path.split(keySeparator).reduce((acc, key) => acc && acc[key], obj);
|
|
78
78
|
// The extractor writes a key that cannot be used as a path ("Loading...", or a
|
|
79
|
-
// natural-language key such as "Hello.
|
|
79
|
+
// natural-language key such as "Hello world. Bye") as a single flat top-level key.
|
|
80
80
|
if (value === undefined && obj != null && Object.prototype.hasOwnProperty.call(obj, path)) {
|
|
81
81
|
return obj[path];
|
|
82
82
|
}
|
|
@@ -124,7 +124,38 @@ function getNestedKeys(obj, keySeparator, prefix = '') {
|
|
|
124
124
|
return acc;
|
|
125
125
|
}, []);
|
|
126
126
|
}
|
|
127
|
+
const naturalLanguageChars = [' ', ',', '?', '!', ';'];
|
|
128
|
+
/**
|
|
129
|
+
* Builds the regex that marks a key as natural language (like i18next does): any of
|
|
130
|
+
* ` ,?!;` that is not itself used as the namespace or key separator.
|
|
131
|
+
*/
|
|
132
|
+
function naturalLanguageRegexFor(nsSeparator, keySeparator) {
|
|
133
|
+
const possibleChars = naturalLanguageChars.filter((c) => nsSeparator.indexOf(c) < 0 && (typeof keySeparator === 'string' ? keySeparator.indexOf(c) < 0 : true));
|
|
134
|
+
return possibleChars.length > 0
|
|
135
|
+
? new RegExp(`(${possibleChars.map((c) => (c === '?' ? '\\?' : c)).join('|')})`)
|
|
136
|
+
: null;
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* The separator a key is stored with in a translation file, or `false` when it is
|
|
140
|
+
* stored as one flat key: a serialized Trans component (`<...`), a natural-language
|
|
141
|
+
* key such as "Hello world. Bye", or a key with empty segments such as "Loading...".
|
|
142
|
+
*/
|
|
143
|
+
function storedKeySeparator(key, keySeparator, naturalLanguageRegex) {
|
|
144
|
+
if (keySeparator === false || key.startsWith('<'))
|
|
145
|
+
return false;
|
|
146
|
+
if (naturalLanguageRegex) {
|
|
147
|
+
const ki = key.indexOf(keySeparator);
|
|
148
|
+
const isPath = !naturalLanguageRegex.test(key) || (ki > 0 && !naturalLanguageRegex.test(key.substring(0, ki)));
|
|
149
|
+
if (!isPath)
|
|
150
|
+
return false;
|
|
151
|
+
}
|
|
152
|
+
if (key.split(keySeparator).some(s => s === ''))
|
|
153
|
+
return false;
|
|
154
|
+
return keySeparator;
|
|
155
|
+
}
|
|
127
156
|
|
|
128
157
|
exports.getNestedKeys = getNestedKeys;
|
|
129
158
|
exports.getNestedValue = getNestedValue;
|
|
159
|
+
exports.naturalLanguageRegexFor = naturalLanguageRegexFor;
|
|
130
160
|
exports.setNestedValue = setNestedValue;
|
|
161
|
+
exports.storedKeySeparator = storedKeySeparator;
|
package/dist/esm/cli.js
CHANGED
|
@@ -33,7 +33,7 @@ const program = new Command();
|
|
|
33
33
|
program
|
|
34
34
|
.name('i18next-cli')
|
|
35
35
|
.description('A unified, high-performance i18next CLI.')
|
|
36
|
-
.version('1.80.
|
|
36
|
+
.version('1.80.4') // This string is replaced with the actual version at build time by rollup
|
|
37
37
|
.addHelpText('after', '\nUsing an AI coding agent? Install the i18next-localization skill: npx skills add i18next/i18next-cli\n');
|
|
38
38
|
// new: global config override option
|
|
39
39
|
program.option('-c, --config <path>', 'Path to i18next-cli config file (overrides detection)');
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { resolve, basename, extname } from 'node:path';
|
|
2
2
|
import { glob } from 'glob';
|
|
3
|
-
import { getNestedKeys, getNestedValue, setNestedValue } from '../../utils/nested-object.js';
|
|
3
|
+
import { naturalLanguageRegexFor, getNestedKeys, getNestedValue, setNestedValue, storedKeySeparator } from '../../utils/nested-object.js';
|
|
4
4
|
import { getOutputPath, loadTranslationFile } from '../../utils/file-utils.js';
|
|
5
5
|
import { resolveDefaultValue } from '../../utils/default-value.js';
|
|
6
6
|
import { ConsoleLogger } from '../../utils/logger.js';
|
|
@@ -9,8 +9,6 @@ import { parseNestedReferences } from '../../utils/nesting.js';
|
|
|
9
9
|
import { usesMessageFormat } from '../../utils/message-format.js';
|
|
10
10
|
import { isContextVariantOfAcceptingKey } from '../../utils/context-variants.js';
|
|
11
11
|
|
|
12
|
-
// used for natural language check
|
|
13
|
-
const chars = [' ', ',', '?', '!', ';'];
|
|
14
12
|
const pluralForms = ['zero', 'one', 'two', 'few', 'many', 'other'];
|
|
15
13
|
/**
|
|
16
14
|
* Converts a glob pattern to a regular expression for matching keys
|
|
@@ -22,31 +20,6 @@ function globToRegex(glob) {
|
|
|
22
20
|
const regexString = `^${escaped.replace(/\*/g, '.*')}$`;
|
|
23
21
|
return new RegExp(regexString);
|
|
24
22
|
}
|
|
25
|
-
/**
|
|
26
|
-
* Checks if a key looks like an object path or natural language.
|
|
27
|
-
* (like in i18next)
|
|
28
|
-
*/
|
|
29
|
-
function looksLikeObjectPath(key, separator, regex) {
|
|
30
|
-
if (!regex)
|
|
31
|
-
return true;
|
|
32
|
-
let matched = !regex.test(key);
|
|
33
|
-
if (!matched) {
|
|
34
|
-
const ki = key.indexOf(separator);
|
|
35
|
-
if (ki > 0 && !regex.test(key.substring(0, ki))) {
|
|
36
|
-
matched = true;
|
|
37
|
-
}
|
|
38
|
-
}
|
|
39
|
-
return matched;
|
|
40
|
-
}
|
|
41
|
-
/**
|
|
42
|
-
* Returns true when splitting `key` by `separator` would produce at least one
|
|
43
|
-
* empty string segment (e.g. "Loading..." split by "." → ["Loading","","",""]).
|
|
44
|
-
* Keys with empty segments must be treated as flat keys, not nested paths,
|
|
45
|
-
* otherwise they create `{ "": { "": "..." } }` entries in the JSON output.
|
|
46
|
-
*/
|
|
47
|
-
function hasEmptySegments(key, separator) {
|
|
48
|
-
return key.split(separator).some(s => s === '');
|
|
49
|
-
}
|
|
50
23
|
/**
|
|
51
24
|
* Detects a nesting conflict for `key` against the object being built.
|
|
52
25
|
* Returns the conflicting ancestor/descendant key path as a string when a
|
|
@@ -206,10 +179,11 @@ function buildNewTranslationsForNs(nsKeys, existingTranslations, config, locale,
|
|
|
206
179
|
return false;
|
|
207
180
|
};
|
|
208
181
|
// Prepare regex for natural language detection
|
|
209
|
-
const
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
182
|
+
const naturalLanguageRegex = naturalLanguageRegexFor(nsSep, keySeparator ?? '.');
|
|
183
|
+
// Serialized Trans components, natural-language keys and keys with empty segments
|
|
184
|
+
// (e.g. "Loading..." would become { "Loading": { "": { "": "…" } } }) are stored flat.
|
|
185
|
+
// Every write goes through this, so plural and context variants land next to their base key.
|
|
186
|
+
const separatorFor = (key) => storedKeySeparator(key, keySeparator ?? '.', naturalLanguageRegex);
|
|
213
187
|
// Build a set of base keys that accept context (only if preserveContextVariants is enabled)
|
|
214
188
|
// These are keys that were called with a context parameter in the source code
|
|
215
189
|
const keysAcceptingContext = new Set();
|
|
@@ -508,7 +482,7 @@ function buildNewTranslationsForNs(nsKeys, existingTranslations, config, locale,
|
|
|
508
482
|
const isContextVariant = !shouldPreserve && isContextVariantOfAcceptingKey(existingKey, keysAcceptingContext, pluralSeparator, contextSeparator);
|
|
509
483
|
if (shouldPreserve || (preserveContextVariants && isContextVariant)) {
|
|
510
484
|
const value = getNestedValue(existingTranslations, existingKey, keySeparator ?? '.');
|
|
511
|
-
setNestedValue(newTranslations, existingKey, value,
|
|
485
|
+
setNestedValue(newTranslations, existingKey, value, separatorFor(existingKey));
|
|
512
486
|
}
|
|
513
487
|
}
|
|
514
488
|
// PROPAGATE CONTEXT VARIANTS FROM PRIMARY TO SECONDARY (issue #242):
|
|
@@ -527,7 +501,7 @@ function buildNewTranslationsForNs(nsKeys, existingTranslations, config, locale,
|
|
|
527
501
|
const isContextVariant = isContextVariantOfAcceptingKey(primaryKey, keysAcceptingContext, pluralSeparator, contextSeparator);
|
|
528
502
|
if (!isContextVariant)
|
|
529
503
|
continue;
|
|
530
|
-
const separator = primaryKey
|
|
504
|
+
const separator = separatorFor(primaryKey);
|
|
531
505
|
const alreadySet = getNestedValue(newTranslations, primaryKey, separator);
|
|
532
506
|
if (alreadySet !== undefined)
|
|
533
507
|
continue;
|
|
@@ -577,7 +551,7 @@ function buildNewTranslationsForNs(nsKeys, existingTranslations, config, locale,
|
|
|
577
551
|
if (!isAlreadySet) {
|
|
578
552
|
// This plural form is NOT being generated by our code, so preserve it
|
|
579
553
|
const value = getNestedValue(existingTranslations, existingKey, keySeparator ?? '.');
|
|
580
|
-
setNestedValue(newTranslations, existingKey, value,
|
|
554
|
+
setNestedValue(newTranslations, existingKey, value, separatorFor(existingKey));
|
|
581
555
|
}
|
|
582
556
|
}
|
|
583
557
|
}
|
|
@@ -602,7 +576,7 @@ function buildNewTranslationsForNs(nsKeys, existingTranslations, config, locale,
|
|
|
602
576
|
if (hasBaseInExtracted) {
|
|
603
577
|
// Preserve the existing _zero form
|
|
604
578
|
const value = getNestedValue(existingTranslations, existingKey, keySeparator ?? '.');
|
|
605
|
-
setNestedValue(newTranslations, existingKey, value,
|
|
579
|
+
setNestedValue(newTranslations, existingKey, value, separatorFor(existingKey));
|
|
606
580
|
}
|
|
607
581
|
}
|
|
608
582
|
}
|
|
@@ -665,7 +639,7 @@ function buildNewTranslationsForNs(nsKeys, existingTranslations, config, locale,
|
|
|
665
639
|
const finalKey = isOrdinal
|
|
666
640
|
? `${base}${pluralSeparator}${form}`
|
|
667
641
|
: `${base}${pluralSeparator}${form}`;
|
|
668
|
-
const separator = finalKey
|
|
642
|
+
const separator = separatorFor(finalKey);
|
|
669
643
|
const existingVariantValue = getNestedValue(existingTranslations, finalKey, separator);
|
|
670
644
|
if (existingVariantValue === undefined) {
|
|
671
645
|
// Use the default value for secondary locale forms
|
|
@@ -688,7 +662,7 @@ function buildNewTranslationsForNs(nsKeys, existingTranslations, config, locale,
|
|
|
688
662
|
const finalKey = isOrdinal
|
|
689
663
|
? `${base}${pluralSeparator}${form}`
|
|
690
664
|
: `${base}${pluralSeparator}${form}`;
|
|
691
|
-
const separator = finalKey
|
|
665
|
+
const separator = separatorFor(finalKey);
|
|
692
666
|
const existingVariantValue = getNestedValue(existingTranslations, finalKey, separator);
|
|
693
667
|
if (existingVariantValue !== undefined) {
|
|
694
668
|
// Preserve manually-added forms
|
|
@@ -711,7 +685,7 @@ function buildNewTranslationsForNs(nsKeys, existingTranslations, config, locale,
|
|
|
711
685
|
const finalKey = isOrdinal
|
|
712
686
|
? `${base}${pluralSeparator}${form}`
|
|
713
687
|
: `${base}${pluralSeparator}${form}`;
|
|
714
|
-
const separator = finalKey
|
|
688
|
+
const separator = separatorFor(finalKey);
|
|
715
689
|
const existingVariantValue = getNestedValue(existingTranslations, finalKey, separator);
|
|
716
690
|
if (existingVariantValue === undefined) {
|
|
717
691
|
// Prefer explicit defaultValue extracted for this key; fall back to configured defaultValue
|
|
@@ -739,20 +713,7 @@ function buildNewTranslationsForNs(nsKeys, existingTranslations, config, locale,
|
|
|
739
713
|
}
|
|
740
714
|
}
|
|
741
715
|
}
|
|
742
|
-
|
|
743
|
-
let separator = key.startsWith('<') ? false : (keySeparator ?? '.');
|
|
744
|
-
if (separator && typeof separator === 'string') {
|
|
745
|
-
if (!looksLikeObjectPath(key, separator, naturalLanguageRegex)) {
|
|
746
|
-
// Natural-language key — treat as flat
|
|
747
|
-
separator = false;
|
|
748
|
-
}
|
|
749
|
-
else if (hasEmptySegments(key, separator)) {
|
|
750
|
-
// Splitting would produce empty-string segments (e.g. "Loading..." split by "."
|
|
751
|
-
// yields ["Loading","","",""]). Storing those creates { "": { "": "…" } }
|
|
752
|
-
// noise in the JSON, so treat the whole key as a flat leaf instead.
|
|
753
|
-
separator = false;
|
|
754
|
-
}
|
|
755
|
-
}
|
|
716
|
+
const separator = separatorFor(key);
|
|
756
717
|
const existingValue = getNestedValue(existingTranslations, key, separator);
|
|
757
718
|
const primaryExistingValue = locale === primaryLanguage
|
|
758
719
|
? existingValue
|
|
@@ -903,7 +864,7 @@ function buildNewTranslationsForNs(nsKeys, existingTranslations, config, locale,
|
|
|
903
864
|
for (const base of expandedBases) {
|
|
904
865
|
for (const form of allLocalesCardinalCategories) {
|
|
905
866
|
const finalKey = `${base}${pluralSeparator}${form}`;
|
|
906
|
-
const separator = finalKey
|
|
867
|
+
const separator = separatorFor(finalKey);
|
|
907
868
|
const existingInNew = getNestedValue(newTranslations, finalKey, separator);
|
|
908
869
|
if (existingInNew === undefined) {
|
|
909
870
|
const existingVariantValue = getNestedValue(existingTranslations, finalKey, separator);
|
package/dist/esm/rename-key.js
CHANGED
|
@@ -3,7 +3,7 @@ import { readFile, writeFile } from 'node:fs/promises';
|
|
|
3
3
|
import { resolve, basename } from 'node:path';
|
|
4
4
|
import { ConsoleLogger } from './utils/logger.js';
|
|
5
5
|
import { getOutputPath, loadTranslationFile, serializeTranslationFile } from './utils/file-utils.js';
|
|
6
|
-
import { getNestedValue, setNestedValue } from './utils/nested-object.js';
|
|
6
|
+
import { getNestedValue, naturalLanguageRegexFor, storedKeySeparator, setNestedValue } from './utils/nested-object.js';
|
|
7
7
|
import { shouldShowFunnel, recordFunnelShown } from './utils/funnel-msg-tracker.js';
|
|
8
8
|
import { styleText } from 'node:util';
|
|
9
9
|
|
|
@@ -289,6 +289,9 @@ function replaceKeyWithRegex(code, oldParts, newParts, config, namespaceKeyMap)
|
|
|
289
289
|
let newCode = code;
|
|
290
290
|
const nsSeparator = config.extract.nsSeparator ?? ':';
|
|
291
291
|
const configuredFunctions = config.extract.functions || ['t', '*.t'];
|
|
292
|
+
// An optional string default value after the key: t('key', 'Default') or t('key', 'Default', { ... })
|
|
293
|
+
const stringLiteral = ['\'', '"', '`'].map(q => `${q}(?:[^${q}\\\\]|\\\\.)*${q}`).join('|');
|
|
294
|
+
const defaultValueArg = `(?:\\s*,\\s*(?:${stringLiteral}))?`;
|
|
292
295
|
// Helper to create function-prefix regex fragment
|
|
293
296
|
const fnPrefixToRegex = (fnPattern) => {
|
|
294
297
|
if (fnPattern.startsWith('*.')) {
|
|
@@ -336,16 +339,16 @@ function replaceKeyWithRegex(code, oldParts, newParts, config, namespaceKeyMap)
|
|
|
336
339
|
oldParts.namespace !== newParts.namespace &&
|
|
337
340
|
config.extract.defaultNS === newParts.namespace &&
|
|
338
341
|
hasKeyInNamespace(oldParts.namespace)) {
|
|
339
|
-
const nsRegexToDefault = new RegExp(`${prefix}\\s*\\(\\s*(['"\`])${escapeRegex(oldParts.key)}\\1\\s*,\\s*\\{([^}]*)\\bns\\s*:\\s*(['"\`])${escapeRegex(oldParts.namespace)}\\3([^}]*)\\}\\s*\\)`, 'g');
|
|
342
|
+
const nsRegexToDefault = new RegExp(`${prefix}\\s*\\(\\s*(['"\`])${escapeRegex(oldParts.key)}\\1${defaultValueArg}\\s*,\\s*\\{([^}]*)\\bns\\s*:\\s*(['"\`])${escapeRegex(oldParts.namespace)}\\3([^}]*)\\}\\s*\\)`, 'g');
|
|
340
343
|
newCode = newCode.replace(nsRegexToDefault, (match, keyQ, beforeNs, nsQ, afterNs) => {
|
|
341
344
|
changes++;
|
|
342
345
|
const obj = (beforeNs + afterNs).replace(/,?\s*$/, '').replace(/^\s*,?/, '').trim();
|
|
343
346
|
let updated = match.replace(new RegExp(`(['"\`])${escapeRegex(oldParts.key)}\\1`), `${keyQ}${newParts.key}${keyQ}`);
|
|
344
347
|
if (obj) {
|
|
345
|
-
updated = updated.replace(/\{
|
|
348
|
+
updated = updated.replace(/\{[^}]*\}(?=\s*\)$)/, `{${obj}}`);
|
|
346
349
|
}
|
|
347
350
|
else {
|
|
348
|
-
updated = updated.replace(/\s*,\s*\{[^}]*\}\s*\)
|
|
351
|
+
updated = updated.replace(/\s*,\s*\{[^}]*\}\s*\)$/, ')');
|
|
349
352
|
}
|
|
350
353
|
return updated;
|
|
351
354
|
});
|
|
@@ -358,7 +361,7 @@ function replaceKeyWithRegex(code, oldParts, newParts, config, namespaceKeyMap)
|
|
|
358
361
|
// Only run if old namespace actually contains the key (to avoid touching unrelated ns calls).
|
|
359
362
|
//
|
|
360
363
|
if (oldParts.namespace && newParts.namespace && hasKeyInNamespace(oldParts.namespace)) {
|
|
361
|
-
const nsRegexFullKey = new RegExp(`${prefix}\\s*\\(\\s*(['"\`])${escapeRegex(oldParts.key)}\\1\\s*,\\s*\\{([^}]*)\\bns\\s*:\\s*(['"\`])${escapeRegex(oldParts.namespace)}\\3([^}]*)\\}\\s*\\)`, 'g');
|
|
364
|
+
const nsRegexFullKey = new RegExp(`${prefix}\\s*\\(\\s*(['"\`])${escapeRegex(oldParts.key)}\\1${defaultValueArg}\\s*,\\s*\\{([^}]*)\\bns\\s*:\\s*(['"\`])${escapeRegex(oldParts.namespace)}\\3([^}]*)\\}\\s*\\)`, 'g');
|
|
362
365
|
newCode = newCode.replace(nsRegexFullKey, (match, keyQ, beforeNs, nsQ, afterNs) => {
|
|
363
366
|
changes++;
|
|
364
367
|
// remaining props except ns
|
|
@@ -368,7 +371,7 @@ function replaceKeyWithRegex(code, oldParts, newParts, config, namespaceKeyMap)
|
|
|
368
371
|
if (oldParts.namespace === newParts.namespace) {
|
|
369
372
|
// same namespace: keep ns value untouched, but keep other props
|
|
370
373
|
if (obj) {
|
|
371
|
-
updated = updated.replace(/\{
|
|
374
|
+
updated = updated.replace(/\{[^}]*\}(?=\s*\)$)/, `{${obj}}`);
|
|
372
375
|
}
|
|
373
376
|
}
|
|
374
377
|
else {
|
|
@@ -376,10 +379,10 @@ function replaceKeyWithRegex(code, oldParts, newParts, config, namespaceKeyMap)
|
|
|
376
379
|
if (config.extract.defaultNS === newParts.namespace) {
|
|
377
380
|
// moving INTO the default namespace -> remove the ns property
|
|
378
381
|
if (obj) {
|
|
379
|
-
updated = updated.replace(/\{
|
|
382
|
+
updated = updated.replace(/\{[^}]*\}(?=\s*\)$)/, `{${obj}}`);
|
|
380
383
|
}
|
|
381
384
|
else {
|
|
382
|
-
updated = updated.replace(/\s*,\s*\{[^}]*\}\s*\)
|
|
385
|
+
updated = updated.replace(/\s*,\s*\{[^}]*\}\s*\)$/, ')');
|
|
383
386
|
}
|
|
384
387
|
}
|
|
385
388
|
else {
|
|
@@ -462,7 +465,7 @@ function replaceKeyWithRegex(code, oldParts, newParts, config, namespaceKeyMap)
|
|
|
462
465
|
oldParts.namespace !== newParts.namespace &&
|
|
463
466
|
config.extract.defaultNS === oldParts.namespace &&
|
|
464
467
|
hasKeyInNamespace(oldParts.namespace)) {
|
|
465
|
-
const regexOptionsNoNs = new RegExp(`${prefix}\\s*\\(\\s*(['"\`])${escapeRegex(oldParts.key)}\\1\\s*,\\s*\\{([^}]*)\\}\\s*\\)`, 'g');
|
|
468
|
+
const regexOptionsNoNs = new RegExp(`${prefix}\\s*\\(\\s*(['"\`])${escapeRegex(oldParts.key)}\\1${defaultValueArg}\\s*,\\s*\\{([^}]*)\\}\\s*\\)`, 'g');
|
|
466
469
|
newCode = newCode.replace(regexOptionsNoNs, (match, q, objContents) => {
|
|
467
470
|
// If object already contains ns, skip (other branches handle it).
|
|
468
471
|
if (/\bns\s*:\s*['"`]/.test(objContents))
|
|
@@ -473,13 +476,13 @@ function replaceKeyWithRegex(code, oldParts, newParts, config, namespaceKeyMap)
|
|
|
473
476
|
// replace the key and the object contents (preserve spacing minimally)
|
|
474
477
|
return match
|
|
475
478
|
.replace(new RegExp(`(['"\`])${escapeRegex(oldParts.key)}\\1`), `${q}${newParts.key}${q}`)
|
|
476
|
-
.replace(/\{
|
|
479
|
+
.replace(/\{[^}]*\}(?=\s*\)$)/, `{ ${newObj} }`);
|
|
477
480
|
});
|
|
478
481
|
}
|
|
479
482
|
// 4.5b) Same-namespace rename where call already has options object (no ns):
|
|
480
483
|
// t('key', { user: 'name' }) -> t('key2', { user: 'name' })
|
|
481
484
|
if (oldParts.namespace === newParts.namespace && oldParts.namespace === effectiveDefaultNS) {
|
|
482
|
-
const regexKeyWithOptions = new RegExp(`${prefix}\\s*\\(\\s*(['"\`])${escapeRegex(oldParts.key)}\\1\\s*,\\s*\\{([^}]*)\\}\\s*\\)`, 'g');
|
|
485
|
+
const regexKeyWithOptions = new RegExp(`${prefix}\\s*\\(\\s*(['"\`])${escapeRegex(oldParts.key)}\\1${defaultValueArg}\\s*,\\s*\\{([^}]*)\\}\\s*\\)`, 'g');
|
|
483
486
|
newCode = newCode.replace(regexKeyWithOptions, (match, q, objContents) => {
|
|
484
487
|
// don't touch objects that already explicitly set ns (handled elsewhere)
|
|
485
488
|
if (/\bns\s*:\s*['"`]/.test(objContents))
|
|
@@ -498,10 +501,12 @@ function replaceKeyWithRegex(code, oldParts, newParts, config, namespaceKeyMap)
|
|
|
498
501
|
oldParts.namespace !== newParts.namespace &&
|
|
499
502
|
config.extract.defaultNS === oldParts.namespace &&
|
|
500
503
|
hasKeyInNamespace(oldParts.namespace)) {
|
|
501
|
-
const regexKeyWithParen = new RegExp(`${prefix}\\s*\\(\\s*(['"\`])${escapeRegex(oldParts.key)}\\1\\s*\\)`, 'g');
|
|
504
|
+
const regexKeyWithParen = new RegExp(`${prefix}\\s*\\(\\s*(['"\`])${escapeRegex(oldParts.key)}\\1${defaultValueArg}\\s*\\)`, 'g');
|
|
502
505
|
newCode = newCode.replace(regexKeyWithParen, (match, quote) => {
|
|
503
506
|
changes++;
|
|
504
|
-
return match
|
|
507
|
+
return match
|
|
508
|
+
.replace(new RegExp(`(['"\`])${escapeRegex(oldParts.key)}\\1`), `${quote}${newParts.key}${quote}`)
|
|
509
|
+
.replace(/\s*\)$/, `, { ns: '${newParts.namespace}' })`);
|
|
505
510
|
});
|
|
506
511
|
}
|
|
507
512
|
//
|
|
@@ -515,7 +520,7 @@ function replaceKeyWithRegex(code, oldParts, newParts, config, namespaceKeyMap)
|
|
|
515
520
|
{
|
|
516
521
|
const effectiveDefaultNS = config.extract.defaultNS ?? 'translation';
|
|
517
522
|
if (oldParts.namespace === effectiveDefaultNS) {
|
|
518
|
-
const regexKeyNoOptions = new RegExp(`${prefix}\\s*\\(\\s*(['"\`])${escapeRegex(oldParts.key)}\\1\\s*\\)`, 'g');
|
|
523
|
+
const regexKeyNoOptions = new RegExp(`${prefix}\\s*\\(\\s*(['"\`])${escapeRegex(oldParts.key)}\\1${defaultValueArg}\\s*\\)`, 'g');
|
|
519
524
|
newCode = newCode.replace(regexKeyNoOptions, (match, q) => {
|
|
520
525
|
changes++;
|
|
521
526
|
const replacementKey = newParts.key;
|
|
@@ -549,6 +554,12 @@ function escapeRegex(str) {
|
|
|
549
554
|
async function updateTranslationFiles(oldParts, newParts, config, dryRun, namespaceKeyMap, logger) {
|
|
550
555
|
const results = [];
|
|
551
556
|
const keySeparator = config.extract.keySeparator ?? '.';
|
|
557
|
+
// Write the new key the way the extractor would store it (flat for "Loading..." or
|
|
558
|
+
// natural-language keys), and remove the old one the way it is actually stored.
|
|
559
|
+
const nsSeparator = config.extract.nsSeparator;
|
|
560
|
+
const naturalLanguageRegex = naturalLanguageRegexFor(typeof nsSeparator === 'string' ? nsSeparator : ':', keySeparator);
|
|
561
|
+
const newKeySeparator = storedKeySeparator(newParts.key, keySeparator, naturalLanguageRegex);
|
|
562
|
+
const oldKeySeparatorIn = (translations) => Object.prototype.hasOwnProperty.call(translations, oldParts.key) ? false : keySeparator;
|
|
552
563
|
// Helper: determine whether a flattened key-set indicates presence of `baseKey`.
|
|
553
564
|
const namespaceHasKey = (set, baseKey) => {
|
|
554
565
|
if (!set)
|
|
@@ -675,8 +686,8 @@ async function updateTranslationFiles(oldParts, newParts, config, dryRun, namesp
|
|
|
675
686
|
if (oldValue !== undefined) {
|
|
676
687
|
if (ns === targetNamespace) {
|
|
677
688
|
// rename within same file (nested)
|
|
678
|
-
deleteNestedValue(oldTranslations, oldParts.key,
|
|
679
|
-
setNestedValue(oldTranslations, newParts.key, oldValue,
|
|
689
|
+
deleteNestedValue(oldTranslations, oldParts.key, oldKeySeparatorIn(oldTranslations));
|
|
690
|
+
setNestedValue(oldTranslations, newParts.key, oldValue, newKeySeparator);
|
|
680
691
|
if (!dryRun) {
|
|
681
692
|
const content = serializeTranslationFile(oldTranslations, config.extract.outputFormat, config.extract.indentation);
|
|
682
693
|
await writeFile(oldFullPath, content, 'utf-8');
|
|
@@ -689,7 +700,7 @@ async function updateTranslationFiles(oldParts, newParts, config, dryRun, namesp
|
|
|
689
700
|
else {
|
|
690
701
|
// move nested value across namespaces
|
|
691
702
|
const updatedOld = { ...oldTranslations };
|
|
692
|
-
deleteNestedValue(updatedOld, oldParts.key,
|
|
703
|
+
deleteNestedValue(updatedOld, oldParts.key, oldKeySeparatorIn(updatedOld));
|
|
693
704
|
if (!dryRun) {
|
|
694
705
|
const contentOld = serializeTranslationFile(updatedOld, config.extract.outputFormat, config.extract.indentation);
|
|
695
706
|
await writeFile(oldFullPath, contentOld, 'utf-8');
|
|
@@ -704,7 +715,7 @@ async function updateTranslationFiles(oldParts, newParts, config, dryRun, namesp
|
|
|
704
715
|
catch { }
|
|
705
716
|
if (!newTranslations)
|
|
706
717
|
newTranslations = {};
|
|
707
|
-
setNestedValue(newTranslations, newParts.key, oldValue,
|
|
718
|
+
setNestedValue(newTranslations, newParts.key, oldValue, newKeySeparator);
|
|
708
719
|
if (!dryRun) {
|
|
709
720
|
const contentNew = serializeTranslationFile(newTranslations, config.extract.outputFormat, config.extract.indentation);
|
|
710
721
|
await writeFile(newFullPath, contentNew, 'utf-8');
|
package/dist/esm/syncer.js
CHANGED
|
@@ -181,7 +181,7 @@ async function runSyncer(config, options = {}) {
|
|
|
181
181
|
const existingSecondaryKeys = getNestedKeys(existingSecondaryTranslations, keySeparator ?? '.');
|
|
182
182
|
// Keep a key flat when the primary or the existing secondary file has it as one flat
|
|
183
183
|
// top-level key, which is how the extractor writes keys like "Loading..." or
|
|
184
|
-
// "Hello.
|
|
184
|
+
// "Hello world. Bye". Splitting them on the separator would nest them under new parents.
|
|
185
185
|
const keySeparatorFor = (key) => Object.prototype.hasOwnProperty.call(primaryTranslations, key) ||
|
|
186
186
|
Object.prototype.hasOwnProperty.call(existingSecondaryTranslations, key)
|
|
187
187
|
? false
|
|
@@ -74,7 +74,7 @@ function getNestedValue(obj, path, keySeparator) {
|
|
|
74
74
|
}
|
|
75
75
|
const value = path.split(keySeparator).reduce((acc, key) => acc && acc[key], obj);
|
|
76
76
|
// The extractor writes a key that cannot be used as a path ("Loading...", or a
|
|
77
|
-
// natural-language key such as "Hello.
|
|
77
|
+
// natural-language key such as "Hello world. Bye") as a single flat top-level key.
|
|
78
78
|
if (value === undefined && obj != null && Object.prototype.hasOwnProperty.call(obj, path)) {
|
|
79
79
|
return obj[path];
|
|
80
80
|
}
|
|
@@ -122,5 +122,34 @@ function getNestedKeys(obj, keySeparator, prefix = '') {
|
|
|
122
122
|
return acc;
|
|
123
123
|
}, []);
|
|
124
124
|
}
|
|
125
|
+
const naturalLanguageChars = [' ', ',', '?', '!', ';'];
|
|
126
|
+
/**
|
|
127
|
+
* Builds the regex that marks a key as natural language (like i18next does): any of
|
|
128
|
+
* ` ,?!;` that is not itself used as the namespace or key separator.
|
|
129
|
+
*/
|
|
130
|
+
function naturalLanguageRegexFor(nsSeparator, keySeparator) {
|
|
131
|
+
const possibleChars = naturalLanguageChars.filter((c) => nsSeparator.indexOf(c) < 0 && (typeof keySeparator === 'string' ? keySeparator.indexOf(c) < 0 : true));
|
|
132
|
+
return possibleChars.length > 0
|
|
133
|
+
? new RegExp(`(${possibleChars.map((c) => (c === '?' ? '\\?' : c)).join('|')})`)
|
|
134
|
+
: null;
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* The separator a key is stored with in a translation file, or `false` when it is
|
|
138
|
+
* stored as one flat key: a serialized Trans component (`<...`), a natural-language
|
|
139
|
+
* key such as "Hello world. Bye", or a key with empty segments such as "Loading...".
|
|
140
|
+
*/
|
|
141
|
+
function storedKeySeparator(key, keySeparator, naturalLanguageRegex) {
|
|
142
|
+
if (keySeparator === false || key.startsWith('<'))
|
|
143
|
+
return false;
|
|
144
|
+
if (naturalLanguageRegex) {
|
|
145
|
+
const ki = key.indexOf(keySeparator);
|
|
146
|
+
const isPath = !naturalLanguageRegex.test(key) || (ki > 0 && !naturalLanguageRegex.test(key.substring(0, ki)));
|
|
147
|
+
if (!isPath)
|
|
148
|
+
return false;
|
|
149
|
+
}
|
|
150
|
+
if (key.split(keySeparator).some(s => s === ''))
|
|
151
|
+
return false;
|
|
152
|
+
return keySeparator;
|
|
153
|
+
}
|
|
125
154
|
|
|
126
|
-
export { getNestedKeys, getNestedValue, setNestedValue };
|
|
155
|
+
export { getNestedKeys, getNestedValue, naturalLanguageRegexFor, setNestedValue, storedKeySeparator };
|
package/package.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"translation-manager.d.ts","sourceRoot":"","sources":["../../../src/extractor/core/translation-manager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,YAAY,EAAE,oBAAoB,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAA;
|
|
1
|
+
{"version":3,"file":"translation-manager.d.ts","sourceRoot":"","sources":["../../../src/extractor/core/translation-manager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,YAAY,EAAE,oBAAoB,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAA;AA2sC9F;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAsB,eAAe,CACnC,IAAI,EAAE,GAAG,CAAC,MAAM,EAAE,YAAY,CAAC,EAC/B,UAAU,EAAE,GAAG,CAAC,MAAM,CAAC,EACvB,MAAM,EAAE,oBAAoB,EAC5B,EACE,uBAA+B,EAC/B,OAAe,EACf,oBAA4B,EAC5B,MAA4B,EAC5B,YAAiB,EAClB,GAAE;IACD,uBAAuB,CAAC,EAAE,OAAO,CAAC;IAClC,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,oBAAoB,CAAC,EAAE,OAAO,CAAC;IAC/B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,YAAY,CAAC,EAAE,YAAY,EAAE,CAAA;CACzB,GACL,OAAO,CAAC,iBAAiB,EAAE,CAAC,CA6K9B"}
|
|
@@ -68,4 +68,15 @@ export declare function getNestedValue(obj: Record<string, any>, path: string, k
|
|
|
68
68
|
* ```
|
|
69
69
|
*/
|
|
70
70
|
export declare function getNestedKeys(obj: object, keySeparator: string | false, prefix?: string): string[];
|
|
71
|
+
/**
|
|
72
|
+
* Builds the regex that marks a key as natural language (like i18next does): any of
|
|
73
|
+
* ` ,?!;` that is not itself used as the namespace or key separator.
|
|
74
|
+
*/
|
|
75
|
+
export declare function naturalLanguageRegexFor(nsSeparator: string, keySeparator: string | false): RegExp | null;
|
|
76
|
+
/**
|
|
77
|
+
* The separator a key is stored with in a translation file, or `false` when it is
|
|
78
|
+
* stored as one flat key: a serialized Trans component (`<...`), a natural-language
|
|
79
|
+
* key such as "Hello world. Bye", or a key with empty segments such as "Loading...".
|
|
80
|
+
*/
|
|
81
|
+
export declare function storedKeySeparator(key: string, keySeparator: string | false, naturalLanguageRegex: RegExp | null): string | false;
|
|
71
82
|
//# sourceMappingURL=nested-object.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"nested-object.d.ts","sourceRoot":"","sources":["../../src/utils/nested-object.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,cAAc,CAC5B,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EACxB,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE,GAAG,EACV,YAAY,EAAE,MAAM,GAAG,KAAK,GAC3B,IAAI,CAoCN;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,cAAc,CAC5B,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EACxB,IAAI,EAAE,MAAM,EACZ,YAAY,EAAE,MAAM,GAAG,KAAK,GAC3B,GAAG,CAWL;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,wBAAgB,aAAa,CAAE,GAAG,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,GAAG,KAAK,EAAE,MAAM,SAAK,GAAG,MAAM,EAAE,CAa/F"}
|
|
1
|
+
{"version":3,"file":"nested-object.d.ts","sourceRoot":"","sources":["../../src/utils/nested-object.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,cAAc,CAC5B,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EACxB,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE,GAAG,EACV,YAAY,EAAE,MAAM,GAAG,KAAK,GAC3B,IAAI,CAoCN;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,cAAc,CAC5B,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EACxB,IAAI,EAAE,MAAM,EACZ,YAAY,EAAE,MAAM,GAAG,KAAK,GAC3B,GAAG,CAWL;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,wBAAgB,aAAa,CAAE,GAAG,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,GAAG,KAAK,EAAE,MAAM,SAAK,GAAG,MAAM,EAAE,CAa/F;AAID;;;GAGG;AACH,wBAAgB,uBAAuB,CAAE,WAAW,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,GAAG,KAAK,GAAG,MAAM,GAAG,IAAI,CAOzG;AAED;;;;GAIG;AACH,wBAAgB,kBAAkB,CAAE,GAAG,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,GAAG,KAAK,EAAE,oBAAoB,EAAE,MAAM,GAAG,IAAI,GAAG,MAAM,GAAG,KAAK,CASlI"}
|