i18next-cli 1.89.0 → 1.91.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +57 -7
  2. package/dist/cjs/cli.js +8 -4
  3. package/dist/cjs/config.js +13 -12
  4. package/dist/cjs/extractor/core/extractor.js +1 -3
  5. package/dist/cjs/extractor/parsers/jsx-parser.js +4 -2
  6. package/dist/cjs/heuristic-config.js +51 -6
  7. package/dist/cjs/init.js +5 -0
  8. package/dist/cjs/instrumenter/core/instrumenter.js +272 -23
  9. package/dist/cjs/instrumenter/core/key-generator.js +1 -0
  10. package/dist/cjs/instrumenter/core/next-files.js +104 -0
  11. package/dist/cjs/instrumenter/core/transformer.js +97 -73
  12. package/dist/cjs/linter.js +190 -23
  13. package/dist/cjs/localize/agent-prompt.js +5 -2
  14. package/dist/cjs/localize/detect.js +1 -0
  15. package/dist/cjs/localize/localize.js +25 -4
  16. package/dist/esm/cli.js +8 -4
  17. package/dist/esm/config.js +13 -12
  18. package/dist/esm/extractor/core/extractor.js +1 -3
  19. package/dist/esm/extractor/parsers/jsx-parser.js +4 -3
  20. package/dist/esm/heuristic-config.js +52 -7
  21. package/dist/esm/init.js +5 -0
  22. package/dist/esm/instrumenter/core/instrumenter.js +273 -24
  23. package/dist/esm/instrumenter/core/key-generator.js +1 -0
  24. package/dist/esm/instrumenter/core/next-files.js +101 -0
  25. package/dist/esm/instrumenter/core/transformer.js +97 -73
  26. package/dist/esm/linter.js +192 -25
  27. package/dist/esm/localize/agent-prompt.js +5 -2
  28. package/dist/esm/localize/detect.js +1 -0
  29. package/dist/esm/localize/localize.js +25 -4
  30. package/package.json +2 -1
  31. package/types/cli.d.ts.map +1 -1
  32. package/types/config.d.ts.map +1 -1
  33. package/types/extractor/core/extractor.d.ts.map +1 -1
  34. package/types/extractor/parsers/jsx-parser.d.ts +1 -0
  35. package/types/extractor/parsers/jsx-parser.d.ts.map +1 -1
  36. package/types/heuristic-config.d.ts.map +1 -1
  37. package/types/init.d.ts.map +1 -1
  38. package/types/instrumenter/core/instrumenter.d.ts.map +1 -1
  39. package/types/instrumenter/core/key-generator.d.ts.map +1 -1
  40. package/types/instrumenter/core/next-files.d.ts +25 -0
  41. package/types/instrumenter/core/next-files.d.ts.map +1 -0
  42. package/types/instrumenter/core/transformer.d.ts +6 -0
  43. package/types/instrumenter/core/transformer.d.ts.map +1 -1
  44. package/types/linter.d.ts.map +1 -1
  45. package/types/localize/agent-prompt.d.ts +1 -1
  46. package/types/localize/agent-prompt.d.ts.map +1 -1
  47. package/types/localize/detect.d.ts +2 -0
  48. package/types/localize/detect.d.ts.map +1 -1
  49. package/types/localize/localize.d.ts.map +1 -1
  50. package/types/types.d.ts +54 -2
  51. package/types/types.d.ts.map +1 -1
@@ -1,6 +1,6 @@
1
1
  import { readFile, mkdir, writeFile, access } from 'node:fs/promises';
2
2
  import { glob } from 'glob';
3
- import { dirname, extname, join, relative, isAbsolute, resolve } from 'node:path';
3
+ import { dirname, resolve, extname, isAbsolute, relative, join } from 'node:path';
4
4
  import { parse } from '@swc/core';
5
5
  import { prompt } from '../../utils/prompt.js';
6
6
  import { styleText } from 'node:util';
@@ -14,6 +14,7 @@ import { normalizeSpansToCharIndices, collectIgnoredLineRanges } from '../../ext
14
14
  import { readProjectDeps, getOutputPath } from '../../utils/file-utils.js';
15
15
  import { findKeys } from '../../extractor/core/key-finder.js';
16
16
  import { matchesFunctionPattern } from '../../extractor/utils/function-matcher.js';
17
+ import { classifyNextFiles, projectPath } from './next-files.js';
17
18
  import { usesMessageFormat, toMessageFormatPlaceholders } from '../../utils/message-format.js';
18
19
 
