i18next-cli 1.89.0 → 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.
- package/README.md +46 -7
- package/dist/cjs/cli.js +8 -4
- package/dist/cjs/config.js +13 -12
- package/dist/cjs/extractor/core/extractor.js +1 -3
- package/dist/cjs/heuristic-config.js +51 -6
- package/dist/cjs/init.js +5 -0
- package/dist/cjs/instrumenter/core/instrumenter.js +272 -23
- package/dist/cjs/instrumenter/core/key-generator.js +1 -0
- package/dist/cjs/instrumenter/core/next-files.js +104 -0
- package/dist/cjs/instrumenter/core/transformer.js +97 -73
- package/dist/cjs/localize/agent-prompt.js +5 -2
- package/dist/cjs/localize/detect.js +1 -0
- package/dist/cjs/localize/localize.js +25 -4
- package/dist/esm/cli.js +8 -4
- package/dist/esm/config.js +13 -12
- package/dist/esm/extractor/core/extractor.js +1 -3
- package/dist/esm/heuristic-config.js +52 -7
- package/dist/esm/init.js +5 -0
- package/dist/esm/instrumenter/core/instrumenter.js +273 -24
- package/dist/esm/instrumenter/core/key-generator.js +1 -0
- package/dist/esm/instrumenter/core/next-files.js +101 -0
- package/dist/esm/instrumenter/core/transformer.js +97 -73
- package/dist/esm/localize/agent-prompt.js +5 -2
- package/dist/esm/localize/detect.js +1 -0
- package/dist/esm/localize/localize.js +25 -4
- package/package.json +1 -1
- package/types/cli.d.ts.map +1 -1
- package/types/config.d.ts.map +1 -1
- package/types/extractor/core/extractor.d.ts.map +1 -1
- package/types/heuristic-config.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.map +1 -1
- package/types/instrumenter/core/next-files.d.ts +25 -0
- package/types/instrumenter/core/next-files.d.ts.map +1 -0
- package/types/instrumenter/core/transformer.d.ts +6 -0
- package/types/instrumenter/core/transformer.d.ts.map +1 -1
- package/types/localize/agent-prompt.d.ts +1 -1
- package/types/localize/agent-prompt.d.ts.map +1 -1
- package/types/localize/detect.d.ts +2 -0
- package/types/localize/detect.d.ts.map +1 -1
- package/types/localize/localize.d.ts.map +1 -1
- package/types/types.d.ts +39 -0
- package/types/types.d.ts.map +1 -1
|
@@ -7,6 +7,18 @@ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
|
7
7
|
|
|
8
8
|
var MagicString__default = /*#__PURE__*/_interopDefault(MagicString);
|
|
9
9
|
|
|
10
|
+
/** The hook a component gets `t` from, and where `useTranslation`/`useT`/`getT` and `Trans` are imported from. */
|
|
11
|
+
function bindingsFor(next) {
|
|
12
|
+
switch (next?.kind) {
|
|
13
|
+
case 'server': return { hook: 'getT', hookModule: next.serverModule, transModule: 'react-i18next/TransWithoutContext', call: args => `await getT(${args})` };
|
|
14
|
+
// its `t` is a prop: no hook; a <Trans> without context works on both sides
|
|
15
|
+
case 'shared':
|
|
16
|
+
case 'unknown': return { hook: 'useT', hookModule: 'next-i18next/client', transModule: 'react-i18next/TransWithoutContext', call: args => `useT(${args})` };
|
|
17
|
+
case 'client': return { hook: 'useT', hookModule: 'next-i18next/client', transModule: 'next-i18next/client', call: args => `useT(${args})` };
|
|
18
|
+
case 'pages': return { hook: 'useTranslation', hookModule: 'next-i18next/pages', transModule: 'next-i18next/pages', call: args => `useTranslation(${args})` };
|
|
19
|
+
default: return { hook: 'useTranslation', hookModule: 'react-i18next', transModule: 'react-i18next', call: args => `useTranslation(${args})` };
|
|
20
|
+
}
|
|
21
|
+
}
|
|
10
22
|
/**
|
|
11
23
|
* Transforms a source file, replacing candidate strings with instrumented code.
|
|
12
24
|
* Also injects useTranslation() hooks into React function components that
|
|
@@ -27,6 +39,10 @@ function transformFile(content, file, candidates, options) {
|
|
|
27
39
|
importAdded: false,
|
|
28
40
|
hookInjected: false
|
|
29
41
|
};
|
|
42
|
+
const bindings = bindingsFor(options.next);
|
|
43
|
+
// A <Trans> in a Server Component has no React context: it takes `t` and `i18n` from getT()
|
|
44
|
+
// (and in a component that Server and Client Components both render, from its props)
|
|
45
|
+
const transProps = ['server', 'shared', 'unknown'].includes(options.next?.kind ?? '') ? ' t={t} i18n={i18n}' : '';
|
|
30
46
|
// <Trans> attributes in the quotes the file's JSX attributes use (`title='…'` or `title="…"`)
|
|
31
47
|
// (a file without quoted attributes: the quotes of its imports)
|
|
32
48
|
const singleQuoted = (single, double) => Math.sign((content.match(single)?.length ?? 0) - (content.match(double)?.length ?? 0));
|
|
@@ -89,7 +105,7 @@ function transformFile(content, file, candidates, options) {
|
|
|
89
105
|
// <Trans> works in any render code, a helper outside a component too; without React the text stays
|
|
90
106
|
if (candidate.type === 'jsx-mixed' && !options.hasReact)
|
|
91
107
|
continue;
|
|
92
|
-
const replacement = buildReplacement(candidate, key, useHookStyle, nsForReplacement, jsxQuote);
|
|
108
|
+
const replacement = buildReplacement(candidate, key, useHookStyle, nsForReplacement, jsxQuote, transProps);
|
|
93
109
|
if (replacement) {
|
|
94
110
|
s.overwrite(candidate.offset, candidate.endOffset, replacement);
|
|
95
111
|
transformCount++;
|
|
@@ -98,8 +114,9 @@ function transformFile(content, file, candidates, options) {
|
|
|
98
114
|
if (candidate.type === 'jsx-mixed') {
|
|
99
115
|
hasTransCandidates = true;
|
|
100
116
|
}
|
|
101
|
-
// jsx-mixed candidates use <Trans>, not t(), so they need neither useTranslation nor i18next
|
|
102
|
-
|
|
117
|
+
// jsx-mixed candidates use <Trans>, not t(), so they need neither useTranslation nor i18next (but in a
|
|
118
|
+
// Server Component its `t` and `i18n`)
|
|
119
|
+
if (candidate.type !== 'jsx-mixed' || (transProps && candidate.insideComponent)) {
|
|
103
120
|
if (candidate.insideComponent) {
|
|
104
121
|
transformedComponents.add(candidate.insideComponent);
|
|
105
122
|
}
|
|
@@ -131,10 +148,6 @@ function transformFile(content, file, candidates, options) {
|
|
|
131
148
|
const components = options.components || [];
|
|
132
149
|
// Inject useTranslation() hooks into affected React components
|
|
133
150
|
if (options.hasReact && transformedComponents.size > 0) {
|
|
134
|
-
// Process components in reverse order of bodyStart to avoid offset shifts
|
|
135
|
-
const affectedComponents = components
|
|
136
|
-
.filter(c => transformedComponents.has(c.name) && !c.hasUseTranslation)
|
|
137
|
-
.sort((a, b) => b.bodyStart - a.bodyStart);
|
|
138
151
|
const addHookLine = (comp, line) => {
|
|
139
152
|
const indent = comp.expressionBody ? lineIndent(content, comp.bodyStart) + ' ' : detectIndent(content, comp.bodyStart);
|
|
140
153
|
if (comp.expressionBody) {
|
|
@@ -145,60 +158,58 @@ function transformFile(content, file, candidates, options) {
|
|
|
145
158
|
else {
|
|
146
159
|
s.appendRight(comp.bodyStart + 1, `\n${indent}${line}`);
|
|
147
160
|
}
|
|
161
|
+
// getT() is awaited: a Server Component becomes async, and `export const metadata = {…}` the function
|
|
162
|
+
// Next.js calls instead, `export async function generateMetadata () { …; return {…} }`
|
|
163
|
+
if (comp.metadataHead) {
|
|
164
|
+
const { start, end, type } = comp.metadataHead;
|
|
165
|
+
// contentOnly: the block that wraps the object starts at `end`, and stays
|
|
166
|
+
s.overwrite(start, end, `async function generateMetadata ()${type ? `: Promise<${type}>` : ''} `, { contentOnly: true });
|
|
167
|
+
}
|
|
168
|
+
else if (options.next?.kind === 'server' && !comp.isAsync && comp.start !== undefined) {
|
|
169
|
+
s.appendLeft(comp.start, 'async ');
|
|
170
|
+
// an async function returns a promise: `(): JSX.Element` becomes `(): Promise<JSX.Element>`
|
|
171
|
+
const type = comp.returnType;
|
|
172
|
+
if (type && !/^Promise\s*</.test(content.slice(type.start, type.end))) {
|
|
173
|
+
s.appendLeft(type.start, 'Promise<');
|
|
174
|
+
s.appendRight(type.end, '>');
|
|
175
|
+
}
|
|
176
|
+
}
|
|
148
177
|
injections.hookInjected = true;
|
|
149
178
|
};
|
|
150
|
-
|
|
179
|
+
// Components in reverse order of bodyStart to avoid offset shifts
|
|
180
|
+
for (const comp of components.filter(c => transformedComponents.has(c.name)).sort((a, b) => b.bodyStart - a.bodyStart)) {
|
|
151
181
|
const defaultNS = options.config.extract?.defaultNS ?? 'translation';
|
|
152
182
|
const nsArg = (options.namespace && options.namespace !== defaultNS) ? `'${options.namespace}'` : '';
|
|
153
|
-
//
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
const
|
|
157
|
-
const
|
|
158
|
-
|
|
159
|
-
if (needsT)
|
|
160
|
-
parts.push('t');
|
|
161
|
-
if (needsI18n)
|
|
162
|
-
parts.push('i18n');
|
|
163
|
-
// Skip if component needs neither t nor i18n
|
|
164
|
-
// (e.g. component only has jsx-mixed / <Trans> candidates)
|
|
165
|
-
if (!needsT && !needsI18n)
|
|
183
|
+
// `t` for its t() calls (and a <Trans> in a Server Component), `i18n` for a language change (and that <Trans>)
|
|
184
|
+
const own = highConfidenceCandidates.filter(c => c.insideComponent === comp.name);
|
|
185
|
+
const needsT = !comp.hasUseTranslation && own.some(c => c.type !== 'jsx-mixed' || transProps);
|
|
186
|
+
const needsI18n = componentsNeedingI18n.has(comp.name) || (!!transProps && !comp.i18nParam && own.some(c => c.type === 'jsx-mixed'));
|
|
187
|
+
const missing = [needsT && 't', needsI18n && !comp.hookPattern?.names.includes('i18n') && 'i18n'].filter(Boolean);
|
|
188
|
+
if (!missing.length)
|
|
166
189
|
continue;
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
const
|
|
181
|
-
const hookMatch = hookRe.exec(bodyText);
|
|
182
|
-
if (hookMatch) {
|
|
183
|
-
const absStart = comp.bodyStart + hookMatch.index;
|
|
184
|
-
const absEnd = absStart + hookMatch[0].length;
|
|
185
|
-
const upgraded = hookMatch[0].replace(/\{\s*t\s*\}/, '{ t, i18n }');
|
|
186
|
-
s.overwrite(absStart, absEnd, upgraded);
|
|
187
|
-
}
|
|
188
|
-
else {
|
|
189
|
-
// its `t` is a prop or comes from another hook: `i18n` needs a hook of its own
|
|
190
|
-
addHookLine(comp, 'const { i18n } = useTranslation()');
|
|
191
|
-
}
|
|
190
|
+
// that call gives `t` only to the code after it: a text before it would read `t` before its declaration
|
|
191
|
+
const before = (offset) => offset < comp.hookPattern.statement;
|
|
192
|
+
const usedBefore = comp.hookPattern && (own.some(c => before(c.offset)) ||
|
|
193
|
+
languageChangeSites.some(site => site.insideComponent === comp.name && before(site.callStart)));
|
|
194
|
+
if (comp.hookPattern && !usedBefore && (comp.hasUseTranslation || !comp.hookPattern.names.includes('t'))) {
|
|
195
|
+
// it calls a translation hook already (`const { i18n } = useT('ns')`): that call gives them, from its
|
|
196
|
+
// namespace (`{ t, i18n }`)
|
|
197
|
+
if (missing.includes('t'))
|
|
198
|
+
s.appendLeft(comp.hookPattern.first, 't, ');
|
|
199
|
+
if (missing.includes('i18n'))
|
|
200
|
+
s.appendRight(comp.hookPattern.last, ', i18n');
|
|
201
|
+
}
|
|
202
|
+
else {
|
|
203
|
+
addHookLine(comp, `const { ${missing.join(', ')} } = ${bindings.call(missing.includes('t') ? nsArg : '')}`);
|
|
192
204
|
}
|
|
193
205
|
}
|
|
194
206
|
}
|
|
195
207
|
// Add import statements
|
|
196
|
-
addImportStatements(s, content,
|
|
208
|
+
addImportStatements(s, content, [
|
|
197
209
|
// only for a hook injected here: a component with a `t` of its own (a prop) needs none
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
}, options.imports);
|
|
210
|
+
...(injections.hookInjected ? [{ name: bindings.hook, module: bindings.hookModule }] : []),
|
|
211
|
+
...(hasTransCandidates && options.hasReact ? [{ name: 'Trans', module: bindings.transModule }] : [])
|
|
212
|
+
], hasNonComponentCandidates || !options.hasReact, options.imports);
|
|
202
213
|
injections.importAdded = true;
|
|
203
214
|
}
|
|
204
215
|
// Warn when i18next.t() is used in React projects (translations may not be loaded yet)
|
|
@@ -230,7 +241,7 @@ function transformFile(content, file, candidates, options) {
|
|
|
230
241
|
* @param useHookStyle - If true, uses t() (from useTranslation hook); otherwise uses i18next.t()
|
|
231
242
|
* @param namespace - Optional namespace (only set when different from defaultNS)
|
|
232
243
|
*/
|
|
233
|
-
function buildReplacement(candidate, key, useHookStyle, namespace, jsxQuote = '"') {
|
|
244
|
+
function buildReplacement(candidate, key, useHookStyle, namespace, jsxQuote = '"', transProps = '') {
|
|
234
245
|
const tFunc = useHookStyle ? 't' : 'i18next.t';
|
|
235
246
|
const escapedContent = escapeString(candidate.content);
|
|
236
247
|
// ── Plural form: t('key', { defaultValue_zero: '…', …, count: expr }) ──
|
|
@@ -281,7 +292,7 @@ function buildReplacement(candidate, key, useHookStyle, namespace, jsxQuote = '"
|
|
|
281
292
|
return `{${tCall}}`;
|
|
282
293
|
case 'jsx-mixed': {
|
|
283
294
|
const nsAttr = namespace ? ` ns=${jsxQuote}${namespace}${jsxQuote}` : '';
|
|
284
|
-
return `<Trans i18nKey=${jsxQuote}${key}${jsxQuote}${nsAttr}>${candidate.content}</Trans>`;
|
|
295
|
+
return `<Trans i18nKey=${jsxQuote}${key}${jsxQuote}${nsAttr}${transProps}>${candidate.content}</Trans>`;
|
|
285
296
|
}
|
|
286
297
|
case 'template-literal':
|
|
287
298
|
case 'string-literal':
|
|
@@ -339,33 +350,33 @@ function detectIndent(content, braceOffset) {
|
|
|
339
350
|
return ' ';
|
|
340
351
|
}
|
|
341
352
|
/**
|
|
342
|
-
* Adds
|
|
353
|
+
* Adds the import statements the rewrite needs: the named imports `needed` (a hook, `Trans`), each from its module
|
|
354
|
+
* (added to an import of that module the file has), and `i18next` for `i18next.t()`.
|
|
343
355
|
*/
|
|
344
|
-
function addImportStatements(s, content,
|
|
356
|
+
function addImportStatements(s, content, needed, needsI18next, imports) {
|
|
345
357
|
let importStatement = '';
|
|
346
358
|
const imported = (moduleName) => imports
|
|
347
359
|
? imports.some(i => i.source === moduleName) || new RegExp(`require\\(['"]${moduleName}['"]\\)`).test(content)
|
|
348
360
|
: hasImport(content, moduleName);
|
|
349
361
|
// A name the file imports already, from any module (`useTranslation` re-exported by a shared package)
|
|
350
362
|
const bound = (name) => !!imports?.some(i => i.locals?.includes(name));
|
|
351
|
-
|
|
352
|
-
const
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
importStatement += `import { ${reactI18nextImports.join(', ')} } from 'react-i18next'\n`;
|
|
363
|
+
const byModule = new Map();
|
|
364
|
+
for (const { name, module } of needed) {
|
|
365
|
+
if (!bound(name))
|
|
366
|
+
byModule.set(module, [...(byModule.get(module) ?? []), name]);
|
|
367
|
+
}
|
|
368
|
+
for (const [module, names] of byModule) {
|
|
369
|
+
if (!imported(module)) {
|
|
370
|
+
importStatement += `import { ${names.join(', ')} } from '${module}'\n`;
|
|
360
371
|
}
|
|
361
372
|
else {
|
|
362
|
-
//
|
|
363
|
-
const existing = imports?.find(i => i.source ===
|
|
364
|
-
|
|
373
|
+
// the module is imported already: augment it with the missing named exports
|
|
374
|
+
const existing = imports?.find(i => i.source === module);
|
|
375
|
+
augmentNamedImport(s, content, module, names, existing?.start ?? 0);
|
|
365
376
|
}
|
|
366
377
|
}
|
|
367
378
|
// `i18next.t()` needs that name: with the AST, an import of i18next under another name does not count
|
|
368
|
-
if (
|
|
379
|
+
if (needsI18next && (imports ? !bound('i18next') : !imported('i18next'))) {
|
|
369
380
|
importStatement += "import i18next from 'i18next'\n";
|
|
370
381
|
}
|
|
371
382
|
if (!importStatement)
|
|
@@ -376,6 +387,13 @@ function addImportStatements(s, content, needs, imports) {
|
|
|
376
387
|
if (content.startsWith('#!')) {
|
|
377
388
|
insertPos = content.indexOf('\n') + 1;
|
|
378
389
|
}
|
|
390
|
+
// and the directives (`'use client'`), which must stay the first statements
|
|
391
|
+
const directives = DIRECTIVES_RE.exec(content.slice(insertPos));
|
|
392
|
+
if (directives) {
|
|
393
|
+
insertPos += directives[0].length;
|
|
394
|
+
if (content[insertPos - 1] !== '\n')
|
|
395
|
+
importStatement = `\n${importStatement}`;
|
|
396
|
+
}
|
|
379
397
|
if (imports) {
|
|
380
398
|
// After the last import declaration's line
|
|
381
399
|
const lastEnd = Math.max(...imports.map(i => i.end), -1);
|
|
@@ -405,6 +423,8 @@ function addImportStatements(s, content, needs, imports) {
|
|
|
405
423
|
importStatement = `\n${importStatement}`;
|
|
406
424
|
s.appendRight(insertPos, importStatement);
|
|
407
425
|
}
|
|
426
|
+
/** The directive prologue: `'use client'`, `'use strict'` and the like, with the comments around them, to the line end. */
|
|
427
|
+
const DIRECTIVES_RE = /^(?:(?:\s|\/\/[^\n]*\n|\/\*[\s\S]*?\*\/)*(['"])use [\w ]+\1;?[^\S\n]*(?:\/\/[^\n]*)?(?:\n|$))+/;
|
|
408
428
|
/**
|
|
409
429
|
* Returns the offset just past the end of the import statement that begins at
|
|
410
430
|
* `start`, handling multi-line imports with `{ ... }` clauses. The statement
|
|
@@ -453,21 +473,25 @@ function findImportStatementEnd(content, start) {
|
|
|
453
473
|
return content.length;
|
|
454
474
|
}
|
|
455
475
|
/**
|
|
456
|
-
* Augments an existing `import { ... } from '
|
|
476
|
+
* Augments an existing `import { ... } from '<module>'` with any missing
|
|
457
477
|
* named exports (e.g. adds `Trans` when only `useTranslation` is imported).
|
|
478
|
+
* A module imported without braces (`import i18n from …`) gets its own import.
|
|
458
479
|
*/
|
|
459
|
-
function
|
|
460
|
-
const
|
|
480
|
+
function augmentNamedImport(s, content, module, needed, from = 0) {
|
|
481
|
+
const quoted = module.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&');
|
|
482
|
+
const importRegex = new RegExp(`import\\s*\\{([^}]*)\\}\\s*from\\s*['"]${quoted}['"]`, 'g');
|
|
461
483
|
importRegex.lastIndex = from;
|
|
462
484
|
const importMatch = importRegex.exec(content);
|
|
463
|
-
if (!importMatch)
|
|
485
|
+
if (!importMatch) {
|
|
486
|
+
s.prependLeft(from, `import { ${needed.join(', ')} } from '${module}'\n`);
|
|
464
487
|
return;
|
|
488
|
+
}
|
|
465
489
|
const existingImports = importMatch[1].split(',').map(x => x.trim()).filter(Boolean);
|
|
466
490
|
const toAdd = needed.filter(n => !existingImports.includes(n));
|
|
467
491
|
if (toAdd.length === 0)
|
|
468
492
|
return;
|
|
469
493
|
const newImports = [...existingImports, ...toAdd].join(', ');
|
|
470
|
-
const newImportStatement = `import { ${newImports} } from '
|
|
494
|
+
const newImportStatement = `import { ${newImports} } from '${module}'`;
|
|
471
495
|
const matchStart = importMatch.index;
|
|
472
496
|
const matchEnd = matchStart + importMatch[0].length;
|
|
473
497
|
s.overwrite(matchStart, matchEnd, newImportStatement);
|
|
@@ -52,8 +52,11 @@ all commands.
|
|
|
52
52
|
for future agent sessions.
|
|
53
53
|
3. Instrument: run \`npx i18next-cli instrument --dry-run\` and review the
|
|
54
54
|
planned changes; then \`npx i18next-cli instrument\` to apply. Inspect the
|
|
55
|
-
git diff carefully
|
|
56
|
-
|
|
55
|
+
git diff carefully and the warnings it prints. In a Next.js app it writes
|
|
56
|
+
next-i18next's calls (await getT() in Server Components, useT() in Client
|
|
57
|
+
Components); texts it left (components that Server and Client Components
|
|
58
|
+
both render, texts outside components) are listed: move them or give the
|
|
59
|
+
component a t prop. If it printed next-i18next setup steps, do them. Commit.
|
|
57
60
|
4. Extract: run \`npx i18next-cli extract\`. Verify the locale JSON files were
|
|
58
61
|
written (check the extract.output path in the config). If the developer
|
|
59
62
|
chose repository files only: translate the extracted keys yourself or
|
|
@@ -49,6 +49,7 @@ async function detectStack(findInitFile) {
|
|
|
49
49
|
initFile: await findInitFile(),
|
|
50
50
|
hasAppRouter,
|
|
51
51
|
hasParaglide,
|
|
52
|
+
usesNextI18next: framework === 'next' && (has('next-i18next') || !(has('i18next') || has('react-i18next'))),
|
|
52
53
|
};
|
|
53
54
|
}
|
|
54
55
|
/** File extensions associated with frameworks the instrumenter cannot transform natively. */
|
|
@@ -140,12 +140,33 @@ function printCompleteness(completeness) {
|
|
|
140
140
|
console.log(node_util.styleText(color, ` ${locale}: ${translated}/${total} (${pct}%)`));
|
|
141
141
|
}
|
|
142
142
|
}
|
|
143
|
-
function printEpilogue(config) {
|
|
143
|
+
function printEpilogue(config, nextApp = false) {
|
|
144
144
|
const projectId = config.locize?.projectId || '<your-project-id>';
|
|
145
145
|
console.log(node_util.styleText('green', '\n✅ Done. Your app is localized.'));
|
|
146
146
|
console.log(node_util.styleText('cyan', '\nYour AI translations come with confidence scores; low-confidence ones are flagged for review in Locize.'));
|
|
147
147
|
console.log('\nOptional — switch to CDN delivery so translation fixes go live without redeploying your app:');
|
|
148
148
|
console.log(node_util.styleText('cyan', ' npm install i18next-locize-backend'));
|
|
149
|
+
if (nextApp) {
|
|
150
|
+
// next-i18next takes the backend in its config (and, for the browser, in I18nProvider's `use`: see the docs)
|
|
151
|
+
console.log(node_util.styleText('gray', `
|
|
152
|
+
// in your next-i18next config (i18n.config):
|
|
153
|
+
import LocizeBackend from 'i18next-locize-backend'
|
|
154
|
+
|
|
155
|
+
export default defineConfig({
|
|
156
|
+
// ...
|
|
157
|
+
use: [LocizeBackend],
|
|
158
|
+
i18nextOptions: {
|
|
159
|
+
backend: {
|
|
160
|
+
projectId: '${projectId}',
|
|
161
|
+
version: 'latest', // no apiKey in production!
|
|
162
|
+
},
|
|
163
|
+
},
|
|
164
|
+
})
|
|
165
|
+
`));
|
|
166
|
+
console.log('Docs: https://github.com/i18next/next-i18next#i18next-locize-backend');
|
|
167
|
+
console.log('Your current setup (local translation files) keeps working either way; run `i18next-cli locize-download` in CI to refresh the files.');
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
149
170
|
console.log(node_util.styleText('gray', `
|
|
150
171
|
// in your i18n init file:
|
|
151
172
|
import LocizeBackend from 'i18next-locize-backend'
|
|
@@ -270,8 +291,8 @@ async function runLocalize(options = {}, configPath) {
|
|
|
270
291
|
if (!proceed)
|
|
271
292
|
skipInstrument = true;
|
|
272
293
|
}
|
|
273
|
-
if (stack.
|
|
274
|
-
warn(
|
|
294
|
+
if (stack.usesNextI18next) {
|
|
295
|
+
warn('Next.js: instrument writes next-i18next calls, await getT() in Server Components and useT() in Client Components. Review the diff and the texts it lists as left.');
|
|
275
296
|
}
|
|
276
297
|
if (!skipInstrument) {
|
|
277
298
|
const results = await instrumenter.runInstrumenter(config$1, {
|
|
@@ -472,7 +493,7 @@ async function runLocalize(options = {}, configPath) {
|
|
|
472
493
|
else if (completeness.length > 0) {
|
|
473
494
|
ok('All languages translated and downloaded.');
|
|
474
495
|
}
|
|
475
|
-
printEpilogue(config$1);
|
|
496
|
+
printEpilogue(config$1, stack.usesNextI18next);
|
|
476
497
|
}
|
|
477
498
|
|
|
478
499
|
exports.runLocalize = runLocalize;
|
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.
|
|
36
|
+
.version('1.90.0') // 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)');
|
|
@@ -99,7 +99,7 @@ program
|
|
|
99
99
|
return inputGlobs.some(g => minimatch(f, g, { dot: true })) &&
|
|
100
100
|
!ignoreGlobs.some(g => minimatch(f, g, { dot: true }));
|
|
101
101
|
};
|
|
102
|
-
const watcher = chokidar.watch(Array.from(new Set(inputGlobs.
|
|
102
|
+
const watcher = chokidar.watch(Array.from(new Set(inputGlobs.flatMap(globBases))), {
|
|
103
103
|
ignored: (path, stats) => /node_modules/.test(path) || (!!stats?.isFile() && !isInput(path)),
|
|
104
104
|
ignoreInitial: true,
|
|
105
105
|
persistent: true,
|
|
@@ -459,14 +459,18 @@ const deriveOutputIgnore = (output) => {
|
|
|
459
459
|
return [output.replace(/\{\{[^}]+\}\}/g, '*')];
|
|
460
460
|
};
|
|
461
461
|
// static leading folder of a glob: 'src/**/*.ts' -> 'src'
|
|
462
|
-
|
|
462
|
+
// the directories a glob starts in: `{app,components}/**` starts in two, not in the project root
|
|
463
|
+
const globBases = (pattern) => {
|
|
464
|
+
const brace = /^((?:[^*?[\]{}()!/]+\/)*)\{([^{}]+)\}(\/.*)?$/.exec(pattern);
|
|
465
|
+
if (brace)
|
|
466
|
+
return brace[2].split(',').flatMap(alt => globBases(`${brace[1]}${alt}${brace[3] ?? ''}`));
|
|
463
467
|
const parts = [];
|
|
464
468
|
for (const segment of pattern.split('/')) {
|
|
465
469
|
if (/[*?[\]{}()!]/.test(segment))
|
|
466
470
|
break;
|
|
467
471
|
parts.push(segment);
|
|
468
472
|
}
|
|
469
|
-
return parts.join('/') || '.';
|
|
473
|
+
return [parts.join('/') || '.'];
|
|
470
474
|
};
|
|
471
475
|
// helper to expand one or many glob patterns
|
|
472
476
|
const expandGlobs = async (patterns = []) => {
|
package/dist/esm/config.js
CHANGED
|
@@ -156,20 +156,21 @@ async function ensureConfig(configPath, logger = new ConsoleLogger()) {
|
|
|
156
156
|
async function findTsConfigFile() {
|
|
157
157
|
let currentDir = process.cwd();
|
|
158
158
|
while (true) {
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
catch {
|
|
165
|
-
// File not found, move to parent directory
|
|
166
|
-
const parentDir = dirname(currentDir);
|
|
167
|
-
if (parentDir === currentDir) {
|
|
168
|
-
// Reached the root of the file system
|
|
169
|
-
return null;
|
|
159
|
+
// a JavaScript project keeps its `paths` in jsconfig.json (`@/*` in a Next.js app)
|
|
160
|
+
for (const name of ['tsconfig.json', 'jsconfig.json']) {
|
|
161
|
+
try {
|
|
162
|
+
await access(join(currentDir, name));
|
|
163
|
+
return join(currentDir, name);
|
|
170
164
|
}
|
|
171
|
-
|
|
165
|
+
catch { }
|
|
166
|
+
}
|
|
167
|
+
// File not found, move to parent directory
|
|
168
|
+
const parentDir = dirname(currentDir);
|
|
169
|
+
if (parentDir === currentDir) {
|
|
170
|
+
// Reached the root of the file system
|
|
171
|
+
return null;
|
|
172
172
|
}
|
|
173
|
+
currentDir = parentDir;
|
|
173
174
|
}
|
|
174
175
|
}
|
|
175
176
|
/**
|
|
@@ -256,7 +256,7 @@ async function processFile(file, plugins, astVisitors, pluginContext, config, lo
|
|
|
256
256
|
});
|
|
257
257
|
}
|
|
258
258
|
catch (err) {
|
|
259
|
-
// Fallback for .ts files with JSX (already present)
|
|
259
|
+
// Fallback for .ts files with JSX (already present); JSX in a .js file is common enough to need no note
|
|
260
260
|
if (effectiveExt === '.ts' && !isTSX) {
|
|
261
261
|
try {
|
|
262
262
|
ast = await parse(code, {
|
|
@@ -266,7 +266,6 @@ async function processFile(file, plugins, astVisitors, pluginContext, config, lo
|
|
|
266
266
|
dynamicImport: true,
|
|
267
267
|
comments: true,
|
|
268
268
|
});
|
|
269
|
-
logger.info?.(`Parsed ${file} using TSX fallback`);
|
|
270
269
|
}
|
|
271
270
|
catch (err2) {
|
|
272
271
|
throw new ExtractorError('Failed to process file', file, err2);
|
|
@@ -282,7 +281,6 @@ async function processFile(file, plugins, astVisitors, pluginContext, config, lo
|
|
|
282
281
|
dynamicImport: true,
|
|
283
282
|
comments: true,
|
|
284
283
|
});
|
|
285
|
-
logger.info?.(`Parsed ${file} using JSX fallback`);
|
|
286
284
|
}
|
|
287
285
|
catch (err2) {
|
|
288
286
|
throw new ExtractorError('Failed to process file', file, err2);
|
|
@@ -1,7 +1,56 @@
|
|
|
1
1
|
import { glob } from 'glob';
|
|
2
|
-
import { readdir } from 'node:fs/promises';
|
|
2
|
+
import { readdir, readFile, stat } from 'node:fs/promises';
|
|
3
3
|
import { extname, dirname, join } from 'node:path';
|
|
4
|
+
import { readProjectDeps } from './utils/file-utils.js';
|
|
4
5
|
|
|
6
|
+
/** The directories source files usually live in, one glob for those that exist (`{app,components}/**`). */
|
|
7
|
+
async function sourceInput() {
|
|
8
|
+
const dirs = [];
|
|
9
|
+
// not `lib`, often the build output of a package
|
|
10
|
+
for (const dir of ['src', 'app', 'pages', 'components']) {
|
|
11
|
+
if (await stat(dir).then(found => found.isDirectory(), () => false))
|
|
12
|
+
dirs.push(dir);
|
|
13
|
+
}
|
|
14
|
+
const exts = '**/*.{js,jsx,mjs,ts,tsx}';
|
|
15
|
+
return [dirs.length > 1 ? `{${dirs.join(',')}}/${exts}` : `${dirs[0] ?? 'src'}/${exts}`];
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* The extract options the app's own setup decides: next-i18next's `defaultNS` (from its config, `common` when it
|
|
19
|
+
* sets none), the message format of i18next-icu or i18next-mf2, and `keySeparator: false` for translation files
|
|
20
|
+
* with flat keys that contain dots (`"blog.title": "…"`).
|
|
21
|
+
*/
|
|
22
|
+
async function setupOptions(translationFiles) {
|
|
23
|
+
const deps = await readProjectDeps();
|
|
24
|
+
const options = {};
|
|
25
|
+
if (deps['next-i18next']) {
|
|
26
|
+
const configs = await glob('{i18n.config,next-i18next.config,i18n.shared}.{ts,js,mjs,cjs}', { ignore: 'node_modules/**' });
|
|
27
|
+
for (const file of configs) {
|
|
28
|
+
const ns = /\bdefaultNS\s*:\s*['"]([^'"]+)['"]/.exec(await readFile(file, 'utf-8'))?.[1];
|
|
29
|
+
if (ns) {
|
|
30
|
+
options.defaultNS = ns;
|
|
31
|
+
break;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
options.defaultNS ??= 'common';
|
|
35
|
+
}
|
|
36
|
+
if (deps['i18next-icu'])
|
|
37
|
+
options.messageFormat = 'icu';
|
|
38
|
+
else if (deps['i18next-mf2'])
|
|
39
|
+
options.messageFormat = 'mf2';
|
|
40
|
+
const flat = [];
|
|
41
|
+
for (const file of translationFiles.filter(f => extname(f) === '.json')) {
|
|
42
|
+
try {
|
|
43
|
+
const json = JSON.parse(await readFile(file, 'utf-8'));
|
|
44
|
+
if (Object.values(json).some(v => typeof v === 'object'))
|
|
45
|
+
return options;
|
|
46
|
+
flat.push(Object.keys(json).some(key => key.includes('.')));
|
|
47
|
+
}
|
|
48
|
+
catch { }
|
|
49
|
+
}
|
|
50
|
+
if (flat.includes(true))
|
|
51
|
+
options.keySeparator = false;
|
|
52
|
+
return options;
|
|
53
|
+
}
|
|
5
54
|
// A list of common glob patterns for the primary language ('en') or ('dev') translation files.
|
|
6
55
|
const HEURISTIC_PATTERNS = [
|
|
7
56
|
'public/locales/dev/*.json',
|
|
@@ -88,15 +137,11 @@ async function detectConfig() {
|
|
|
88
137
|
return {
|
|
89
138
|
locales,
|
|
90
139
|
extract: {
|
|
91
|
-
input:
|
|
92
|
-
'src/**/*.{js,jsx,mjs,ts,tsx}',
|
|
93
|
-
'app/**/*.{js,jsx,mjs,ts,tsx}',
|
|
94
|
-
'pages/**/*.{js,jsx,mjs,ts,tsx}',
|
|
95
|
-
'components/**/*.{js,jsx,mjs,ts,tsx}'
|
|
96
|
-
],
|
|
140
|
+
input: await sourceInput(),
|
|
97
141
|
output: join(basePath, '{{language}}', `{{namespace}}${extension}`),
|
|
98
142
|
outputFormat,
|
|
99
143
|
primaryLanguage: locales.includes('en') ? 'en' : locales[0],
|
|
144
|
+
...await setupOptions(files),
|
|
100
145
|
},
|
|
101
146
|
};
|
|
102
147
|
}
|
package/dist/esm/init.js
CHANGED
|
@@ -188,11 +188,16 @@ async function runInit(options = {}) {
|
|
|
188
188
|
const isTypeScript = answers.fileType.includes('TypeScript');
|
|
189
189
|
const isEsm = await isEsmProject();
|
|
190
190
|
const fileName = isTypeScript ? 'i18next.config.ts' : 'i18next.config.js';
|
|
191
|
+
// what the app's own setup decides (next-i18next's defaultNS, ICU, flat keys), as detected
|
|
192
|
+
const { defaultNS, messageFormat, keySeparator } = detectedConfig?.extract ?? {};
|
|
191
193
|
const configObject = {
|
|
192
194
|
locales: answers.locales,
|
|
193
195
|
extract: {
|
|
194
196
|
input: answers.input,
|
|
195
197
|
output: answers.output,
|
|
198
|
+
...(defaultNS !== undefined && { defaultNS }),
|
|
199
|
+
...(messageFormat && { messageFormat }),
|
|
200
|
+
...(keySeparator !== undefined && { keySeparator }),
|
|
196
201
|
},
|
|
197
202
|
};
|
|
198
203
|
if (locizeConfig)
|