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.
- package/README.md +104 -12
- package/dist/cjs/cli.js +25 -6
- package/dist/cjs/config.js +13 -12
- package/dist/cjs/extractor/core/extractor.js +1 -3
- package/dist/cjs/extractor/core/translation-manager.js +9 -2
- package/dist/cjs/heuristic-config.js +51 -6
- package/dist/cjs/index.js +2 -1
- package/dist/cjs/init.js +8 -11
- package/dist/cjs/instrumenter/core/instrumenter.js +1372 -218
- package/dist/cjs/instrumenter/core/key-generator.js +20 -9
- package/dist/cjs/instrumenter/core/next-files.js +104 -0
- package/dist/cjs/instrumenter/core/string-detector.js +106 -29
- package/dist/cjs/instrumenter/core/transformer.js +165 -83
- package/dist/cjs/localize/agent-prompt.js +5 -2
- package/dist/cjs/localize/detect.js +3 -11
- package/dist/cjs/localize/localize.js +27 -5
- package/dist/cjs/utils/file-utils.js +48 -0
- package/dist/cjs/utils/jsx-attributes.js +3 -1
- package/dist/esm/cli.js +25 -6
- package/dist/esm/config.js +13 -12
- package/dist/esm/extractor/core/extractor.js +1 -3
- package/dist/esm/extractor/core/translation-manager.js +9 -2
- package/dist/esm/heuristic-config.js +52 -7
- package/dist/esm/index.js +2 -1
- package/dist/esm/init.js +8 -11
- package/dist/esm/instrumenter/core/instrumenter.js +1376 -222
- package/dist/esm/instrumenter/core/key-generator.js +20 -9
- package/dist/esm/instrumenter/core/next-files.js +101 -0
- package/dist/esm/instrumenter/core/string-detector.js +107 -31
- package/dist/esm/instrumenter/core/transformer.js +165 -83
- package/dist/esm/localize/agent-prompt.js +5 -2
- package/dist/esm/localize/detect.js +4 -12
- package/dist/esm/localize/localize.js +27 -5
- package/dist/esm/utils/file-utils.js +49 -2
- package/dist/esm/utils/jsx-attributes.js +3 -1
- package/package.json +1 -1
- package/types/cli.d.ts.map +1 -1
- package/types/config.d.ts.map +1 -1
- package/types/extractor/core/extractor.d.ts.map +1 -1
- package/types/extractor/core/translation-manager.d.ts.map +1 -1
- package/types/heuristic-config.d.ts.map +1 -1
- package/types/index.d.ts +1 -1
- package/types/index.d.ts.map +1 -1
- package/types/init.d.ts.map +1 -1
- package/types/instrumenter/core/instrumenter.d.ts.map +1 -1
- package/types/instrumenter/core/key-generator.d.ts +2 -0
- package/types/instrumenter/core/key-generator.d.ts.map +1 -1
- package/types/instrumenter/core/next-files.d.ts +25 -0
- package/types/instrumenter/core/next-files.d.ts.map +1 -0
- package/types/instrumenter/core/string-detector.d.ts +5 -1
- package/types/instrumenter/core/string-detector.d.ts.map +1 -1
- package/types/instrumenter/core/transformer.d.ts +16 -1
- package/types/instrumenter/core/transformer.d.ts.map +1 -1
- package/types/instrumenter/index.d.ts +1 -1
- package/types/instrumenter/index.d.ts.map +1 -1
- package/types/localize/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 +87 -1
- package/types/types.d.ts.map +1 -1
- package/types/utils/file-utils.d.ts +7 -0
- package/types/utils/file-utils.d.ts.map +1 -1
- package/types/utils/jsx-attributes.d.ts.map +1 -1
|
@@ -14,6 +14,9 @@ var logger = require('../../utils/logger.js');
|
|
|
14
14
|
var jsxAttributes = require('../../utils/jsx-attributes.js');
|
|
15
15
|
var astUtils = require('../../extractor/parsers/ast-utils.js');
|
|
16
16
|
var fileUtils = require('../../utils/file-utils.js');
|
|
17
|
+
var keyFinder = require('../../extractor/core/key-finder.js');
|
|
18
|
+
var functionMatcher = require('../../extractor/utils/function-matcher.js');
|
|
19
|
+
var nextFiles = require('./next-files.js');
|
|
17
20
|
var messageFormat = require('../../utils/message-format.js');
|
|
18
21
|
|
|
19
22
|
/**
|
|
@@ -41,9 +44,44 @@ async function runInstrumenter(config, options, logger$1 = new logger.ConsoleLog
|
|
|
41
44
|
let totalSkipped = 0;
|
|
42
45
|
let totalLanguageChanges = 0;
|
|
43
46
|
let usesI18nextT = false;
|
|
47
|
+
// The same warning for many files is printed once, with the files below it
|
|
48
|
+
const warnings = new Map();
|
|
49
|
+
const warnFor = (where, message) => {
|
|
50
|
+
warnings.set(message, [...(warnings.get(message) ?? []), where]);
|
|
51
|
+
};
|
|
52
|
+
let moduleScopeTotal = 0;
|
|
53
|
+
// The code imports i18next before it is instrumented: it is set up already, here or in a shared package
|
|
54
|
+
let i18nextInUse = false;
|
|
55
|
+
// Keys the code uses already: a new text gets another key, unless it is the same text, and no new key is
|
|
56
|
+
// the parent of nested ones (`tenants` beside `tenants.title` is a nesting conflict at extract)
|
|
57
|
+
// Best effort, without plugins (their hooks are for extract): a file it cannot read reserves nothing
|
|
58
|
+
const separator = config.extract.keySeparator ?? '.';
|
|
59
|
+
const existingKeys = await keyFinder.findKeys({ ...config, plugins: [] }, { info() { }, warn() { }, error() { } })
|
|
60
|
+
.then(found => found.allKeys, () => new Map());
|
|
61
|
+
for (const { key, defaultValue } of existingKeys.values()) {
|
|
62
|
+
const parent = separator ? key.split(separator)[0] : key;
|
|
63
|
+
if (parent !== key)
|
|
64
|
+
keyRegistry.reserve(parent);
|
|
65
|
+
else
|
|
66
|
+
keyRegistry.reserve(key, defaultValue ?? key);
|
|
67
|
+
}
|
|
44
68
|
// Detect framework and language
|
|
45
69
|
const hasReact = await isProjectUsingReact();
|
|
46
70
|
const hasTypeScript = await isProjectUsingTypeScript();
|
|
71
|
+
// A Next.js app gets next-i18next's calls: getT() in Server Components, useT() in Client Components,
|
|
72
|
+
// useTranslation() from next-i18next/pages in the Pages Router. Also one with i18next not set up at all,
|
|
73
|
+
// whose Server Components no plain react-i18next hook would work in; one with an i18next setup of its own
|
|
74
|
+
// keeps it.
|
|
75
|
+
const contents = new Map();
|
|
76
|
+
for (const file of sourceFiles)
|
|
77
|
+
contents.set(file, await promises.readFile(file, 'utf-8'));
|
|
78
|
+
const deps = await fileUtils.readProjectDeps();
|
|
79
|
+
const code = [...contents.values()];
|
|
80
|
+
const nextI18next = !!deps['next-i18next'] || code.some(c => NEXT_I18NEXT_IMPORT_RE.test(c)) ||
|
|
81
|
+
(!!deps.next && !deps.i18next && !deps['react-i18next'] && !code.some(c => I18NEXT_IMPORT_RE.test(c)));
|
|
82
|
+
const nextFiles$1 = nextI18next ? await nextFiles.classifyNextFiles(contents) : undefined;
|
|
83
|
+
const nextKinds = nextFiles$1?.kinds;
|
|
84
|
+
const serverModule = nextI18next ? findServerModule(contents) : undefined;
|
|
47
85
|
// Initialize plugins
|
|
48
86
|
const plugins = config.plugins || [];
|
|
49
87
|
await initializeInstrumentPlugins(plugins, { config, logger: logger$1 });
|
|
@@ -65,24 +103,34 @@ async function runInstrumenter(config, options, logger$1 = new logger.ConsoleLog
|
|
|
65
103
|
}
|
|
66
104
|
for (const file of sourceFiles) {
|
|
67
105
|
try {
|
|
68
|
-
let content =
|
|
106
|
+
let content = contents.get(file);
|
|
69
107
|
// Run instrumentOnLoad plugin pipeline
|
|
70
108
|
const loadResult = await runInstrumentOnLoadPipeline(content, file, plugins, logger$1);
|
|
71
109
|
if (loadResult === null)
|
|
72
110
|
continue; // plugin says skip this file
|
|
73
111
|
content = loadResult;
|
|
74
|
-
|
|
112
|
+
i18nextInUse ||= I18NEXT_IMPORT_RE.test(content) || NEXT_I18NEXT_IMPORT_RE.test(content);
|
|
113
|
+
const nextKind = nextKinds?.get(file);
|
|
114
|
+
const scanResult = await scanFileForCandidates(content, file, config, nextKind);
|
|
75
115
|
let { candidates } = scanResult;
|
|
76
|
-
const { components, languageChangeSites } = scanResult;
|
|
116
|
+
const { components, languageChangeSites, imports, memoHooks, pluralHelperImports } = scanResult;
|
|
77
117
|
// Run instrumentOnResult plugin pipeline
|
|
78
118
|
candidates = await runInstrumentOnResultPipeline(file, candidates, plugins, logger$1);
|
|
119
|
+
if (scanResult.ownTSkipped) {
|
|
120
|
+
totalCandidates += scanResult.ownTSkipped;
|
|
121
|
+
totalSkipped += scanResult.ownTSkipped;
|
|
122
|
+
warnFor(`${file} (${scanResult.ownTSkipped})`, 'Skipped the texts of components that declare a `t` of their own (not a translation function): rename it, then run instrument again.');
|
|
123
|
+
}
|
|
124
|
+
for (const { message, count, lines } of scanResult.dropped ?? []) {
|
|
125
|
+
totalCandidates += count;
|
|
126
|
+
totalSkipped += count;
|
|
127
|
+
warnFor(lines ? lines.map(line => `${file}:${line}`).join(', ') : `${file} (${count})`, message);
|
|
128
|
+
}
|
|
79
129
|
if (scanResult.moduleScopeSkipped > 0) {
|
|
80
130
|
totalCandidates += scanResult.moduleScopeSkipped;
|
|
81
131
|
totalSkipped += scanResult.moduleScopeSkipped;
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
'Move the text into a component/hook (e.g. a useSections() hook calling useTranslation()), or read the key at render time. ' +
|
|
85
|
-
'See: https://www.locize.com/blog/how-to-use-i18next-t-outside-react-components/');
|
|
132
|
+
moduleScopeTotal += scanResult.moduleScopeSkipped;
|
|
133
|
+
warnFor(`${file} (${scanResult.moduleScopeSkipped})`, MODULE_SCOPE_WARNING);
|
|
86
134
|
}
|
|
87
135
|
if (candidates.length === 0 && languageChangeSites.length === 0) {
|
|
88
136
|
continue;
|
|
@@ -107,7 +155,7 @@ async function runInstrumenter(config, options, logger$1 = new logger.ConsoleLog
|
|
|
107
155
|
]);
|
|
108
156
|
switch (action) {
|
|
109
157
|
case 'approve':
|
|
110
|
-
candidate.key = keyGenerator.generateKeyFromContent(candidate.content);
|
|
158
|
+
candidate.key = keyRegistry.add(keyGenerator.generateKeyFromContent(keySourceOf(candidate)), candidate.content);
|
|
111
159
|
break;
|
|
112
160
|
case 'skip':
|
|
113
161
|
candidate.skipReason = 'User skipped';
|
|
@@ -118,10 +166,11 @@ async function runInstrumenter(config, options, logger$1 = new logger.ConsoleLog
|
|
|
118
166
|
type: 'input',
|
|
119
167
|
name: 'key',
|
|
120
168
|
message: 'New key:',
|
|
121
|
-
default: keyGenerator.generateKeyFromContent(candidate
|
|
169
|
+
default: keyGenerator.generateKeyFromContent(keySourceOf(candidate))
|
|
122
170
|
}
|
|
123
171
|
]);
|
|
124
172
|
candidate.key = key;
|
|
173
|
+
keyRegistry.reserve(key, candidate.content);
|
|
125
174
|
break;
|
|
126
175
|
}
|
|
127
176
|
case 'edit-value': {
|
|
@@ -134,7 +183,7 @@ async function runInstrumenter(config, options, logger$1 = new logger.ConsoleLog
|
|
|
134
183
|
}
|
|
135
184
|
]);
|
|
136
185
|
candidate.content = value;
|
|
137
|
-
candidate.key = keyGenerator.generateKeyFromContent(value);
|
|
186
|
+
candidate.key = keyRegistry.add(keyGenerator.generateKeyFromContent(value), value);
|
|
138
187
|
break;
|
|
139
188
|
}
|
|
140
189
|
}
|
|
@@ -146,7 +195,7 @@ async function runInstrumenter(config, options, logger$1 = new logger.ConsoleLog
|
|
|
146
195
|
// Generate keys for approved candidates
|
|
147
196
|
for (const candidate of approvedCandidates) {
|
|
148
197
|
if (!candidate.key) {
|
|
149
|
-
candidate.key = keyRegistry.add(keyGenerator.generateKeyFromContent(candidate
|
|
198
|
+
candidate.key = keyRegistry.add(keyGenerator.generateKeyFromContent(keySourceOf(candidate)), candidate.content);
|
|
150
199
|
}
|
|
151
200
|
}
|
|
152
201
|
// After key generation, so ICU/MF2 syntax does not end up in generated keys
|
|
@@ -160,7 +209,11 @@ async function runInstrumenter(config, options, logger$1 = new logger.ConsoleLog
|
|
|
160
209
|
config,
|
|
161
210
|
components,
|
|
162
211
|
namespace: targetNamespace,
|
|
163
|
-
languageChangeSites
|
|
212
|
+
languageChangeSites,
|
|
213
|
+
imports,
|
|
214
|
+
memoHooks,
|
|
215
|
+
pluralHelperImports,
|
|
216
|
+
next: nextKind && { kind: nextKind, serverModule: serverModuleFor(serverModule, file) }
|
|
164
217
|
});
|
|
165
218
|
if (!options.isDryRun && transformResult.modified) {
|
|
166
219
|
// Write the transformed file
|
|
@@ -174,16 +227,15 @@ async function runInstrumenter(config, options, logger$1 = new logger.ConsoleLog
|
|
|
174
227
|
if (!usesI18nextT && approvedCandidates.some(c => !c.insideComponent && c.confidence >= 0.7)) {
|
|
175
228
|
usesI18nextT = true;
|
|
176
229
|
}
|
|
177
|
-
//
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
logger$1.warn(warning);
|
|
181
|
-
}
|
|
230
|
+
// Collect warnings (e.g. i18next.t() in React files) and candidates that could not be rewritten
|
|
231
|
+
for (const warning of [...(transformResult.warnings ?? []), ...transformResult.errors]) {
|
|
232
|
+
warnFor(file, warning.startsWith(`${file}: `) ? warning.slice(file.length + 2) : warning);
|
|
182
233
|
}
|
|
183
234
|
results.push({
|
|
184
235
|
file,
|
|
185
236
|
candidates: approvedCandidates,
|
|
186
|
-
result: transformResult
|
|
237
|
+
result: transformResult,
|
|
238
|
+
languageChangeSites
|
|
187
239
|
});
|
|
188
240
|
}
|
|
189
241
|
else {
|
|
@@ -196,8 +248,33 @@ async function runInstrumenter(config, options, logger$1 = new logger.ConsoleLog
|
|
|
196
248
|
}
|
|
197
249
|
const langChangeSuffix = totalLanguageChanges > 0 ? `, ${totalLanguageChanges} language-change site(s)` : '';
|
|
198
250
|
spinner.succeed(node_util.styleText('bold', `Scanned complete: ${totalCandidates} candidates, ${totalTransformed} approved${langChangeSuffix}`));
|
|
251
|
+
for (const [message, where] of warnings) {
|
|
252
|
+
const head = message === MODULE_SCOPE_WARNING ? `Skipped ${moduleScopeTotal} module-scope string(s). ${message}` : message;
|
|
253
|
+
logger$1.warn(`${head}\n${where.map(w => ` ${w}`).join('\n')}`);
|
|
254
|
+
}
|
|
255
|
+
if (nextI18next && totalTransformed > 0) {
|
|
256
|
+
// next-i18next sets i18next up itself (its config, the proxy, the root layout or appWithTranslation)
|
|
257
|
+
// a page loads its namespaces itself, with serverSideTranslations() (or a helper it imports that calls it)
|
|
258
|
+
const loads = (file) => [file, ...nextFiles$1.imports.get(file) ?? []].some(f => contents.get(f).includes('serverSideTranslations'));
|
|
259
|
+
const pagesWithoutProps = results.filter(r => nextKinds?.get(r.file) === 'pages' && isPagesRoute(r.file) && !loads(r.file)).map(r => r.file);
|
|
260
|
+
if (pagesWithoutProps.length) {
|
|
261
|
+
logger$1.warn(`These pages need serverSideTranslations() in getStaticProps or getServerSideProps, or their texts render untranslated (https://github.com/i18next/next-i18next#pages-router-setup):\n${pagesWithoutProps.map(f => ` ${f}`).join('\n')}`);
|
|
262
|
+
}
|
|
263
|
+
if (!i18nextInUse && !await nextI18nextConfigured()) {
|
|
264
|
+
const kinds = new Set(results.map(r => nextKinds?.get(r.file)));
|
|
265
|
+
logger$1.info([
|
|
266
|
+
'The code now uses next-i18next. Set it up:',
|
|
267
|
+
` npm install next-i18next i18next react-i18next${config.extract.messageFormat === 'icu' ? ' i18next-icu intl-messageformat' : config.extract.messageFormat === 'mf2' ? ' i18next-mf2' : ''}`,
|
|
268
|
+
...(kinds.has('server') || kinds.has('client') ? [' App Router: i18n.config, proxy and root layout, https://github.com/i18next/next-i18next#app-router-setup (no [lng] folder: localeInPath: false)'] : []),
|
|
269
|
+
...(kinds.has('pages') ? [' Pages Router: next-i18next.config.js, appWithTranslation and serverSideTranslations, https://github.com/i18next/next-i18next#pages-router-setup'] : [])
|
|
270
|
+
].join('\n'));
|
|
271
|
+
}
|
|
272
|
+
}
|
|
199
273
|
// Generate i18n init file if needed and any transformations were made
|
|
200
|
-
if ((totalTransformed > 0 || totalLanguageChanges > 0) && !options.isDryRun) {
|
|
274
|
+
if ((totalTransformed > 0 || totalLanguageChanges > 0) && !options.isDryRun && !nextI18next && i18nextInUse) {
|
|
275
|
+
logger$1.info('Your code imports i18next already, so it is set up somewhere: no i18n init file generated.');
|
|
276
|
+
}
|
|
277
|
+
if ((totalTransformed > 0 || totalLanguageChanges > 0) && !options.isDryRun && !nextI18next && !i18nextInUse) {
|
|
201
278
|
const initFilePath = await ensureI18nInitFile(hasReact, hasTypeScript, config, logger$1, usesI18nextT);
|
|
202
279
|
if (initFilePath) {
|
|
203
280
|
await injectI18nImportIntoEntryFile(initFilePath, logger$1);
|
|
@@ -218,14 +295,67 @@ async function runInstrumenter(config, options, logger$1 = new logger.ConsoleLog
|
|
|
218
295
|
throw error;
|
|
219
296
|
}
|
|
220
297
|
}
|
|
298
|
+
/** The text a key is made from: a <Trans> candidate's words, not its JSX source (`<a href=…>`). */
|
|
299
|
+
function keySourceOf(candidate) {
|
|
300
|
+
return candidate.transValue?.replace(/<\/?\d+>/g, '') ?? candidate.content;
|
|
301
|
+
}
|
|
302
|
+
/** An import of next-i18next, which sets i18next up itself. */
|
|
303
|
+
const NEXT_I18NEXT_IMPORT_RE = /\bfrom\s*['"]next-i18next(?:\/[\w/]+)?['"]|\brequire\(\s*['"]next-i18next(?:\/[\w/]+)?['"]\s*\)/;
|
|
304
|
+
/**
|
|
305
|
+
* The module the app imports `getT` from when it is not `next-i18next/server` (`createServerI18next` in its
|
|
306
|
+
* own `i18n.server.ts`, so no init order matters): an alias as written, a relative one as an absolute path.
|
|
307
|
+
*/
|
|
308
|
+
function findServerModule(contents) {
|
|
309
|
+
for (const [file, code] of contents) {
|
|
310
|
+
for (const [, names, source] of code.matchAll(/import\s*\{([^}]*)\}\s*from\s*['"]([^'"]+)['"]/g)) {
|
|
311
|
+
if (!/\bgetT\b/.test(names) || source === 'next-i18next/server')
|
|
312
|
+
continue;
|
|
313
|
+
return source.startsWith('.') ? node_path.resolve(node_path.dirname(file), source) : source;
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
return undefined;
|
|
317
|
+
}
|
|
318
|
+
/** The specifier a file imports `getT` with: `next-i18next/server`, the app's alias, or a path relative to it. */
|
|
319
|
+
function serverModuleFor(serverModule, file) {
|
|
320
|
+
if (!serverModule)
|
|
321
|
+
return 'next-i18next/server';
|
|
322
|
+
if (!node_path.isAbsolute(serverModule))
|
|
323
|
+
return serverModule;
|
|
324
|
+
const rel = node_path.relative(node_path.dirname(node_path.resolve(file)), serverModule).replace(/\\/g, '/').replace(/\.(?:tsx?|jsx?|mjs)$/, '');
|
|
325
|
+
return rel.startsWith('.') ? rel : `./${rel}`;
|
|
326
|
+
}
|
|
327
|
+
/** A page of the Pages Router (not `_app`, `_document`, `_error` or an API route), which loads its own translations. */
|
|
328
|
+
function isPagesRoute(file) {
|
|
329
|
+
const rel = nextFiles.projectPath(file);
|
|
330
|
+
return rel.startsWith('pages/') && !/^pages\/(?:_app|_document|_error|api\/)/.test(rel);
|
|
331
|
+
}
|
|
332
|
+
/** next-i18next has a config of its own already: `i18n.config.*` (App Router) or `next-i18next.config.*` (Pages Router). */
|
|
333
|
+
async function nextI18nextConfigured() {
|
|
334
|
+
const names = ['i18n.config', 'next-i18next.config'].flatMap(name => ['ts', 'js', 'mjs', 'cjs'].map(ext => `${name}.${ext}`));
|
|
335
|
+
for (const name of names) {
|
|
336
|
+
if (await fileExists(node_path.join(process.cwd(), name)) || await fileExists(node_path.join(process.cwd(), 'src', name)))
|
|
337
|
+
return true;
|
|
338
|
+
}
|
|
339
|
+
return false;
|
|
340
|
+
}
|
|
341
|
+
/** An import of i18next or react-i18next (`.init()` alone is any library's: `Sentry.init()`). */
|
|
342
|
+
const I18NEXT_IMPORT_RE = /\bfrom\s*['"](?:i18next|react-i18next)['"]|\brequire\(\s*['"](?:i18next|react-i18next)['"]\s*\)/;
|
|
343
|
+
const MODULE_SCOPE_WARNING = 'A t() call there runs once at import time — before i18next may be initialized — and never updates on language change. ' +
|
|
344
|
+
'Move the text into a component/hook (e.g. a useSections() hook calling useTranslation()), or read the key at render time. ' +
|
|
345
|
+
'See: https://www.locize.com/blog/how-to-use-i18next-t-outside-react-components/';
|
|
221
346
|
/**
|
|
222
347
|
* Scans a source file for hardcoded string candidates and React component boundaries.
|
|
223
348
|
*/
|
|
224
|
-
async function scanFileForCandidates(content, file, config) {
|
|
349
|
+
async function scanFileForCandidates(content, file, config, nextKind) {
|
|
225
350
|
const candidates = [];
|
|
226
351
|
const components = [];
|
|
227
352
|
const languageChangeSites = [];
|
|
228
353
|
let moduleScopeSkipped = 0;
|
|
354
|
+
let ownTSkipped = 0;
|
|
355
|
+
let imports;
|
|
356
|
+
const memoHooks = [];
|
|
357
|
+
let pluralHelperImports;
|
|
358
|
+
const dropped = [];
|
|
229
359
|
const fileExt = node_path.extname(file).toLowerCase();
|
|
230
360
|
const isTypeScriptFile = ['.ts', '.tsx', '.mts', '.cts'].includes(fileExt);
|
|
231
361
|
const isTSX = fileExt === '.tsx';
|
|
@@ -273,22 +403,47 @@ async function scanFileForCandidates(content, file, config) {
|
|
|
273
403
|
// indices — without the conversion every emoji / accented char / CJK char
|
|
274
404
|
// shifts all subsequent offsets.
|
|
275
405
|
astUtils.normalizeSpansToCharIndices(ast, content);
|
|
406
|
+
imports = ast.body
|
|
407
|
+
.filter((item) => item.type === 'ImportDeclaration')
|
|
408
|
+
.map((item) => ({
|
|
409
|
+
source: item.source.value,
|
|
410
|
+
start: item.span.start,
|
|
411
|
+
end: item.span.end,
|
|
412
|
+
locals: (item.specifiers ?? []).map((spec) => spec.local?.value).filter(Boolean)
|
|
413
|
+
}));
|
|
414
|
+
collectMemoHooks(ast, memoHooks);
|
|
276
415
|
// Detect React function component boundaries
|
|
277
|
-
detectComponentBoundaries(ast, content, components);
|
|
416
|
+
detectComponentBoundaries(ast, content, components, nextKind === 'server');
|
|
278
417
|
// Collect function spans so module-scope strings can be excluded below
|
|
279
418
|
const functionSpans = [];
|
|
280
419
|
collectFunctionSpans(ast, functionSpans);
|
|
420
|
+
// Next.js reads the texts of `export const metadata` once; generateMetadata() can get them with getT()
|
|
421
|
+
if (nextKind === 'server' && !/\bgenerateMetadata\b/.test(content)) {
|
|
422
|
+
const metadata = metadataExport(ast, content);
|
|
423
|
+
if (metadata) {
|
|
424
|
+
components.push(metadata);
|
|
425
|
+
functionSpans.push({ start: metadata.bodyStart, end: metadata.bodyEnd });
|
|
426
|
+
}
|
|
427
|
+
}
|
|
281
428
|
// Visit AST to find string literals; the object form of extract.acceptedAttributes
|
|
282
429
|
// sets which attributes hold text per JSX element
|
|
283
430
|
const attributeRules = config.extract.acceptedAttributes;
|
|
284
431
|
const jsx = attributeRules && !Array.isArray(attributeRules)
|
|
285
432
|
? { rules: attributeRules, aliases: jsxAttributes.importAliases(ast) }
|
|
286
433
|
: undefined;
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
434
|
+
consoleOnlyNames.set(file, collectConsoleOnlyNames(ast));
|
|
435
|
+
fileDataStrings.set(file, collectDataStrings(ast));
|
|
436
|
+
try {
|
|
437
|
+
visitNodeForStrings(ast, content, file, config, candidates, jsx);
|
|
438
|
+
// Detect JSX interpolation patterns (merge adjacent text + expression children)
|
|
439
|
+
detectJSXInterpolation(ast, content, file, config, candidates);
|
|
440
|
+
// Detect plural conditional patterns (ternary chains checking count === 0/1/other)
|
|
441
|
+
detectPluralPatterns(ast, content, file, config, candidates);
|
|
442
|
+
}
|
|
443
|
+
finally {
|
|
444
|
+
consoleOnlyNames.delete(file);
|
|
445
|
+
fileDataStrings.delete(file);
|
|
446
|
+
}
|
|
292
447
|
// Detect language-change call sites (e.g. updateSettings({ language: code }))
|
|
293
448
|
detectLanguageChangeSites(ast, content, languageChangeSites);
|
|
294
449
|
// Annotate candidates with their enclosing component (if any)
|
|
@@ -300,6 +455,15 @@ async function scanFileForCandidates(content, file, config) {
|
|
|
300
455
|
}
|
|
301
456
|
}
|
|
302
457
|
}
|
|
458
|
+
// A component whose `t` is something else (`const [t, setT] = useState(0)`) keeps its texts: a t() call
|
|
459
|
+
// there would call that `t`
|
|
460
|
+
const ownT = new Set(components.filter(c => c.ownT).map(c => c.name));
|
|
461
|
+
if (ownT.size) {
|
|
462
|
+
const keep = candidates.filter(c => !c.insideComponent || !ownT.has(c.insideComponent));
|
|
463
|
+
ownTSkipped = candidates.length - keep.length;
|
|
464
|
+
candidates.length = 0;
|
|
465
|
+
candidates.push(...keep);
|
|
466
|
+
}
|
|
303
467
|
// Drop module-scope candidates: wrapping them yields a t() call evaluated
|
|
304
468
|
// once at import time — possibly before i18next is initialized, and never
|
|
305
469
|
// re-evaluated on language change. See issue #278.
|
|
@@ -310,6 +474,15 @@ async function scanFileForCandidates(content, file, config) {
|
|
|
310
474
|
candidates.length = 0;
|
|
311
475
|
candidates.push(...keep);
|
|
312
476
|
}
|
|
477
|
+
if (nextKind) {
|
|
478
|
+
dropped.push(...dropForNextI18next(candidates, components, nextKind, isApiRoute(file), serverDirectiveSpans(ast)));
|
|
479
|
+
// next-i18next switches the language through the route or useChangeLanguage(): `i18n.changeLanguage()`
|
|
480
|
+
// would change the client instance alone. A call of that switch is no site at all.
|
|
481
|
+
const sites = languageChangeSites.filter(site => !/^(?:\w+\.)?changeLanguage\(/.test(content.slice(site.callStart, site.callEnd)));
|
|
482
|
+
if (sites.length)
|
|
483
|
+
dropped.push({ message: NEXT_LANGUAGE_CHANGE, count: sites.length, lines: sites.map(site => site.line) });
|
|
484
|
+
languageChangeSites.length = 0;
|
|
485
|
+
}
|
|
313
486
|
// Annotate language change sites with their enclosing component (if any)
|
|
314
487
|
for (const site of languageChangeSites) {
|
|
315
488
|
for (const comp of components) {
|
|
@@ -339,11 +512,131 @@ async function scanFileForCandidates(content, file, config) {
|
|
|
339
512
|
candidates.length = 0;
|
|
340
513
|
candidates.push(...keep);
|
|
341
514
|
}
|
|
515
|
+
const helperNames = new Set(candidates.map(c => c.pluralHelper).filter((n) => !!n));
|
|
516
|
+
if (helperNames.size)
|
|
517
|
+
pluralHelperImports = findPluralHelperImports(ast, content, helperNames);
|
|
518
|
+
// Two candidates whose spans overlap cannot both be rewritten (a template literal in another one's `${}`):
|
|
519
|
+
// the outer one wins, the inner text stays in its interpolation value as written
|
|
520
|
+
const bySize = [...candidates].sort((a, b) => (b.endOffset - b.offset) - (a.endOffset - a.offset));
|
|
521
|
+
const kept = new Set();
|
|
522
|
+
for (const c of bySize) {
|
|
523
|
+
if (![...kept].some(k => c.offset < k.endOffset && k.offset < c.endOffset))
|
|
524
|
+
kept.add(c);
|
|
525
|
+
}
|
|
526
|
+
if (kept.size < candidates.length) {
|
|
527
|
+
const keep = candidates.filter(c => kept.has(c));
|
|
528
|
+
candidates.length = 0;
|
|
529
|
+
candidates.push(...keep);
|
|
530
|
+
}
|
|
342
531
|
}
|
|
343
532
|
catch (err) {
|
|
344
533
|
// Silently skip files that can't be parsed
|
|
345
534
|
}
|
|
346
|
-
return { candidates, components, languageChangeSites, moduleScopeSkipped };
|
|
535
|
+
return { candidates, components, languageChangeSites, moduleScopeSkipped, ownTSkipped, imports, memoHooks, pluralHelperImports, dropped };
|
|
536
|
+
}
|
|
537
|
+
/** `export const metadata = { title: '…' }` (with or without a type) as the scope of a generateMetadata() to be. */
|
|
538
|
+
function metadataExport(ast, content) {
|
|
539
|
+
for (const item of ast.body ?? []) {
|
|
540
|
+
const decl = item.type === 'ExportDeclaration' ? item.declaration : null;
|
|
541
|
+
const [declarator] = decl?.type === 'VariableDeclaration' && decl.declarations?.length === 1 ? decl.declarations : [];
|
|
542
|
+
if (declarator?.id?.value !== 'metadata' || declarator.init?.type !== 'ObjectExpression')
|
|
543
|
+
continue;
|
|
544
|
+
const annotation = declarator.id.typeAnnotation?.typeAnnotation;
|
|
545
|
+
return {
|
|
546
|
+
name: `metadata@${declarator.init.span.start}`,
|
|
547
|
+
bodyStart: declarator.init.span.start,
|
|
548
|
+
bodyEnd: declarator.init.span.end,
|
|
549
|
+
hasUseTranslation: false,
|
|
550
|
+
expressionBody: true,
|
|
551
|
+
isAsync: true,
|
|
552
|
+
metadataHead: {
|
|
553
|
+
start: decl.span.start,
|
|
554
|
+
end: declarator.init.span.start,
|
|
555
|
+
type: annotation?.span ? content.slice(annotation.span.start, annotation.span.end) : undefined
|
|
556
|
+
}
|
|
557
|
+
};
|
|
558
|
+
}
|
|
559
|
+
return null;
|
|
560
|
+
}
|
|
561
|
+
/** A route handler (`route.ts` under `app/`, a file under `pages/api/`): its texts are responses of an API, not of a page. */
|
|
562
|
+
function isApiRoute(file) {
|
|
563
|
+
const rel = nextFiles.projectPath(file);
|
|
564
|
+
return /^app\/(?:.*\/)?route\.[cm]?[jt]sx?$/.test(rel) || rel.startsWith('pages/api/');
|
|
565
|
+
}
|
|
566
|
+
/**
|
|
567
|
+
* The functions that run as Server Actions or cached (`'use server'`, `'use cache'` as their first statement), all
|
|
568
|
+
* of the file for such a directive at its top: they have no root params, so getT() there needs `{ lng }` passed in.
|
|
569
|
+
*/
|
|
570
|
+
function serverDirectiveSpans(ast) {
|
|
571
|
+
const directive = (stmts) => stmts.some((st) => st.type === 'ExpressionStatement' &&
|
|
572
|
+
st.expression?.type === 'StringLiteral' && /^use (?:server|cache)\b/.test(st.expression.value));
|
|
573
|
+
// the directive prologue: the string statements a body or module starts with
|
|
574
|
+
const leading = (stmts = []) => {
|
|
575
|
+
const end = stmts.findIndex((st) => st.type !== 'ExpressionStatement' || st.expression?.type !== 'StringLiteral');
|
|
576
|
+
return end < 0 ? stmts : stmts.slice(0, end);
|
|
577
|
+
};
|
|
578
|
+
if (directive(leading(ast.body)))
|
|
579
|
+
return [{ start: 0, end: Infinity }];
|
|
580
|
+
const spans = [];
|
|
581
|
+
const walk = (node) => {
|
|
582
|
+
if (!node || typeof node !== 'object')
|
|
583
|
+
return;
|
|
584
|
+
if (FUNCTION_LIKE.has(node.type) && isBlockBody(node.body) && directive(leading(node.body.stmts))) {
|
|
585
|
+
spans.push({ start: node.body.span.start, end: node.body.span.end });
|
|
586
|
+
return;
|
|
587
|
+
}
|
|
588
|
+
for (const key in node) {
|
|
589
|
+
const value = node[key];
|
|
590
|
+
if (Array.isArray(value))
|
|
591
|
+
value.forEach(walk);
|
|
592
|
+
else if (value && typeof value === 'object' && key !== 'span')
|
|
593
|
+
walk(value);
|
|
594
|
+
}
|
|
595
|
+
};
|
|
596
|
+
walk(ast);
|
|
597
|
+
return spans;
|
|
598
|
+
}
|
|
599
|
+
const NEXT_API = 'Left API routes as they are: their texts are responses, not pages (getT() there needs { lng } from the request).';
|
|
600
|
+
const NEXT_DIRECTIVE = "Left Server Actions and cached functions ('use server', 'use cache') as they are: getT() there needs { lng } passed in.";
|
|
601
|
+
const NEXT_UNKNOWN = "Skipped the texts of files that no page or layout imports (as far as the imports resolve), so it is not known whether Server or Client Components render them: add 'use client' to a Client Component, then run instrument again.";
|
|
602
|
+
const NEXT_OUTSIDE = 'Skipped texts outside components: next-i18next has no global t(). Move them into a component (or, in a Server Component file, an async function), then run instrument again.';
|
|
603
|
+
const NEXT_SHARED = 'Skipped the texts of components that Server and Client Components both render, where neither getT() nor a hook works: give them a `t` prop (from getT() or useT() in the callers), then run instrument again.';
|
|
604
|
+
const NEXT_WRAPPED = 'Skipped the texts of Server Components wrapped in a call (memo, forwardRef), which cannot become async for getT().';
|
|
605
|
+
const NEXT_LANGUAGE_CHANGE = 'Language switches left as they are: next-i18next changes the language through the route (/de/…) or useChangeLanguage() from next-i18next/client. Wire these by hand.';
|
|
606
|
+
/**
|
|
607
|
+
* Takes out the candidates next-i18next cannot translate where they are: outside a component (no global `t`), in
|
|
608
|
+
* a component rendered on both sides without a `t` prop, a <Trans> there, in a Server Component that cannot
|
|
609
|
+
* become async. Returns what it dropped, by reason.
|
|
610
|
+
*/
|
|
611
|
+
function dropForNextI18next(candidates, components, kind, apiRoute, directiveSpans) {
|
|
612
|
+
const componentOf = (c) => components.find(comp => comp.name === c.insideComponent);
|
|
613
|
+
const reasonOf = (c) => {
|
|
614
|
+
if (apiRoute)
|
|
615
|
+
return NEXT_API;
|
|
616
|
+
if (directiveSpans.some(span => c.offset >= span.start && c.endOffset <= span.end))
|
|
617
|
+
return NEXT_DIRECTIVE;
|
|
618
|
+
const comp = componentOf(c);
|
|
619
|
+
// a <Trans> takes its `t` from the React context, in any render code of a Client Component
|
|
620
|
+
if (!comp)
|
|
621
|
+
return c.type === 'jsx-mixed' && (kind === 'client' || kind === 'pages') ? null : NEXT_OUTSIDE;
|
|
622
|
+
// with `t` and `i18n` props, a <Trans> takes them both and works on either side
|
|
623
|
+
if ((kind === 'shared' || kind === 'unknown') && (!comp.hasUseTranslation || (c.type === 'jsx-mixed' && !comp.i18nParam))) {
|
|
624
|
+
return kind === 'shared' ? NEXT_SHARED : NEXT_UNKNOWN;
|
|
625
|
+
}
|
|
626
|
+
if (kind === 'server' && comp.wrapped && !comp.hasUseTranslation)
|
|
627
|
+
return NEXT_WRAPPED;
|
|
628
|
+
return null;
|
|
629
|
+
};
|
|
630
|
+
const counts = new Map();
|
|
631
|
+
const keep = candidates.filter(c => {
|
|
632
|
+
const reason = reasonOf(c);
|
|
633
|
+
if (reason)
|
|
634
|
+
counts.set(reason, (counts.get(reason) ?? 0) + 1);
|
|
635
|
+
return !reason;
|
|
636
|
+
});
|
|
637
|
+
candidates.length = 0;
|
|
638
|
+
candidates.push(...keep);
|
|
639
|
+
return [...counts].map(([message, count]) => ({ message, count }));
|
|
347
640
|
}
|
|
348
641
|
/**
|
|
349
642
|
* Node types whose span delimits deferred (call-time) evaluation. A string
|
|
@@ -406,7 +699,7 @@ function lineOfOffset(content, offset) {
|
|
|
406
699
|
* - forwardRef wrappers: `const Greeting = React.forwardRef((props, ref) => { ... })`
|
|
407
700
|
* - memo wrappers: `const Greeting = React.memo(() => { ... })`
|
|
408
701
|
*/
|
|
409
|
-
function detectComponentBoundaries(node, content, components) {
|
|
702
|
+
function detectComponentBoundaries(node, content, components, serverFile = false) {
|
|
410
703
|
if (!node)
|
|
411
704
|
return;
|
|
412
705
|
// FunctionDeclaration with uppercase name
|
|
@@ -417,7 +710,8 @@ function detectComponentBoundaries(node, content, components) {
|
|
|
417
710
|
name: node.identifier.value,
|
|
418
711
|
bodyStart: body.span.start,
|
|
419
712
|
bodyEnd: body.span.end,
|
|
420
|
-
|
|
713
|
+
...tBinding(node, body),
|
|
714
|
+
...functionFacts(node)
|
|
421
715
|
});
|
|
422
716
|
}
|
|
423
717
|
}
|
|
@@ -435,7 +729,8 @@ function detectComponentBoundaries(node, content, components) {
|
|
|
435
729
|
name: node.identifier.value,
|
|
436
730
|
bodyStart: body.span.start,
|
|
437
731
|
bodyEnd: body.span.end,
|
|
438
|
-
|
|
732
|
+
...tBinding(node, body),
|
|
733
|
+
...functionFacts(node)
|
|
439
734
|
});
|
|
440
735
|
}
|
|
441
736
|
}
|
|
@@ -461,25 +756,59 @@ function detectComponentBoundaries(node, content, components) {
|
|
|
461
756
|
if (isWrapper && init.arguments?.length > 0) {
|
|
462
757
|
const arg = init.arguments[0]?.expression || init.arguments[0];
|
|
463
758
|
if (arg && (arg.type === 'ArrowFunctionExpression' || arg.type === 'FunctionExpression')) {
|
|
464
|
-
addComponentFromFunctionNode(node.id.value, arg, content, components);
|
|
759
|
+
addComponentFromFunctionNode(node.id.value, arg, content, components, true);
|
|
465
760
|
}
|
|
466
761
|
}
|
|
467
762
|
}
|
|
468
763
|
}
|
|
469
764
|
}
|
|
765
|
+
// Not a component, but a function with a `t` of its own (`const { t } = await getT()` in `generateMetadata`,
|
|
766
|
+
// a custom hook), or in a Server Component file one that can await getT(): an async one, or the metadata
|
|
767
|
+
// functions Next.js awaits
|
|
768
|
+
if (FUNCTION_LIKE.has(node.type) && node.body?.span && !components.some(c => c.bodyStart === node.body.span.start)) {
|
|
769
|
+
const name = node.identifier?.value;
|
|
770
|
+
const ownHook = isBlockBody(node.body) && bindsT({}, node.body) === 'translation';
|
|
771
|
+
if (ownHook || (serverFile && (node.async || /^generate(?:Metadata|Viewport)$/.test(name ?? '')))) {
|
|
772
|
+
addComponentFromFunctionNode(`${name ?? 'function'}@${node.body.span.start}`, node, content, components, false, true);
|
|
773
|
+
}
|
|
774
|
+
}
|
|
470
775
|
// Recurse into children
|
|
471
776
|
for (const key in node) {
|
|
472
777
|
const value = node[key];
|
|
473
778
|
if (value && typeof value === 'object') {
|
|
474
779
|
if (Array.isArray(value)) {
|
|
475
|
-
value.forEach(item => detectComponentBoundaries(item, content, components));
|
|
780
|
+
value.forEach(item => detectComponentBoundaries(item, content, components, serverFile));
|
|
476
781
|
}
|
|
477
782
|
else {
|
|
478
|
-
detectComponentBoundaries(value, content, components);
|
|
783
|
+
detectComponentBoundaries(value, content, components, serverFile);
|
|
479
784
|
}
|
|
480
785
|
}
|
|
481
786
|
}
|
|
482
787
|
}
|
|
788
|
+
const FUNCTION_LIKE = new Set(['FunctionDeclaration', 'FunctionExpression', 'ArrowFunctionExpression']);
|
|
789
|
+
/** Where a function starts, whether it is async, and the translation hook it calls without taking `t`. */
|
|
790
|
+
function functionFacts(fnNode, wrapped = false) {
|
|
791
|
+
const facts = { start: fnNode.span?.start, isAsync: !!fnNode.async };
|
|
792
|
+
if (wrapped)
|
|
793
|
+
facts.wrapped = true;
|
|
794
|
+
if ((fnNode.params ?? []).some((p) => patternBinds(p, 'i18n')))
|
|
795
|
+
facts.i18nParam = true;
|
|
796
|
+
const returnType = fnNode.returnType?.typeAnnotation?.span;
|
|
797
|
+
if (returnType)
|
|
798
|
+
facts.returnType = { start: returnType.start, end: returnType.end };
|
|
799
|
+
for (const stmt of isBlockBody(fnNode.body) ? fnNode.body.stmts ?? [] : []) {
|
|
800
|
+
for (const d of stmt.type === 'VariableDeclaration' ? stmt.declarations ?? [] : []) {
|
|
801
|
+
const call = d.init?.type === 'AwaitExpression' ? d.init.argument : d.init;
|
|
802
|
+
const hook = call?.type === 'CallExpression' ? dottedName(call.callee)?.split('.').pop() : null;
|
|
803
|
+
const props = d.id?.type === 'ObjectPattern' ? d.id.properties ?? [] : [];
|
|
804
|
+
if (!hook || !HOOK_CALL_RE.test(hook) || !props.length || props.some((p) => p.type === 'RestElement'))
|
|
805
|
+
continue;
|
|
806
|
+
facts.hookPattern = { statement: stmt.span.start, first: props[0].span.start, last: props[props.length - 1].span.end, names: props.map((p) => p.key?.value).filter(Boolean) };
|
|
807
|
+
return facts;
|
|
808
|
+
}
|
|
809
|
+
}
|
|
810
|
+
return facts;
|
|
811
|
+
}
|
|
483
812
|
/**
|
|
484
813
|
* swc >=1.16 types function bodies as 'FunctionBody'; older versions used 'BlockStatement'.
|
|
485
814
|
*/
|
|
@@ -490,17 +819,85 @@ function isBlockBody(body) {
|
|
|
490
819
|
* Helper: extracts a ComponentBoundary from an ArrowFunctionExpression or FunctionExpression
|
|
491
820
|
* that has a block body.
|
|
492
821
|
*/
|
|
493
|
-
function addComponentFromFunctionNode(name, fnNode, content, components) {
|
|
822
|
+
function addComponentFromFunctionNode(name, fnNode, content, components, wrapped = false, anyExpressionBody = false) {
|
|
494
823
|
const body = fnNode.body;
|
|
495
|
-
if (body
|
|
824
|
+
if (isBlockBody(body) && body.span) {
|
|
825
|
+
components.push({
|
|
826
|
+
name,
|
|
827
|
+
bodyStart: body.span.start,
|
|
828
|
+
bodyEnd: body.span.end,
|
|
829
|
+
...tBinding(fnNode, body),
|
|
830
|
+
...functionFacts(fnNode, wrapped)
|
|
831
|
+
});
|
|
832
|
+
}
|
|
833
|
+
else if ((isJSXExpression(body) || anyExpressionBody) && body?.span) {
|
|
834
|
+
// `const Hint = () => <p>…</p>`: a component too; its body becomes a block when it needs the hook
|
|
835
|
+
// (as does `async () => ({ title: … })`, a server function)
|
|
496
836
|
components.push({
|
|
497
837
|
name,
|
|
498
838
|
bodyStart: body.span.start,
|
|
499
839
|
bodyEnd: body.span.end,
|
|
500
|
-
|
|
840
|
+
...tBinding(fnNode, {}),
|
|
841
|
+
...functionFacts(fnNode, wrapped),
|
|
842
|
+
expressionBody: true
|
|
501
843
|
});
|
|
502
844
|
}
|
|
503
845
|
}
|
|
846
|
+
/** JSX, possibly in parentheses. */
|
|
847
|
+
function isJSXExpression(expr) {
|
|
848
|
+
if (expr?.type === 'ParenthesisExpression')
|
|
849
|
+
return isJSXExpression(expr.expression);
|
|
850
|
+
return expr?.type === 'JSXElement' || expr?.type === 'JSXFragment';
|
|
851
|
+
}
|
|
852
|
+
/**
|
|
853
|
+
* The `t` a component has already: `'translation'` for a parameter (`({ t })`, a prop passed down) or one
|
|
854
|
+
* destructured from a translation hook (`const { t } = useTranslation('ns')`, also re-exported or renamed:
|
|
855
|
+
* `useT`, `useAppTranslation`, `getTranslations`), `'other'` for any other `t` in its body
|
|
856
|
+
* (`const [t, setT] = useState(0)`), null for none. Another `const { t }` would be a redeclaration, and the
|
|
857
|
+
* `t()` calls would call the other `t`.
|
|
858
|
+
*/
|
|
859
|
+
function bindsT(fnNode, body) {
|
|
860
|
+
if ((fnNode.params ?? []).some((p) => patternBinds(p, 't')))
|
|
861
|
+
return 'translation';
|
|
862
|
+
for (const stmt of body.stmts ?? []) {
|
|
863
|
+
if (stmt.type === 'FunctionDeclaration' && stmt.identifier?.value === 't')
|
|
864
|
+
return 'other';
|
|
865
|
+
for (const d of stmt.type === 'VariableDeclaration' ? stmt.declarations ?? [] : []) {
|
|
866
|
+
if (!patternBinds(d.id, 't'))
|
|
867
|
+
continue;
|
|
868
|
+
const call = d.init?.type === 'AwaitExpression' ? d.init.argument : d.init;
|
|
869
|
+
const hook = call?.type === 'CallExpression' ? dottedName(call.callee)?.split('.').pop() : null;
|
|
870
|
+
// `const t = i18n.getFixedT(lng, 'footer')` is one too
|
|
871
|
+
if (d.id.type === 'Identifier' && hook === 'getFixedT')
|
|
872
|
+
return 'translation';
|
|
873
|
+
return d.id.type === 'ObjectPattern' && hook && TRANSLATION_HOOK_RE.test(hook) ? 'translation' : 'other';
|
|
874
|
+
}
|
|
875
|
+
}
|
|
876
|
+
return null;
|
|
877
|
+
}
|
|
878
|
+
/** The translation hooks a call to which can take `t` as well; an app's own `useRoleTranslations()` returns data. */
|
|
879
|
+
const HOOK_CALL_RE = /^(?:useTranslation|useT|getT)$/;
|
|
880
|
+
/** Names of the hooks and functions that give a translation `t`. */
|
|
881
|
+
const TRANSLATION_HOOK_RE = /^(?:use|get)\w*(?:Translation|T|I18n|Intl)\w*$/;
|
|
882
|
+
/** A component's `hasUseTranslation`, and `ownT` when its `t` is something else (see `bindsT`). */
|
|
883
|
+
function tBinding(fnNode, body) {
|
|
884
|
+
const kind = bindsT(fnNode, body);
|
|
885
|
+
return kind === 'other' ? { hasUseTranslation: true, ownT: true } : { hasUseTranslation: kind === 'translation' };
|
|
886
|
+
}
|
|
887
|
+
/** Whether a binding pattern (a parameter, a destructuring) binds `name`; defaults and renamed keys aside. */
|
|
888
|
+
function patternBinds(pat, name) {
|
|
889
|
+
switch (pat?.type) {
|
|
890
|
+
case 'Identifier': return pat.value === name;
|
|
891
|
+
case 'Parameter': return patternBinds(pat.pat, name);
|
|
892
|
+
case 'AssignmentPattern': return patternBinds(pat.left, name);
|
|
893
|
+
case 'RestElement': return patternBinds(pat.argument, name);
|
|
894
|
+
case 'ArrayPattern': return (pat.elements ?? []).some((e) => patternBinds(e, name));
|
|
895
|
+
case 'ObjectPattern': return (pat.properties ?? []).some((p) => p.type === 'KeyValuePatternProperty'
|
|
896
|
+
? patternBinds(p.value, name)
|
|
897
|
+
: p.type === 'AssignmentPatternProperty' ? p.key?.value === name : patternBinds(p.argument, name));
|
|
898
|
+
default: return false;
|
|
899
|
+
}
|
|
900
|
+
}
|
|
504
901
|
// Non-translatable JSX attributes are defined in utils/jsx-attributes.ts
|
|
505
902
|
// and shared with the linter. The instrumenter uses `ignoredAttributeSet`
|
|
506
903
|
// to skip recursing into non-translatable attribute values.
|
|
@@ -508,22 +905,183 @@ function addComponentFromFunctionNode(name, fnNode, content, components) {
|
|
|
508
905
|
* Returns true when the AST node is a `t(...)` or `i18next.t(...)` call
|
|
509
906
|
* expression — i.e. code that was already instrumented.
|
|
510
907
|
*/
|
|
511
|
-
function isTranslationCall(node) {
|
|
908
|
+
function isTranslationCall(node, functions = []) {
|
|
909
|
+
const name = dottedName(node.callee);
|
|
910
|
+
if (!name)
|
|
911
|
+
return false;
|
|
912
|
+
// t(...), $t(...), i18next.t(...), props.t(...), this.$t(...), and the project's own (`extract.functions`)
|
|
913
|
+
return name === 't' || name === '$t' || /\.\$?t$/.test(name) || functions.some(fn => functionMatcher.matchesFunctionPattern(name, fn));
|
|
914
|
+
}
|
|
915
|
+
/** A callee as a dotted name (`this.props.t`, `i18n.t`), or null for a computed one. */
|
|
916
|
+
function dottedName(callee) {
|
|
917
|
+
if (callee?.type === 'Identifier')
|
|
918
|
+
return callee.value;
|
|
919
|
+
if (callee?.type === 'ThisExpression')
|
|
920
|
+
return 'this';
|
|
921
|
+
if (callee?.type !== 'MemberExpression' || callee.property?.type !== 'Identifier')
|
|
922
|
+
return null;
|
|
923
|
+
const object = dottedName(callee.object);
|
|
924
|
+
return object && `${object}.${callee.property.value}`;
|
|
925
|
+
}
|
|
926
|
+
/**
|
|
927
|
+
* Methods whose string arguments are never text shown to a user: selectors, attribute and storage names,
|
|
928
|
+
* and the strings a text is searched for or compared with (translating `msg.includes('not found')` breaks it).
|
|
929
|
+
*/
|
|
930
|
+
const NON_TEXT_METHODS = new Set([
|
|
931
|
+
'querySelector', 'querySelectorAll', 'closest', 'matches', 'getElementById', 'getElementsByClassName',
|
|
932
|
+
'getElementsByTagName', 'getElementsByName', 'addEventListener', 'removeEventListener',
|
|
933
|
+
'getAttribute', 'hasAttribute', 'removeAttribute', 'getPropertyValue', 'setProperty', 'removeProperty',
|
|
934
|
+
'getItem', 'setItem', 'removeItem',
|
|
935
|
+
// analytics event and user names: a translated one splits the data by language
|
|
936
|
+
'track', 'trackEvent', 'logEvent', 'capture', 'captureMessage', 'captureException', 'identify',
|
|
937
|
+
// event names, and format patterns (`dayjs(d).format('DD MMM YYYY')`)
|
|
938
|
+
'emit', 'on', 'once', 'off', 'addListener', 'removeListener', 'format',
|
|
939
|
+
'indexOf', 'lastIndexOf', 'includes', 'startsWith', 'endsWith', 'match', 'matchAll', 'search', 'replace',
|
|
940
|
+
'replaceAll', 'split', 'localeCompare'
|
|
941
|
+
]);
|
|
942
|
+
/**
|
|
943
|
+
* Functions whose string arguments are never text: `gtag('event', 'Sign Up Completed')`, `require('x')`,
|
|
944
|
+
* `RegExp('…')`, `format(date, 'yyyy-MM-dd')`.
|
|
945
|
+
*/
|
|
946
|
+
const NON_TEXT_FUNCTIONS = new Set(['gtag', 'require', 'RegExp', 'format']);
|
|
947
|
+
/** Objects whose method calls are logs or error reports, for developers whatever they say. */
|
|
948
|
+
const LOG_OBJECTS = /^(?:logger|log|Sentry|sentry|Bugsnag|bugsnag|Rollbar|rollbar|winston|pino)$/;
|
|
949
|
+
/** A call to one of `NON_TEXT_METHODS` or `NON_TEXT_FUNCTIONS` (`el.closest('button, a')`, `gtag(…)`). */
|
|
950
|
+
function isNonTextMethodCall(node) {
|
|
512
951
|
const callee = node.callee;
|
|
513
|
-
if (
|
|
952
|
+
if (callee?.type === 'Identifier')
|
|
953
|
+
return NON_TEXT_FUNCTIONS.has(callee.value);
|
|
954
|
+
if (callee?.type !== 'MemberExpression' || callee.property?.type !== 'Identifier')
|
|
514
955
|
return false;
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
956
|
+
return NON_TEXT_METHODS.has(callee.property.value) || (callee.object?.type === 'Identifier' && LOG_OBJECTS.test(callee.object.value));
|
|
957
|
+
}
|
|
958
|
+
/**
|
|
959
|
+
* The names of a file's variables whose every use is inside a `console.*` call: a variable declared twice
|
|
960
|
+
* counts as one name, and any use elsewhere takes it out.
|
|
961
|
+
*/
|
|
962
|
+
function collectConsoleOnlyNames(ast) {
|
|
963
|
+
const declared = new Set();
|
|
964
|
+
const inConsole = new Set();
|
|
965
|
+
const elsewhere = new Set();
|
|
966
|
+
const walk = (node, inLog) => {
|
|
967
|
+
if (!node || typeof node !== 'object')
|
|
968
|
+
return;
|
|
969
|
+
if (Array.isArray(node)) {
|
|
970
|
+
node.forEach(n => walk(n, inLog));
|
|
971
|
+
return;
|
|
972
|
+
}
|
|
973
|
+
if (node.type === 'VariableDeclarator') {
|
|
974
|
+
if (node.id?.type === 'Identifier')
|
|
975
|
+
declared.add(node.id.value);
|
|
976
|
+
else
|
|
977
|
+
walk(node.id, inLog);
|
|
978
|
+
walk(node.init, inLog);
|
|
979
|
+
return;
|
|
980
|
+
}
|
|
981
|
+
if (node.type === 'MemberExpression') {
|
|
982
|
+
walk(node.object, inLog);
|
|
983
|
+
if (node.property?.type === 'Computed')
|
|
984
|
+
walk(node.property, inLog);
|
|
985
|
+
return;
|
|
986
|
+
}
|
|
987
|
+
if (node.type === 'KeyValueProperty') {
|
|
988
|
+
walk(node.value, inLog);
|
|
989
|
+
return;
|
|
990
|
+
}
|
|
991
|
+
if (node.type === 'Identifier')
|
|
992
|
+
(inLog ? inConsole : elsewhere).add(node.value);
|
|
993
|
+
const log = inLog || (node.type === 'CallExpression' && isConsoleCall(node));
|
|
994
|
+
for (const key in node)
|
|
995
|
+
if (key !== 'span')
|
|
996
|
+
walk(node[key], log);
|
|
997
|
+
};
|
|
998
|
+
walk(ast, false);
|
|
999
|
+
return new Set([...declared].filter(n => inConsole.has(n) && !elsewhere.has(n)));
|
|
1000
|
+
}
|
|
1001
|
+
/** Per file, the names `collectConsoleOnlyNames` found for its content (set by the scan, read by the visit). */
|
|
1002
|
+
const consoleOnlyNames = new Map();
|
|
1003
|
+
/** The property names whose value is text (`label`, `title`, …), lower-cased. */
|
|
1004
|
+
const translatablePropertyLowerSet = new Set([...jsxAttributes.translatablePropertySet].map(p => p.toLowerCase()));
|
|
1005
|
+
/** String literals a JSX element renders (see `markRendered`): text whatever their words. */
|
|
1006
|
+
const renderedStrings = new WeakSet();
|
|
1007
|
+
/** Marks the strings an expression rendered as a JSX child can produce: itself, a branch, a fallback. */
|
|
1008
|
+
function markRendered(expr) {
|
|
1009
|
+
if (!expr)
|
|
1010
|
+
return;
|
|
1011
|
+
if (expr.type === 'StringLiteral')
|
|
1012
|
+
renderedStrings.add(expr);
|
|
1013
|
+
else if (expr.type === 'ConditionalExpression') {
|
|
1014
|
+
markRendered(expr.consequent);
|
|
1015
|
+
markRendered(expr.alternate);
|
|
1016
|
+
}
|
|
1017
|
+
else if (expr.type === 'BinaryExpression' && LOGICAL_OPERATORS.has(expr.operator)) {
|
|
1018
|
+
// swc types `&&`, `||` and `??` as a BinaryExpression
|
|
1019
|
+
markRendered(expr.right);
|
|
1020
|
+
}
|
|
1021
|
+
else if (expr.type === 'ParenthesisExpression')
|
|
1022
|
+
markRendered(expr.expression);
|
|
1023
|
+
}
|
|
1024
|
+
/** Per file, the strings `collectDataStrings` found (set by the scan, read by the visit). */
|
|
1025
|
+
const fileDataStrings = new Map();
|
|
1026
|
+
/** Property and attribute names whose string value is data the code matches against. */
|
|
1027
|
+
const DATA_KEYS = new Set(['id', 'key', 'value', 'type', 'code', 'kind']);
|
|
1028
|
+
/** Names of lists whose strings are values to match (`order: ['2FA', 'no 2FA']`). */
|
|
1029
|
+
const DATA_LISTS = /^(?:order|ids|keys|values|types|kinds|codes)$/i;
|
|
1030
|
+
/**
|
|
1031
|
+
* The strings a file uses as data: compared (`=== 'no 2FA'`), a `case`, an object key, the value of an `id`,
|
|
1032
|
+
* `key`, `value`, `type`, `code` or `kind`, an entry of an `order`/`ids`/`values` list, or an argument of a
|
|
1033
|
+
* method that compares (`includes`). The same string as text elsewhere in that file is then data too: a
|
|
1034
|
+
* facet's `of()` returning `'no 2FA'` must keep matching `order: ['2FA', 'no 2FA']`.
|
|
1035
|
+
*/
|
|
1036
|
+
function collectDataStrings(ast) {
|
|
1037
|
+
const found = new Set();
|
|
1038
|
+
const add = (node) => { if (node?.type === 'StringLiteral')
|
|
1039
|
+
found.add(node.value); };
|
|
1040
|
+
const addList = (node) => { if (node?.type === 'ArrayExpression')
|
|
1041
|
+
for (const e of node.elements ?? [])
|
|
1042
|
+
add(e?.expression); };
|
|
1043
|
+
const walk = (node) => {
|
|
1044
|
+
if (!node || typeof node !== 'object')
|
|
1045
|
+
return;
|
|
1046
|
+
if (Array.isArray(node)) {
|
|
1047
|
+
node.forEach(walk);
|
|
1048
|
+
return;
|
|
1049
|
+
}
|
|
1050
|
+
if (node.type === 'BinaryExpression' && COMPARISON_OPERATORS.has(node.operator)) {
|
|
1051
|
+
add(node.left);
|
|
1052
|
+
add(node.right);
|
|
1053
|
+
}
|
|
1054
|
+
if (node.type === 'SwitchCase')
|
|
1055
|
+
add(node.test);
|
|
1056
|
+
if (node.type === 'KeyValueProperty') {
|
|
1057
|
+
add(node.key);
|
|
1058
|
+
const name = propertyName(node.key);
|
|
1059
|
+
if (name && DATA_KEYS.has(name))
|
|
1060
|
+
add(node.value);
|
|
1061
|
+
if (name && DATA_LISTS.test(name))
|
|
1062
|
+
addList(node.value);
|
|
1063
|
+
}
|
|
1064
|
+
if (node.type === 'VariableDeclarator' && DATA_LISTS.test(node.id?.value ?? ''))
|
|
1065
|
+
addList(node.init);
|
|
1066
|
+
if (node.type === 'JSXAttribute' && DATA_KEYS.has(node.name?.value) && node.value?.type === 'StringLiteral')
|
|
1067
|
+
add(node.value);
|
|
1068
|
+
if (node.type === 'CallExpression' && isNonTextMethodCall(node)) {
|
|
1069
|
+
for (const arg of node.arguments ?? [])
|
|
1070
|
+
add(arg.expression);
|
|
1071
|
+
if (node.callee?.type === 'MemberExpression')
|
|
1072
|
+
addList(node.callee.object);
|
|
1073
|
+
}
|
|
1074
|
+
for (const key in node)
|
|
1075
|
+
if (key !== 'span')
|
|
1076
|
+
walk(node[key]);
|
|
1077
|
+
};
|
|
1078
|
+
walk(ast);
|
|
1079
|
+
return found;
|
|
1080
|
+
}
|
|
1081
|
+
/** `console.log(...)`, `console.warn(...)`: their arguments are for developers, however they are built. */
|
|
1082
|
+
function isConsoleCall(node) {
|
|
1083
|
+
const callee = node.callee;
|
|
1084
|
+
return callee?.type === 'MemberExpression' && callee.object?.type === 'Identifier' && callee.object.value === 'console';
|
|
527
1085
|
}
|
|
528
1086
|
/**
|
|
529
1087
|
* Recursively visits AST nodes to find string literals.
|
|
@@ -536,14 +1094,22 @@ function visitNodeForStrings(node, content, file, config, candidates, jsx) {
|
|
|
536
1094
|
if (node.type === 'JSXOpeningElement' && jsx) {
|
|
537
1095
|
jsx = { ...jsx, element: jsxAttributes.resolveElementAttributes(jsx.rules, jsxAttributes.jsxElementName(node.name, jsx.aliases)) };
|
|
538
1096
|
}
|
|
539
|
-
|
|
540
|
-
//
|
|
541
|
-
//
|
|
542
|
-
if (node.type === 'CallExpression' &&
|
|
1097
|
+
const visit = (child) => visitNodeForStrings(child, content, file, config, candidates, jsx);
|
|
1098
|
+
// Its string arguments are not text; what it is called on and the functions it gets may hold some
|
|
1099
|
+
// (`el.addEventListener('click', () => { status.textContent = 'Copied to clipboard' })`)
|
|
1100
|
+
if (node.type === 'CallExpression' && isNonTextMethodCall(node)) {
|
|
1101
|
+
visit(node.callee);
|
|
1102
|
+
for (const arg of node.arguments ?? [])
|
|
1103
|
+
visitTextHolders(arg.expression, content, file, config, candidates, jsx);
|
|
1104
|
+
return;
|
|
1105
|
+
}
|
|
1106
|
+
const parts = nonTextParts(node, file, config, true);
|
|
1107
|
+
if (parts === 'all')
|
|
543
1108
|
return;
|
|
544
|
-
|
|
545
|
-
|
|
1109
|
+
if (parts) {
|
|
1110
|
+
forEachChild(node, parts, visit);
|
|
546
1111
|
return;
|
|
1112
|
+
}
|
|
547
1113
|
// Skip non-translatable JSX attributes entirely (e.g. className={...})
|
|
548
1114
|
if (node.type === 'JSXAttribute') {
|
|
549
1115
|
const nameNode = node.name;
|
|
@@ -557,31 +1123,47 @@ function visitNodeForStrings(node, content, file, config, candidates, jsx) {
|
|
|
557
1123
|
}
|
|
558
1124
|
// A rule that adds an attribute on this element wins over the built-in skip list (e.g. `name`)
|
|
559
1125
|
const added = attrName != null && jsx?.element?.accepted.has(attrName.toLowerCase());
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
//
|
|
563
|
-
|
|
1126
|
+
// The value of an ignored attribute, or one a rule removed on this element, is not text; but the
|
|
1127
|
+
// elements and functions in it hold text as anywhere else (`action={<Button>change</Button>}`,
|
|
1128
|
+
// `onClick={() => setMessage('Copied')}`)
|
|
1129
|
+
const notText = !!attrName && ((jsxAttributes.ignoredAttributeSet.has(attrName) && !added) ||
|
|
1130
|
+
!!jsx?.element?.removed.has(attrName.toLowerCase()) ||
|
|
1131
|
+
// For hyphenated names (data-testid), also check with the raw text
|
|
1132
|
+
(attrName.includes(':') && jsxAttributes.ignoredAttributeSet.has(attrName.replace(':', '-'))));
|
|
1133
|
+
if (notText) {
|
|
1134
|
+
visitTextHolders(node.value, content, file, config, candidates, jsx);
|
|
564
1135
|
return;
|
|
565
|
-
// For hyphenated names (data-testid), also check with the raw text
|
|
566
|
-
if (attrName?.includes(':')) {
|
|
567
|
-
const hyphenated = attrName.replace(':', '-');
|
|
568
|
-
if (jsxAttributes.ignoredAttributeSet.has(hyphenated))
|
|
569
|
-
return;
|
|
570
1136
|
}
|
|
571
1137
|
}
|
|
1138
|
+
// What a JSX element renders from an expression is text, a single word too: `{used ? <>…</> : 'Never used'}`,
|
|
1139
|
+
// `{busy && 'saving'}`, `{name || 'the organization'}`
|
|
1140
|
+
if (node.type === 'JSXElement' || node.type === 'JSXFragment') {
|
|
1141
|
+
for (const child of node.children ?? [])
|
|
1142
|
+
if (child.type === 'JSXExpressionContainer')
|
|
1143
|
+
markRendered(child.expression);
|
|
1144
|
+
}
|
|
1145
|
+
// The two branches of a ternary are alternatives of one text: when one is text, a string on the other side
|
|
1146
|
+
// is too (`running ? 'Confirm all reviews' : 'stop'`, `n ? \`Pay invoice ${n}\` : 'Pay invoice'`)
|
|
1147
|
+
if (node.type === 'ConditionalExpression') {
|
|
1148
|
+
visit(node.test);
|
|
1149
|
+
visit(node.consequent);
|
|
1150
|
+
visit(node.alternate);
|
|
1151
|
+
const branches = [node.consequent, node.alternate];
|
|
1152
|
+
const found = (b) => candidates.some(c => c.offset === b?.span?.start && c.endOffset === b?.span?.end);
|
|
1153
|
+
branches.forEach((b, i) => {
|
|
1154
|
+
if (b?.type !== 'StringLiteral' || found(b) || !found(branches[1 - i]))
|
|
1155
|
+
return;
|
|
1156
|
+
const candidate = stringCandidate(b, content, file, config, jsx?.element?.accepted, true);
|
|
1157
|
+
if (candidate)
|
|
1158
|
+
candidates.push(candidate);
|
|
1159
|
+
});
|
|
1160
|
+
return;
|
|
1161
|
+
}
|
|
572
1162
|
// Check if this is a string literal
|
|
573
1163
|
if (node.type === 'StringLiteral') {
|
|
574
|
-
const
|
|
575
|
-
if (
|
|
576
|
-
|
|
577
|
-
if (candidate && candidate.confidence >= 0.7) {
|
|
578
|
-
// Detect JSX attribute context: in JSX, attr="value" has = right before the opening quote
|
|
579
|
-
if (stringNode.span.start > 0 && content[stringNode.span.start - 1] === '=') {
|
|
580
|
-
candidate.type = 'jsx-attribute';
|
|
581
|
-
}
|
|
582
|
-
candidates.push(candidate);
|
|
583
|
-
}
|
|
584
|
-
}
|
|
1164
|
+
const candidate = stringCandidate(node, content, file, config, jsx?.element?.accepted, renderedStrings.has(node));
|
|
1165
|
+
if (candidate)
|
|
1166
|
+
candidates.push(candidate);
|
|
585
1167
|
}
|
|
586
1168
|
// Template literals
|
|
587
1169
|
if (node.type === 'TemplateLiteral') {
|
|
@@ -603,18 +1185,26 @@ function visitNodeForStrings(node, content, file, config, candidates, jsx) {
|
|
|
603
1185
|
}
|
|
604
1186
|
}
|
|
605
1187
|
else if (quasis?.length > 1 && expressions?.length > 0 && node.span) {
|
|
606
|
-
// Template literal with interpolation, e.g. `${count}-day streak
|
|
607
|
-
const
|
|
608
|
-
|
|
1188
|
+
// Template literal with interpolation, e.g. `${count}-day streak`, possibly with a plural in it
|
|
1189
|
+
const plural = buildPluralTemplate(quasis, expressions, content);
|
|
1190
|
+
const result = plural
|
|
1191
|
+
? { text: plural.pluralForms.other, interpolations: plural.interpolations }
|
|
1192
|
+
: buildInterpolatedTemplate(quasis, expressions, content);
|
|
1193
|
+
if (result && hasWordsBesidePlaceholders(result.text)) {
|
|
609
1194
|
const trimmed = result.text.trim();
|
|
610
1195
|
if (trimmed) {
|
|
611
1196
|
const candidate = stringDetector.detectCandidate(trimmed, node.span.start, node.span.end, file, content, config);
|
|
612
1197
|
if (candidate) {
|
|
613
1198
|
candidate.content = trimmed;
|
|
614
1199
|
candidate.type = 'template-literal';
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
1200
|
+
if (result.interpolations.length)
|
|
1201
|
+
candidate.interpolations = result.interpolations;
|
|
1202
|
+
if (plural) {
|
|
1203
|
+
candidate.pluralForms = plural.pluralForms;
|
|
1204
|
+
candidate.pluralHelper = plural.pluralHelper;
|
|
1205
|
+
}
|
|
1206
|
+
// Template literals mixing text + expressions are likely user-facing, plurals always
|
|
1207
|
+
candidate.confidence = Math.min(1, candidate.confidence + (plural ? 0.3 : 0.15));
|
|
618
1208
|
if (node.span.start > 0 && content[node.span.start - 1] === '=') {
|
|
619
1209
|
candidate.type = 'jsx-attribute';
|
|
620
1210
|
}
|
|
@@ -635,7 +1225,7 @@ function visitNodeForStrings(node, content, file, config, candidates, jsx) {
|
|
|
635
1225
|
const trimmedStart = raw.indexOf(trimmed);
|
|
636
1226
|
const offset = node.span.start + trimmedStart;
|
|
637
1227
|
const endOffset = offset + trimmed.length;
|
|
638
|
-
const candidate = stringDetector.detectCandidate(trimmed, offset, endOffset, file, content, config);
|
|
1228
|
+
const candidate = stringDetector.detectCandidate(jsxTextValue(trimmed), offset, endOffset, file, content, config, undefined, true);
|
|
639
1229
|
if (candidate) {
|
|
640
1230
|
candidate.type = 'jsx-text';
|
|
641
1231
|
// JSXText is almost always user-visible content; boost confidence
|
|
@@ -660,6 +1250,183 @@ function visitNodeForStrings(node, content, file, config, candidates, jsx) {
|
|
|
660
1250
|
}
|
|
661
1251
|
}
|
|
662
1252
|
}
|
|
1253
|
+
/**
|
|
1254
|
+
* Whether a name says it holds a language model's input: a function or variable (not a component) whose
|
|
1255
|
+
* camelCase words include `prompt` and one of system, user, ai, llm, gpt, assistant, chat, model
|
|
1256
|
+
* (`getSystemPrompt`, `aiFixPrompt`, `userPromptBatch`). A bare `prompt` may ask the user something
|
|
1257
|
+
* (`deletePrompt`), and `EmailPrompt` or `UserPromptDialog` are components.
|
|
1258
|
+
*/
|
|
1259
|
+
function isModelPromptName(name) {
|
|
1260
|
+
if (!name || !/^[a-z]/.test(name))
|
|
1261
|
+
return false;
|
|
1262
|
+
const words = name.split(/(?=[A-Z])|_/).map(w => w.toLowerCase());
|
|
1263
|
+
return words.includes('prompt') && words.some(w => MODEL_WORDS.has(w));
|
|
1264
|
+
}
|
|
1265
|
+
const MODEL_WORDS = new Set(['system', 'user', 'ai', 'llm', 'gpt', 'assistant', 'chat', 'model']);
|
|
1266
|
+
/**
|
|
1267
|
+
* JSX text as React renders it: each line trimmed where it meets a line break, the lines joined by one space,
|
|
1268
|
+
* entities decoded (`can't` → `can't`). In a `t()` default the source form would show as written.
|
|
1269
|
+
*/
|
|
1270
|
+
function jsxTextValue(raw) {
|
|
1271
|
+
const lines = raw.split(/\r\n|\n|\r/);
|
|
1272
|
+
let lastNonEmpty = 0;
|
|
1273
|
+
lines.forEach((line, i) => { if (/[^ \t]/.test(line))
|
|
1274
|
+
lastNonEmpty = i; });
|
|
1275
|
+
let text = '';
|
|
1276
|
+
lines.forEach((line, i) => {
|
|
1277
|
+
let part = line.replace(/\t/g, ' ');
|
|
1278
|
+
if (i > 0)
|
|
1279
|
+
part = part.replace(/^ +/, '');
|
|
1280
|
+
if (i < lines.length - 1)
|
|
1281
|
+
part = part.replace(/ +$/, '');
|
|
1282
|
+
if (part)
|
|
1283
|
+
text += i < lastNonEmpty ? `${part} ` : part;
|
|
1284
|
+
});
|
|
1285
|
+
return text.replace(stringDetector.HTML_ENTITY_RE, entity => decodeEntity(entity));
|
|
1286
|
+
}
|
|
1287
|
+
const NAMED_ENTITIES = {
|
|
1288
|
+
amp: '&',
|
|
1289
|
+
lt: '<',
|
|
1290
|
+
gt: '>',
|
|
1291
|
+
quot: '"',
|
|
1292
|
+
apos: "'",
|
|
1293
|
+
nbsp: '\u00a0',
|
|
1294
|
+
ndash: '–',
|
|
1295
|
+
mdash: '—',
|
|
1296
|
+
hellip: '…',
|
|
1297
|
+
lsquo: '‘',
|
|
1298
|
+
rsquo: '’',
|
|
1299
|
+
ldquo: '“',
|
|
1300
|
+
rdquo: '”',
|
|
1301
|
+
laquo: '«',
|
|
1302
|
+
raquo: '»',
|
|
1303
|
+
middot: '·',
|
|
1304
|
+
bull: '•',
|
|
1305
|
+
times: '×',
|
|
1306
|
+
copy: '©',
|
|
1307
|
+
reg: '®',
|
|
1308
|
+
trade: '™',
|
|
1309
|
+
euro: '€',
|
|
1310
|
+
deg: '°'
|
|
1311
|
+
};
|
|
1312
|
+
/** One HTML character reference as its character; an unknown name stays as written. */
|
|
1313
|
+
function decodeEntity(entity) {
|
|
1314
|
+
const body = entity.slice(1, -1);
|
|
1315
|
+
if (body[0] === '#') {
|
|
1316
|
+
const code = body[1] === 'x' || body[1] === 'X' ? parseInt(body.slice(2), 16) : parseInt(body.slice(1), 10);
|
|
1317
|
+
return Number.isFinite(code) && code <= 0x10FFFF ? String.fromCodePoint(code) : entity;
|
|
1318
|
+
}
|
|
1319
|
+
return NAMED_ENTITIES[body] ?? NAMED_ENTITIES[body.toLowerCase()] ?? entity;
|
|
1320
|
+
}
|
|
1321
|
+
/**
|
|
1322
|
+
* What of a node is never text, the same for every walker looking for text: `'all'` (a t() call, a console
|
|
1323
|
+
* call, a <Trans>, an icon, code, a prompt for a language model, a log line, an error or a pattern), the
|
|
1324
|
+
* child keys that are not (an object key, a member property, a compared operand, a `case` value, the strings
|
|
1325
|
+
* of a non-text call), or null (all of it may be). `withTextHolders` is for the walker that visits the
|
|
1326
|
+
* functions and elements passed to a non-text call itself.
|
|
1327
|
+
*/
|
|
1328
|
+
function nonTextParts(node, file, config, withTextHolders) {
|
|
1329
|
+
switch (node.type) {
|
|
1330
|
+
case 'CallExpression':
|
|
1331
|
+
// already instrumented (also its options on a second run), or for developers however it is built
|
|
1332
|
+
if (isTranslationCall(node, config.extract.functions) || isConsoleCall(node))
|
|
1333
|
+
return 'all';
|
|
1334
|
+
return !withTextHolders && isNonTextMethodCall(node) ? ['arguments'] : null;
|
|
1335
|
+
case 'NewExpression':
|
|
1336
|
+
// `new Error('…')` is for developers, `new RegExp('…')` a pattern
|
|
1337
|
+
return node.callee?.type === 'Identifier' && /^RegExp$|Error$/.test(node.callee.value) ? 'all' : null;
|
|
1338
|
+
case 'JSXElement': {
|
|
1339
|
+
if (isTransComponent(node, config.extract.transComponents) || isIconElement(node))
|
|
1340
|
+
return 'all';
|
|
1341
|
+
// what code, scripts and styles show (`ignoredTags`, as for lint); inside a sentence it stays in its <Trans>
|
|
1342
|
+
const tag = node.opening?.name?.type === 'Identifier' ? node.opening.name.value.toLowerCase() : null;
|
|
1343
|
+
return tag && (jsxAttributes.ignoredTags.includes(tag) || config.extract.ignoredTags?.some(t => t.toLowerCase() === tag)) ? 'all' : null;
|
|
1344
|
+
}
|
|
1345
|
+
case 'KeyValueProperty':
|
|
1346
|
+
// a key names something and is never text; a call there is even a syntax error (`{ 'a b': 1 }`)
|
|
1347
|
+
return isModelPromptName(propertyName(node.key)) ? 'all' : ['key'];
|
|
1348
|
+
case 'MemberExpression':
|
|
1349
|
+
return ['property'];
|
|
1350
|
+
case 'BinaryExpression':
|
|
1351
|
+
// the strings a value is compared with are data (`status === 'Active'`)
|
|
1352
|
+
if (!COMPARISON_OPERATORS.has(node.operator))
|
|
1353
|
+
return null;
|
|
1354
|
+
return ['left', 'right'].filter(k => node[k]?.type === 'StringLiteral' || node[k]?.type === 'TemplateLiteral');
|
|
1355
|
+
case 'SwitchCase':
|
|
1356
|
+
return ['test'];
|
|
1357
|
+
case 'FunctionDeclaration':
|
|
1358
|
+
// a prompt is the input of a language model: translating it changes what the model does
|
|
1359
|
+
return isModelPromptName(node.identifier?.value) ? 'all' : null;
|
|
1360
|
+
case 'VariableDeclarator':
|
|
1361
|
+
// a prompt, or a variable used only in console calls (a log line: `const took = …; console.log(took)`)
|
|
1362
|
+
return isModelPromptName(node.id?.value) ||
|
|
1363
|
+
(node.id?.type === 'Identifier' && consoleOnlyNames.get(file)?.has(node.id.value))
|
|
1364
|
+
? 'all'
|
|
1365
|
+
: null;
|
|
1366
|
+
default:
|
|
1367
|
+
return null;
|
|
1368
|
+
}
|
|
1369
|
+
}
|
|
1370
|
+
/** Calls `visit` for each child node, but not those under the keys `except`. */
|
|
1371
|
+
function forEachChild(node, except, visit) {
|
|
1372
|
+
if (except === 'all')
|
|
1373
|
+
return;
|
|
1374
|
+
for (const key in node) {
|
|
1375
|
+
if (key === 'span' || except?.includes(key))
|
|
1376
|
+
continue;
|
|
1377
|
+
const value = node[key];
|
|
1378
|
+
if (Array.isArray(value))
|
|
1379
|
+
value.forEach(item => item && typeof item === 'object' && visit(item));
|
|
1380
|
+
else if (value && typeof value === 'object')
|
|
1381
|
+
visit(value);
|
|
1382
|
+
}
|
|
1383
|
+
}
|
|
1384
|
+
/** A string literal as a candidate of enough confidence, or null; `textSlot` takes a single word as text. */
|
|
1385
|
+
function stringCandidate(stringNode, content, file, config, accepted, textSlot) {
|
|
1386
|
+
if (!stringNode.span || typeof stringNode.span.start !== 'number')
|
|
1387
|
+
return null;
|
|
1388
|
+
// the same string as data elsewhere in the file: translating it here breaks the match there (what a JSX
|
|
1389
|
+
// element renders and an attribute's value, `data-tip='overridden'`, are shown, never matched)
|
|
1390
|
+
// nor a text property's (`{ value: 'Weekly', label: 'Weekly' }`)
|
|
1391
|
+
const attributeValue = stringNode.span.start > 0 && content[stringNode.span.start - 1] === '=';
|
|
1392
|
+
const property = /([\w]+)\s*:\s*$/.exec(content.slice(Math.max(0, stringNode.span.start - 40), stringNode.span.start))?.[1];
|
|
1393
|
+
const textProperty = !!property && translatablePropertyLowerSet.has(property.toLowerCase());
|
|
1394
|
+
if (fileDataStrings.get(file)?.has(stringNode.value) && !renderedStrings.has(stringNode) && !attributeValue && !textProperty)
|
|
1395
|
+
return null;
|
|
1396
|
+
const candidate = stringDetector.detectCandidate(stringNode.value, stringNode.span.start, stringNode.span.end, file, content, config, accepted, textSlot);
|
|
1397
|
+
// in a text slot the place says it is text, whatever the words score
|
|
1398
|
+
if (candidate && textSlot)
|
|
1399
|
+
candidate.confidence = Math.max(candidate.confidence, 0.7);
|
|
1400
|
+
if (!candidate || candidate.confidence < 0.7)
|
|
1401
|
+
return null;
|
|
1402
|
+
// Detect JSX attribute context: in JSX, attr="value" has = right before the opening quote
|
|
1403
|
+
if (stringNode.span.start > 0 && content[stringNode.span.start - 1] === '=')
|
|
1404
|
+
candidate.type = 'jsx-attribute';
|
|
1405
|
+
return candidate;
|
|
1406
|
+
}
|
|
1407
|
+
const LOGICAL_OPERATORS = new Set(['&&', '||', '??']);
|
|
1408
|
+
const COMPARISON_OPERATORS = new Set(['===', '!==', '==', '!=', 'in', 'instanceof']);
|
|
1409
|
+
/** The name of an object property's key (`label`, `'aria-label'`), or null for a computed one. */
|
|
1410
|
+
function propertyName(key) {
|
|
1411
|
+
return key?.type === 'Identifier' || key?.type === 'StringLiteral' ? key.value : null;
|
|
1412
|
+
}
|
|
1413
|
+
/** Visits the JSX elements and functions inside a value that is not text itself, and nothing else of it. */
|
|
1414
|
+
function visitTextHolders(node, ...rest) {
|
|
1415
|
+
if (!node || typeof node !== 'object')
|
|
1416
|
+
return;
|
|
1417
|
+
if (TEXT_HOLDERS.has(node.type)) {
|
|
1418
|
+
visitNodeForStrings(node, ...rest);
|
|
1419
|
+
return;
|
|
1420
|
+
}
|
|
1421
|
+
for (const key in node) {
|
|
1422
|
+
const value = node[key];
|
|
1423
|
+
if (Array.isArray(value))
|
|
1424
|
+
value.forEach(item => visitTextHolders(item, ...rest));
|
|
1425
|
+
else
|
|
1426
|
+
visitTextHolders(value, ...rest);
|
|
1427
|
+
}
|
|
1428
|
+
}
|
|
1429
|
+
const TEXT_HOLDERS = new Set(['JSXElement', 'JSXFragment', 'ArrowFunctionExpression', 'FunctionExpression']);
|
|
663
1430
|
// ─── Template-literal interpolation helpers ──────────────────────────────────
|
|
664
1431
|
/**
|
|
665
1432
|
* Builds a merged text with `{{var}}` placeholders from a template literal's
|
|
@@ -667,7 +1434,7 @@ function visitNodeForStrings(node, content, file, config, candidates, jsx) {
|
|
|
667
1434
|
*/
|
|
668
1435
|
function buildInterpolatedTemplate(quasis, expressions, content) {
|
|
669
1436
|
const interpolations = [];
|
|
670
|
-
const usedNames = new
|
|
1437
|
+
const usedNames = new Map();
|
|
671
1438
|
let text = '';
|
|
672
1439
|
for (let i = 0; i < quasis.length; i++) {
|
|
673
1440
|
const quasi = quasis[i];
|
|
@@ -677,38 +1444,169 @@ function buildInterpolatedTemplate(quasis, expressions, content) {
|
|
|
677
1444
|
if (!info)
|
|
678
1445
|
return null; // un-resolvable expression — bail
|
|
679
1446
|
text += `{{${info.name}}}`;
|
|
680
|
-
|
|
1447
|
+
if (!info.reused)
|
|
1448
|
+
interpolations.push(info);
|
|
681
1449
|
}
|
|
682
1450
|
}
|
|
683
1451
|
return interpolations.length > 0 ? { text, interpolations } : null;
|
|
684
1452
|
}
|
|
685
1453
|
/**
|
|
686
|
-
*
|
|
687
|
-
*
|
|
688
|
-
*
|
|
689
|
-
*
|
|
690
|
-
*
|
|
1454
|
+
* Whether a text with `{{placeholders}}` holds at least one word standing on its own, and is not a
|
|
1455
|
+
* kebab-case name. A word: two letters or more, not camelCase, punctuation around it, a placeholder only
|
|
1456
|
+
* after it (`review{{suffix}}.`), not before it nor joined by `_`, `.` or `-`. Ids, paths, keys, flags and
|
|
1457
|
+
* class names built in a template literal have none: `{{projectId}}-{{version}}`, `weight_{{code}}`,
|
|
1458
|
+
* `{{baseUrl}}/api/{{id}}`, `{{id}}.collapsed`, `{{metric}}Avg`, `nameField{{i}}`, `--ct {{cdnType}}`,
|
|
1459
|
+
* `locize-dropzone {{state}}`.
|
|
1460
|
+
*/
|
|
1461
|
+
function hasWordsBesidePlaceholders(text) {
|
|
1462
|
+
// a placeholder becomes one private-use character, neither letter nor punctuation
|
|
1463
|
+
const bare = text.replace(stringDetector.HTML_ENTITY_RE, ' ').replace(/\{\{[^}]*\}\}/g, '\uE000');
|
|
1464
|
+
if (/^[a-z0-9]+(?:-[a-z0-9]+)+$/.test(bare.replace(/\uE000/g, ' ').trim()))
|
|
1465
|
+
return false;
|
|
1466
|
+
return bare.split(/\s+/).some(token => {
|
|
1467
|
+
// (a name with digits in a later part counts: `next-i18next v{{version}}`)
|
|
1468
|
+
const word = /^[^\p{L}\p{N}\uE000_.-]*(\p{L}{2,}(?:['’-]\p{N}*\p{L}[\p{L}\p{N}]*)*)[^\p{L}\p{N}_]*$/u.exec(token)?.[1];
|
|
1469
|
+
// `zh-{{country}}`, `{{a}}/{{b}}`: a placeholder joined to the word by a separator makes an id, not a phrase
|
|
1470
|
+
if (/[-_./:#@=&?|\\]\uE000/.test(token))
|
|
1471
|
+
return false;
|
|
1472
|
+
// one Han, Kana or Hangul character is a word of its own (`共 {{n}} 条`)
|
|
1473
|
+
return (!!word && !/\p{Ll}\p{Lu}/u.test(word)) || /[\p{sc=Han}\p{sc=Hiragana}\p{sc=Katakana}\p{sc=Hangul}]/u.test(token);
|
|
1474
|
+
});
|
|
1475
|
+
}
|
|
1476
|
+
/**
|
|
1477
|
+
* A template literal one of whose expressions is a plural (a plural helper call or a `count === 1` ternary),
|
|
1478
|
+
* as one text per plural form: `${n(keys)} ${plural(keys, 'key', 'keys')} unused` → one: '{{keys}} key unused',
|
|
1479
|
+
* other: '{{keys}} keys unused', count: keys. An expression that is the count itself becomes `{{count}}`.
|
|
1480
|
+
*/
|
|
1481
|
+
function buildPluralTemplate(quasis, expressions, content) {
|
|
1482
|
+
const pluralIndex = expressions.findIndex(e => parsePluralExpression(e, content));
|
|
1483
|
+
if (pluralIndex < 0)
|
|
1484
|
+
return null;
|
|
1485
|
+
const plural = parsePluralExpression(expressions[pluralIndex], content);
|
|
1486
|
+
const usedNames = new Map();
|
|
1487
|
+
const interpolations = [];
|
|
1488
|
+
const formText = (form) => {
|
|
1489
|
+
let text = '';
|
|
1490
|
+
for (let i = 0; i < quasis.length; i++) {
|
|
1491
|
+
text += quasis[i].cooked ?? quasis[i].raw ?? '';
|
|
1492
|
+
if (i >= expressions.length)
|
|
1493
|
+
continue;
|
|
1494
|
+
if (i === pluralIndex) {
|
|
1495
|
+
text += form;
|
|
1496
|
+
continue;
|
|
1497
|
+
}
|
|
1498
|
+
const expression = content.slice(expressions[i].span.start, expressions[i].span.end);
|
|
1499
|
+
if (expression === plural.countExpression) {
|
|
1500
|
+
text += '{{count}}';
|
|
1501
|
+
continue;
|
|
1502
|
+
}
|
|
1503
|
+
const info = resolveExpressionName(expressions[i], content, usedNames);
|
|
1504
|
+
if (!info)
|
|
1505
|
+
return null;
|
|
1506
|
+
text += `{{${info.name}}}`;
|
|
1507
|
+
if (!info.reused)
|
|
1508
|
+
interpolations.push(info);
|
|
1509
|
+
}
|
|
1510
|
+
return text.trim();
|
|
1511
|
+
};
|
|
1512
|
+
const other = formText(plural.other);
|
|
1513
|
+
const one = plural.one !== undefined ? formText(plural.one) : undefined;
|
|
1514
|
+
const zero = plural.zero !== undefined ? formText(plural.zero) : undefined;
|
|
1515
|
+
if (!other || one === null || zero === null)
|
|
1516
|
+
return null;
|
|
1517
|
+
if (!mergeInterpolations(interpolations, plural.interpolations))
|
|
1518
|
+
return null;
|
|
1519
|
+
return { pluralForms: { countExpression: plural.countExpression, zero, one, other }, interpolations, pluralHelper: pluralHelperOf(expressions[pluralIndex]) };
|
|
1520
|
+
}
|
|
1521
|
+
/** The name of the plural helper a call expression calls (`plural(n, …)` → `plural`), or undefined. */
|
|
1522
|
+
function pluralHelperOf(expr) {
|
|
1523
|
+
return expr?.type === 'CallExpression' && expr.callee?.type === 'Identifier' ? expr.callee.value : undefined;
|
|
1524
|
+
}
|
|
1525
|
+
/**
|
|
1526
|
+
* Adds a plural's own placeholders (from its forms) to the text's; false when a name stands for two
|
|
1527
|
+
* different expressions.
|
|
1528
|
+
*/
|
|
1529
|
+
function mergeInterpolations(into, from = []) {
|
|
1530
|
+
for (const item of from) {
|
|
1531
|
+
const same = into.find(i => i.name === item.name);
|
|
1532
|
+
if (same && same.expression !== item.expression)
|
|
1533
|
+
return false;
|
|
1534
|
+
if (!same)
|
|
1535
|
+
into.push(item);
|
|
1536
|
+
}
|
|
1537
|
+
return true;
|
|
1538
|
+
}
|
|
1539
|
+
/**
|
|
1540
|
+
* The name an expression's value says best what it is, or null:
|
|
1541
|
+
* - `Identifier` → itself (`count`); `MemberExpression` → its last property (`profile.name` → `name`)
|
|
1542
|
+
* - a formatter's call, by its argument: `format.date(user.lastLogin)` → `lastLogin`, `n(queue)` → `queue`,
|
|
1543
|
+
* `Math.floor(m / 60)` → `m` (a namespace or a formatter keeps the meaning of what it gets)
|
|
1544
|
+
* - a string method's call, by what it is called on: `input.value.trim()` → `value`
|
|
1545
|
+
* - any other call, by the function: `price(plan)` → `price`, `api.calculatePercentage(stats)` → `calculatePercentage`
|
|
1546
|
+
* - `a - b`, `a || b`, `(a)`, `a as T`, `a!` → the name of `a`
|
|
1547
|
+
*/
|
|
1548
|
+
function nameOfExpression(expr) {
|
|
1549
|
+
switch (expr?.type) {
|
|
1550
|
+
case 'Identifier': return expr.value;
|
|
1551
|
+
case 'MemberExpression':
|
|
1552
|
+
return !expr.computed && expr.property?.type === 'Identifier' ? expr.property.value : null;
|
|
1553
|
+
case 'CallExpression': {
|
|
1554
|
+
const callee = expr.callee;
|
|
1555
|
+
const argument = () => nameOfExpression(expr.arguments?.[0]?.expression);
|
|
1556
|
+
if (callee?.type === 'Identifier')
|
|
1557
|
+
return FORMATTER_RE.test(callee.value) ? argument() : callee.value;
|
|
1558
|
+
if (callee?.type !== 'MemberExpression' || callee.property?.type !== 'Identifier')
|
|
1559
|
+
return null;
|
|
1560
|
+
const object = callee.object;
|
|
1561
|
+
const method = callee.property.value;
|
|
1562
|
+
if (object?.type === 'Identifier' && (/^[A-Z]/.test(object.value) || FORMATTER_NAMESPACE_RE.test(object.value)))
|
|
1563
|
+
return argument();
|
|
1564
|
+
// `date.toLocaleDateString()`, `terms.map(…).join(', ')`: still the value it is called on
|
|
1565
|
+
if (STRING_METHODS.has(method) || ARRAY_METHODS.has(method))
|
|
1566
|
+
return nameOfExpression(object);
|
|
1567
|
+
return method;
|
|
1568
|
+
}
|
|
1569
|
+
case 'BinaryExpression':
|
|
1570
|
+
// `name || email` (swc types `||`, `&&`, `??` as a BinaryExpression), `i + 1`: the value meant; any other
|
|
1571
|
+
// arithmetic is a new quantity (`segments * tokensPerSegment`), which no operand names
|
|
1572
|
+
if (LOGICAL_OPERATORS.has(expr.operator))
|
|
1573
|
+
return nameOfExpression(expr.left);
|
|
1574
|
+
if ((expr.operator === '+' || expr.operator === '-') && expr.right?.type === 'NumericLiteral')
|
|
1575
|
+
return nameOfExpression(expr.left);
|
|
1576
|
+
return null;
|
|
1577
|
+
case 'ParenthesisExpression':
|
|
1578
|
+
case 'TsAsExpression':
|
|
1579
|
+
case 'TsNonNullExpression':
|
|
1580
|
+
case 'TsSatisfiesExpression': return nameOfExpression(expr.expression);
|
|
1581
|
+
default: return null;
|
|
1582
|
+
}
|
|
1583
|
+
}
|
|
1584
|
+
/** Names of formatter functions: their call shows the value they get (`n(queue)`, `formatDate(createdAt)`). */
|
|
1585
|
+
const FORMATTER_RE = /^(?:format\w*|fmt|formatter|n|num|number|money|percent)$/i;
|
|
1586
|
+
/** Names of formatting namespaces (`format.date(x)`); a capitalized one (`Math`, `Intl`) is one too. */
|
|
1587
|
+
const FORMATTER_NAMESPACE_RE = /^(?:format\w*|fmt|formatter|intl)$/i;
|
|
1588
|
+
/** Array methods whose result still holds what they are called on. */
|
|
1589
|
+
const ARRAY_METHODS = new Set(['map', 'filter', 'sort', 'slice', 'flat', 'flatMap', 'concat', 'reverse']);
|
|
1590
|
+
/**
|
|
1591
|
+
* Resolves a human-friendly interpolation name from an AST expression node (see `nameOfExpression`;
|
|
1592
|
+
* `val`, `val2`, ... when none). The same expression twice in one text gets one name (`reused`), so the
|
|
1593
|
+
* options name it once.
|
|
691
1594
|
*/
|
|
692
1595
|
function resolveExpressionName(expr, content, usedNames) {
|
|
693
1596
|
if (!expr?.span)
|
|
694
1597
|
return null;
|
|
695
1598
|
const expression = content.slice(expr.span.start, expr.span.end);
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
}
|
|
700
|
-
else if (expr.type === 'MemberExpression' && !expr.computed && expr.property?.type === 'Identifier') {
|
|
701
|
-
baseName = expr.property.value;
|
|
702
|
-
}
|
|
703
|
-
else {
|
|
704
|
-
baseName = 'val';
|
|
1599
|
+
for (const [name, expr] of usedNames) {
|
|
1600
|
+
if (expr === expression)
|
|
1601
|
+
return { name, expression, reused: true };
|
|
705
1602
|
}
|
|
1603
|
+
const baseName = nameOfExpression(expr) ?? 'val';
|
|
706
1604
|
let name = baseName;
|
|
707
1605
|
let counter = 2;
|
|
708
1606
|
while (usedNames.has(name)) {
|
|
709
1607
|
name = `${baseName}${counter++}`;
|
|
710
1608
|
}
|
|
711
|
-
usedNames.
|
|
1609
|
+
usedNames.set(name, expression);
|
|
712
1610
|
return { name, expression };
|
|
713
1611
|
}
|
|
714
1612
|
// ─── JSX sibling interpolation merging ───────────────────────────────────────
|
|
@@ -722,8 +1620,9 @@ function resolveExpressionName(expr, content, usedNames) {
|
|
|
722
1620
|
function detectJSXInterpolation(node, content, file, config, candidates) {
|
|
723
1621
|
if (!node)
|
|
724
1622
|
return;
|
|
725
|
-
//
|
|
726
|
-
|
|
1623
|
+
// Not text (a <Trans>, code, an icon, a prompt, a log line, a key, …): nothing to merge in it
|
|
1624
|
+
const parts = nonTextParts(node, file, config, false);
|
|
1625
|
+
if (parts === 'all')
|
|
727
1626
|
return;
|
|
728
1627
|
const children = (node.type === 'JSXElement' || node.type === 'JSXFragment') ? node.children : null;
|
|
729
1628
|
if (children?.length > 1) {
|
|
@@ -734,13 +1633,12 @@ function detectJSXInterpolation(node, content, file, config, candidates) {
|
|
|
734
1633
|
if (child.type === 'JSXText') {
|
|
735
1634
|
currentRun.push(child);
|
|
736
1635
|
}
|
|
737
|
-
else if (child.type === 'JSXExpressionContainer' && isSimpleJSXExpression(child.expression)) {
|
|
1636
|
+
else if (child.type === 'JSXExpressionContainer' && (isSimpleJSXExpression(child.expression) || child.expression?.type === 'StringLiteral')) {
|
|
1637
|
+
// a simple expression, or literal text such as {' '}
|
|
738
1638
|
currentRun.push(child);
|
|
739
1639
|
}
|
|
740
|
-
else if (child.type === 'JSXExpressionContainer' &&
|
|
741
|
-
|
|
742
|
-
tryParsePluralTernary(child.expression, content)) {
|
|
743
|
-
// Plural ternary expression — include in the run for merged handling
|
|
1640
|
+
else if (child.type === 'JSXExpressionContainer' && parsePluralExpression(child.expression, content)) {
|
|
1641
|
+
// Plural ternary or plural helper call: part of the run, merged with it
|
|
744
1642
|
currentRun.push(child);
|
|
745
1643
|
}
|
|
746
1644
|
else if (child.type === 'JSXElement' && isSimpleJSXElement(child)) {
|
|
@@ -758,7 +1656,12 @@ function detectJSXInterpolation(node, content, file, config, candidates) {
|
|
|
758
1656
|
if (currentRun.length > 0) {
|
|
759
1657
|
runs.push(currentRun);
|
|
760
1658
|
}
|
|
761
|
-
for (const
|
|
1659
|
+
for (const fullRun of runs) {
|
|
1660
|
+
// Whitespace at a run's edges stays in the source: a rewrite of it would drop a space the page shows
|
|
1661
|
+
// (`provider:{' '}<strong>…`)
|
|
1662
|
+
const run = trimRun(fullRun);
|
|
1663
|
+
if (!run.length)
|
|
1664
|
+
continue;
|
|
762
1665
|
const hasText = run.some(c => c.type === 'JSXText' && c.value?.trim());
|
|
763
1666
|
const hasExpr = run.some(c => c.type === 'JSXExpressionContainer');
|
|
764
1667
|
const hasElement = run.some(c => c.type === 'JSXElement');
|
|
@@ -771,9 +1674,8 @@ function detectJSXInterpolation(node, content, file, config, candidates) {
|
|
|
771
1674
|
let pluralChild = null;
|
|
772
1675
|
let pluralData = null;
|
|
773
1676
|
for (const child of run) {
|
|
774
|
-
if (child.type === 'JSXExpressionContainer'
|
|
775
|
-
child.expression
|
|
776
|
-
const p = tryParsePluralTernary(child.expression, content);
|
|
1677
|
+
if (child.type === 'JSXExpressionContainer') {
|
|
1678
|
+
const p = parsePluralExpression(child.expression, content);
|
|
777
1679
|
if (p) {
|
|
778
1680
|
pluralChild = child;
|
|
779
1681
|
pluralData = p;
|
|
@@ -781,12 +1683,15 @@ function detectJSXInterpolation(node, content, file, config, candidates) {
|
|
|
781
1683
|
}
|
|
782
1684
|
}
|
|
783
1685
|
}
|
|
1686
|
+
// A sentence with both an element and a plural stays in its parts: in a <Trans> the plural's forms would
|
|
1687
|
+
// end up untranslated in an interpolation, and a plural t() cannot hold the element
|
|
1688
|
+
if (hasElement && pluralChild)
|
|
1689
|
+
continue;
|
|
784
1690
|
if (hasElement) {
|
|
785
1691
|
// ── JSX sibling run with nested HTML elements → <Trans> ──
|
|
786
|
-
const spanStart = run
|
|
787
|
-
const spanEnd = run[run.length - 1].span.end;
|
|
1692
|
+
const [spanStart, spanEnd] = runSpan(run, content);
|
|
788
1693
|
// Build the translation string (with indexed tags) and text-only version (for scoring)
|
|
789
|
-
const usedNames = new
|
|
1694
|
+
const usedNames = new Map();
|
|
790
1695
|
const interpolations = [];
|
|
791
1696
|
let transValue = '';
|
|
792
1697
|
let textOnly = '';
|
|
@@ -796,9 +1701,19 @@ function detectJSXInterpolation(node, content, file, config, candidates) {
|
|
|
796
1701
|
for (const child of run) {
|
|
797
1702
|
if (child.type === 'JSXText') {
|
|
798
1703
|
const raw = content.slice(child.span.start, child.span.end);
|
|
799
|
-
|
|
800
|
-
|
|
1704
|
+
const text = jsxTextValue(raw);
|
|
1705
|
+
transValue += text;
|
|
1706
|
+
textOnly += text;
|
|
801
1707
|
transContent += raw;
|
|
1708
|
+
// whitespace with a line break is no child of the element at all
|
|
1709
|
+
if (text)
|
|
1710
|
+
childIndex++;
|
|
1711
|
+
}
|
|
1712
|
+
else if (child.type === 'JSXExpressionContainer' && child.expression?.type === 'StringLiteral') {
|
|
1713
|
+
// {' '} and other literal text: part of the sentence, kept as written
|
|
1714
|
+
transValue += child.expression.value;
|
|
1715
|
+
textOnly += child.expression.value;
|
|
1716
|
+
transContent += content.slice(child.span.start, child.span.end);
|
|
802
1717
|
childIndex++;
|
|
803
1718
|
}
|
|
804
1719
|
else if (child.type === 'JSXExpressionContainer') {
|
|
@@ -812,7 +1727,8 @@ function detectJSXInterpolation(node, content, file, config, candidates) {
|
|
|
812
1727
|
// In <Trans> children, simple expressions become {{ obj }} syntax
|
|
813
1728
|
const objExpr = info.name === info.expression ? info.name : `${info.name}: ${info.expression}`;
|
|
814
1729
|
transContent += `{{ ${objExpr} }}`;
|
|
815
|
-
|
|
1730
|
+
if (!info.reused)
|
|
1731
|
+
interpolations.push(info);
|
|
816
1732
|
childIndex++;
|
|
817
1733
|
}
|
|
818
1734
|
else if (child.type === 'JSXElement') {
|
|
@@ -855,12 +1771,12 @@ function detectJSXInterpolation(node, content, file, config, candidates) {
|
|
|
855
1771
|
// ── JSX sibling run with embedded plural ternary ──
|
|
856
1772
|
const countExpr = pluralData.countExpression;
|
|
857
1773
|
// Resolve names for non-count, non-plural expressions
|
|
858
|
-
const usedNames = new
|
|
1774
|
+
const usedNames = new Map();
|
|
859
1775
|
const extraInterpolations = [];
|
|
860
1776
|
const exprNameMap = new Map();
|
|
861
1777
|
let valid = true;
|
|
862
1778
|
for (const child of run) {
|
|
863
|
-
if (child.type === 'JSXExpressionContainer' && child !== pluralChild) {
|
|
1779
|
+
if (child.type === 'JSXExpressionContainer' && child !== pluralChild && child.expression?.type !== 'StringLiteral') {
|
|
864
1780
|
const exprText = content.slice(child.expression.span.start, child.expression.span.end);
|
|
865
1781
|
if (exprText === countExpr) {
|
|
866
1782
|
exprNameMap.set(child, 'count');
|
|
@@ -872,11 +1788,12 @@ function detectJSXInterpolation(node, content, file, config, candidates) {
|
|
|
872
1788
|
break;
|
|
873
1789
|
}
|
|
874
1790
|
exprNameMap.set(child, info.name);
|
|
875
|
-
|
|
1791
|
+
if (!info.reused)
|
|
1792
|
+
extraInterpolations.push(info);
|
|
876
1793
|
}
|
|
877
1794
|
}
|
|
878
1795
|
}
|
|
879
|
-
if (!valid)
|
|
1796
|
+
if (!valid || !mergeInterpolations(extraInterpolations, pluralData.interpolations))
|
|
880
1797
|
continue;
|
|
881
1798
|
// Build merged text for each plural form
|
|
882
1799
|
const forms = [
|
|
@@ -889,7 +1806,10 @@ function detectJSXInterpolation(node, content, file, config, candidates) {
|
|
|
889
1806
|
let text = '';
|
|
890
1807
|
for (const child of run) {
|
|
891
1808
|
if (child.type === 'JSXText') {
|
|
892
|
-
text += content.slice(child.span.start, child.span.end);
|
|
1809
|
+
text += jsxTextValue(content.slice(child.span.start, child.span.end));
|
|
1810
|
+
}
|
|
1811
|
+
else if (child.expression?.type === 'StringLiteral') {
|
|
1812
|
+
text += child.expression.value;
|
|
893
1813
|
}
|
|
894
1814
|
else if (child === pluralChild) {
|
|
895
1815
|
const formText = form === 'zero'
|
|
@@ -906,8 +1826,7 @@ function detectJSXInterpolation(node, content, file, config, candidates) {
|
|
|
906
1826
|
}
|
|
907
1827
|
formTexts[form] = text.trim();
|
|
908
1828
|
}
|
|
909
|
-
const spanStart = run
|
|
910
|
-
const spanEnd = run[run.length - 1].span.end;
|
|
1829
|
+
const [spanStart, spanEnd] = runSpan(run, content);
|
|
911
1830
|
const otherText = formTexts.other;
|
|
912
1831
|
if (!otherText)
|
|
913
1832
|
continue;
|
|
@@ -924,6 +1843,7 @@ function detectJSXInterpolation(node, content, file, config, candidates) {
|
|
|
924
1843
|
if (extraInterpolations.length > 0) {
|
|
925
1844
|
candidate.interpolations = extraInterpolations;
|
|
926
1845
|
}
|
|
1846
|
+
candidate.pluralHelper = pluralHelperOf(pluralChild.expression);
|
|
927
1847
|
// Plural + JSX merge is always user-facing
|
|
928
1848
|
candidate.confidence = Math.min(1, candidate.confidence + 0.3);
|
|
929
1849
|
if (candidate.confidence >= 0.7) {
|
|
@@ -940,13 +1860,16 @@ function detectJSXInterpolation(node, content, file, config, candidates) {
|
|
|
940
1860
|
else {
|
|
941
1861
|
// ── Original JSX sibling merging (text + expressions, no elements) ──
|
|
942
1862
|
// Build the interpolated text from the run
|
|
943
|
-
const usedNames = new
|
|
1863
|
+
const usedNames = new Map();
|
|
944
1864
|
const interpolations = [];
|
|
945
1865
|
let text = '';
|
|
946
1866
|
let valid = true;
|
|
947
1867
|
for (const child of run) {
|
|
948
1868
|
if (child.type === 'JSXText') {
|
|
949
|
-
text += content.slice(child.span.start, child.span.end);
|
|
1869
|
+
text += jsxTextValue(content.slice(child.span.start, child.span.end));
|
|
1870
|
+
}
|
|
1871
|
+
else if (child.expression?.type === 'StringLiteral') {
|
|
1872
|
+
text += child.expression.value;
|
|
950
1873
|
}
|
|
951
1874
|
else {
|
|
952
1875
|
const info = resolveExpressionName(child.expression, content, usedNames);
|
|
@@ -955,21 +1878,23 @@ function detectJSXInterpolation(node, content, file, config, candidates) {
|
|
|
955
1878
|
break;
|
|
956
1879
|
}
|
|
957
1880
|
text += `{{${info.name}}}`;
|
|
958
|
-
|
|
1881
|
+
if (!info.reused)
|
|
1882
|
+
interpolations.push(info);
|
|
959
1883
|
}
|
|
960
1884
|
}
|
|
961
1885
|
if (!valid)
|
|
962
1886
|
continue;
|
|
963
1887
|
const trimmed = text.trim();
|
|
964
|
-
|
|
1888
|
+
const literalPiece = run.some(c => c.expression?.type === 'StringLiteral');
|
|
1889
|
+
if (!trimmed || (interpolations.length === 0 && !literalPiece) || !hasWordsBesidePlaceholders(trimmed))
|
|
965
1890
|
continue;
|
|
966
|
-
const spanStart = run
|
|
967
|
-
const spanEnd = run[run.length - 1].span.end;
|
|
1891
|
+
const [spanStart, spanEnd] = runSpan(run, content);
|
|
968
1892
|
const candidate = stringDetector.detectCandidate(trimmed, spanStart, spanEnd, file, content, config);
|
|
969
1893
|
if (candidate) {
|
|
970
1894
|
candidate.type = 'jsx-text';
|
|
971
1895
|
candidate.content = trimmed;
|
|
972
|
-
|
|
1896
|
+
if (interpolations.length)
|
|
1897
|
+
candidate.interpolations = interpolations;
|
|
973
1898
|
// Mixed text + expressions in JSX is almost always user-facing
|
|
974
1899
|
candidate.confidence = Math.min(1, candidate.confidence + 0.2);
|
|
975
1900
|
if (candidate.confidence >= 0.7) {
|
|
@@ -986,17 +1911,36 @@ function detectJSXInterpolation(node, content, file, config, candidates) {
|
|
|
986
1911
|
}
|
|
987
1912
|
}
|
|
988
1913
|
// Recurse into children
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1914
|
+
forEachChild(node, parts, child => detectJSXInterpolation(child, content, file, config, candidates));
|
|
1915
|
+
}
|
|
1916
|
+
/** A run without the whitespace-only text, `{' '}` pieces and empty elements (`<hr />`, `<br />`) at its two ends. */
|
|
1917
|
+
function trimRun(run) {
|
|
1918
|
+
const blank = (c) => (c.type === 'JSXText' && !c.value?.trim()) ||
|
|
1919
|
+
(c.type === 'JSXExpressionContainer' && c.expression?.type === 'StringLiteral' && !c.expression.value.trim()) ||
|
|
1920
|
+
(c.type === 'JSXElement' && !c.children?.length);
|
|
1921
|
+
let start = 0;
|
|
1922
|
+
let end = run.length;
|
|
1923
|
+
while (start < end && blank(run[start]))
|
|
1924
|
+
start++;
|
|
1925
|
+
while (end > start && blank(run[end - 1]))
|
|
1926
|
+
end--;
|
|
1927
|
+
return run.slice(start, end);
|
|
1928
|
+
}
|
|
1929
|
+
/** Where a run's rewrite starts and ends: inside the whitespace of its first and last text. */
|
|
1930
|
+
function runSpan(run, content) {
|
|
1931
|
+
const first = run[0];
|
|
1932
|
+
const last = run[run.length - 1];
|
|
1933
|
+
let start = first.span.start;
|
|
1934
|
+
let end = last.span.end;
|
|
1935
|
+
if (first.type === 'JSXText') {
|
|
1936
|
+
const raw = content.slice(first.span.start, first.span.end);
|
|
1937
|
+
start += raw.length - raw.trimStart().length;
|
|
1938
|
+
}
|
|
1939
|
+
if (last.type === 'JSXText') {
|
|
1940
|
+
const raw = content.slice(last.span.start, last.span.end);
|
|
1941
|
+
end -= raw.length - raw.trimEnd().length;
|
|
1942
|
+
}
|
|
1943
|
+
return [start, end];
|
|
1000
1944
|
}
|
|
1001
1945
|
/**
|
|
1002
1946
|
* Returns true when the expression is a simple Identifier or non-computed
|
|
@@ -1009,36 +1953,77 @@ function isSimpleJSXExpression(expr) {
|
|
|
1009
1953
|
return true;
|
|
1010
1954
|
if (expr.type === 'MemberExpression' && !expr.computed && expr.property?.type === 'Identifier')
|
|
1011
1955
|
return true;
|
|
1956
|
+
// A string or number made from one, inside a sentence as a placeholder (`up to {n.toLocaleString()} segments`,
|
|
1957
|
+
// `{Math.round(score * 100)}%`, `+ {total - shown} more`); any other call may return elements
|
|
1958
|
+
if (expr.type === 'ParenthesisExpression')
|
|
1959
|
+
return isSimpleJSXExpression(expr.expression);
|
|
1960
|
+
if (expr.type === 'NumericLiteral')
|
|
1961
|
+
return true;
|
|
1962
|
+
if (expr.type === 'BinaryExpression' && ARITHMETIC_OPERATORS.has(expr.operator)) {
|
|
1963
|
+
return isSimpleJSXExpression(expr.left) && isSimpleJSXExpression(expr.right);
|
|
1964
|
+
}
|
|
1965
|
+
// a choice between such values (`{young ? 3 : 2}`); a choice between strings is text of its own, which a
|
|
1966
|
+
// placeholder would leave untranslated
|
|
1967
|
+
if (expr.type === 'ConditionalExpression') {
|
|
1968
|
+
return [expr.consequent, expr.alternate].every(b => b?.type !== 'StringLiteral' && b?.type !== 'TemplateLiteral' && isSimpleJSXExpression(b));
|
|
1969
|
+
}
|
|
1970
|
+
// `format.date(x)`, `formatPrice(x)`: a formatter returns a string
|
|
1971
|
+
if (expr.type === 'CallExpression' && expr.callee?.type === 'Identifier')
|
|
1972
|
+
return /^format[A-Z]/.test(expr.callee.value);
|
|
1973
|
+
if (expr.type === 'CallExpression' && expr.callee?.type === 'MemberExpression' && expr.callee.property?.type === 'Identifier') {
|
|
1974
|
+
const object = expr.callee.object;
|
|
1975
|
+
const method = expr.callee.property.value;
|
|
1976
|
+
return STRING_METHODS.has(method) || /^format/.test(method) ||
|
|
1977
|
+
(object?.type === 'Identifier' && (object.value === 'Math' || object.value === 'Number' || /^(?:format|formatter|fmt|intl)$/i.test(object.value)));
|
|
1978
|
+
}
|
|
1012
1979
|
return false;
|
|
1013
1980
|
}
|
|
1981
|
+
const ARITHMETIC_OPERATORS = new Set(['-', '*', '/', '%']);
|
|
1982
|
+
/**
|
|
1983
|
+
* Methods that return a string whatever they are called on (`list.map(…).join(', ')`), so their call in JSX
|
|
1984
|
+
* text is a placeholder like a variable; not `slice`, which keeps an array of elements.
|
|
1985
|
+
*/
|
|
1986
|
+
const STRING_METHODS = new Set([
|
|
1987
|
+
'join', 'toString', 'toLocaleString', 'toLocaleDateString', 'toLocaleTimeString', 'toFixed', 'toPrecision',
|
|
1988
|
+
'trim', 'toUpperCase', 'toLowerCase', 'padStart', 'padEnd', 'substring', 'replace', 'replaceAll'
|
|
1989
|
+
]);
|
|
1014
1990
|
/**
|
|
1015
1991
|
* Returns true when a JSXElement is "simple" enough to be included in a
|
|
1016
1992
|
* `<Trans>` JSX sibling run. Accepts:
|
|
1017
|
-
* - Self-closing elements (`<br />`, `<img />`)
|
|
1018
|
-
* -
|
|
1019
|
-
*
|
|
1020
|
-
*
|
|
1993
|
+
* - Self-closing HTML elements (`<br />`, `<img />`)
|
|
1994
|
+
* - HTML elements whose only children are `JSXText` nodes
|
|
1995
|
+
* - Components whose only children are text, a link in a sentence
|
|
1996
|
+
* (`Leave your <DialogLink to='/'>projects</DialogLink> first.`); a component
|
|
1997
|
+
* without text (`<Icon />`) breaks the run
|
|
1021
1998
|
*/
|
|
1022
1999
|
function isSimpleJSXElement(node) {
|
|
1023
|
-
if (node.type !== 'JSXElement')
|
|
2000
|
+
if (node.type !== 'JSXElement' || isIconElement(node))
|
|
1024
2001
|
return false;
|
|
1025
2002
|
const namePart = node.opening?.name;
|
|
1026
2003
|
if (!namePart)
|
|
1027
2004
|
return false;
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
if (namePart.type === '
|
|
1031
|
-
|
|
2005
|
+
const children = node.children || [];
|
|
2006
|
+
const textOnly = children.every((c) => c.type === 'JSXText');
|
|
2007
|
+
if (namePart.type === 'JSXMemberExpression') {
|
|
2008
|
+
const name = `${namePart.object?.value ?? ''}.${namePart.property?.value ?? ''}`;
|
|
2009
|
+
return INLINE_COMPONENT_RE.test(name) && children.length > 0 && textOnly;
|
|
1032
2010
|
}
|
|
1033
|
-
if (
|
|
2011
|
+
if (namePart.type !== 'Identifier')
|
|
1034
2012
|
return false;
|
|
2013
|
+
const tagName = namePart.value;
|
|
2014
|
+
if (tagName[0] !== tagName[0].toLowerCase())
|
|
2015
|
+
return INLINE_COMPONENT_RE.test(tagName) && children.some((c) => c.value?.trim()) && textOnly;
|
|
1035
2016
|
// Self-closing elements are simple
|
|
1036
2017
|
if (node.opening?.selfClosing)
|
|
1037
2018
|
return true;
|
|
1038
2019
|
// Elements with only text children (or empty) are simple
|
|
1039
|
-
|
|
1040
|
-
return children.length === 0 || children.every((c) => c.type === 'JSXText');
|
|
2020
|
+
return children.length === 0 || textOnly;
|
|
1041
2021
|
}
|
|
2022
|
+
/**
|
|
2023
|
+
* Components that stand inside a sentence: links and text styles (`DialogLink`, `Text.Strong`). A button or a
|
|
2024
|
+
* card next to a text is a piece of its own, not part of the sentence.
|
|
2025
|
+
*/
|
|
2026
|
+
const INLINE_COMPONENT_RE = /Link$|^Text\b|Text$|^(?:Strong|Em|B|I|Code|Mark|Highlight)$/;
|
|
1042
2027
|
/**
|
|
1043
2028
|
* Returns the text content of a simple JSXElement's children.
|
|
1044
2029
|
*/
|
|
@@ -1053,17 +2038,32 @@ function getJSXElementTextContent(node, content) {
|
|
|
1053
2038
|
* Returns true when a JSXElement is a `<Trans>` component
|
|
1054
2039
|
* (already instrumented content).
|
|
1055
2040
|
*/
|
|
1056
|
-
function isTransComponent(node) {
|
|
2041
|
+
function isTransComponent(node, transComponents = []) {
|
|
1057
2042
|
const opening = node.opening;
|
|
1058
2043
|
if (!opening)
|
|
1059
2044
|
return false;
|
|
1060
2045
|
const name = opening.name;
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
2046
|
+
// react-i18next's own: Trans, IcuTrans and their WithoutContext variants for Server Components
|
|
2047
|
+
if (name?.type === 'Identifier')
|
|
2048
|
+
return TRANS_RE.test(name.value) || transComponents.includes(name.value);
|
|
2049
|
+
if (name?.type === 'JSXMemberExpression' && name.property?.type === 'Identifier') {
|
|
2050
|
+
const object = name.object?.type === 'Identifier' ? name.object.value : '';
|
|
2051
|
+
return TRANS_RE.test(name.property.value) || transComponents.includes(`${object}.${name.property.value}`);
|
|
2052
|
+
}
|
|
1065
2053
|
return false;
|
|
1066
2054
|
}
|
|
2055
|
+
const TRANS_RE = /^(?:Icu)?Trans(?:WithoutContext)?$/;
|
|
2056
|
+
/**
|
|
2057
|
+
* An icon: an element whose name ends in `Icon`, or one with a Material icon class. Its text is a ligature
|
|
2058
|
+
* (`<Icon>delete</Icon>`, `<span className='material-icons'>search</span>`) that a translation would break.
|
|
2059
|
+
*/
|
|
2060
|
+
function isIconElement(node) {
|
|
2061
|
+
const name = node.opening?.name;
|
|
2062
|
+
const tag = name?.type === 'Identifier' ? name.value : name?.type === 'JSXMemberExpression' ? name.property?.value : '';
|
|
2063
|
+
if (/Icon$/.test(tag ?? ''))
|
|
2064
|
+
return true;
|
|
2065
|
+
return (node.opening?.attributes ?? []).some((a) => a.name?.value === 'className' && a.value?.type === 'StringLiteral' && /\bmaterial-(?:icons|symbols)/.test(a.value.value));
|
|
2066
|
+
}
|
|
1067
2067
|
// ─── Plural conditional pattern detection ────────────────────────────────────
|
|
1068
2068
|
/**
|
|
1069
2069
|
* Extracts the text value from a string literal or static template literal node.
|
|
@@ -1164,8 +2164,11 @@ function parseCountTest(test, content) {
|
|
|
1164
2164
|
function detectPluralPatterns(node, content, file, config, candidates) {
|
|
1165
2165
|
if (!node)
|
|
1166
2166
|
return;
|
|
1167
|
-
|
|
1168
|
-
|
|
2167
|
+
const parts = nonTextParts(node, file, config, false);
|
|
2168
|
+
if (parts === 'all')
|
|
2169
|
+
return;
|
|
2170
|
+
if (node.type === 'ConditionalExpression' || node.type === 'CallExpression') {
|
|
2171
|
+
const plural = parsePluralExpression(node, content);
|
|
1169
2172
|
if (plural) {
|
|
1170
2173
|
// Use the "other" form as the candidate content (with {{count}})
|
|
1171
2174
|
const spanStart = node.span.start;
|
|
@@ -1185,6 +2188,9 @@ function detectPluralPatterns(node, content, file, config, candidates) {
|
|
|
1185
2188
|
one: plural.one,
|
|
1186
2189
|
other: plural.other
|
|
1187
2190
|
};
|
|
2191
|
+
if (plural.interpolations)
|
|
2192
|
+
candidate.interpolations = plural.interpolations;
|
|
2193
|
+
candidate.pluralHelper = pluralHelperOf(node);
|
|
1188
2194
|
// Plural patterns are always user-facing text — boost confidence
|
|
1189
2195
|
candidate.confidence = Math.min(1, candidate.confidence + 0.3);
|
|
1190
2196
|
if (candidate.confidence >= 0.7) {
|
|
@@ -1202,20 +2208,77 @@ function detectPluralPatterns(node, content, file, config, candidates) {
|
|
|
1202
2208
|
}
|
|
1203
2209
|
}
|
|
1204
2210
|
// Recurse into children
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
2211
|
+
forEachChild(node, parts, child => detectPluralPatterns(child, content, file, config, candidates));
|
|
2212
|
+
}
|
|
2213
|
+
/** A plural helper call or a `count === 1` ternary as its plural forms, or null. */
|
|
2214
|
+
function parsePluralExpression(expr, content) {
|
|
2215
|
+
if (expr?.type === 'ConditionalExpression')
|
|
2216
|
+
return tryParsePluralTernary(expr, content);
|
|
2217
|
+
if (expr?.type === 'CallExpression')
|
|
2218
|
+
return tryParsePluralCall(expr, content);
|
|
2219
|
+
return null;
|
|
2220
|
+
}
|
|
2221
|
+
/** Names of plural helpers whose call reads `(count, one, other)`. */
|
|
2222
|
+
const PLURAL_HELPER_RE = /^(?:plural|pluralize|pluralise)$/i;
|
|
2223
|
+
/**
|
|
2224
|
+
* Attempts to parse a plural helper call into a plural pattern:
|
|
2225
|
+
* plural(count, '# file', '# files') → one: '{{count}} file', other: '{{count}} files'
|
|
2226
|
+
* pluralize(n, 'item', `${n} items`) → one: 'item', other: '{{count}} items'
|
|
2227
|
+
* `#` in a form stands for the number, as in ICU. Only a call whose two forms are text (a string, or a
|
|
2228
|
+
* template literal whose only expression is the count) and whose count is not a string.
|
|
2229
|
+
*/
|
|
2230
|
+
function tryParsePluralCall(node, content) {
|
|
2231
|
+
const callee = node.callee;
|
|
2232
|
+
const name = callee?.type === 'Identifier'
|
|
2233
|
+
? callee.value
|
|
2234
|
+
: callee?.type === 'MemberExpression' && !callee.computed && callee.property?.type === 'Identifier' ? callee.property.value : null;
|
|
2235
|
+
if (!name || !PLURAL_HELPER_RE.test(name))
|
|
2236
|
+
return null;
|
|
2237
|
+
const [count, one, other] = (node.arguments ?? []).map((a) => a?.spread ? null : a?.expression);
|
|
2238
|
+
if (!count?.span || !one || !other || count.type === 'StringLiteral' || count.type === 'TemplateLiteral')
|
|
2239
|
+
return null;
|
|
2240
|
+
const countExpression = content.slice(count.span.start, count.span.end);
|
|
2241
|
+
// A form's other expressions become placeholders, named once for both forms (`showing ${shown} of # user`)
|
|
2242
|
+
const usedNames = new Map();
|
|
2243
|
+
const interpolations = [];
|
|
2244
|
+
const formText = (form) => {
|
|
2245
|
+
const text = extractStaticText(form);
|
|
2246
|
+
if (text !== null)
|
|
2247
|
+
return text;
|
|
2248
|
+
if (form?.type !== 'TemplateLiteral')
|
|
2249
|
+
return null;
|
|
2250
|
+
let result = '';
|
|
2251
|
+
for (let i = 0; i < form.quasis.length; i++) {
|
|
2252
|
+
result += form.quasis[i].cooked ?? form.quasis[i].raw ?? '';
|
|
2253
|
+
const expr = form.expressions?.[i];
|
|
2254
|
+
if (!expr)
|
|
2255
|
+
continue;
|
|
2256
|
+
if (content.slice(expr.span.start, expr.span.end) === countExpression) {
|
|
2257
|
+
result += '{{count}}';
|
|
2258
|
+
continue;
|
|
1213
2259
|
}
|
|
2260
|
+
const info = resolveExpressionName(expr, content, usedNames);
|
|
2261
|
+
if (!info)
|
|
2262
|
+
return null;
|
|
2263
|
+
result += `{{${info.name}}}`;
|
|
2264
|
+
if (!info.reused)
|
|
2265
|
+
interpolations.push(info);
|
|
1214
2266
|
}
|
|
1215
|
-
|
|
2267
|
+
return result;
|
|
2268
|
+
};
|
|
2269
|
+
const oneText = formText(one);
|
|
2270
|
+
const otherText = formText(other);
|
|
2271
|
+
if (oneText === null || otherText === null)
|
|
2272
|
+
return null;
|
|
2273
|
+
return {
|
|
2274
|
+
countExpression,
|
|
2275
|
+
one: oneText.replace(/#/g, '{{count}}'),
|
|
2276
|
+
other: otherText.replace(/#/g, '{{count}}'),
|
|
2277
|
+
...(interpolations.length ? { interpolations } : {})
|
|
2278
|
+
};
|
|
1216
2279
|
}
|
|
1217
2280
|
/**
|
|
1218
|
-
*
|
|
2281
|
+
* Parses the shape of a `ConditionalExpression` tree into a plural pattern (see `tryParsePluralTernary`).
|
|
1219
2282
|
*
|
|
1220
2283
|
* Supported shapes:
|
|
1221
2284
|
* count === 0 ? zeroText : count === 1 ? oneText : otherText (3-way)
|
|
@@ -1223,7 +2286,7 @@ function detectPluralPatterns(node, content, file, config, candidates) {
|
|
|
1223
2286
|
*
|
|
1224
2287
|
* Returns `null` when the node doesn't match any recognised plural shape.
|
|
1225
2288
|
*/
|
|
1226
|
-
function
|
|
2289
|
+
function parsePluralTernaryShape(node, content) {
|
|
1227
2290
|
if (node?.type !== 'ConditionalExpression')
|
|
1228
2291
|
return null;
|
|
1229
2292
|
const outerTest = parseCountTest(node.test, content);
|
|
@@ -1262,6 +2325,23 @@ function tryParsePluralTernary(node, content) {
|
|
|
1262
2325
|
}
|
|
1263
2326
|
return null;
|
|
1264
2327
|
}
|
|
2328
|
+
/**
|
|
2329
|
+
* A ternary on `count === 1` is a plural only when its branches are text: `score === 1 ? 'var(--ok)' :
|
|
2330
|
+
* 'var(--warn)'` and `score === 1 ? 'item-full' : 'item-low'` pick a style.
|
|
2331
|
+
*/
|
|
2332
|
+
function tryParsePluralTernary(node, content) {
|
|
2333
|
+
const plural = parsePluralTernaryShape(node, content);
|
|
2334
|
+
if (!plural)
|
|
2335
|
+
return null;
|
|
2336
|
+
// Fragments merged with the text around them (`''`, `'s'`, `${n}`) are fine; a technical form is not
|
|
2337
|
+
const forms = [plural.zero, plural.one, plural.other].filter((f) => f !== undefined);
|
|
2338
|
+
const technical = forms.some(f => f.trim().length > 1 && detectsAsTechnical(f));
|
|
2339
|
+
return !technical && forms.some(f => /\p{L}/u.test(f.replace(/\{\{[^}]*\}\}/g, ''))) ? plural : null;
|
|
2340
|
+
}
|
|
2341
|
+
/** A form that the string detector skips as technical (a CSS value, a class name); a single word is text here. */
|
|
2342
|
+
function detectsAsTechnical(text) {
|
|
2343
|
+
return stringDetector.detectCandidate(text, 0, text.length, 'plural.js', text, { extract: { input: [], output: '' } }, undefined, true) === null;
|
|
2344
|
+
}
|
|
1265
2345
|
// ─── Language-change detection ───────────────────────────────────────────────
|
|
1266
2346
|
/**
|
|
1267
2347
|
* Property names that indicate a "language" value in an object literal.
|
|
@@ -1276,6 +2356,24 @@ const LANGUAGE_PROP_NAMES = new Set(['language', 'lang', 'locale', 'lng']);
|
|
|
1276
2356
|
* Examples: `setLanguage(code)`, `setLocale(lng)`, `changeLanguage(x)`
|
|
1277
2357
|
*/
|
|
1278
2358
|
const LANGUAGE_SETTER_RE = /^(?:set|change|update|select)(?:Language|Lang|Locale|Lng)$/i;
|
|
2359
|
+
/**
|
|
2360
|
+
* A variable or a property (`code`, `lang.code`, `e.target.value`): the injected `changeLanguage()` repeats
|
|
2361
|
+
* the expression, which must then give the same value without doing anything (`getDefault(…)` would run twice).
|
|
2362
|
+
*/
|
|
2363
|
+
function isPlainValue(expr) {
|
|
2364
|
+
if (expr?.type === 'Identifier')
|
|
2365
|
+
return true;
|
|
2366
|
+
return expr?.type === 'MemberExpression' && expr.property?.type === 'Identifier' && isPlainValue(expr.object);
|
|
2367
|
+
}
|
|
2368
|
+
/** Nodes whose statements are a list, where one more statement can go before another. */
|
|
2369
|
+
const STATEMENT_LISTS = new Set(['FunctionBody', 'BlockStatement', 'Module', 'Script', 'SwitchCase']);
|
|
2370
|
+
/**
|
|
2371
|
+
* Callees whose object argument holds the user's settings, so a language property there is the app's
|
|
2372
|
+
* language (`updateSettings({ language })`, `saveProfile({ locale })`, `setState({ locale })`). Elsewhere a
|
|
2373
|
+
* `language`/`lng` property is data (`fetchTranslations({ lng })`, `list.push({ lng })`), and hooks
|
|
2374
|
+
* (`useState({ lng: [] })`) never are.
|
|
2375
|
+
*/
|
|
2376
|
+
const SETTINGS_CALLEE_RE = /settings|preferences|prefs|profile|user|account|state|locale|language/i;
|
|
1279
2377
|
/**
|
|
1280
2378
|
* Walks the AST looking for call expressions that appear to change the
|
|
1281
2379
|
* application language. Detected sites will later be augmented with an
|
|
@@ -1291,11 +2389,18 @@ const LANGUAGE_SETTER_RE = /^(?:set|change|update|select)(?:Language|Lang|Locale
|
|
|
1291
2389
|
* `setLanguage(code)`
|
|
1292
2390
|
* `setLocale(lng)`
|
|
1293
2391
|
* `changeLanguage(selectedLng)`
|
|
2392
|
+
*
|
|
2393
|
+
* Only a call that is a statement of its own in a block or an arrow function's expression body: the
|
|
2394
|
+
* injected call goes before it, which would change any other place (`const x = setLocale(l)`,
|
|
2395
|
+
* `return save({ locale })`, `if (ok) setLocale(l)`).
|
|
1294
2396
|
*/
|
|
1295
|
-
function detectLanguageChangeSites(node, content, sites) {
|
|
2397
|
+
function detectLanguageChangeSites(node, content, sites, parent, grandparent) {
|
|
1296
2398
|
if (!node)
|
|
1297
2399
|
return;
|
|
1298
|
-
|
|
2400
|
+
const standsAlone = (parent?.type === 'ExpressionStatement' && parent.expression === node &&
|
|
2401
|
+
STATEMENT_LISTS.has(grandparent?.type)) ||
|
|
2402
|
+
(parent?.type === 'ArrowFunctionExpression' && parent.body === node);
|
|
2403
|
+
if (node.type === 'CallExpression' && node.span && standsAlone) {
|
|
1299
2404
|
const detected = tryParseLanguageChangeCall(node, content);
|
|
1300
2405
|
if (detected) {
|
|
1301
2406
|
// Check if changeLanguage() already exists nearby (e.g. same arrow body)
|
|
@@ -1326,14 +2431,89 @@ function detectLanguageChangeSites(node, content, sites) {
|
|
|
1326
2431
|
const value = node[key];
|
|
1327
2432
|
if (value && typeof value === 'object') {
|
|
1328
2433
|
if (Array.isArray(value)) {
|
|
1329
|
-
value.forEach(item => detectLanguageChangeSites(item, content, sites));
|
|
2434
|
+
value.forEach(item => detectLanguageChangeSites(item, content, sites, node, parent));
|
|
1330
2435
|
}
|
|
1331
2436
|
else {
|
|
1332
|
-
detectLanguageChangeSites(value, content, sites);
|
|
2437
|
+
detectLanguageChangeSites(value, content, sites, node, parent);
|
|
1333
2438
|
}
|
|
1334
2439
|
}
|
|
1335
2440
|
}
|
|
1336
2441
|
}
|
|
2442
|
+
/**
|
|
2443
|
+
* The imports of the plural helpers `names` (`import { plural, number } from './format'`), each with the
|
|
2444
|
+
* number of other identifiers naming it in the file and the text that removes its import.
|
|
2445
|
+
*/
|
|
2446
|
+
function findPluralHelperImports(ast, content, names) {
|
|
2447
|
+
const found = [];
|
|
2448
|
+
for (const decl of ast.body ?? []) {
|
|
2449
|
+
if (decl.type !== 'ImportDeclaration')
|
|
2450
|
+
continue;
|
|
2451
|
+
const specifiers = decl.specifiers ?? [];
|
|
2452
|
+
// `import fmt, { plural } from …` mixes a default with the braces: removing one of them takes more than a
|
|
2453
|
+
// specifier and a comma, so such an import stays
|
|
2454
|
+
const named = specifiers.every((spec) => spec.type === 'ImportSpecifier');
|
|
2455
|
+
specifiers.forEach((spec, i) => {
|
|
2456
|
+
const name = spec.local?.value;
|
|
2457
|
+
if (!names.has(name) || (!named && specifiers.length > 1))
|
|
2458
|
+
return;
|
|
2459
|
+
let [removeStart, removeEnd] = specifiers.length === 1
|
|
2460
|
+
? [decl.span.start, decl.span.end]
|
|
2461
|
+
: i < specifiers.length - 1
|
|
2462
|
+
? [spec.span.start, specifiers[i + 1].span.start]
|
|
2463
|
+
: [specifiers[i - 1].span.end, spec.span.end];
|
|
2464
|
+
if (specifiers.length === 1)
|
|
2465
|
+
removeEnd += /^\r?\n/.exec(content.slice(removeEnd))?.[0].length ?? 0;
|
|
2466
|
+
found.push({ name, references: 0, removeStart, removeEnd });
|
|
2467
|
+
});
|
|
2468
|
+
}
|
|
2469
|
+
const count = (node) => {
|
|
2470
|
+
if (!node || typeof node !== 'object')
|
|
2471
|
+
return;
|
|
2472
|
+
if (node.type === 'ImportDeclaration')
|
|
2473
|
+
return;
|
|
2474
|
+
if (node.type === 'Identifier') {
|
|
2475
|
+
const helper = found.find(h => h.name === node.value);
|
|
2476
|
+
if (helper)
|
|
2477
|
+
helper.references++;
|
|
2478
|
+
}
|
|
2479
|
+
for (const key in node) {
|
|
2480
|
+
const value = node[key];
|
|
2481
|
+
if (Array.isArray(value))
|
|
2482
|
+
value.forEach(count);
|
|
2483
|
+
else if (value && typeof value === 'object')
|
|
2484
|
+
count(value);
|
|
2485
|
+
}
|
|
2486
|
+
};
|
|
2487
|
+
count(ast);
|
|
2488
|
+
return found;
|
|
2489
|
+
}
|
|
2490
|
+
/** The `useMemo`/`useCallback` calls with a callback and a dependency array (see `MemoHookSpan`). */
|
|
2491
|
+
function collectMemoHooks(node, hooks) {
|
|
2492
|
+
if (!node || typeof node !== 'object')
|
|
2493
|
+
return;
|
|
2494
|
+
if (node.type === 'CallExpression' && ['useMemo', 'useCallback'].includes(getCalleeName(node.callee) ?? '')) {
|
|
2495
|
+
const [callback, deps] = (node.arguments ?? []).map((a) => a?.expression);
|
|
2496
|
+
if (callback?.span && deps?.type === 'ArrayExpression' && deps.span) {
|
|
2497
|
+
const elements = (deps.elements ?? []).filter(Boolean).map((e) => e.expression);
|
|
2498
|
+
hooks.push({
|
|
2499
|
+
callbackStart: callback.span.start,
|
|
2500
|
+
callbackEnd: callback.span.end,
|
|
2501
|
+
insertAt: elements.length ? elements[elements.length - 1].span.end : deps.span.start + 1,
|
|
2502
|
+
hasDeps: elements.length > 0,
|
|
2503
|
+
hasT: elements.some((e) => e.type === 'Identifier' && e.value === 't')
|
|
2504
|
+
});
|
|
2505
|
+
}
|
|
2506
|
+
}
|
|
2507
|
+
for (const key in node) {
|
|
2508
|
+
const value = node[key];
|
|
2509
|
+
if (value && typeof value === 'object') {
|
|
2510
|
+
if (Array.isArray(value))
|
|
2511
|
+
value.forEach(item => collectMemoHooks(item, hooks));
|
|
2512
|
+
else
|
|
2513
|
+
collectMemoHooks(value, hooks);
|
|
2514
|
+
}
|
|
2515
|
+
}
|
|
2516
|
+
}
|
|
1337
2517
|
/**
|
|
1338
2518
|
* Inspects a single CallExpression node to determine if it is a language-change
|
|
1339
2519
|
* call. Returns the detected site data (without line/column) or `null`.
|
|
@@ -1350,10 +2530,10 @@ function tryParseLanguageChangeCall(node, content) {
|
|
|
1350
2530
|
if (objName === 'i18n' || objName === 'i18next')
|
|
1351
2531
|
return null;
|
|
1352
2532
|
}
|
|
1353
|
-
// ── Pattern 1: direct setter
|
|
2533
|
+
// ── Pattern 1: direct setter, setLanguage(expr), changeLocale(expr) etc. ──
|
|
1354
2534
|
if (calleeName && LANGUAGE_SETTER_RE.test(calleeName)) {
|
|
1355
2535
|
const firstArg = node.arguments[0]?.expression;
|
|
1356
|
-
if (firstArg?.span) {
|
|
2536
|
+
if (firstArg?.span && isPlainValue(firstArg)) {
|
|
1357
2537
|
const langExpr = content.slice(firstArg.span.start, firstArg.span.end);
|
|
1358
2538
|
// Skip if the argument is already an i18next.changeLanguage call
|
|
1359
2539
|
if (langExpr.includes('changeLanguage'))
|
|
@@ -1365,7 +2545,9 @@ function tryParseLanguageChangeCall(node, content) {
|
|
|
1365
2545
|
};
|
|
1366
2546
|
}
|
|
1367
2547
|
}
|
|
1368
|
-
// ── Pattern 2: object with language property
|
|
2548
|
+
// ── Pattern 2: object with language property, updateSettings({ language: expr }) ──
|
|
2549
|
+
if (!calleeName || /^use[A-Z]/.test(calleeName) || !SETTINGS_CALLEE_RE.test(calleeName))
|
|
2550
|
+
return null;
|
|
1369
2551
|
for (const arg of node.arguments) {
|
|
1370
2552
|
const expr = arg.expression ?? arg;
|
|
1371
2553
|
if (expr?.type !== 'ObjectExpression')
|
|
@@ -1385,8 +2567,8 @@ function tryParseLanguageChangeCall(node, content) {
|
|
|
1385
2567
|
const valNode = prop.value;
|
|
1386
2568
|
if (valNode?.span) {
|
|
1387
2569
|
const langExpr = content.slice(valNode.span.start, valNode.span.end);
|
|
1388
|
-
// Skip if value is a static string (e.g. `{ language: 'en' }` in a config)
|
|
1389
|
-
if (valNode.type === 'StringLiteral')
|
|
2570
|
+
// Skip if value is a static string (e.g. `{ language: 'en' }` in a config), or not a plain value
|
|
2571
|
+
if (valNode.type === 'StringLiteral' || !isPlainValue(valNode))
|
|
1390
2572
|
continue;
|
|
1391
2573
|
// Skip if already contains changeLanguage
|
|
1392
2574
|
if (langExpr.includes('changeLanguage'))
|
|
@@ -1420,7 +2602,11 @@ function getCalleeName(callee) {
|
|
|
1420
2602
|
* Gets the list of source files to instrument.
|
|
1421
2603
|
*/
|
|
1422
2604
|
async function getSourceFilesForInstrumentation(config) {
|
|
1423
|
-
|
|
2605
|
+
// Stories, mocks and fixtures hold sample data, not the app's texts
|
|
2606
|
+
const defaultIgnore = [
|
|
2607
|
+
'node_modules/**', 'dist/**', 'build/**', '.next/**',
|
|
2608
|
+
'**/*.{stories,story,storybook}.*', '**/__mocks__/**', '**/__fixtures__/**', '**/__tests__/**'
|
|
2609
|
+
];
|
|
1424
2610
|
const userIgnore = Array.isArray(config.extract.ignore)
|
|
1425
2611
|
? config.extract.ignore
|
|
1426
2612
|
: config.extract.ignore ? [config.extract.ignore] : [];
|
|
@@ -1435,16 +2621,8 @@ async function getSourceFilesForInstrumentation(config) {
|
|
|
1435
2621
|
* Checks if the project uses React.
|
|
1436
2622
|
*/
|
|
1437
2623
|
async function isProjectUsingReact() {
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
const content = await promises.readFile(packageJsonPath, 'utf-8');
|
|
1441
|
-
const packageJson = JSON.parse(content);
|
|
1442
|
-
const deps = { ...packageJson.dependencies, ...packageJson.devDependencies };
|
|
1443
|
-
return !!deps.react || !!deps['react-i18next'];
|
|
1444
|
-
}
|
|
1445
|
-
catch {
|
|
1446
|
-
return false;
|
|
1447
|
-
}
|
|
2624
|
+
const deps = await fileUtils.readProjectDeps();
|
|
2625
|
+
return !!deps.react || !!deps['react-i18next'];
|
|
1448
2626
|
}
|
|
1449
2627
|
/** Well-known frontend framework packages (presence → browser environment). */
|
|
1450
2628
|
const FRONTEND_FRAMEWORKS = [
|
|
@@ -1481,13 +2659,7 @@ const SERVER_FRAMEWORKS = [
|
|
|
1481
2659
|
*/
|
|
1482
2660
|
async function detectProjectEnvironment() {
|
|
1483
2661
|
try {
|
|
1484
|
-
const
|
|
1485
|
-
const raw = await promises.readFile(packageJsonPath, 'utf-8');
|
|
1486
|
-
const packageJson = JSON.parse(raw);
|
|
1487
|
-
const allDeps = {
|
|
1488
|
-
...packageJson.dependencies,
|
|
1489
|
-
...packageJson.devDependencies
|
|
1490
|
-
};
|
|
2662
|
+
const allDeps = await fileUtils.readProjectDeps();
|
|
1491
2663
|
const has = (list) => list.some(dep => !!allDeps[dep]);
|
|
1492
2664
|
// 1. Edge / serverless (check first — these projects may also list a
|
|
1493
2665
|
// bundler or even a framework, but they have no filesystem)
|
|
@@ -1586,28 +2758,10 @@ function buildDynamicImportPath(outputTemplate, initDir) {
|
|
|
1586
2758
|
*/
|
|
1587
2759
|
async function ensureI18nInitFile(hasReact, hasTypeScript, config, logger, usesI18nextT) {
|
|
1588
2760
|
const cwd = process.cwd();
|
|
1589
|
-
// Check for existing init files in common locations
|
|
2761
|
+
// Check for existing init files in common locations (an init elsewhere imports i18next, see runInstrumenter)
|
|
1590
2762
|
if (await findExistingI18nInitFile()) {
|
|
1591
2763
|
return null; // Init file already exists
|
|
1592
2764
|
}
|
|
1593
|
-
// Check if i18next.init() is called anywhere in the source
|
|
1594
|
-
try {
|
|
1595
|
-
const sourceFiles = await getSourceFilesForInstrumentation(config);
|
|
1596
|
-
for (const file of sourceFiles) {
|
|
1597
|
-
try {
|
|
1598
|
-
const content = await promises.readFile(file, 'utf-8');
|
|
1599
|
-
if (content.includes('i18next.init') || content.includes('.init(') || content.includes('i18n.init')) {
|
|
1600
|
-
return null; // Init is already present somewhere
|
|
1601
|
-
}
|
|
1602
|
-
}
|
|
1603
|
-
catch {
|
|
1604
|
-
// Skip unreadable files
|
|
1605
|
-
}
|
|
1606
|
-
}
|
|
1607
|
-
}
|
|
1608
|
-
catch {
|
|
1609
|
-
// Skip if file scanning fails
|
|
1610
|
-
}
|
|
1611
2765
|
// Determine output location — prefer src/ if it exists
|
|
1612
2766
|
const srcExists = await fileExists(node_path.join(cwd, 'src'));
|
|
1613
2767
|
const initDir = srcExists ? node_path.join(cwd, 'src') : cwd;
|