19
20
  /**
@@ -65,6 +66,20 @@ async function runInstrumenter(config, options, logger = new ConsoleLogger()) {
65
66
  // Detect framework and language
66
67
  const hasReact = await isProjectUsingReact();
67
68
  const hasTypeScript = await isProjectUsingTypeScript();
69
+ // A Next.js app gets next-i18next's calls: getT() in Server Components, useT() in Client Components,
70
+ // useTranslation() from next-i18next/pages in the Pages Router. Also one with i18next not set up at all,
71
+ // whose Server Components no plain react-i18next hook would work in; one with an i18next setup of its own
72
+ // keeps it.
73
+ const contents = new Map();
74
+ for (const file of sourceFiles)
75
+ contents.set(file, await readFile(file, 'utf-8'));
76
+ const deps = await readProjectDeps();
77
+ const code = [...contents.values()];
78
+ const nextI18next = !!deps['next-i18next'] || code.some(c => NEXT_I18NEXT_IMPORT_RE.test(c)) ||
79
+ (!!deps.next && !deps.i18next && !deps['react-i18next'] && !code.some(c => I18NEXT_IMPORT_RE.test(c)));
80
+ const nextFiles = nextI18next ? await classifyNextFiles(contents) : undefined;
81
+ const nextKinds = nextFiles?.kinds;
82
+ const serverModule = nextI18next ? findServerModule(contents) : undefined;
68
83
  // Initialize plugins
69
84
  const plugins = config.plugins || [];
70
85
  await initializeInstrumentPlugins(plugins, { config, logger });
@@ -86,14 +101,15 @@ async function runInstrumenter(config, options, logger = new ConsoleLogger()) {
86
101
  }
87
102
  for (const file of sourceFiles) {
88
103
  try {
89
- let content = await readFile(file, 'utf-8');
104
+ let content = contents.get(file);
90
105
  // Run instrumentOnLoad plugin pipeline
91
106
  const loadResult = await runInstrumentOnLoadPipeline(content, file, plugins, logger);
92
107
  if (loadResult === null)
93
108
  continue; // plugin says skip this file
94
109
  content = loadResult;
95
- i18nextInUse ||= I18NEXT_IMPORT_RE.test(content);
96
- const scanResult = await scanFileForCandidates(content, file, config);
110
+ i18nextInUse ||= I18NEXT_IMPORT_RE.test(content) || NEXT_I18NEXT_IMPORT_RE.test(content);
111
+ const nextKind = nextKinds?.get(file);
112
+ const scanResult = await scanFileForCandidates(content, file, config, nextKind);
97
113
  let { candidates } = scanResult;
98
114
  const { components, languageChangeSites, imports, memoHooks, pluralHelperImports } = scanResult;
99
115
  // Run instrumentOnResult plugin pipeline
@@ -103,6 +119,11 @@ async function runInstrumenter(config, options, logger = new ConsoleLogger()) {
103
119
  totalSkipped += scanResult.ownTSkipped;
104
120
  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.');
105
121
  }
122
+ for (const { message, count, lines } of scanResult.dropped ?? []) {
123
+ totalCandidates += count;
124
+ totalSkipped += count;
125
+ warnFor(lines ? lines.map(line => `${file}:${line}`).join(', ') : `${file} (${count})`, message);
126
+ }
106
127
  if (scanResult.moduleScopeSkipped > 0) {
107
128
  totalCandidates += scanResult.moduleScopeSkipped;
108
129
  totalSkipped += scanResult.moduleScopeSkipped;
@@ -189,7 +210,8 @@ async function runInstrumenter(config, options, logger = new ConsoleLogger()) {
189
210
  languageChangeSites,
190
211
  imports,
191
212
  memoHooks,
192
- pluralHelperImports
213
+ pluralHelperImports,
214
+ next: nextKind && { kind: nextKind, serverModule: serverModuleFor(serverModule, file) }
193
215
  });
194
216
  if (!options.isDryRun && transformResult.modified) {
195
217
  // Write the transformed file
@@ -228,11 +250,29 @@ async function runInstrumenter(config, options, logger = new ConsoleLogger()) {
228
250
  const head = message === MODULE_SCOPE_WARNING ? `Skipped ${moduleScopeTotal} module-scope string(s). ${message}` : message;
229
251
  logger.warn(`${head}\n${where.map(w => ` ${w}`).join('\n')}`);
230
252
  }
253
+ if (nextI18next && totalTransformed > 0) {
254
+ // next-i18next sets i18next up itself (its config, the proxy, the root layout or appWithTranslation)
255
+ // a page loads its namespaces itself, with serverSideTranslations() (or a helper it imports that calls it)
256
+ const loads = (file) => [file, ...nextFiles.imports.get(file) ?? []].some(f => contents.get(f).includes('serverSideTranslations'));
257
+ const pagesWithoutProps = results.filter(r => nextKinds?.get(r.file) === 'pages' && isPagesRoute(r.file) && !loads(r.file)).map(r => r.file);
258
+ if (pagesWithoutProps.length) {
259
+ logger.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')}`);
260
+ }
261
+ if (!i18nextInUse && !await nextI18nextConfigured()) {
262
+ const kinds = new Set(results.map(r => nextKinds?.get(r.file)));
263
+ logger.info([
264
+ 'The code now uses next-i18next. Set it up:',
265
+ ` npm install next-i18next i18next react-i18next${config.extract.messageFormat === 'icu' ? ' i18next-icu intl-messageformat' : config.extract.messageFormat === 'mf2' ? ' i18next-mf2' : ''}`,
266
+ ...(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)'] : []),
267
+ ...(kinds.has('pages') ? [' Pages Router: next-i18next.config.js, appWithTranslation and serverSideTranslations, https://github.com/i18next/next-i18next#pages-router-setup'] : [])
268
+ ].join('\n'));
269
+ }
270
+ }
231
271
  // Generate i18n init file if needed and any transformations were made
232
- if ((totalTransformed > 0 || totalLanguageChanges > 0) && !options.isDryRun && i18nextInUse) {
272
+ if ((totalTransformed > 0 || totalLanguageChanges > 0) && !options.isDryRun && !nextI18next && i18nextInUse) {
233
273
  logger.info('Your code imports i18next already, so it is set up somewhere: no i18n init file generated.');
234
274
  }
235
- if ((totalTransformed > 0 || totalLanguageChanges > 0) && !options.isDryRun && !i18nextInUse) {
275
+ if ((totalTransformed > 0 || totalLanguageChanges > 0) && !options.isDryRun && !nextI18next && !i18nextInUse) {
236
276
  const initFilePath = await ensureI18nInitFile(hasReact, hasTypeScript, config, logger, usesI18nextT);
237
277
  if (initFilePath) {
238
278
  await injectI18nImportIntoEntryFile(initFilePath, logger);
@@ -257,6 +297,45 @@ async function runInstrumenter(config, options, logger = new ConsoleLogger()) {
257
297
  function keySourceOf(candidate) {
258
298
  return candidate.transValue?.replace(/<\/?\d+>/g, '') ?? candidate.content;
259
299
  }
300
+ /** An import of next-i18next, which sets i18next up itself. */
301
+ const NEXT_I18NEXT_IMPORT_RE = /\bfrom\s*['"]next-i18next(?:\/[\w/]+)?['"]|\brequire\(\s*['"]next-i18next(?:\/[\w/]+)?['"]\s*\)/;
302
+ /**
303
+ * The module the app imports `getT` from when it is not `next-i18next/server` (`createServerI18next` in its
304
+ * own `i18n.server.ts`, so no init order matters): an alias as written, a relative one as an absolute path.
305
+ */
306
+ function findServerModule(contents) {
307
+ for (const [file, code] of contents) {
308
+ for (const [, names, source] of code.matchAll(/import\s*\{([^}]*)\}\s*from\s*['"]([^'"]+)['"]/g)) {
309
+ if (!/\bgetT\b/.test(names) || source === 'next-i18next/server')
310
+ continue;
311
+ return source.startsWith('.') ? resolve(dirname(file), source) : source;
312
+ }
313
+ }
314
+ return undefined;
315
+ }
316
+ /** The specifier a file imports `getT` with: `next-i18next/server`, the app's alias, or a path relative to it. */
317
+ function serverModuleFor(serverModule, file) {
318
+ if (!serverModule)
319
+ return 'next-i18next/server';
320
+ if (!isAbsolute(serverModule))
321
+ return serverModule;
322
+ const rel = relative(dirname(resolve(file)), serverModule).replace(/\\/g, '/').replace(/\.(?:tsx?|jsx?|mjs)$/, '');
323
+ return rel.startsWith('.') ? rel : `./${rel}`;
324
+ }
325
+ /** A page of the Pages Router (not `_app`, `_document`, `_error` or an API route), which loads its own translations. */
326
+ function isPagesRoute(file) {
327
+ const rel = projectPath(file);
328
+ return rel.startsWith('pages/') && !/^pages\/(?:_app|_document|_error|api\/)/.test(rel);
329
+ }
330
+ /** next-i18next has a config of its own already: `i18n.config.*` (App Router) or `next-i18next.config.*` (Pages Router). */
331
+ async function nextI18nextConfigured() {
332
+ const names = ['i18n.config', 'next-i18next.config'].flatMap(name => ['ts', 'js', 'mjs', 'cjs'].map(ext => `${name}.${ext}`));
333
+ for (const name of names) {
334
+ if (await fileExists(join(process.cwd(), name)) || await fileExists(join(process.cwd(), 'src', name)))
335
+ return true;
336
+ }
337
+ return false;
338
+ }
260
339
  /** An import of i18next or react-i18next (`.init()` alone is any library's: `Sentry.init()`). */
