i18next-cli 1.88.1 → 1.89.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +62 -9
- package/dist/cjs/cli.js +18 -3
- package/dist/cjs/extractor/core/translation-manager.js +9 -2
- package/dist/cjs/index.js +2 -1
- package/dist/cjs/init.js +3 -11
- package/dist/cjs/instrumenter/core/instrumenter.js +1114 -209
- package/dist/cjs/instrumenter/core/key-generator.js +19 -9
- package/dist/cjs/instrumenter/core/string-detector.js +106 -29
- package/dist/cjs/instrumenter/core/transformer.js +89 -31
- package/dist/cjs/localize/detect.js +2 -11
- package/dist/cjs/localize/localize.js +2 -1
- package/dist/cjs/utils/file-utils.js +48 -0
- package/dist/cjs/utils/jsx-attributes.js +3 -1
- package/dist/esm/cli.js +18 -3
- package/dist/esm/extractor/core/translation-manager.js +9 -2
- package/dist/esm/index.js +2 -1
- package/dist/esm/init.js +3 -11
- package/dist/esm/instrumenter/core/instrumenter.js +1117 -212
- package/dist/esm/instrumenter/core/key-generator.js +19 -9
- package/dist/esm/instrumenter/core/string-detector.js +107 -31
- package/dist/esm/instrumenter/core/transformer.js +89 -31
- package/dist/esm/localize/detect.js +3 -12
- package/dist/esm/localize/localize.js +2 -1
- package/dist/esm/utils/file-utils.js +49 -2
- package/dist/esm/utils/jsx-attributes.js +3 -1
- package/package.json +1 -1
- package/types/cli.d.ts.map +1 -1
- package/types/extractor/core/translation-manager.d.ts.map +1 -1
- package/types/index.d.ts +1 -1
- package/types/index.d.ts.map +1 -1
- package/types/init.d.ts.map +1 -1
- package/types/instrumenter/core/instrumenter.d.ts.map +1 -1
- package/types/instrumenter/core/key-generator.d.ts +2 -0
- package/types/instrumenter/core/key-generator.d.ts.map +1 -1
- package/types/instrumenter/core/string-detector.d.ts +5 -1
- package/types/instrumenter/core/string-detector.d.ts.map +1 -1
- package/types/instrumenter/core/transformer.d.ts +10 -1
- package/types/instrumenter/core/transformer.d.ts.map +1 -1
- package/types/instrumenter/index.d.ts +1 -1
- package/types/instrumenter/index.d.ts.map +1 -1
- package/types/localize/detect.d.ts.map +1 -1
- package/types/types.d.ts +48 -1
- package/types/types.d.ts.map +1 -1
- package/types/utils/file-utils.d.ts +7 -0
- package/types/utils/file-utils.d.ts.map +1 -1
- package/types/utils/jsx-attributes.d.ts.map +1 -1
package/README.md
CHANGED
|
@@ -446,7 +446,7 @@ npx i18next-cli instrument
|
|
|
446
446
|
```
|
|
447
447
|
|
|
448
448
|
**Options:**
|
|
449
|
-
- `--dry-run`: Preview changes without writing files to disk
|
|
449
|
+
- `--dry-run`: Preview changes without writing files to disk: each text with the key it would get, by file
|
|
450
450
|
- `--interactive`: Prompt for approval of each candidate string
|
|
451
451
|
- `--namespace <ns>`: Target a specific namespace for extracted keys
|
|
452
452
|
- `-q, --quiet`: Suppress spinner and output
|
|
@@ -491,6 +491,35 @@ The `instrument` command detects four types of transformations:
|
|
|
491
491
|
// After
|
|
492
492
|
<p><Trans i18nKey="clickHereLabel">Click <a href="/docs">here</a> to continue</Trans></p>
|
|
493
493
|
```
|
|
494
|
+
A link or text component whose only children are text (`<Link to="/docs">here</Link>`, `<Text.Strong>`) and
|
|
495
|
+
`{' '}` stay in the sentence too; a button or an icon does not. The key is made from the words, and the
|
|
496
|
+
`i18nKey` takes the quotes the file's JSX attributes use.
|
|
497
|
+
|
|
498
|
+
5. **Plurals → one `t()` with `count`:** a `count === 1 ? … : …` ternary, or a call of a plural helper named
|
|
499
|
+
`plural`, `pluralize` or `pluralise` that takes `(count, one, other)`, also inside a template literal. `#` in
|
|
500
|
+
a form stands for the number, as in ICU:
|
|
501
|
+
```javascript
|
|
502
|
+
// Before
|
|
503
|
+
`${n} ${plural(n, 'key', 'keys')} unused`
|
|
504
|
+
plural(files.length, '# file', '# files')
|
|
505
|
+
|
|
506
|
+
// After
|
|
507
|
+
t('countKeysUnused', { defaultValue_one: '{{count}} key unused', defaultValue_other: '{{count}} keys unused', count: n })
|
|
508
|
+
t('countFiles', { defaultValue_one: '{{count}} file', defaultValue_other: '{{count}} files', count: files.length })
|
|
509
|
+
```
|
|
510
|
+
Once every call of an imported helper is rewritten, its import goes.
|
|
511
|
+
|
|
512
|
+
A sentence stays whole around a value: a variable, a property, a string or number formatted from one
|
|
513
|
+
(`{items.join(', ')}`, `{n.toLocaleString()}`, `{format.date(d)}`), a choice between such values. A placeholder is
|
|
514
|
+
named after what it shows: `` `Last login ${format.date(user.lastLogin)}` `` becomes `'Last login {{lastLogin}}'`;
|
|
515
|
+
the same expression twice is one placeholder. A key keeps the first words of a long text (at most 40 characters,
|
|
516
|
+
no `_`, which i18next reads as a plural or context suffix), and a key the code uses already is never reused for
|
|
517
|
+
another text nor made the parent of nested ones: `Tenants` next to an existing `t('tenants.title')` gets `tenants2`.
|
|
518
|
+
|
|
519
|
+
What JSX shows is text, a single word too: JSX text (as it renders: lines joined, `'` decoded), a
|
|
520
|
+
translatable attribute (`title`, `aria-label`, `data-tip`, …), and a string an element renders from an
|
|
521
|
+
expression (`{busy ? 'saving' : 'saved'}`, `{name || 'unnamed'}`). When one branch of a ternary is text, the
|
|
522
|
+
other string branch is too.
|
|
494
523
|
|
|
495
524
|
**Namespace targeting:**
|
|
496
525
|
|
|
@@ -530,16 +559,38 @@ export default defineConfig({
|
|
|
530
559
|
**What it skips (by design):**
|
|
531
560
|
|
|
532
561
|
The instrumenter uses confidence heuristics to avoid transforming:
|
|
533
|
-
- Test files (`*.test.*`, `*.spec.*`)
|
|
562
|
+
- Test files (`*.test.*`, `*.spec.*`), stories (`*.stories.*`, `*.story.*`, `*.storybook.*`) and the folders
|
|
563
|
+
`__tests__`, `__mocks__`, `__fixtures__`; other fixture folders go into `extract.ignore`
|
|
534
564
|
- Empty strings and single characters
|
|
535
565
|
- Pure numbers and numeric IDs
|
|
536
566
|
- URL strings and file paths
|
|
537
567
|
- CSS class names and technical identifiers
|
|
538
568
|
- Developer-facing error codes (all-caps patterns like `ERROR_NOT_FOUND`)
|
|
539
|
-
- `console
|
|
540
|
-
-
|
|
541
|
-
|
|
542
|
-
|
|
569
|
+
- `console.*` calls, everything in them, and variables used only there (a log line built beforehand)
|
|
570
|
+
- Object keys and computed keys, compared strings and `case` values; and a string the file also uses as data
|
|
571
|
+
(compared, an `id`/`key`/`value`/`type`/`code`, an entry of an `order`/`ids`/`values` list), everywhere in that
|
|
572
|
+
file unless an element renders it or it is an attribute's value: a facet's `of()` returning `'no 2FA'` keeps
|
|
573
|
+
matching `order: ['2FA', 'no 2FA']`
|
|
574
|
+
- Prompts for a language model: the functions, variables and properties named like `getSystemPrompt`,
|
|
575
|
+
`userPrompt` or `aiAssistantPrompt` (a translated prompt changes what the model does)
|
|
576
|
+
- Analytics event names (`track`, `trackEvent`, `logEvent`, `capture`, `identify`, `gtag`), event names (`emit`,
|
|
577
|
+
`on`), log and error-report calls (`logger.*`, `Sentry.*`), `new Error()` and `RegExp` arguments (errors are for
|
|
578
|
+
developers; show users a text of your own), format patterns (`dayjs(d).format('DD MMM YYYY')`)
|
|
579
|
+
- Icon ligatures: the content of an element named `…Icon` or with a `material-icons`/`material-symbols` class
|
|
580
|
+
- CSS values (`var(--brand)`, `inset 0 0 5px 1px var(--shadow)`), and strings in a `classes`/`style` variable
|
|
581
|
+
- Strings a text is compared with or searched for (`msg.includes('not found')`, `split`, `replace`, …),
|
|
582
|
+
selectors (`querySelector`, `closest`), attribute and storage names (`getAttribute`, `setItem`, …)
|
|
583
|
+
- camelCase identifiers (`aiReview`), rules and key paths (`required|min:2`), strings without a letter (` / `),
|
|
584
|
+
code snippets shown as text (several lines of code or shell commands)
|
|
585
|
+
- The content of `<code>`, `<script>` and `<style>` (and of `extract.ignoredTags`); inside a sentence they stay
|
|
586
|
+
part of its `<Trans>`
|
|
587
|
+
- HTML attribute values that appear technical (which attributes hold text can be set per element, see [Translatable attributes per element](#translatable-attributes-per-element)); the JSX and functions inside such an attribute (`action={<Button>Change</Button>}`, `onClick={() => notify('Copied')}`) are checked as anywhere else
|
|
588
|
+
- Template literals with no word besides their expressions: ids, paths, keys, language codes and class names
|
|
589
|
+
built in code (`` `${projectId}-${version}` ``, `` `weight_${code}` ``, `` `${baseUrl}/api/${id}` ``,
|
|
590
|
+
`` `zh-${country}` ``); and values of technical properties (`` { 'Authorization': `Bearer ${token}` } ``,
|
|
591
|
+
`url`, `id`, `type`, `code`, `className`, …)
|
|
592
|
+
- Strings already inside `t()` calls or `<Trans>` components, including the project's own `extract.functions`
|
|
593
|
+
and `extract.transComponents`
|
|
543
594
|
- **Module-scope strings** — anything outside a function body, e.g. a top-level config/registry array:
|
|
544
595
|
```ts
|
|
545
596
|
export const SETTINGS_SECTIONS = [
|
|
@@ -560,10 +611,12 @@ The instrumenter uses confidence heuristics to avoid transforming:
|
|
|
560
611
|
|
|
561
612
|
When transformations are applied, the command automatically:
|
|
562
613
|
- Injects `import { useTranslation } from 'react-i18next'` in React files (or `import i18next from 'i18next'` for non-React files)
|
|
563
|
-
- Injects `const { t } = useTranslation()` into each React function component that contains transformed strings
|
|
564
|
-
-
|
|
614
|
+
- Injects `const { t } = useTranslation()` into each React function component that contains transformed strings (an arrow component with an expression body, `() => <p>…</p>`, gets a block for it), unless it has a `t` already (a prop, or a hook from a module that re-exports it), and adds `t` to the dependencies of a `useMemo` or `useCallback` whose callback now calls it
|
|
615
|
+
- Places the imports after the file's import declarations (never inside a string that shows code), and imports no name the file has already, from whatever module
|
|
616
|
+
- Detects the project's framework from `package.json` dependencies, dev and peer dependencies included; in a workspace package (npm/yarn `workspaces`, `pnpm-workspace.yaml`) also from the workspace root's
|
|
565
617
|
- Uses `useTranslation()` hook style `t()` inside React components, or `i18next.t()` for utility / non-component code
|
|
566
|
-
- Generates an `i18n.ts` (or `i18n.js` for JS-only projects) initialization file if none exists, pre-configured with [`i18next-resources-to-backend`](https://github.com/i18next/i18next-resources-to-backend) to lazy-load your translation files via dynamic imports
|
|
618
|
+
- Generates an `i18n.ts` (or `i18n.js` for JS-only projects) initialization file if none exists and the code imports neither `i18next` nor `react-i18next` yet (an app that does is set up somewhere, perhaps in a shared package), pre-configured with [`i18next-resources-to-backend`](https://github.com/i18next/i18next-resources-to-backend) to lazy-load your translation files via dynamic imports
|
|
619
|
+
- Adds `i18n.changeLanguage()` next to a call that sets the user's language: `setLanguage(code)`, or a settings, profile or user call with a `language`/`locale` property (`updateSettings({ language: code })`). Only where that call is a statement of its own in a block or an arrow function's body, with a plain variable or property as the language (the injected call repeats it), and not for a `language` property passed as data (`fetchTranslations({ lng })`). `--dry-run` lists every such site; in an app where a language is data (a translation tool's view filter), review them
|
|
567
620
|
|
|
568
621
|
**Recommended workflow:**
|
|
569
622
|
|
package/dist/cjs/cli.js
CHANGED
|
@@ -27,7 +27,7 @@ var status = require('./status.js');
|
|
|
27
27
|
var locize = require('./locize.js');
|
|
28
28
|
var renameKey = require('./rename-key.js');
|
|
29
29
|
var instrumenter = require('./instrumenter/core/instrumenter.js');
|
|
30
|
-
require('./
|
|
30
|
+
require('./instrumenter/core/string-detector.js');
|
|
31
31
|
require('magic-string');
|
|
32
32
|
var localize = require('./localize/localize.js');
|
|
33
33
|
|
|
@@ -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.
|
|
42
|
+
.version('1.89.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)');
|
|
@@ -327,6 +327,21 @@ program
|
|
|
327
327
|
});
|
|
328
328
|
// Display results
|
|
329
329
|
if (!options.quiet) {
|
|
330
|
+
// The preview: each text with the key it would get, by file
|
|
331
|
+
if (options.dryRun) {
|
|
332
|
+
for (const { file, candidates, languageChangeSites } of results.files) {
|
|
333
|
+
if (!candidates.length && !languageChangeSites?.length)
|
|
334
|
+
continue;
|
|
335
|
+
console.log(node_util.styleText('bold', `\n${file}`));
|
|
336
|
+
for (const c of candidates) {
|
|
337
|
+
const text = c.content.replace(/\s+/g, ' ');
|
|
338
|
+
console.log(` ${c.line}: "${text.length > 80 ? text.slice(0, 79) + '…' : text}" → ${c.key}`);
|
|
339
|
+
}
|
|
340
|
+
for (const site of languageChangeSites ?? []) {
|
|
341
|
+
console.log(` ${site.line}: changeLanguage(${site.languageExpression}) before the call that sets the language`);
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
}
|
|
330
345
|
console.log(node_util.styleText('bold', '\nInstrumentation Summary:'));
|
|
331
346
|
console.log(` Total candidates: ${results.totalCandidates}`);
|
|
332
347
|
console.log(` Approved: ${results.totalTransformed}`);
|
|
@@ -339,7 +354,7 @@ program
|
|
|
339
354
|
console.log('Run again without --dry-run to apply changes.');
|
|
340
355
|
}
|
|
341
356
|
if (results.files.length > 0) {
|
|
342
|
-
console.log(node_util.styleText('green', `\n✅ ${results.files.length} file(s) ready for instrumentation`));
|
|
357
|
+
console.log(node_util.styleText('green', `\n✅ ${results.files.length} file(s) ${options.dryRun ? 'ready for instrumentation' : 'instrumented'}`));
|
|
343
358
|
}
|
|
344
359
|
else {
|
|
345
360
|
console.log(node_util.styleText('yellow', '\n⚠️ No files required instrumentation'));
|
|
@@ -854,8 +854,15 @@ function buildNewTranslationsForNs(nsKeys, existingTranslations, config, locale,
|
|
|
854
854
|
if (separator && typeof separator === 'string') {
|
|
855
855
|
const conflictingPath = findNestingConflict(newTranslations, key, separator);
|
|
856
856
|
if (conflictingPath !== null) {
|
|
857
|
-
|
|
858
|
-
|
|
857
|
+
// The keys come from the code, the same for every language: reported once, with the primary one (or
|
|
858
|
+
// the first language, when the primary one is not among them)
|
|
859
|
+
if (locale === (config.locales.includes(primaryLanguage) ? primaryLanguage : config.locales[0])) {
|
|
860
|
+
const conflict = conflictingPath === key
|
|
861
|
+
? `key "${key}" is also the parent of nested keys ("${key}${separator}…")`
|
|
862
|
+
: `key "${key}" conflicts with existing key "${conflictingPath}"`;
|
|
863
|
+
logger$1.error(`Error: Nesting conflict: ${conflict}. ` +
|
|
864
|
+
`"${key}" will be skipped — fix the overlapping key paths in your source code to avoid missing translations at runtime.`);
|
|
865
|
+
}
|
|
859
866
|
continue;
|
|
860
867
|
}
|
|
861
868
|
}
|
package/dist/cjs/index.js
CHANGED
|
@@ -8,6 +8,7 @@ require('node:path');
|
|
|
8
8
|
require('node:fs/promises');
|
|
9
9
|
require('glob');
|
|
10
10
|
require('jsonc-parser');
|
|
11
|
+
require('minimatch');
|
|
11
12
|
require('jiti');
|
|
12
13
|
require('@croct/json5-parser');
|
|
13
14
|
require('yaml');
|
|
@@ -19,7 +20,7 @@ var status = require('./status.js');
|
|
|
19
20
|
var typesGenerator = require('./types-generator.js');
|
|
20
21
|
var renameKey = require('./rename-key.js');
|
|
21
22
|
var instrumenter = require('./instrumenter/core/instrumenter.js');
|
|
22
|
-
require('./
|
|
23
|
+
require('./instrumenter/core/string-detector.js');
|
|
23
24
|
require('magic-string');
|
|
24
25
|
var localize = require('./localize/localize.js');
|
|
25
26
|
var agentPrompt = require('./localize/agent-prompt.js');
|
package/dist/cjs/init.js
CHANGED
|
@@ -7,6 +7,7 @@ var heuristicConfig = require('./heuristic-config.js');
|
|
|
7
7
|
var locizeOnboarding = require('./utils/locize-onboarding.js');
|
|
8
8
|
var inlangScaffold = require('./utils/inlang-scaffold.js');
|
|
9
9
|
var agentNote = require('./utils/agent-note.js');
|
|
10
|
+
var fileUtils = require('./utils/file-utils.js');
|
|
10
11
|
|
|
11
12
|
const LOCIZE_SIGNUP_URL = 'https://www.locize.app/register?from=i18next_cli__init-wizard';
|
|
12
13
|
/**
|
|
@@ -41,19 +42,10 @@ async function isEsmProject() {
|
|
|
41
42
|
* When running via `npx` without a local install, `defineConfig` would not be available
|
|
42
43
|
* at runtime, so the generated config should fall back to a plain object export.
|
|
43
44
|
*
|
|
44
|
-
* @returns Promise resolving to true if i18next-cli is
|
|
45
|
+
* @returns Promise resolving to true if i18next-cli is a declared dependency (see readProjectDeps)
|
|
45
46
|
*/
|
|
46
47
|
async function isCliLocallyInstalled() {
|
|
47
|
-
|
|
48
|
-
const packageJsonPath = node_path.resolve(process.cwd(), 'package.json');
|
|
49
|
-
const content = await promises.readFile(packageJsonPath, 'utf-8');
|
|
50
|
-
const packageJson = JSON.parse(content);
|
|
51
|
-
const deps = { ...packageJson.dependencies, ...packageJson.devDependencies };
|
|
52
|
-
return !!deps['i18next-cli'];
|
|
53
|
-
}
|
|
54
|
-
catch {
|
|
55
|
-
return false;
|
|
56
|
-
}
|
|
48
|
+
return !!(await fileUtils.readProjectDeps())['i18next-cli'];
|
|
57
49
|
}
|
|
58
50
|
/**
|
|
59
51
|
* Checks whether the project uses TypeScript by looking for a tsconfig.json.
|