i18next-cli 1.88.1 → 1.90.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 (65) hide show
  1. package/README.md +104 -12
  2. package/dist/cjs/cli.js +25 -6
  3. package/dist/cjs/config.js +13 -12
  4. package/dist/cjs/extractor/core/extractor.js +1 -3
  5. package/dist/cjs/extractor/core/translation-manager.js +9 -2
  6. package/dist/cjs/heuristic-config.js +51 -6
  7. package/dist/cjs/index.js +2 -1
  8. package/dist/cjs/init.js +8 -11
  9. package/dist/cjs/instrumenter/core/instrumenter.js +1372 -218
  10. package/dist/cjs/instrumenter/core/key-generator.js +20 -9
  11. package/dist/cjs/instrumenter/core/next-files.js +104 -0
  12. package/dist/cjs/instrumenter/core/string-detector.js +106 -29
  13. package/dist/cjs/instrumenter/core/transformer.js +165 -83
  14. package/dist/cjs/localize/agent-prompt.js +5 -2
  15. package/dist/cjs/localize/detect.js +3 -11
  16. package/dist/cjs/localize/localize.js +27 -5
  17. package/dist/cjs/utils/file-utils.js +48 -0
  18. package/dist/cjs/utils/jsx-attributes.js +3 -1
  19. package/dist/esm/cli.js +25 -6
  20. package/dist/esm/config.js +13 -12
  21. package/dist/esm/extractor/core/extractor.js +1 -3
  22. package/dist/esm/extractor/core/translation-manager.js +9 -2
  23. package/dist/esm/heuristic-config.js +52 -7
  24. package/dist/esm/index.js +2 -1
  25. package/dist/esm/init.js +8 -11
  26. package/dist/esm/instrumenter/core/instrumenter.js +1376 -222
  27. package/dist/esm/instrumenter/core/key-generator.js +20 -9
  28. package/dist/esm/instrumenter/core/next-files.js +101 -0
  29. package/dist/esm/instrumenter/core/string-detector.js +107 -31
  30. package/dist/esm/instrumenter/core/transformer.js +165 -83
  31. package/dist/esm/localize/agent-prompt.js +5 -2
  32. package/dist/esm/localize/detect.js +4 -12
  33. package/dist/esm/localize/localize.js +27 -5
  34. package/dist/esm/utils/file-utils.js +49 -2
  35. package/dist/esm/utils/jsx-attributes.js +3 -1
  36. package/package.json +1 -1
  37. package/types/cli.d.ts.map +1 -1
  38. package/types/config.d.ts.map +1 -1
  39. package/types/extractor/core/extractor.d.ts.map +1 -1
  40. package/types/extractor/core/translation-manager.d.ts.map +1 -1
  41. package/types/heuristic-config.d.ts.map +1 -1
  42. package/types/index.d.ts +1 -1
  43. package/types/index.d.ts.map +1 -1
  44. package/types/init.d.ts.map +1 -1
  45. package/types/instrumenter/core/instrumenter.d.ts.map +1 -1
  46. package/types/instrumenter/core/key-generator.d.ts +2 -0
  47. package/types/instrumenter/core/key-generator.d.ts.map +1 -1
  48. package/types/instrumenter/core/next-files.d.ts +25 -0
  49. package/types/instrumenter/core/next-files.d.ts.map +1 -0
  50. package/types/instrumenter/core/string-detector.d.ts +5 -1
  51. package/types/instrumenter/core/string-detector.d.ts.map +1 -1
  52. package/types/instrumenter/core/transformer.d.ts +16 -1
  53. package/types/instrumenter/core/transformer.d.ts.map +1 -1
  54. package/types/instrumenter/index.d.ts +1 -1
  55. package/types/instrumenter/index.d.ts.map +1 -1
  56. package/types/localize/agent-prompt.d.ts +1 -1
  57. package/types/localize/agent-prompt.d.ts.map +1 -1
  58. package/types/localize/detect.d.ts +2 -0
  59. package/types/localize/detect.d.ts.map +1 -1
  60. package/types/localize/localize.d.ts.map +1 -1
  61. package/types/types.d.ts +87 -1
  62. package/types/types.d.ts.map +1 -1
  63. package/types/utils/file-utils.d.ts +7 -0
  64. package/types/utils/file-utils.d.ts.map +1 -1
  65. package/types/utils/jsx-attributes.d.ts.map +1 -1