261
340
  const I18NEXT_IMPORT_RE = /\bfrom\s*['"](?:i18next|react-i18next)['"]|\brequire\(\s*['"](?:i18next|react-i18next)['"]\s*\)/;
262
341
  const MODULE_SCOPE_WARNING = 'A t() call there runs once at import time — before i18next may be initialized — and never updates on language change. ' +
@@ -265,7 +344,7 @@ const MODULE_SCOPE_WARNING = 'A t() call there runs once at import time — befo
265
344
  /**
266
345
  * Scans a source file for hardcoded string candidates and React component boundaries.
267
346
  */
268
- async function scanFileForCandidates(content, file, config) {
347
+ async function scanFileForCandidates(content, file, config, nextKind) {
269
348
  const candidates = [];
270
349
  const components = [];
271
350
  const languageChangeSites = [];
@@ -274,6 +353,7 @@ async function scanFileForCandidates(content, file, config) {
274
353
  let imports;
275
354
  const memoHooks = [];
276
355
  let pluralHelperImports;
356
+ const dropped = [];
277
357
  const fileExt = extname(file).toLowerCase();
278
358
  const isTypeScriptFile = ['.ts', '.tsx', '.mts', '.cts'].includes(fileExt);
279
359
  const isTSX = fileExt === '.tsx';
@@ -331,10 +411,18 @@ async function scanFileForCandidates(content, file, config) {
331
411
  }));
332
412
  collectMemoHooks(ast, memoHooks);
333
413
  // Detect React function component boundaries
334
- detectComponentBoundaries(ast, content, components);
414
+ detectComponentBoundaries(ast, content, components, nextKind === 'server');
335
415
  // Collect function spans so module-scope strings can be excluded below
336
416
  const functionSpans = [];
337
417
  collectFunctionSpans(ast, functionSpans);
418
+ // Next.js reads the texts of `export const metadata` once; generateMetadata() can get them with getT()
419
+ if (nextKind === 'server' && !/\bgenerateMetadata\b/.test(content)) {
420
+ const metadata = metadataExport(ast, content);
421
+ if (metadata) {
422
+ components.push(metadata);
423
+ functionSpans.push({ start: metadata.bodyStart, end: metadata.bodyEnd });
424
+ }
425
+ }
338
426
  // Visit AST to find string literals; the object form of extract.acceptedAttributes
339
427
  // sets which attributes hold text per JSX element
340
428
  const attributeRules = config.extract.acceptedAttributes;
@@ -384,6 +472,15 @@ async function scanFileForCandidates(content, file, config) {
384
472
  candidates.length = 0;
385
473
  candidates.push(...keep);
386
474
  }
475
+ if (nextKind) {
476
+ dropped.push(...dropForNextI18next(candidates, components, nextKind, isApiRoute(file), serverDirectiveSpans(ast)));
477
+ // next-i18next switches the language through the route or useChangeLanguage(): `i18n.changeLanguage()`
478
+ // would change the client instance alone. A call of that switch is no site at all.
479
+ const sites = languageChangeSites.filter(site => !/^(?:\w+\.)?changeLanguage\(/.test(content.slice(site.callStart, site.callEnd)));
480
+ if (sites.length)
481
+ dropped.push({ message: NEXT_LANGUAGE_CHANGE, count: sites.length, lines: sites.map(site => site.line) });
482
+ languageChangeSites.length = 0;
483
+ }
387
484
  // Annotate language change sites with their enclosing component (if any)
388
485
  for (const site of languageChangeSites) {
389
486
  for (const comp of components) {
@@ -433,7 +530,111 @@ async function scanFileForCandidates(content, file, config) {
433
530
  catch (err) {
434
531
  // Silently skip files that can't be parsed
435
532
  }
436
- return { candidates, components, languageChangeSites, moduleScopeSkipped, ownTSkipped, imports, memoHooks, pluralHelperImports };
533
+ return { candidates, components, languageChangeSites, moduleScopeSkipped, ownTSkipped, imports, memoHooks, pluralHelperImports, dropped };
534
+ }
535
+ /** `export const metadata = { title: '…' }` (with or without a type) as the scope of a generateMetadata() to be. */
536
+ function metadataExport(ast, content) {
537
+ for (const item of ast.body ?? []) {
538
+ const decl = item.type === 'ExportDeclaration' ? item.declaration : null;
539
+ const [declarator] = decl?.type === 'VariableDeclaration' && decl.declarations?.length === 1 ? decl.declarations : [];
540
+ if (declarator?.id?.value !== 'metadata' || declarator.init?.type !== 'ObjectExpression')
541
+ continue;
542
+ const annotation = declarator.id.typeAnnotation?.typeAnnotation;
543
+ return {
544
+ name: `metadata@${declarator.init.span.start}`,
545
+ bodyStart: declarator.init.span.start,
546
+ bodyEnd: declarator.init.span.end,
547
+ hasUseTranslation: false,
548
+ expressionBody: true,
549
+ isAsync: true,
550
+ metadataHead: {
551
+ start: decl.span.start,
552
+ end: declarator.init.span.start,
553
+ type: annotation?.span ? content.slice(annotation.span.start, annotation.span.end) : undefined
554
+ }
555
+ };
556
+ }
557
+ return null;
558
+ }
559
+ /** A route handler (`route.ts` under `app/`, a file under `pages/api/`): its texts are responses of an API, not of a page. */
560
+ function isApiRoute(file) {
561
+ const rel = projectPath(file);
562
+ return /^app\/(?:.*\/)?route\.[cm]?[jt]sx?$/.test(rel) || rel.startsWith('pages/api/');
563
+ }
564
+ /**
565
+ * The functions that run as Server Actions or cached (`'use server'`, `'use cache'` as their first statement), all
566
+ * of the file for such a directive at its top: they have no root params, so getT() there needs `{ lng }` passed in.
567
+ */
568
+ function serverDirectiveSpans(ast) {
569
+ const directive = (stmts) => stmts.some((st) => st.type === 'ExpressionStatement' &&
570
+ st.expression?.type === 'StringLiteral' && /^use (?:server|cache)\b/.test(st.expression.value));
571
+ // the directive prologue: the string statements a body or module starts with
572
+ const leading = (stmts = []) => {
573
+ const end = stmts.findIndex((st) => st.type !== 'ExpressionStatement' || st.expression?.type !== 'StringLiteral');
574
+ return end < 0 ? stmts : stmts.slice(0, end);
575
+ };
576
+ if (directive(leading(ast.body)))
577
+ return [{ start: 0, end: Infinity }];
578
+ const spans = [];
579
+ const walk = (node) => {
580
+ if (!node || typeof node !== 'object')
581
+ return;
582
+ if (FUNCTION_LIKE.has(node.type) && isBlockBody(node.body) && directive(leading(node.body.stmts))) {
583
+ spans.push({ start: node.body.span.start, end: node.body.span.end });
584
+ return;
585
+ }
586
+ for (const key in node) {
587
+ const value = node[key];
588
+ if (Array.isArray(value))
589
+ value.forEach(walk);
590
+ else if (value && typeof value === 'object' && key !== 'span')
591
+ walk(value);
592
+ }
593
+ };
594
+ walk(ast);
595
+ return spans;
596
+ }
597
+ const NEXT_API = 'Left API routes as they are: their texts are responses, not pages (getT() there needs { lng } from the request).';
598
+ const NEXT_DIRECTIVE = "Left Server Actions and cached functions ('use server', 'use cache') as they are: getT() there needs { lng } passed in.";
599
+ 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.";
600
+ 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.';
601
+ 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.';
602
+ const NEXT_WRAPPED = 'Skipped the texts of Server Components wrapped in a call (memo, forwardRef), which cannot become async for getT().';
603
+ 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.';
604
+ /**
605
+ * Takes out the candidates next-i18next cannot translate where they are: outside a component (no global `t`), in
606
+ * a component rendered on both sides without a `t` prop, a <Trans> there, in a Server Component that cannot
607
+ * become async. Returns what it dropped, by reason.
608
+ */
609
+ function dropForNextI18next(candidates, components, kind, apiRoute, directiveSpans) {
610
+ const componentOf = (c) => components.find(comp => comp.name === c.insideComponent);
611
+ const reasonOf = (c) => {
612
+ if (apiRoute)
613
+ return NEXT_API;
614
+ if (directiveSpans.some(span => c.offset >= span.start && c.endOffset <= span.end))
615
+ return NEXT_DIRECTIVE;
616
+ const comp = componentOf(c);
617
+ // a <Trans> takes its `t` from the React context, in any render code of a Client Component
618
+ if (!comp)
619
+ return c.type === 'jsx-mixed' && (kind === 'client' || kind === 'pages') ? null : NEXT_OUTSIDE;
620
+ // with `t` and `i18n` props, a <Trans> takes them both and works on either side
621
+ if ((kind === 'shared' || kind === 'unknown') && (!comp.hasUseTranslation || (c.type === 'jsx-mixed' && !comp.i18nParam))) {
622
+ return kind === 'shared' ? NEXT_SHARED : NEXT_UNKNOWN;
623
+ }
624
+ if (kind === 'server' && comp.wrapped && !comp.hasUseTranslation)
625
+ return NEXT_WRAPPED;
626
+ return null;
627
+ };
628
+ const counts = new Map();
629
+ const keep = candidates.filter(c => {
630
+ const reason = reasonOf(c);
631
+ if (reason)
632
+ counts.set(reason, (counts.get(reason) ?? 0) + 1);
633
+ return !reason;
634
+ });
635
+ candidates.length = 0;
636
+ candidates.push(...keep);
637
+ return [...counts].map(([message, count]) => ({ message, count }));
437
638
  }
438
639
  /**
439
640
  * Node types whose span delimits deferred (call-time) evaluation. A string
@@ -496,7 +697,7 @@ function lineOfOffset(content, offset) {
496
697
  * - forwardRef wrappers: `const Greeting = React.forwardRef((props, ref) => { ... })`
497
698
  * - memo wrappers: `const Greeting = React.memo(() => { ... })`
498
699
  */
499
- function detectComponentBoundaries(node, content, components) {
700
+ function detectComponentBoundaries(node, content, components, serverFile = false) {
500
701
  if (!node)
501
702
  return;
502
703
  // FunctionDeclaration with uppercase name
@@ -507,7 +708,8 @@ function detectComponentBoundaries(node, content, components) {
507
708
  name: node.identifier.value,
508
709
  bodyStart: body.span.start,
509
710
  bodyEnd: body.span.end,
510
- ...tBinding(node, body)
711
+ ...tBinding(node, body),
712
+ ...functionFacts(node)
511
713
  });
512
714
  }
513
715
  }
@@ -525,7 +727,8 @@ function detectComponentBoundaries(node, content, components) {
525
727
  name: node.identifier.value,
526
728
  bodyStart: body.span.start,
527
729
  bodyEnd: body.span.end,
528
- ...tBinding(node, body)
730
+ ...tBinding(node, body),
731
+ ...functionFacts(node)
529
732
  });
530
733
  }
531
734
  }
@@ -551,25 +754,59 @@ function detectComponentBoundaries(node, content, components) {
551
754
  if (isWrapper && init.arguments?.length > 0) {
552
755
  const arg = init.arguments[0]?.expression || init.arguments[0];
553
756
  if (arg && (arg.type === 'ArrowFunctionExpression' || arg.type === 'FunctionExpression')) {
554
- addComponentFromFunctionNode(node.id.value, arg, content, components);
757
+ addComponentFromFunctionNode(node.id.value, arg, content, components, true);
555
758
  }
556
759
  }
557
760
  }
558
761
  }
