i18next-cli 1.79.1 ā 1.80.1
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 +29 -1
- package/dist/cjs/cli.js +3 -2
- package/dist/cjs/linter.js +53 -25
- package/dist/cjs/localize/agent-prompt.js +3 -1
- package/dist/cjs/status.js +94 -55
- package/dist/cjs/utils/lint-baseline.js +72 -0
- package/dist/cjs/utils/locize-funnel.js +3 -1
- package/dist/cjs/utils/message-format.js +123 -7
- package/dist/esm/cli.js +3 -2
- package/dist/esm/linter.js +55 -27
- package/dist/esm/localize/agent-prompt.js +3 -1
- package/dist/esm/status.js +94 -55
- package/dist/esm/utils/lint-baseline.js +67 -0
- package/dist/esm/utils/locize-funnel.js +3 -1
- package/dist/esm/utils/message-format.js +122 -8
- package/package.json +18 -18
- package/types/cli.d.ts.map +1 -1
- package/types/linter.d.ts +13 -1
- package/types/linter.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/status.d.ts.map +1 -1
- package/types/types.d.ts +33 -3
- package/types/types.d.ts.map +1 -1
- package/types/utils/lint-baseline.d.ts +24 -0
- package/types/utils/lint-baseline.d.ts.map +1 -0
- package/types/utils/locize-funnel.d.ts +2 -0
- package/types/utils/locize-funnel.d.ts.map +1 -1
- package/types/utils/message-format.d.ts +18 -0
- package/types/utils/message-format.d.ts.map +1 -1
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var promises = require('node:fs/promises');
|
|
4
|
+
var node_path = require('node:path');
|
|
5
|
+
|
|
6
|
+
/** The baseline file: `lint.baseline`, default `i18next-lint-baseline.json` in the working directory. */
|
|
7
|
+
const lintBaselinePath = (config) => node_path.resolve(process.cwd(), config.lint?.baseline ?? 'i18next-lint-baseline.json');
|
|
8
|
+
const fileKey = (file) => node_path.relative(process.cwd(), node_path.resolve(process.cwd(), file)).split(node_path.sep).join('/');
|
|
9
|
+
const issueKey = (issue) => `${issue.type ?? 'hardcoded'}: ${issue.text}`;
|
|
10
|
+
/** The baseline, or undefined when the file does not exist. A file that does not parse throws. */
|
|
11
|
+
async function readLintBaseline(path) {
|
|
12
|
+
let content;
|
|
13
|
+
try {
|
|
14
|
+
content = await promises.readFile(path, 'utf-8');
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
return undefined;
|
|
18
|
+
}
|
|
19
|
+
try {
|
|
20
|
+
return JSON.parse(content);
|
|
21
|
+
}
|
|
22
|
+
catch (err) {
|
|
23
|
+
throw new Error(`could not parse the lint baseline ${path}: ${err?.message ?? err}. Run "npx i18next-cli lint --update-baseline" to write it again.`);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
/** Writes every issue into the baseline, sorted for stable diffs. Returns the number of issues written. */
|
|
27
|
+
async function writeLintBaseline(path, files) {
|
|
28
|
+
const baseline = {};
|
|
29
|
+
let count = 0;
|
|
30
|
+
for (const [file, issues] of Object.entries(files).sort(([a], [b]) => fileKey(a).localeCompare(fileKey(b)))) {
|
|
31
|
+
const counts = {};
|
|
32
|
+
for (const key of issues.map(issueKey).sort())
|
|
33
|
+
counts[key] = (counts[key] ?? 0) + 1;
|
|
34
|
+
baseline[fileKey(file)] = counts;
|
|
35
|
+
count += issues.length;
|
|
36
|
+
}
|
|
37
|
+
await promises.writeFile(path, JSON.stringify(baseline, null, 2) + '\n');
|
|
38
|
+
return count;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Leaves out the issues the baseline holds. Returns the remaining issues, how many were left out,
|
|
42
|
+
* and how many baseline entries no longer occur (fixed issues, to drop with `--update-baseline`).
|
|
43
|
+
*/
|
|
44
|
+
function applyLintBaseline(files, baseline) {
|
|
45
|
+
const left = new Map(Object.entries(baseline).map(([file, counts]) => [file, { ...counts }]));
|
|
46
|
+
const remaining = {};
|
|
47
|
+
let existing = 0;
|
|
48
|
+
for (const [file, issues] of Object.entries(files)) {
|
|
49
|
+
const counts = left.get(fileKey(file));
|
|
50
|
+
const fresh = issues.filter(issue => {
|
|
51
|
+
const key = issueKey(issue);
|
|
52
|
+
if (!counts?.[key])
|
|
53
|
+
return true;
|
|
54
|
+
counts[key]--;
|
|
55
|
+
existing++;
|
|
56
|
+
return false;
|
|
57
|
+
});
|
|
58
|
+
if (fresh.length)
|
|
59
|
+
remaining[file] = fresh;
|
|
60
|
+
}
|
|
61
|
+
let stale = 0;
|
|
62
|
+
for (const counts of left.values()) {
|
|
63
|
+
for (const n of Object.values(counts))
|
|
64
|
+
stale += n;
|
|
65
|
+
}
|
|
66
|
+
return { files: remaining, existing, stale };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
exports.applyLintBaseline = applyLintBaseline;
|
|
70
|
+
exports.lintBaselinePath = lintBaselinePath;
|
|
71
|
+
exports.readLintBaseline = readLintBaseline;
|
|
72
|
+
exports.writeLintBaseline = writeLintBaseline;
|
|
@@ -22,7 +22,9 @@ async function printUntranslatedFunnel(funnelKey, gaps, signupUrl, log = console
|
|
|
22
22
|
const where = open.length === 1
|
|
23
23
|
? `in ${open[0].locale}`
|
|
24
24
|
: `(${open.map(g => `${g.locale} ${g.untranslated}`).join(', ')})`;
|
|
25
|
-
|
|
25
|
+
const identical = open.reduce((sum, g) => sum + (g.identical ?? 0), 0);
|
|
26
|
+
const copied = identical ? `, ${identical} of them still identical to the primary language` : '';
|
|
27
|
+
log(`\nš” ${total} untranslated key${total === 1 ? '' : 's'} ${where}${copied}. Translate them with AI in one command: ${node_util.styleText('cyan', 'npx i18next-cli localize')} (sign up: ${signupUrl})`);
|
|
26
28
|
return funnelMsgTracker.recordFunnelShown(funnelKey);
|
|
27
29
|
}
|
|
28
30
|
|
|
@@ -5,7 +5,28 @@ var node_path = require('node:path');
|
|
|
5
5
|
var glob = require('glob');
|
|
6
6
|
var jsoncParser = require('jsonc-parser');
|
|
7
7
|
var fileUtils = require('./file-utils.js');
|
|
8
|
+
var nesting = require('./nesting.js');
|
|
8
9
|
|
|
10
|
+
const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
11
|
+
/**
|
|
12
|
+
* The variable names of the i18next interpolations in a value: `{{name}}`, `{{- name}}` (unescaped),
|
|
13
|
+
* `{{val, number}}` and `{{ user.name }}` give `name`, `name`, `val` and `user.name`.
|
|
14
|
+
* Read like i18next's Interpolator: anything between prefix and suffix, trimmed, a `-` right after the
|
|
15
|
+
* prefix marks it unescaped, and a format follows the first `,`.
|
|
16
|
+
* ponytail: i18next's defaults for unescapePrefix (`-`) and formatSeparator (`,`); custom ones are not read.
|
|
17
|
+
*/
|
|
18
|
+
function interpolationNames(value, extract) {
|
|
19
|
+
const prefix = escapeRegExp(extract.interpolationPrefix ?? '{{');
|
|
20
|
+
const suffix = escapeRegExp(extract.interpolationSuffix ?? '}}');
|
|
21
|
+
const names = [];
|
|
22
|
+
for (const [, inner] of value.matchAll(new RegExp(`${prefix}(.+?)${suffix}`, 'g'))) {
|
|
23
|
+
const name = inner.replace(/^-/, '').split(',')[0].trim();
|
|
24
|
+
// a brace means ICU (`one {{count} item}`) in a project without extract.messageFormat, not a variable
|
|
25
|
+
if (name && !/[{}]/.test(name))
|
|
26
|
+
names.push(name);
|
|
27
|
+
}
|
|
28
|
+
return names;
|
|
29
|
+
}
|
|
9
30
|
/**
|
|
10
31
|
* True for `extract.messageFormat` `'icu'` and `'mf2'`. These formats put plurals and selects into the
|
|
11
32
|
* message itself and have no `$t()` nesting, so the CLI writes no plural or context suffix keys for them.
|
|
@@ -222,6 +243,15 @@ async function lineFinder(file) {
|
|
|
222
243
|
return node ? content.slice(0, node.parent?.offset ?? node.offset).split('\n').length : 0;
|
|
223
244
|
};
|
|
224
245
|
}
|
|
246
|
+
// Namespace discovery as in `sync`: the primary language's files
|
|
247
|
+
async function primaryNamespaces(config, primary) {
|
|
248
|
+
const { output, ignoreNamespaces = [] } = config.extract;
|
|
249
|
+
if (typeof output === 'string' && !output.includes('{{namespace}}'))
|
|
250
|
+
return [undefined];
|
|
251
|
+
return (await glob.glob(fileUtils.getOutputPath(output, primary, '*').replace(/\\/g, '/')))
|
|
252
|
+
.map(file => node_path.basename(file).split('.')[0])
|
|
253
|
+
.filter(ns => !ignoreNamespaces.includes(ns));
|
|
254
|
+
}
|
|
225
255
|
/**
|
|
226
256
|
* Checks every translation value of every locale for `extract.messageFormat` `'icu'` or `'mf2'`:
|
|
227
257
|
* syntax, argument names against the primary language, and plural categories per locale.
|
|
@@ -231,16 +261,11 @@ async function lintMessageFormatResources(config, analyze) {
|
|
|
231
261
|
const isMf2 = config.extract.messageFormat === 'mf2';
|
|
232
262
|
const formatName = isMf2 ? 'MF2' : 'ICU';
|
|
233
263
|
const arg = (name) => isMf2 ? `{$${name}}` : `{${name}}`;
|
|
234
|
-
const { output
|
|
264
|
+
const { output } = config.extract;
|
|
235
265
|
const keySeparator = config.extract.keySeparator || '.';
|
|
236
266
|
const primary = config.extract.primaryLanguage || config.locales[0] || 'en';
|
|
237
267
|
const locales = [primary, ...config.locales.filter(l => l !== primary)];
|
|
238
|
-
|
|
239
|
-
const namespaces = typeof output === 'string' && !output.includes('{{namespace}}')
|
|
240
|
-
? [undefined]
|
|
241
|
-
: (await glob.glob(fileUtils.getOutputPath(output, primary, '*').replace(/\\/g, '/')))
|
|
242
|
-
.map(file => node_path.basename(file).split('.')[0])
|
|
243
|
-
.filter(ns => !ignoreNamespaces.includes(ns));
|
|
268
|
+
const namespaces = await primaryNamespaces(config, primary);
|
|
244
269
|
const issuesByFile = new Map();
|
|
245
270
|
for (const ns of namespaces) {
|
|
246
271
|
let primaryShapes = new Map();
|
|
@@ -303,7 +328,98 @@ async function lintMessageFormatResources(config, analyze) {
|
|
|
303
328
|
}
|
|
304
329
|
return issuesByFile;
|
|
305
330
|
}
|
|
331
|
+
/**
|
|
332
|
+
* Checks the translation values of every locale in the i18next format against the primary language: the
|
|
333
|
+
* interpolations (by name, so `{{val, number}}` and `{{ val }}` are both `val`), the nested `$t(key)` references and
|
|
334
|
+
* the tags (`<0>`, `<1/>`, `<bold>`), except the basic HTML react-i18next keeps (`transKeepBasicHtmlNodesFor`).
|
|
335
|
+
* Plural forms are compared as a group (the union over `_one`, `_other`, ...), since a language may leave `{{count}}`
|
|
336
|
+
* out of `_one` or `_zero` and has forms the primary language lacks.
|
|
337
|
+
* The same idea as Locize's check 240 (`checkI18nFeatures`). Returns the issues per translation file.
|
|
338
|
+
* ponytail: a placeholder dropped from one plural form while another form keeps it passes; a per-form rule would flag `{{count}}`.
|
|
339
|
+
*/
|
|
340
|
+
async function lintI18nextResources(config, severity) {
|
|
341
|
+
const { output, interpolationPrefix = '{{', interpolationSuffix = '}}', nestingPrefix = '$t(', nestingSuffix = ')', nestingOptionsSeparator } = config.extract;
|
|
342
|
+
const keySeparator = config.extract.keySeparator || '.';
|
|
343
|
+
const nsSeparator = config.extract.nsSeparator ?? ':';
|
|
344
|
+
// the suffixes i18next's PluralResolver appends: `_one`, `_ordinal_two`, and `_zero` for a count of 0
|
|
345
|
+
const s = escapeRegExp(config.extract.pluralSeparator ?? '_');
|
|
346
|
+
const pluralSuffix = new RegExp(`(?:${s}ordinal)?${s}(?:zero|one|two|few|many|other)$`);
|
|
347
|
+
// react-i18next's default, src/defaults.js
|
|
348
|
+
const keptHtml = new Set(config.extract.transKeepBasicHtmlNodesFor ?? ['br', 'strong', 'i', 'p']);
|
|
349
|
+
const primary = config.extract.primaryLanguage || config.locales[0] || 'en';
|
|
350
|
+
const locales = config.locales.filter(l => l !== primary);
|
|
351
|
+
const placeholders = (value) => [
|
|
352
|
+
...interpolationNames(value, config.extract).map(name => `${interpolationPrefix}${name}${interpolationSuffix}`),
|
|
353
|
+
...nesting.parseNestedReferences(value, { nestingPrefix, nestingSuffix, nestingOptionsSeparator, nsSeparator })
|
|
354
|
+
.map(ref => `${nestingPrefix}${ref.ns ? `${ref.ns}${nsSeparator}` : ''}${ref.key}${nestingSuffix}`),
|
|
355
|
+
// <Trans> renders <0>ā¦</0> from its children and <bold> from its components; an unknown tag shows up as
|
|
356
|
+
// text. The kept basic HTML (<br/>, <strong>) is rendered as is, so a language may add or drop it.
|
|
357
|
+
...[...value.matchAll(/<([A-Za-z0-9][\w.:-]*)(?:\s(?:"[^"]*"|'[^']*'|[^'">])*)?\/?>/g)]
|
|
358
|
+
.filter(match => !keptHtml.has(match[1]))
|
|
359
|
+
.map(match => `<${match[1]}>`),
|
|
360
|
+
];
|
|
361
|
+
const groupsOf = (resources) => {
|
|
362
|
+
const groups = new Map();
|
|
363
|
+
for (const [path, value] of leaves(resources)) {
|
|
364
|
+
if (typeof value !== 'string')
|
|
365
|
+
continue;
|
|
366
|
+
const key = path.join(keySeparator);
|
|
367
|
+
const base = key.replace(pluralSuffix, '');
|
|
368
|
+
let group = groups.get(base);
|
|
369
|
+
if (!group)
|
|
370
|
+
groups.set(base, group = { path, label: key, values: 0, empty: false, tokens: new Set() });
|
|
371
|
+
else
|
|
372
|
+
group.label = base;
|
|
373
|
+
if (value === '') {
|
|
374
|
+
group.empty = true;
|
|
375
|
+
continue;
|
|
376
|
+
}
|
|
377
|
+
group.values++;
|
|
378
|
+
for (const token of placeholders(value))
|
|
379
|
+
group.tokens.add(token);
|
|
380
|
+
}
|
|
381
|
+
return groups;
|
|
382
|
+
};
|
|
383
|
+
// A file that does not parse makes `extract`, `sync` and `status` fail loudly, so `lint` skips it
|
|
384
|
+
const load = (file) => fileUtils.loadTranslationFile(file).catch(() => null);
|
|
385
|
+
const issuesByFile = new Map();
|
|
386
|
+
for (const ns of await primaryNamespaces(config, primary)) {
|
|
387
|
+
const primaryResources = await load(fileUtils.getOutputPath(output, primary, ns));
|
|
388
|
+
if (!primaryResources)
|
|
389
|
+
continue;
|
|
390
|
+
const primaryGroups = groupsOf(primaryResources);
|
|
391
|
+
for (const lng of locales) {
|
|
392
|
+
const file = fileUtils.getOutputPath(output, lng, ns);
|
|
393
|
+
const resources = await load(file);
|
|
394
|
+
if (!resources)
|
|
395
|
+
continue;
|
|
396
|
+
const problems = [];
|
|
397
|
+
for (const [base, group] of groupsOf(resources)) {
|
|
398
|
+
const source = primaryGroups.get(base);
|
|
399
|
+
if (!source?.values || !group.values)
|
|
400
|
+
continue;
|
|
401
|
+
// a partly translated plural may still lack the form that carries {{count}}
|
|
402
|
+
const missing = group.empty ? [] : [...source.tokens].filter(t => !group.tokens.has(t));
|
|
403
|
+
const unexpected = [...group.tokens].filter(t => !source.tokens.has(t));
|
|
404
|
+
if (!missing.length && !unexpected.length)
|
|
405
|
+
continue;
|
|
406
|
+
const diff = [
|
|
407
|
+
missing.length ? `missing ${missing.join(', ')}` : '',
|
|
408
|
+
unexpected.length ? `unexpected ${unexpected.join(', ')}` : '',
|
|
409
|
+
].filter(Boolean).join(', ');
|
|
410
|
+
problems.push({ path: group.path, text: `${group.label}: ${diff} (compared with "${primary}")` });
|
|
411
|
+
}
|
|
412
|
+
if (problems.length) {
|
|
413
|
+
const lineOf = await lineFinder(file);
|
|
414
|
+
issuesByFile.set(file, problems.map(({ path, text }) => ({ text, line: lineOf(path), type: 'placeholder', severity })));
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
return issuesByFile;
|
|
419
|
+
}
|
|
306
420
|
|
|
421
|
+
exports.interpolationNames = interpolationNames;
|
|
422
|
+
exports.lintI18nextResources = lintI18nextResources;
|
|
307
423
|
exports.lintMessageFormatResources = lintMessageFormatResources;
|
|
308
424
|
exports.loadMessageAnalyzer = loadMessageAnalyzer;
|
|
309
425
|
exports.pluralCategories = pluralCategories;
|
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.80.1') // 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)');
|
|
@@ -234,6 +234,7 @@ program
|
|
|
234
234
|
.description('Find potential issues like hardcoded strings in your codebase.')
|
|
235
235
|
.option('-w, --watch', 'Watch for file changes and re-run the linter.')
|
|
236
236
|
.option('-q, --quiet', 'Suppress spinner and output')
|
|
237
|
+
.option('--update-baseline', 'Write all current issues to the baseline file (lint.baseline, default i18next-lint-baseline.json); lint then fails only on new issues. Commit the file.')
|
|
237
238
|
.action(async (options) => {
|
|
238
239
|
const cfgPath = program.opts().config;
|
|
239
240
|
const loadAndRunLinter = async () => {
|
|
@@ -250,7 +251,7 @@ program
|
|
|
250
251
|
console.log(styleText('green', 'Project structure detected successfully!'));
|
|
251
252
|
config = detected;
|
|
252
253
|
}
|
|
253
|
-
await runLinterCli(config, { quiet: !!options.quiet });
|
|
254
|
+
await runLinterCli(config, { quiet: !!options.quiet, updateBaseline: !!options.updateBaseline });
|
|
254
255
|
};
|
|
255
256
|
// Run the linter once initially
|
|
256
257
|
await loadAndRunLinter();
|
package/dist/esm/linter.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { glob } from 'glob';
|
|
2
2
|
import { readFile } from 'node:fs/promises';
|
|
3
3
|
import { parse } from '@swc/core';
|
|
4
|
-
import { extname, resolve } from 'node:path';
|
|
4
|
+
import { relative, extname, resolve } from 'node:path';
|
|
5
5
|
import { EventEmitter } from 'node:events';
|
|
6
6
|
import { styleText } from 'node:util';
|
|
7
7
|
import { ConsoleLogger } from './utils/logger.js';
|
|
@@ -9,8 +9,11 @@ import { createSpinnerLike } from './utils/wrap-ora.js';
|
|
|
9
9
|
import { acceptedTags, translatableAttributes, ignoredTags, ignoredAttributeLowerSet } from './utils/jsx-attributes.js';
|
|
10
10
|
import { normalizeSpansToCharIndices, collectIgnoredLineRanges, lineColumnFromOffset } from './extractor/parsers/ast-utils.js';
|
|
11
11
|
import { matchesFunctionPattern } from './extractor/utils/function-matcher.js';
|
|
12
|
-
import { loadMessageAnalyzer, lintMessageFormatResources } from './utils/message-format.js';
|
|
12
|
+
import { loadMessageAnalyzer, lintMessageFormatResources, lintI18nextResources, interpolationNames } from './utils/message-format.js';
|
|
13
|
+
import { lintBaselinePath, writeLintBaseline, readLintBaseline, applyLintBaseline } from './utils/lint-baseline.js';
|
|
14
|
+
import { shouldShowFunnel, recordFunnelShown } from './utils/funnel-msg-tracker.js';
|
|
13
15
|
|
|
16
|
+
const LOCIZE_SIGNUP_URL = 'https://www.locize.app/register?from=i18next_cli__lint';
|
|
14
17
|
/**
|
|
15
18
|
* Loads all translation values from the primary locale's JSON files and returns
|
|
16
19
|
* a flat Map of key -> translated string. Used by the interpolation linter so it
|
|
@@ -72,20 +75,6 @@ async function loadPrimaryTranslationValues(config) {
|
|
|
72
75
|
}
|
|
73
76
|
return result;
|
|
74
77
|
}
|
|
75
|
-
// Helper to extract interpolation keys from a translation string
|
|
76
|
-
function extractInterpolationKeys(str, config) {
|
|
77
|
-
const prefix = config.extract.interpolationPrefix ?? '{{';
|
|
78
|
-
const suffix = config.extract.interpolationSuffix ?? '}}';
|
|
79
|
-
// Regex to match {{key}} or {{key, format}} (i18next formatting syntax)
|
|
80
|
-
const regex = new RegExp(`${prefix.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&')}\\s*([\\w.-]+)\\s*(?:,[^}]*)?${suffix.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&')}`, 'g');
|
|
81
|
-
const keys = [];
|
|
82
|
-
let match;
|
|
83
|
-
while ((match = regex.exec(str))) {
|
|
84
|
-
if (match[1])
|
|
85
|
-
keys.push(match[1]);
|
|
86
|
-
}
|
|
87
|
-
return keys;
|
|
88
|
-
}
|
|
89
78
|
// Known i18next t() option keys that are NOT interpolation parameters.
|
|
90
79
|
// These should not be flagged as "unused" in the translation string.
|
|
91
80
|
const i18nextOptionKeys = new Set([
|
|
@@ -284,7 +273,7 @@ function lintInterpolationParams(ast, code, config, translationValues, analyze)
|
|
|
284
273
|
continue;
|
|
285
274
|
lastSearchIndex = position + searchText.length;
|
|
286
275
|
const issueLineNumber = getLineNumber(position);
|
|
287
|
-
const keys = analyze ? messageArgs(analyze, translationStr) :
|
|
276
|
+
const keys = analyze ? messageArgs(analyze, translationStr) : interpolationNames(translationStr, config.extract);
|
|
288
277
|
// Only check for unused parameters if there is at least one interpolation key in the string
|
|
289
278
|
if (keys.length > 0) {
|
|
290
279
|
// i18next supports nested object access via dot notation (e.g. {{author.name}} with { author }).
|
|
@@ -523,7 +512,8 @@ class Linter extends EventEmitter {
|
|
|
523
512
|
}
|
|
524
513
|
return new Error(`${prefix}${String(error)}`);
|
|
525
514
|
}
|
|
526
|
-
|
|
515
|
+
/** @param options.ignoreBaseline - report every issue, also those the baseline file holds (`lint --update-baseline`) */
|
|
516
|
+
async run(options = {}) {
|
|
527
517
|
const { config } = this;
|
|
528
518
|
try {
|
|
529
519
|
this.emit('progress', { message: 'Finding source files to analyze...' });
|
|
@@ -642,18 +632,36 @@ class Linter extends EventEmitter {
|
|
|
642
632
|
issuesByFile.set(file, allIssues);
|
|
643
633
|
}
|
|
644
634
|
}
|
|
635
|
+
const placeholderSetting = config.lint?.checkTranslationPlaceholders;
|
|
636
|
+
let resourceIssues = new Map();
|
|
645
637
|
if (analyze) {
|
|
646
638
|
this.emit('progress', { message: `Checking ${messageFormat === 'mf2' ? 'MF2' : 'ICU'} messages in translation files...` });
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
}
|
|
639
|
+
resourceIssues = await lintMessageFormatResources(config, analyze);
|
|
640
|
+
}
|
|
641
|
+
else if (placeholderSetting !== false && placeholderSetting !== 'off' && config.locales.length > 1) {
|
|
642
|
+
this.emit('progress', { message: 'Checking placeholders in translation files...' });
|
|
643
|
+
resourceIssues = await lintI18nextResources(config, placeholderSetting === 'error' ? 'error' : 'warning');
|
|
644
|
+
}
|
|
645
|
+
for (const [file, issues] of resourceIssues) {
|
|
646
|
+
totalIssues += issues.length;
|
|
647
|
+
issuesByFile.set(file, [...(issuesByFile.get(file) ?? []), ...issues]);
|
|
648
|
+
}
|
|
649
|
+
let files = Object.fromEntries(issuesByFile.entries());
|
|
650
|
+
// Issues the baseline file holds (`lint --update-baseline`) are counted, not reported
|
|
651
|
+
let existingIssues = 0;
|
|
652
|
+
let staleBaselineEntries = 0;
|
|
653
|
+
const baseline = options.ignoreBaseline ? undefined : await readLintBaseline(lintBaselinePath(config));
|
|
654
|
+
if (baseline) {
|
|
655
|
+
({ files, existing: existingIssues, stale: staleBaselineEntries } = applyLintBaseline(files, baseline));
|
|
656
|
+
totalIssues -= existingIssues;
|
|
651
657
|
}
|
|
652
|
-
const files = Object.fromEntries(issuesByFile.entries());
|
|
653
658
|
// `success` reflects errors only ā warning-severity issues (e.g. string
|
|
654
659
|
// concatenation) are reported but do not fail the run / CI.
|
|
655
|
-
const errorCount =
|
|
656
|
-
const
|
|
660
|
+
const errorCount = Object.values(files).flat().filter(i => i.severity !== 'warning').length;
|
|
661
|
+
const message = totalIssues > 0
|
|
662
|
+
? `Linter found ${totalIssues} potential issues${existingIssues ? ` (${existingIssues} more in the baseline)` : ''}.`
|
|
663
|
+
: existingIssues ? `No new issues found (${existingIssues} in the baseline).` : 'No issues found.';
|
|
664
|
+
const data = { success: errorCount === 0, message, files, existingIssues, staleBaselineEntries };
|
|
657
665
|
this.emit('done', data);
|
|
658
666
|
return data;
|
|
659
667
|
}
|
|
@@ -770,13 +778,21 @@ async function runLinter(config) {
|
|
|
770
778
|
}
|
|
771
779
|
async function runLinterCli(config, options = {}) {
|
|
772
780
|
const internalLogger = options.logger ?? new ConsoleLogger();
|
|
781
|
+
const log = (msg) => typeof internalLogger.info === 'function' ? internalLogger.info(msg) : console.log(msg);
|
|
773
782
|
const linter = new Linter(config, internalLogger);
|
|
774
783
|
const spinner = createSpinnerLike('', { quiet: !!options.quiet, logger: options.logger });
|
|
775
784
|
linter.on('progress', (event) => {
|
|
776
785
|
spinner.text = event.message;
|
|
777
786
|
});
|
|
778
787
|
try {
|
|
779
|
-
|
|
788
|
+
if (options.updateBaseline) {
|
|
789
|
+
const { files } = await linter.run({ ignoreBaseline: true });
|
|
790
|
+
const path = lintBaselinePath(config);
|
|
791
|
+
const count = await writeLintBaseline(path, files);
|
|
792
|
+
spinner.succeed(styleText(['green', 'bold'], `Wrote ${count} existing issue${count === 1 ? '' : 's'} to ${relative(process.cwd(), path)}. Commit it: lint now fails only on new issues.`));
|
|
793
|
+
return;
|
|
794
|
+
}
|
|
795
|
+
const { message, files, staleBaselineEntries } = await linter.run();
|
|
780
796
|
const fileEntries = Object.entries(files);
|
|
781
797
|
const allIssues = fileEntries.flatMap(([, issues]) => issues);
|
|
782
798
|
const hasErrors = allIssues.some(i => i.severity !== 'warning');
|
|
@@ -801,7 +817,9 @@ async function runLinterCli(config, options = {}) {
|
|
|
801
817
|
? 'String concatenation'
|
|
802
818
|
: type === 'messageFormat'
|
|
803
819
|
? `${config.extract.messageFormat === 'mf2' ? 'MF2' : 'ICU'} message`
|
|
804
|
-
:
|
|
820
|
+
: type === 'placeholder'
|
|
821
|
+
? 'Placeholder mismatch'
|
|
822
|
+
: 'Found hardcoded string';
|
|
805
823
|
const tag = severity === 'warning' ? styleText('yellow', 'Warning:') : styleText('red', 'Error:');
|
|
806
824
|
// line 0: a translation file whose format has no line lookup (YAML, JS)
|
|
807
825
|
const detail = ` ${line ? `${styleText('gray', `${line}:`)} ` : ''}${tag} ${label}: "${text}"`;
|
|
@@ -811,6 +829,16 @@ async function runLinterCli(config, options = {}) {
|
|
|
811
829
|
console.log(detail);
|
|
812
830
|
});
|
|
813
831
|
}
|
|
832
|
+
if (staleBaselineEntries > 0) {
|
|
833
|
+
log(styleText('gray', `\n${staleBaselineEntries} baseline entr${staleBaselineEntries === 1 ? 'y no longer occurs' : 'ies no longer occur'}. Run "npx i18next-cli lint --update-baseline" to drop ${staleBaselineEntries === 1 ? 'it' : 'them'}.`));
|
|
834
|
+
}
|
|
835
|
+
// A placeholder broken in a translation file was edited outside the code, usually by a
|
|
836
|
+
// translator or a tool: Locize runs the same check in its editor while they type.
|
|
837
|
+
// Gated like the other funnel messages (never in CI/non-TTY, 24h cooldown).
|
|
838
|
+
if (allIssues.some(i => i.type === 'placeholder') && await shouldShowFunnel('lint-placeholders')) {
|
|
839
|
+
log(`\nš” Locize runs this placeholder check while translators type and can fix a mismatch with AI (sign up: ${LOCIZE_SIGNUP_URL})`);
|
|
840
|
+
await recordFunnelShown('lint-placeholders');
|
|
841
|
+
}
|
|
814
842
|
// Only errors fail the process; warning-only runs exit 0.
|
|
815
843
|
if (hasErrors)
|
|
816
844
|
process.exit(1);
|
|
@@ -42,7 +42,9 @@ all commands.
|
|
|
42
42
|
written (check the extract.output path in the config). If the developer
|
|
43
43
|
chose repository files only: translate the extracted keys yourself or
|
|
44
44
|
leave them to the team, run \`npx i18next-cli status\` to confirm every
|
|
45
|
-
language is complete
|
|
45
|
+
language is complete (it also lists values still identical to the primary
|
|
46
|
+
language) and \`npx i18next-cli lint\` to check that every translation keeps
|
|
47
|
+
the placeholders ({{name}}, $t(), <0>) of the primary language, and stop here.
|
|
46
48
|
5. Locize (only if the developer chose it in step 2): ask them for
|
|
47
49
|
LOCIZE_PROJECTID and LOCIZE_API_KEY (they create the project at
|
|
48
50
|
https://www.locize.app/register?from=i18next_cli__agent-prompt
|