package/README.md CHANGED
@@ -168,6 +168,13 @@ write a note for AI coding agents:
168
168
  mode); add it later via a `LOCIZE_API_KEY` environment variable.
169
169
  - **Other / skip** — same as "Local files only" for the wizard's purposes.
170
170
 
171
+ The defaults come from the project: the locales and output path from the translation files it finds, the
172
+ source glob from the directories that exist of `src`, `app`, `pages` and `components` (`{app,components}/**/*.{js,jsx,mjs,ts,tsx}` in a Next.js app
173
+ without `src/`), and what the app's own setup decides is written into `extract` as well: next-i18next's
174
+ `defaultNS` (from `i18n.config` or `next-i18next.config`, `common` when it sets none), `messageFormat` for
175
+ i18next-icu or i18next-mf2, and `keySeparator: false` for translation files whose flat keys contain dots
176
+ (`"blog.title": "…"`), so `extract` keeps them as they are.
177
+
171
178
  **Note for AI coding agents** (off by default): the last question offers to
172
179
  append a short `## Internationalization` section to `AGENTS.md` and, if it
173
180
  exists, `CLAUDE.md` (when neither exists, `AGENTS.md` is created, plus a
@@ -446,7 +453,7 @@ npx i18next-cli instrument
446
453
  ```
447
454
 
448
455
  **Options:**
449
- - `--dry-run`: Preview changes without writing files to disk
456
+ - `--dry-run`: Preview changes without writing files to disk: each text with the key it would get, by file
450
457
  - `--interactive`: Prompt for approval of each candidate string
451
458
  - `--namespace <ns>`: Target a specific namespace for extracted keys
452
459
  - `-q, --quiet`: Suppress spinner and output
@@ -491,6 +498,35 @@ The `instrument` command detects four types of transformations:
491
498
  // After
492
499
  <p><Trans i18nKey="clickHereLabel">Click <a href="/docs">here</a> to continue</Trans></p>
493
500
  ```
501
+ A link or text component whose only children are text (`<Link to="/docs">here</Link>`, `<Text.Strong>`) and
502
+ `{' '}` stay in the sentence too; a button or an icon does not. The key is made from the words, and the
503
+ `i18nKey` takes the quotes the file's JSX attributes use.
504
+
505
+ 5. **Plurals → one `t()` with `count`:** a `count === 1 ? … : …` ternary, or a call of a plural helper named
506
+ `plural`, `pluralize` or `pluralise` that takes `(count, one, other)`, also inside a template literal. `#` in
507
+ a form stands for the number, as in ICU:
508
+ ```javascript
509
+ // Before
510
+ `${n} ${plural(n, 'key', 'keys')} unused`
511
+ plural(files.length, '# file', '# files')
512
+
513
+ // After
514
+ t('countKeysUnused', { defaultValue_one: '{{count}} key unused', defaultValue_other: '{{count}} keys unused', count: n })
515
+ t('countFiles', { defaultValue_one: '{{count}} file', defaultValue_other: '{{count}} files', count: files.length })
516
+ ```
517
+ Once every call of an imported helper is rewritten, its import goes.
518
+
519
+ A sentence stays whole around a value: a variable, a property, a string or number formatted from one
520
+ (`{items.join(', ')}`, `{n.toLocaleString()}`, `{format.date(d)}`), a choice between such values. A placeholder is
521
+ named after what it shows: `` `Last login ${format.date(user.lastLogin)}` `` becomes `'Last login {{lastLogin}}'`;
522
+ the same expression twice is one placeholder. A key keeps the first words of a long text (at most 40 characters,
523
+ no `_`, which i18next reads as a plural or context suffix), and a key the code uses already is never reused for
524
+ another text nor made the parent of nested ones: `Tenants` next to an existing `t('tenants.title')` gets `tenants2`.
525
+
526
+ What JSX shows is text, a single word too: JSX text (as it renders: lines joined, `&apos;` decoded), a
527
+ translatable attribute (`title`, `aria-label`, `data-tip`, …), and a string an element renders from an
528
+ expression (`{busy ? 'saving' : 'saved'}`, `{name || 'unnamed'}`). When one branch of a ternary is text, the
529
+ other string branch is too.
494
530
 
495
531
  **Namespace targeting:**
496
532
 
@@ -530,16 +566,38 @@ export default defineConfig({
530
566
  **What it skips (by design):**
531
567
 
532
568
  The instrumenter uses confidence heuristics to avoid transforming:
533
- - Test files (`*.test.*`, `*.spec.*`)
569
+ - Test files (`*.test.*`, `*.spec.*`), stories (`*.stories.*`, `*.story.*`, `*.storybook.*`) and the folders
570
+ `__tests__`, `__mocks__`, `__fixtures__`; other fixture folders go into `extract.ignore`
534
571
  - Empty strings and single characters
535
572
  - Pure numbers and numeric IDs
536
573
  - URL strings and file paths
537
574
  - CSS class names and technical identifiers
538
575
  - Developer-facing error codes (all-caps patterns like `ERROR_NOT_FOUND`)
539
- - `console.log/warn/error` arguments
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))
541
- - Template literals with only expressions (no static text)
542
- - Strings already inside `t()` calls or `<Trans>` components
576
+ - `console.*` calls, everything in them, and variables used only there (a log line built beforehand)
577
+ - Object keys and computed keys, compared strings and `case` values; and a string the file also uses as data
578
+ (compared, an `id`/`key`/`value`/`type`/`code`, an entry of an `order`/`ids`/`values` list), everywhere in that
579
+ file unless an element renders it or it is an attribute's value: a facet's `of()` returning `'no 2FA'` keeps
580
+ matching `order: ['2FA', 'no 2FA']`
581
+ - Prompts for a language model: the functions, variables and properties named like `getSystemPrompt`,
582
+ `userPrompt` or `aiAssistantPrompt` (a translated prompt changes what the model does)
583
+ - Analytics event names (`track`, `trackEvent`, `logEvent`, `capture`, `identify`, `gtag`), event names (`emit`,
584
+ `on`), log and error-report calls (`logger.*`, `Sentry.*`), `new Error()` and `RegExp` arguments (errors are for
585
+ developers; show users a text of your own), format patterns (`dayjs(d).format('DD MMM YYYY')`)
586
+ - Icon ligatures: the content of an element named `…Icon` or with a `material-icons`/`material-symbols` class
587
+ - CSS values (`var(--brand)`, `inset 0 0 5px 1px var(--shadow)`), and strings in a `classes`/`style` variable
588
+ - Strings a text is compared with or searched for (`msg.includes('not found')`, `split`, `replace`, …),
589
+ selectors (`querySelector`, `closest`), attribute and storage names (`getAttribute`, `setItem`, …)
590
+ - camelCase identifiers (`aiReview`), rules and key paths (`required|min:2`), strings without a letter (` / `),
591
+ code snippets shown as text (several lines of code or shell commands)
592
+ - The content of `<code>`, `<script>` and `<style>` (and of `extract.ignoredTags`); inside a sentence they stay
593
+ part of its `<Trans>`
594
+ - 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
595
+ - Template literals with no word besides their expressions: ids, paths, keys, language codes and class names
596
+ built in code (`` `${projectId}-${version}` ``, `` `weight_${code}` ``, `` `${baseUrl}/api/${id}` ``,
597
+ `` `zh-${country}` ``); and values of technical properties (`` { 'Authorization': `Bearer ${token}` } ``,
598
+ `url`, `id`, `type`, `code`, `className`, …)
599
+ - Strings already inside `t()` calls or `<Trans>`, `<IcuTrans>` and their `…WithoutContext` components (their
600
+ `values` too), including the project's own `extract.functions` and `extract.transComponents`
543
601
  - **Module-scope strings** — anything outside a function body, e.g. a top-level config/registry array:
544
602
  ```ts
545
603
  export const SETTINGS_SECTIONS = [
@@ -560,10 +618,41 @@ The instrumenter uses confidence heuristics to avoid transforming:
560
618
 
561
619
  When transformations are applied, the command automatically:
562
620
  - 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
- - Detects the project's framework from `package.json` dependencies (React, Next.js, Vue, etc.)
621
+ - 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
622
+ - Places the imports after the file's import declarations and directives (`'use client'` stays first; never inside a string that shows code), and imports no name the file has already, from whatever module
623
+ - Takes `t` from a hook call the component makes already, unless a text comes before it: `const { i18n } = useTranslation('settings')` becomes `const { t, i18n } = useTranslation('settings')`, so the new keys go to that namespace; a function that is no component but binds `t` from a translation hook (a custom hook, `generateMetadata` with `getT()`) uses that `t`, not `i18next.t()`
624
+ - 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
625
  - 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
626
+ - 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; not in a Next.js app, see below
627
+ - 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
628
+
629
+ **Next.js apps ([next-i18next](https://github.com/i18next/next-i18next)):**
630
+
631
+ An app with next-i18next (a dependency, or imported), and a Next.js app with no i18next set up at all, gets
632
+ next-i18next's calls, by where each file renders. The import graph decides: a file under `app/` is a Server
633
+ Component unless it says `'use client'`, a `'use client'` file and all it imports are Client Components, a file
634
+ under `pages/` and all it imports render with the Pages Router (imports resolve relative, through the `paths` of
635
+ `tsconfig.json` or `jsconfig.json` and from the project root). A Next.js app with i18next or react-i18next and no
636
+ next-i18next keeps `react-i18next`.
637
+
638
+ - **Server Components:** `const { t } = await getT()` from `next-i18next/server` (or from the module the app
639
+ imports `getT` from, such as its own `createServerI18next` file), and the component becomes `async`. A
640
+ `<Trans>` gets `t={t} i18n={i18n}` and comes from `react-i18next/TransWithoutContext`. `generateMetadata()`
641
+ and other async functions get `getT()` as well, and `export const metadata = { title: '…' }` becomes
642
+ `export async function generateMetadata () { const { t } = await getT(); return { title: t(…) } }`.
643
+ - **Client Components:** `const { t } = useT()` and `Trans` from `next-i18next/client`.
644
+ - **Pages Router:** `useTranslation` and `Trans` from `next-i18next/pages`. A page that loads no translations
645
+ (no `serverSideTranslations()` in it or in a helper it imports) is named in a warning.
646
+ - **A component that Server and Client Components both render** works with neither: its texts stay, named in a
647
+ warning, unless it gets `t` as a prop (and `i18n` too for a `<Trans>`), which it then uses.
648
+ - Left as they are, each named in a warning: texts outside components (next-i18next has no global `t`), files
649
+ no page or layout imports (which side renders them is not known), API routes (`route.ts` under `app/`,
650
+ `pages/api/`), Server Actions and cached functions (`'use server'`, `'use cache'`: `getT()` there needs
651
+ `{ lng }`), a Server Component wrapped in `memo()` or `forwardRef()`, and language switches: next-i18next
652
+ changes the language through the route or `useChangeLanguage()`.
653
+ - No init file: next-i18next sets i18next up itself. When it is not set up yet, the steps are printed (install,
654
+ then `i18n.config`, proxy and root layout for the App Router, `appWithTranslation` and `serverSideTranslations`
655
+ for the Pages Router).
567
656
 
568
657
  **Recommended workflow:**
569
658
 
@@ -674,7 +763,7 @@ The command walks through six steps:
674
763
 
675
764
  **Safe to re-run:** the command is idempotent. Already-wrapped strings are not re-instrumented, extraction is deterministic, and syncing never overwrites translations edited remotely (no `--update-values` unless you pass it; locize-cli's `--reference-language-only` default keeps target languages safe).
676
765
 
677
- > **Next.js App Router:** instrument injects `useTranslation()`, which is client-only. Review the diff for server components — add `'use client'` or switch those to a server-side `t()` pattern.
766
+ > **Next.js:** instrument writes next-i18next's calls, `await getT()` in Server Components and `useT()` in Client Components (see [instrument](#instrument)). Review the warnings: texts in components that both render stay as they are.
678
767
 
679
768
  **Non-React stacks (Vue, Svelte, …):** the instrument step transforms React/JSX out of the box. For other stacks, add a plugin that covers your file type (community: [i18next-cli-vue](https://github.com/PBK-B/i18next-cli-vue), [i18next-cli-plugin-svelte](https://github.com/dreamscached/i18next-cli-plugin-svelte) — or write your own via the [Plugin System](#plugin-system) `instrumentOnLoad`/`onLoad` hooks). With a matching plugin configured, `localize` runs the full flow; without one, the instrument step is skipped with guidance and the remaining steps (extract → Locize → auto-translate) still run.
680
769
 
@@ -727,8 +816,11 @@ all commands.
727
816
  for future agent sessions.
728
817
  3. Instrument: run `npx i18next-cli instrument --dry-run` and review the
729
818
  planned changes; then `npx i18next-cli instrument` to apply. Inspect the
730
- git diff carefully: fix any t() wrapping inside Next.js *server components*
731
- (add 'use client' or refactor to a server-side t() pattern). Commit.
819
+ git diff carefully and the warnings it prints. In a Next.js app it writes
820
+ next-i18next's calls (await getT() in Server Components, useT() in Client
821
+ Components); texts it left (components that Server and Client Components
822
+ both render, texts outside components) are listed: move them or give the
823
+ component a t prop. If it printed next-i18next setup steps, do them. Commit.
732
824
  4. Extract: run `npx i18next-cli extract`. Verify the locale JSON files were
733
825
  written (check the extract.output path in the config). If the developer
734
826
  chose repository files only: translate the extracted keys yourself or
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('./utils/jsx-attributes.js');
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.88.1') // This string is replaced with the actual version at build time by rollup
42
+ .version('1.90.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)');
@@ -105,7 +105,7 @@ program
105
105
  return inputGlobs.some(g => minimatch.minimatch(f, g, { dot: true })) &&
106
106
  !ignoreGlobs.some(g => minimatch.minimatch(f, g, { dot: true }));
107
107
  };
108
- const watcher = chokidar__default.default.watch(Array.from(new Set(inputGlobs.map(globBase))), {
108
+ const watcher = chokidar__default.default.watch(Array.from(new Set(inputGlobs.flatMap(globBases))), {
109
109
  ignored: (path, stats) => /node_modules/.test(path) || (!!stats?.isFile() && !isInput(path)),
110
110
  ignoreInitial: true,
111
111
  persistent: true,
@@ -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'));
@@ -450,14 +465,18 @@ const deriveOutputIgnore = (output) => {
450
465
  return [output.replace(/\{\{[^}]+\}\}/g, '*')];
451
466
  };
452
467
  // static leading folder of a glob: 'src/**/*.ts' -> 'src'
453
- const globBase = (pattern) => {
468
+ // the directories a glob starts in: `{app,components}/**` starts in two, not in the project root
469
+ const globBases = (pattern) => {
470
+ const brace = /^((?:[^*?[\]{}()!/]+\/)*)\{([^{}]+)\}(\/.*)?$/.exec(pattern);
471
+ if (brace)
472
+ return brace[2].split(',').flatMap(alt => globBases(`${brace[1]}${alt}${brace[3] ?? ''}`));
454
473
  const parts = [];
455
474
  for (const segment of pattern.split('/')) {
456
475
  if (/[*?[\]{}()!]/.test(segment))
457
476
  break;
458
477
  parts.push(segment);
459
478
  }
460
- return parts.join('/') || '.';
479
+ return [parts.join('/') || '.'];
461
480
  };
462
481
  // helper to expand one or many glob patterns
463
482
  const expandGlobs = async (patterns = []) => {
@@ -158,20 +158,21 @@ async function ensureConfig(configPath, logger$1 = new logger.ConsoleLogger()) {
158
158
  async function findTsConfigFile() {
159
159
  let currentDir = process.cwd();
160
160
  while (true) {
161
- const tsConfigPath = node_path.join(currentDir, 'tsconfig.json');
162
- try {
163
- await promises.access(tsConfigPath);
164
- return tsConfigPath;
165
- }
166
- catch {
167
- // File not found, move to parent directory
168
- const parentDir = node_path.dirname(currentDir);
169
- if (parentDir === currentDir) {
170
- // Reached the root of the file system
171
- return null;
161
+ // a JavaScript project keeps its `paths` in jsconfig.json (`@/*` in a Next.js app)
162
+ for (const name of ['tsconfig.json', 'jsconfig.json']) {
163
+ try {
164
+ await promises.access(node_path.join(currentDir, name));
165
+ return node_path.join(currentDir, name);
172
166
  }
173
- currentDir = parentDir;
167
+ catch { }
168
+ }
169
+ // File not found, move to parent directory
170
+ const parentDir = node_path.dirname(currentDir);
171
+ if (parentDir === currentDir) {
172
+ // Reached the root of the file system
173
+ return null;
174
174
  }
175
+ currentDir = parentDir;
175
176
  }
176
177
  }
177
178
  /**
@@ -258,7 +258,7 @@ async function processFile(file, plugins, astVisitors, pluginContext, config, lo
258
258
  });
259
259
  }
260
260
  catch (err) {
261
- // Fallback for .ts files with JSX (already present)
261
+ // Fallback for .ts files with JSX (already present); JSX in a .js file is common enough to need no note
262
262
  if (effectiveExt === '.ts' && !isTSX) {
263
263
  try {
264
264
  ast = await core.parse(code, {
@@ -268,7 +268,6 @@ async function processFile(file, plugins, astVisitors, pluginContext, config, lo
268
268
  dynamicImport: true,
269
269
  comments: true,
270
270
  });
271
- logger$1.info?.(`Parsed ${file} using TSX fallback`);
272
271
  }
273
272
  catch (err2) {
274
273
  throw new validation.ExtractorError('Failed to process file', file, err2);
@@ -284,7 +283,6 @@ async function processFile(file, plugins, astVisitors, pluginContext, config, lo
284
283
  dynamicImport: true,
285
284
  comments: true,
286
285
  });
287
- logger$1.info?.(`Parsed ${file} using JSX fallback`);
288
286
  }
289
287
  catch (err2) {
290
288
  throw new validation.ExtractorError('Failed to process file', file, err2);
@@ -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
- logger$1.error(`Error: Nesting conflict: key "${key}" conflicts with existing key "${conflictingPath}". ` +
858
- `"${key}" will be skipped — fix the overlapping key paths in your source code to avoid missing translations at runtime.`);
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
  }
@@ -3,7 +3,56 @@
3
3
  var glob = require('glob');
4
4
  var promises = require('node:fs/promises');
5
5
  var node_path = require('node:path');
6
+ var fileUtils = require('./utils/file-utils.js');
6
7
 
8
+ /** The directories source files usually live in, one glob for those that exist (`{app,components}/**`). */
9
+ async function sourceInput() {
10
+ const dirs = [];
11
+ // not `lib`, often the build output of a package
12
+ for (const dir of ['src', 'app', 'pages', 'components']) {
13
+ if (await promises.stat(dir).then(found => found.isDirectory(), () => false))
14
+ dirs.push(dir);
15
+ }
16
+ const exts = '**/*.{js,jsx,mjs,ts,tsx}';
17
+ return [dirs.length > 1 ? `{${dirs.join(',')}}/${exts}` : `${dirs[0] ?? 'src'}/${exts}`];
18
+ }
19
+ /**
20
+ * The extract options the app's own setup decides: next-i18next's `defaultNS` (from its config, `common` when it
21
+ * sets none), the message format of i18next-icu or i18next-mf2, and `keySeparator: false` for translation files
22
+ * with flat keys that contain dots (`"blog.title": "…"`).
23
+ */
24
+ async function setupOptions(translationFiles) {
25
+ const deps = await fileUtils.readProjectDeps();
26
+ const options = {};
27
+ if (deps['next-i18next']) {
28
+ const configs = await glob.glob('{i18n.config,next-i18next.config,i18n.shared}.{ts,js,mjs,cjs}', { ignore: 'node_modules/**' });
29
+ for (const file of configs) {
30
+ const ns = /\bdefaultNS\s*:\s*['"]([^'"]+)['"]/.exec(await promises.readFile(file, 'utf-8'))?.[1];
31
+ if (ns) {
32
+ options.defaultNS = ns;
33
+ break;
34
+ }
35
+ }
36
+ options.defaultNS ??= 'common';
37
+ }
38
+ if (deps['i18next-icu'])
39
+ options.messageFormat = 'icu';
40
+ else if (deps['i18next-mf2'])
41
+ options.messageFormat = 'mf2';
42
+ const flat = [];
43
+ for (const file of translationFiles.filter(f => node_path.extname(f) === '.json')) {
44
+ try {
45
+ const json = JSON.parse(await promises.readFile(file, 'utf-8'));
46
+ if (Object.values(json).some(v => typeof v === 'object'))
47
+ return options;
48
+ flat.push(Object.keys(json).some(key => key.includes('.')));
49
+ }
50
+ catch { }
51
+ }
52
+ if (flat.includes(true))
53
+ options.keySeparator = false;
54
+ return options;
55
+ }
7
56
  // A list of common glob patterns for the primary language ('en') or ('dev') translation files.
8
57
  const HEURISTIC_PATTERNS = [
9
58
  'public/locales/dev/*.json',
@@ -90,15 +139,11 @@ async function detectConfig() {
90
139
  return {
91
140
  locales,
92
141
  extract: {
93
- input: [
94
- 'src/**/*.{js,jsx,mjs,ts,tsx}',
95
- 'app/**/*.{js,jsx,mjs,ts,tsx}',
96
- 'pages/**/*.{js,jsx,mjs,ts,tsx}',
97
- 'components/**/*.{js,jsx,mjs,ts,tsx}'
98
- ],
142
+ input: await sourceInput(),
99
143
  output: node_path.join(basePath, '{{language}}', `{{namespace}}${extension}`),
100
144
  outputFormat,
101
145
  primaryLanguage: locales.includes('en') ? 'en' : locales[0],
146
+ ...await setupOptions(files),
102
147
  },
103
148
  };
104
149
  }
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('./utils/jsx-attributes.js');
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 in dependencies or devDependencies
45
+ * @returns Promise resolving to true if i18next-cli is a declared dependency (see readProjectDeps)
45
46
  */
46
47
  async function isCliLocallyInstalled() {
47
- try {
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.
@@ -198,11 +190,16 @@ async function runInit(options = {}) {
198
190
  const isTypeScript = answers.fileType.includes('TypeScript');
199
191
  const isEsm = await isEsmProject();
200
192
  const fileName = isTypeScript ? 'i18next.config.ts' : 'i18next.config.js';
193
+ // what the app's own setup decides (next-i18next's defaultNS, ICU, flat keys), as detected
194
+ const { defaultNS, messageFormat, keySeparator } = detectedConfig?.extract ?? {};
201
195
  const configObject = {
202
196
  locales: answers.locales,
203
197
  extract: {
204
198
  input: answers.input,
205
199
  output: answers.output,
200
+ ...(defaultNS !== undefined && { defaultNS }),
201
+ ...(messageFormat && { messageFormat }),
202
+ ...(keySeparator !== undefined && { keySeparator }),
206
203
  },
207
204
  };
208
205
  if (locizeConfig)