559
762
  }
763
+ // Not a component, but a function with a `t` of its own (`const { t } = await getT()` in `generateMetadata`,
764
+ // a custom hook), or in a Server Component file one that can await getT(): an async one, or the metadata
765
+ // functions Next.js awaits
766
+ if (FUNCTION_LIKE.has(node.type) && node.body?.span && !components.some(c => c.bodyStart === node.body.span.start)) {
767
+ const name = node.identifier?.value;
768
+ const ownHook = isBlockBody(node.body) && bindsT({}, node.body) === 'translation';
769
+ if (ownHook || (serverFile && (node.async || /^generate(?:Metadata|Viewport)$/.test(name ?? '')))) {
770
+ addComponentFromFunctionNode(`${name ?? 'function'}@${node.body.span.start}`, node, content, components, false, true);
771
+ }
772
+ }
560
773
  // Recurse into children
561
774
  for (const key in node) {
562
775
  const value = node[key];
563
776
  if (value && typeof value === 'object') {
564
777
  if (Array.isArray(value)) {
565
- value.forEach(item => detectComponentBoundaries(item, content, components));
778
+ value.forEach(item => detectComponentBoundaries(item, content, components, serverFile));
566
779
  }
567
780
  else {
568
- detectComponentBoundaries(value, content, components);
781
+ detectComponentBoundaries(value, content, components, serverFile);
569
782
  }
570
783
  }
571
784
  }
572
785
  }
786
+ const FUNCTION_LIKE = new Set(['FunctionDeclaration', 'FunctionExpression', 'ArrowFunctionExpression']);
787
+ /** Where a function starts, whether it is async, and the translation hook it calls without taking `t`. */
788
+ function functionFacts(fnNode, wrapped = false) {
789
+ const facts = { start: fnNode.span?.start, isAsync: !!fnNode.async };
790
+ if (wrapped)
791
+ facts.wrapped = true;
792
+ if ((fnNode.params ?? []).some((p) => patternBinds(p, 'i18n')))
793
+ facts.i18nParam = true;
794
+ const returnType = fnNode.returnType?.typeAnnotation?.span;
795
+ if (returnType)
796
+ facts.returnType = { start: returnType.start, end: returnType.end };
797
+ for (const stmt of isBlockBody(fnNode.body) ? fnNode.body.stmts ?? [] : []) {
798
+ for (const d of stmt.type === 'VariableDeclaration' ? stmt.declarations ?? [] : []) {
799
+ const call = d.init?.type === 'AwaitExpression' ? d.init.argument : d.init;
800
+ const hook = call?.type === 'CallExpression' ? dottedName(call.callee)?.split('.').pop() : null;
801
+ const props = d.id?.type === 'ObjectPattern' ? d.id.properties ?? [] : [];
802
+ if (!hook || !HOOK_CALL_RE.test(hook) || !props.length || props.some((p) => p.type === 'RestElement'))
803
+ continue;
804
+ 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) };
805
+ return facts;
806
+ }
807
+ }
808
+ return facts;
809
+ }
573
810
  /**
574
811
  * swc >=1.16 types function bodies as 'FunctionBody'; older versions used 'BlockStatement'.
575
812
  */
@@ -580,23 +817,26 @@ function isBlockBody(body) {
580
817
  * Helper: extracts a ComponentBoundary from an ArrowFunctionExpression or FunctionExpression
581
818
  * that has a block body.
582
819
  */
583
- function addComponentFromFunctionNode(name, fnNode, content, components) {
820
+ function addComponentFromFunctionNode(name, fnNode, content, components, wrapped = false, anyExpressionBody = false) {
584
821
  const body = fnNode.body;
585
822
  if (isBlockBody(body) && body.span) {
586
823
  components.push({
587
824
  name,
588
825
  bodyStart: body.span.start,
589
826
  bodyEnd: body.span.end,
590
- ...tBinding(fnNode, body)
827
+ ...tBinding(fnNode, body),
828
+ ...functionFacts(fnNode, wrapped)
591
829
  });
592
830
  }
593
- else if (isJSXExpression(body) && body.span) {
831
+ else if ((isJSXExpression(body) || anyExpressionBody) && body?.span) {
594
832
  // `const Hint = () => <p>…</p>`: a component too; its body becomes a block when it needs the hook
833
+ // (as does `async () => ({ title: … })`, a server function)
595
834
  components.push({
596
835
  name,
597
836
  bodyStart: body.span.start,
598
837
  bodyEnd: body.span.end,
599
838
  ...tBinding(fnNode, {}),
839
+ ...functionFacts(fnNode, wrapped),
600
840
  expressionBody: true
601
841
  });
602
842
  }
@@ -625,11 +865,16 @@ function bindsT(fnNode, body) {
625
865
  continue;
626
866
  const call = d.init?.type === 'AwaitExpression' ? d.init.argument : d.init;
627
867
  const hook = call?.type === 'CallExpression' ? dottedName(call.callee)?.split('.').pop() : null;
868
+ // `const t = i18n.getFixedT(lng, 'footer')` is one too
869
+ if (d.id.type === 'Identifier' && hook === 'getFixedT')
870
+ return 'translation';
628
871
  return d.id.type === 'ObjectPattern' && hook && TRANSLATION_HOOK_RE.test(hook) ? 'translation' : 'other';
629
872
  }
630
873
  }
631
874
  return null;
632
875
  }
876
+ /** The translation hooks a call to which can take `t` as well; an app's own `useRoleTranslations()` returns data. */
877
+ const HOOK_CALL_RE = /^(?:useTranslation|useT|getT)$/;
633
878
  /** Names of the hooks and functions that give a translation `t`. */
634
879
  const TRANSLATION_HOOK_RE = /^(?:use|get)\w*(?:Translation|T|I18n|Intl)\w*$/;
635
880
  /** A component's `hasUseTranslation`, and `ownT` when its `t` is something else (see `bindsT`). */
@@ -1217,7 +1462,8 @@ function hasWordsBesidePlaceholders(text) {
1217
1462
  if (/^[a-z0-9]+(?:-[a-z0-9]+)+$/.test(bare.replace(/\uE000/g, ' ').trim()))
1218
1463
  return false;
1219
1464
  return bare.split(/\s+/).some(token => {
1220
- const word = /^[^\p{L}\p{N}\uE000_.-]*(\p{L}{2,}(?:['’-]\p{L}+)*)[^\p{L}\p{N}_]*$/u.exec(token)?.[1];
1465
+ // (a name with digits in a later part counts: `next-i18next v{{version}}`)
1466
+ 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];
1221
1467
  // `zh-{{country}}`, `{{a}}/{{b}}`: a placeholder joined to the word by a separator makes an id, not a phrase
1222
1468
  if (/[-_./:#@=&?|\\]\uE000/.test(token))
1223
1469
  return false;
@@ -1665,10 +1911,11 @@ function detectJSXInterpolation(node, content, file, config, candidates) {
1665
1911
  // Recurse into children
1666
1912
  forEachChild(node, parts, child => detectJSXInterpolation(child, content, file, config, candidates));
1667
1913
  }
1668
- /** A run without the whitespace-only text and `{' '}` pieces at its two ends. */
1914
+ /** A run without the whitespace-only text, `{' '}` pieces and empty elements (`<hr />`, `<br />`) at its two ends. */
1669
1915
  function trimRun(run) {
1670
1916
  const blank = (c) => (c.type === 'JSXText' && !c.value?.trim()) ||
1671
- (c.type === 'JSXExpressionContainer' && c.expression?.type === 'StringLiteral' && !c.expression.value.trim());
1917
+ (c.type === 'JSXExpressionContainer' && c.expression?.type === 'StringLiteral' && !c.expression.value.trim()) ||
1918
+ (c.type === 'JSXElement' && !c.children?.length);
1672
1919
  let start = 0;
1673
1920
  let end = run.length;
1674
1921
  while (start < end && blank(run[start]))
@@ -1794,14 +2041,16 @@ function isTransComponent(node, transComponents = []) {
1794
2041
  if (!opening)
1795
2042
  return false;
1796
2043
  const name = opening.name;
2044
+ // react-i18next's own: Trans, IcuTrans and their WithoutContext variants for Server Components
1797
2045
  if (name?.type === 'Identifier')
1798
- return name.value === 'Trans' || transComponents.includes(name.value);
2046
+ return TRANS_RE.test(name.value) || transComponents.includes(name.value);
1799
2047
  if (name?.type === 'JSXMemberExpression' && name.property?.type === 'Identifier') {
1800
2048
  const object = name.object?.type === 'Identifier' ? name.object.value : '';
1801
- return name.property.value === 'Trans' || transComponents.includes(`${object}.${name.property.value}`);
2049
+ return TRANS_RE.test(name.property.value) || transComponents.includes(`${object}.${name.property.value}`);
1802
2050
  }
1803
2051
  return false;
1804
2052
  }
2053
+ const TRANS_RE = /^(?:Icu)?Trans(?:WithoutContext)?$/;
1805
2054
  /**
1806
2055
  * An icon: an element whose name ends in `Icon`, or one with a Material icon class. Its text is a ligature
1807
2056
  * (`<Icon>delete</Icon>`, `<span className='material-icons'>search</span>`) that a translation would break.
@@ -15,6 +15,7 @@ function generateKeyFromContent(content) {
15
15
  // A placeholder's name gives words of its own: `{{unreadNews}}` → unread News
16
16
  .replace(/\{\{\s*([^}]*?)\s*\}\}/g, (_, name) => ` ${name.replace(/([a-z0-9])([A-Z])/g, '$1 $2')} `)
17
17
  .replace(/_/g, ' ') // `_` separates plural and context suffixes in i18next keys: none in a generated one
18
+ .normalize('NFD').replace(/[\u0300-\u036f]/g, '') // `Français` → Francais, not Franais
18
19
  .replace(/[^\w\s\d]/g, '') // Remove punctuation
19
20
  .trim();
20
21
  if (!normalized) {
@@ -0,0 +1,101 @@
1
+ import { realpathSync } from 'node:fs';
2
+ import { resolve, sep, dirname, relative } from 'node:path';
3
+ import { getTsConfigAliases } from '../../config.js';
4
+
5
+ /** A `'use client'` directive: the first statement, after comments only. */
6
+ const USE_CLIENT_RE = /^(?:\s|\/\/[^\n]*\n|\/\*[\s\S]*?\*\/)*(['"])use client\1/;
7
+ /** The module specifiers of a file's static, dynamic and `require` imports and its re-exports. */
8
+ const IMPORT_RE = /\bfrom\s*['"]([^'"\n]+)['"]|\bimport\s*\(?\s*['"]([^'"\n]+)['"]|\brequire\(\s*['"]([^'"\n]+)['"]\s*\)/g;
9
+ const EXTENSIONS = ['', '.tsx', '.ts', '.jsx', '.js', '.mjs', '/index.tsx', '/index.ts', '/index.jsx', '/index.js'];
10
+ /**
11
+ * A file's absolute path with symbolic links resolved (`/var` is `/private/var` on macOS); one that does not exist
12
+ * (yet) resolves under the project root's real path.
13
+ */
14
+ function real(file, cwd) {
15
+ const abs = resolve(cwd, file);
16
+ try {
17
+ return realpathSync(abs);
18
+ }
19
+ catch { }
20
+ try {
21
+ return abs.startsWith(cwd + sep) ? realpathSync(cwd) + abs.slice(cwd.length) : abs;
22
+ }
23
+ catch {
24
+ return abs;
25
+ }
26
+ }
27
+ /** A file's path in the project, `/`-separated, without a leading `src/`: `app/page.tsx`, `pages/api/hello.js`. */
28
+ function projectPath(file, cwd = process.cwd()) {
29
+ return relative(real(cwd, cwd), real(file, cwd)).split(sep).join('/').replace(/^src\//, '');
30
+ }
31
+ /** The directory a file lies in under the project root: `app` or `src/app` (App Router), `pages` or `src/pages`. */
32
+ function routerOf(file, cwd) {
33
+ const top = projectPath(file, cwd).split('/')[0];
34
+ return top === 'app' || top === 'pages' ? top : null;
35
+ }
36
+ /**
37
+ * Classifies the files of a Next.js app by the components that render them, from the import graph: a file under
38
+ * `app/` is a Server Component unless it says `'use client'`; a `'use client'` file and all it imports are Client
39
+ * Components; a file under `pages/` and all it imports render with the Pages Router. Imports resolve relative,
40
+ * through the tsconfig `paths`, from the project root (a `baseUrl` import, `components/Card`) and with the `.js`
41
+ * of an ESM import for a `.ts` file; only the given files count.
42
+ *
43
+ * @param contents - The files' contents by path (relative to `cwd` or absolute)
44
+ * @returns The kind of each file and the files it imports, by the paths they were given with; a file nothing
45
+ * reaches is `unknown` (`pages` in an app without `app/`)
46
+ */
47
+ async function classifyNextFiles(contents, cwd = process.cwd()) {
48
+ const aliases = Object.entries(await getTsConfigAliases());
49
+ // by real path: the tsconfig aliases are real paths, and an absolute input glob may name a link (`/var/…`)
50
+ const byAbs = new Map([...contents.keys()].map(f => [real(f, cwd), f]));
51
+ const root = real(cwd, cwd);
52
+ const resolveImport = (from, spec) => {
53
+ const alias = aliases.find(([key]) => spec === key || spec.startsWith(key + '/'));
54
+ const bases = spec.startsWith('.')
55
+ ? [resolve(dirname(from), spec)]
56
+ : alias ? [resolve(alias[1], `.${spec.slice(alias[0].length)}`)] : [resolve(root, spec), resolve(root, 'src', spec)];
57
+ // resolve() again: an extension or `/index` joined to a Windows path
58
+ return bases.flatMap(base => [base, base.replace(/\.(?:m?js|jsx)$/, '')])
59
+ .flatMap(base => EXTENSIONS.map(ext => resolve(base + ext)))
60
+ .find(path => byAbs.has(path));
61
+ };
62
+ const imports = new Map();
63
+ const useClient = new Set();
64
+ for (const [abs, file] of byAbs) {
65
+ const code = contents.get(file);
66
+ if (USE_CLIENT_RE.test(code))
67
+ useClient.add(abs);
68
+ imports.set(abs, [...code.matchAll(IMPORT_RE)]
69
+ .map(m => resolveImport(abs, m[1] ?? m[2] ?? m[3]))
70
+ .filter((path) => !!path));
71
+ }
72
+ // Everything a set of files imports, transitively; a server walk stops at `'use client'`, the client boundary
73
+ const reach = (seeds, stopAtClient) => {
74
+ const seen = new Set();
75
+ const queue = [...seeds];
76
+ while (queue.length) {
77
+ const abs = queue.pop();
78
+ if (seen.has(abs) || (stopAtClient && useClient.has(abs)))
79
+ continue;
80
+ seen.add(abs);
81
+ queue.push(...imports.get(abs));
82
+ }
83
+ return seen;
84
+ };
85
+ const all = [...byAbs.keys()];
86
+ const server = reach(all.filter(abs => routerOf(abs, cwd) === 'app' && !useClient.has(abs)), true);
87
+ const appClient = reach([...useClient].filter(abs => routerOf(abs, cwd) !== 'pages'), false);
88
+ const pages = reach(all.filter(abs => routerOf(abs, cwd) === 'pages'), false);
89
+ const hasApp = all.some(abs => routerOf(abs, cwd) === 'app');
90
+ const kinds = new Map();
91
+ for (const [abs, file] of byAbs) {
92
+ // a file no route reaches may be rendered on either side, through an import that does not resolve
93
+ const kind = server.has(abs)
94
+ ? (appClient.has(abs) || pages.has(abs) ? 'shared' : 'server')
95
+ : appClient.has(abs) ? 'client' : pages.has(abs) || !hasApp ? 'pages' : 'unknown';
96
+ kinds.set(file, kind);
97
+ }
98
+ return { kinds, imports: new Map([...imports].map(([abs, paths]) => [byAbs.get(abs), paths.map(path => byAbs.get(path))])) };
99
+ }
100
+
101
+ export { classifyNextFiles, projectPath };