@babelize/engine 0.3.7 → 0.3.9

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 (50) hide show
  1. package/dist/analysis/analyze.d.ts +3 -0
  2. package/dist/analysis/analyze.js +1 -0
  3. package/dist/index.d.ts +4 -0
  4. package/dist/index.js +16 -1
  5. package/dist/local/hosted-provider.js +1 -0
  6. package/dist/local/translate-core.d.ts +19 -2
  7. package/dist/local/translate-core.js +28 -9
  8. package/dist/local/translate-messages.d.ts +5 -0
  9. package/dist/local/translate-messages.js +1 -1
  10. package/dist/modules/extractor/extract.js +22 -5
  11. package/dist/modules/finalization/finalize.d.ts +6 -0
  12. package/dist/modules/finalization/finalize.js +25 -5
  13. package/dist/modules/finalization/nextjs-finalize.d.ts +63 -6
  14. package/dist/modules/finalization/nextjs-finalize.js +339 -26
  15. package/dist/modules/format-injection/index.js +3 -2
  16. package/dist/modules/injection/inject.js +2 -1
  17. package/dist/modules/locale-builder/adopted.d.ts +29 -2
  18. package/dist/modules/locale-builder/adopted.js +185 -16
  19. package/dist/modules/locale-builder/locales.js +11 -2
  20. package/dist/modules/locale-builder/message-modules.d.ts +40 -0
  21. package/dist/modules/locale-builder/message-modules.js +263 -0
  22. package/dist/modules/sync-detector/sync-detector.js +4 -1
  23. package/dist/modules/translator/client/byok.provider.js +8 -2
  24. package/dist/modules/translator/formality.d.ts +40 -0
  25. package/dist/modules/translator/formality.js +313 -0
  26. package/dist/modules/translator/translate.d.ts +18 -0
  27. package/dist/modules/translator/translate.js +78 -11
  28. package/dist/modules/workspace/existing-setup.d.ts +3 -1
  29. package/dist/modules/workspace/existing-setup.js +32 -15
  30. package/dist/modules/workspace/validate.js +7 -0
  31. package/dist/orchestrator.js +51 -7
  32. package/dist/providers/default-translation-provider.js +2 -2
  33. package/dist/providers/types.d.ts +5 -0
  34. package/dist/qa/check-project.d.ts +7 -0
  35. package/dist/qa/check-project.js +12 -2
  36. package/dist/qa/locale-files.d.ts +8 -5
  37. package/dist/qa/locale-files.js +37 -9
  38. package/dist/qa/locale-qa.d.ts +10 -1
  39. package/dist/qa/locale-qa.js +9 -0
  40. package/dist/qa/review.js +1 -1
  41. package/dist/runtime/types.d.ts +29 -1
  42. package/dist/types.d.ts +2 -0
  43. package/dist/utils/ast-helpers.js +35 -4
  44. package/dist/utils/source-scope.d.ts +30 -0
  45. package/dist/utils/source-scope.js +112 -0
  46. package/dist/utils/translator-caller.d.ts +19 -0
  47. package/dist/utils/translator-caller.js +55 -21
  48. package/dist/utils/ui-copy.d.ts +14 -0
  49. package/dist/utils/ui-copy.js +51 -0
  50. package/package.json +4 -2
@@ -33,9 +33,14 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.NEXT_INTL_DEPENDENCIES = void 0;
36
+ exports.LOCALE_HEADER = exports.NEXT_INTL_DEPENDENCIES = void 0;
37
+ exports.buildLocalesModule = buildLocalesModule;
37
38
  exports.buildRequestConfig = buildRequestConfig;
39
+ exports.buildProxy = buildProxy;
40
+ exports.setHtmlLocale = setHtmlLocale;
41
+ exports.nextMajor = nextMajor;
38
42
  exports.wrapNextConfig = wrapNextConfig;
43
+ exports.usesCacheComponents = usesCacheComponents;
39
44
  exports.wrapRootLayout = wrapRootLayout;
40
45
  exports.finalizeNextIntl = finalizeNextIntl;
41
46
  const fs = __importStar(require("fs"));
@@ -43,16 +48,24 @@ const path = __importStar(require("path"));
43
48
  const file_utils_1 = require("../../utils/file-utils");
44
49
  const writes_1 = require("./writes");
45
50
  const ast_helpers_1 = require("../../utils/ast-helpers");
51
+ const rtl_languages_1 = require("../translator/language-codes/rtl-languages");
46
52
  /**
47
53
  * Next.js finalization for next-intl.
48
54
  *
49
55
  * Injection rewrites Next.js components to next-intl (`getTranslations` in
50
56
  * Server Components, `useTranslations` in Client Components — see
51
57
  * NextIntlStrategy), so the project must be wired for next-intl or every
52
- * page throws at runtime. This sets up next-intl's "without i18n routing"
53
- * mode: the locale comes from a NEXT_LOCALE cookie or the browser's
54
- * Accept-Language header, and messages are the generated
55
- * `public/locales/<locale>.json` files. URLs don't change.
58
+ * page throws at runtime. Each language gets its own URL without moving any
59
+ * route (#380): a generated proxy (middleware before Next 16) serves
60
+ * `/ja/docs` from the existing `app/docs` route and tells next-intl the
61
+ * locale in a request header. The source language stays unprefixed, a
62
+ * NEXT_LOCALE cookie remembers a visitor's choice, and every page announces
63
+ * its translations to search engines with hreflang `Link` headers. The root
64
+ * layout's <html> gets the locale's `lang` and `dir`. Messages are the
65
+ * generated `public/locales/<locale>.json` files.
66
+ *
67
+ * `"routing": "cookie"` in .babelize/config.json keeps one URL for every
68
+ * language (the locale comes from the cookie or Accept-Language).
56
69
  *
57
70
  * Every edit is a minimal text splice (the user's formatting is kept), and
58
71
  * anything that can't be wired automatically becomes a warning — never a
@@ -62,6 +75,11 @@ exports.NEXT_INTL_DEPENDENCIES = {
62
75
  'next-intl': '^4.0.0',
63
76
  };
64
77
  const GENERATED_MARKER = '@babelize-generated next-intl request config';
78
+ const LOCALES_MARKER = '@babelize-generated locale list';
79
+ const PROXY_MARKER = '@babelize-generated locale routing';
80
+ /** Request header the proxy sets with the URL's locale. */
81
+ exports.LOCALE_HEADER = 'x-babelize-locale';
82
+ const PROXY_FILES = ['proxy.ts', 'proxy.js', 'middleware.ts', 'middleware.js'];
65
83
  const NEXT_CONFIG_FILES = ['next.config.ts', 'next.config.mjs', 'next.config.js', 'next.config.cjs'];
66
84
  const LAYOUT_FILES = ['layout.tsx', 'layout.jsx', 'layout.js', 'layout.ts'];
67
85
  function applySplices(content, splices) {
@@ -98,18 +116,52 @@ async function findFirst(dir, names) {
98
116
  }
99
117
  return null;
100
118
  }
119
+ /** `sourceLocale` first, then the rest, without duplicates. */
120
+ function orderedLocales(sourceLocale, locales) {
121
+ return [sourceLocale, ...new Set(locales.filter((l) => l !== sourceLocale))];
122
+ }
123
+ /**
124
+ * `i18n/locales`: the locale list and text direction, shared by the request
125
+ * config, the proxy and the root layout. Plain data, safe to import anywhere.
126
+ */
127
+ function buildLocalesModule(opts) {
128
+ const locales = orderedLocales(opts.sourceLocale, opts.locales);
129
+ const rtl = locales.filter(rtl_languages_1.isRTL);
130
+ const ts = opts.typescript;
131
+ return `// ${LOCALES_MARKER}
132
+ // Babelize regenerates this file while the line above is present.
133
+ export const sourceLocale = ${JSON.stringify(opts.sourceLocale)};
134
+ export const locales = ${JSON.stringify(locales)}${ts ? ' as string[]' : ''};
135
+
136
+ const rightToLeft = ${JSON.stringify(rtl)}${ts ? ' as string[]' : ''};
137
+
138
+ /** \`dir\` for <html>: right-to-left scripts (Arabic, Hebrew, Persian, Urdu…). */
139
+ export function localeDirection(locale${ts ? ': string' : ''})${ts ? ": 'rtl' | 'ltr'" : ''} {
140
+ return rightToLeft.includes(locale) ? 'rtl' : 'ltr';
141
+ }
142
+ `;
143
+ }
101
144
  function buildRequestConfig(opts) {
102
- const locales = [opts.sourceLocale, ...opts.locales.filter((l) => l !== opts.sourceLocale)];
103
145
  const ts = opts.typescript;
104
146
  const importPath = opts.messagesImportPath.replace('__LOCALE__', '${locale}');
147
+ const routed = opts.routing === 'prefix'
148
+ ? ` // The URL's language (/ja/…), from the locale proxy.
149
+ const routed = requestHeaders.get('${exports.LOCALE_HEADER}');
150
+ if (routed && locales.includes(routed)) return { locale: routed, messages: await messagesFor(routed) };
151
+ `
152
+ : '';
105
153
  return `// ${GENERATED_MARKER}
106
154
  // Babelize regenerates this file (to update the locale list) while the line
107
155
  // above is present. Remove that line to take it over.
108
156
  import { getRequestConfig } from 'next-intl/server';
109
157
  import { cookies, headers } from 'next/headers';
158
+ import { locales, sourceLocale } from './locales';
110
159
 
111
- export const sourceLocale = ${JSON.stringify(opts.sourceLocale)};
112
- export const locales = ${JSON.stringify(locales)};
160
+ export { locales, sourceLocale };
161
+
162
+ async function messagesFor(locale${ts ? ': string' : ''}) {
163
+ return (await import(\`${importPath}\`)).default;
164
+ }
113
165
 
114
166
  function pickLocale(candidates${ts ? ': Array<string | undefined>' : ''})${ts ? ': string' : ''} {
115
167
  for (const candidate of candidates) {
@@ -124,19 +176,185 @@ function pickLocale(candidates${ts ? ': Array<string | undefined>' : ''})${ts ?
124
176
  }
125
177
 
126
178
  export default getRequestConfig(async () => {
127
- // Locale preference: the NEXT_LOCALE cookie, then the browser's Accept-Language.
179
+ const requestHeaders = await headers();
180
+ ${routed} // Otherwise the NEXT_LOCALE cookie, then the browser's Accept-Language.
128
181
  const cookieLocale = (await cookies()).get('NEXT_LOCALE')?.value;
129
- const acceptLanguage = ((await headers()).get('accept-language') ?? '')
182
+ const acceptLanguage = (requestHeaders.get('accept-language') ?? '')
130
183
  .split(',')
131
184
  .map((part) => part.split(';')[0].trim());
132
185
  const locale = pickLocale([cookieLocale, ...acceptLanguage]);
133
- return {
134
- locale,
135
- messages: (await import(\`${importPath}\`)).default,
136
- };
186
+ return { locale, messages: await messagesFor(locale) };
137
187
  });
138
188
  `;
139
189
  }
190
+ /**
191
+ * The locale proxy (#380): `/ja/docs` is served by `app/docs` with the
192
+ * locale in a request header; the source language has no prefix. A visitor
193
+ * who picked a language (NEXT_LOCALE cookie) is sent to its URL. Every page
194
+ * lists its translations in hreflang `Link` headers.
195
+ */
196
+ function buildProxy(opts) {
197
+ const ts = opts.typescript;
198
+ const req = ts ? 'request: NextRequest' : 'request';
199
+ return `// ${PROXY_MARKER}
200
+ // Babelize regenerates this file while the line above is present. Remove that
201
+ // line to take it over (keep the ${exports.LOCALE_HEADER} header and the matcher).
202
+ import { NextResponse${ts ? ', type NextRequest' : ''} } from 'next/server';
203
+ import { locales, sourceLocale } from './i18n/locales';
204
+
205
+ const ONE_YEAR = 60 * 60 * 24 * 365;
206
+
207
+ function localized(pathname${ts ? ': string' : ''}, locale${ts ? ': string' : ''}) {
208
+ if (locale === sourceLocale) return pathname;
209
+ return pathname === '/' ? \`/\${locale}\` : \`/\${locale}\${pathname}\`;
210
+ }
211
+
212
+ /** hreflang alternates for search engines, as an HTTP Link header. */
213
+ function alternates(${req}, pathname${ts ? ': string' : ''}) {
214
+ const origin = request.nextUrl.origin;
215
+ const links = locales.map((l) => \`<\${origin}\${localized(pathname, l)}>; rel="alternate"; hreflang="\${l}"\`);
216
+ links.push(\`<\${origin}\${pathname}>; rel="alternate"; hreflang="x-default"\`);
217
+ return links.join(', ');
218
+ }
219
+
220
+ export ${opts.kind === 'proxy' ? 'function proxy' : 'function middleware'}(${req}) {
221
+ const { pathname } = request.nextUrl;
222
+ const [, first = '', ...rest] = pathname.split('/');
223
+ const prefixed = locales.find((l) => l !== sourceLocale && l.toLowerCase() === first.toLowerCase());
224
+
225
+ if (prefixed) {
226
+ // /ja/docs is app/docs, in Japanese.
227
+ const url = request.nextUrl.clone();
228
+ url.pathname = \`/\${rest.join('/')}\`;
229
+ const headers = new Headers(request.headers);
230
+ headers.set('${exports.LOCALE_HEADER}', prefixed);
231
+ const response = NextResponse.rewrite(url, { request: { headers } });
232
+ response.cookies.set('NEXT_LOCALE', prefixed, { path: '/', maxAge: ONE_YEAR, sameSite: 'lax' });
233
+ response.headers.set('Link', alternates(request, url.pathname));
234
+ return response;
235
+ }
236
+
237
+ // An unprefixed URL is the source language, unless the visitor chose another.
238
+ const chosen = request.cookies.get('NEXT_LOCALE')?.value;
239
+ if (chosen && chosen !== sourceLocale && locales.includes(chosen)) {
240
+ const url = request.nextUrl.clone();
241
+ url.pathname = localized(pathname, chosen);
242
+ return NextResponse.redirect(url);
243
+ }
244
+
245
+ const headers = new Headers(request.headers);
246
+ headers.set('${exports.LOCALE_HEADER}', sourceLocale);
247
+ const response = NextResponse.next({ request: { headers } });
248
+ response.headers.set('Link', alternates(request, pathname));
249
+ return response;
250
+ }
251
+
252
+ export const config = {
253
+ // Pages only: not API routes, Next.js internals or files (anything with a dot).
254
+ matcher: ['/((?!api|trpc|_next|_vercel|.*\\\\..*).*)'],
255
+ };
256
+ `;
257
+ }
258
+ /**
259
+ * Give the root layout's <html> the active locale's `lang` and `dir`
260
+ * (#380): `const locale = useLocale()` in the default-exported layout
261
+ * (`await getLocale()` when it is already async). Null when the layout's shape isn't one this
262
+ * can edit safely (no <html>, an expression-bodied arrow, no default export).
263
+ */
264
+ function setHtmlLocale(content, typescript, localesImport) {
265
+ if (/\blocaleDirection\(/.test(content))
266
+ return content;
267
+ let ast;
268
+ try {
269
+ ast = (0, ast_helpers_1.parseCode)(content, { isTypeScript: typescript });
270
+ }
271
+ catch {
272
+ return null;
273
+ }
274
+ let fn = null;
275
+ for (const node of ast.program.body) {
276
+ if (!ast_helpers_1.t.isExportDefaultDeclaration(node))
277
+ continue;
278
+ const decl = node.declaration;
279
+ if (ast_helpers_1.t.isFunctionDeclaration(decl) || ast_helpers_1.t.isFunctionExpression(decl) || ast_helpers_1.t.isArrowFunctionExpression(decl))
280
+ fn = decl;
281
+ else if (ast_helpers_1.t.isIdentifier(decl)) {
282
+ for (const other of ast.program.body) {
283
+ if (ast_helpers_1.t.isFunctionDeclaration(other) && other.id?.name === decl.name)
284
+ fn = other;
285
+ if (ast_helpers_1.t.isVariableDeclaration(other)) {
286
+ for (const d of other.declarations) {
287
+ if (ast_helpers_1.t.isIdentifier(d.id, { name: decl.name }) && (ast_helpers_1.t.isArrowFunctionExpression(d.init) || ast_helpers_1.t.isFunctionExpression(d.init)))
288
+ fn = d.init;
289
+ }
290
+ }
291
+ }
292
+ }
293
+ }
294
+ if (!fn || !ast_helpers_1.t.isBlockStatement(fn.body) || fn.body.start == null || fn.start == null)
295
+ return null;
296
+ let html = null;
297
+ (0, ast_helpers_1.traverse)(ast, {
298
+ JSXOpeningElement(p) {
299
+ if (ast_helpers_1.t.isJSXIdentifier(p.node.name, { name: 'html' })) {
300
+ html = p.node;
301
+ p.stop();
302
+ }
303
+ },
304
+ });
305
+ const opening = html;
306
+ if (!opening || opening.name.end == null)
307
+ return null;
308
+ // A sync layout stays sync: it may call useTranslations(), which next-intl
309
+ // forbids in async components. useLocale() works in sync Server Components.
310
+ const read = fn.async
311
+ ? { importLine: `import { getLocale } from 'next-intl/server';`, call: 'await getLocale()' }
312
+ : { importLine: `import { useLocale } from 'next-intl';`, call: 'useLocale()' };
313
+ // `useLocale` joins an existing `import { … } from 'next-intl'` (the provider's) rather than a second line.
314
+ const source = fn.async ? 'next-intl/server' : 'next-intl';
315
+ const named = fn.async ? 'getLocale' : 'useLocale';
316
+ const existing = ast.program.body.find((n) => ast_helpers_1.t.isImportDeclaration(n) && n.source.value === source && n.importKind !== 'type' &&
317
+ n.specifiers.length > 0 && n.specifiers.every((sp) => ast_helpers_1.t.isImportSpecifier(sp)));
318
+ const lastSpecifier = existing?.specifiers[existing.specifiers.length - 1];
319
+ const imports = [
320
+ ...(lastSpecifier ? [] : [read.importLine]),
321
+ `import { localeDirection } from ${JSON.stringify(localesImport)};`,
322
+ ].join('\n');
323
+ const splices = [
324
+ ...(lastSpecifier?.end != null ? [{ at: lastSpecifier.end, insert: `, ${named}` }] : []),
325
+ insertTopLevel(ast, imports),
326
+ { at: fn.body.start + 1, insert: `\n const locale = ${read.call};` },
327
+ ];
328
+ // New attributes go after the existing ones: <html lang={locale} dir={…}>.
329
+ const lastAttr = opening.attributes[opening.attributes.length - 1];
330
+ const appendAt = lastAttr?.end ?? opening.name.end;
331
+ for (const [name, value] of [['lang', '{locale}'], ['dir', '{localeDirection(locale)}']]) {
332
+ const attr = opening.attributes.find((a) => ast_helpers_1.t.isJSXAttribute(a) && ast_helpers_1.t.isJSXIdentifier(a.name, { name }));
333
+ if (attr?.value && attr.value.start != null && attr.value.end != null) {
334
+ splices.push({ at: attr.value.start, remove: attr.value.end - attr.value.start, insert: value });
335
+ }
336
+ else if (!attr) {
337
+ splices.push({ at: appendAt, insert: ` ${name}=${value}` });
338
+ }
339
+ }
340
+ return applySplices(content, splices);
341
+ }
342
+ /** Next.js major version from package.json (`^16.1.0` → 16); null when unknown. */
343
+ function nextMajor(packageJson) {
344
+ const range = packageJson?.dependencies?.next ?? packageJson?.devDependencies?.next;
345
+ const m = typeof range === 'string' ? /(\d+)/.exec(range) : null;
346
+ return m ? Number(m[1]) : null;
347
+ }
348
+ /** `routing` from .babelize/config.json: `cookie` opts out of locale URLs. */
349
+ async function readRouting(workspacePath) {
350
+ try {
351
+ const raw = JSON.parse(await fs.promises.readFile(path.join(workspacePath, '.babelize', 'config.json'), 'utf8'));
352
+ return raw?.routing === 'cookie' ? 'cookie' : 'prefix';
353
+ }
354
+ catch {
355
+ return 'prefix';
356
+ }
357
+ }
140
358
  /** Wrap the next.config default export / module.exports with next-intl's plugin. */
141
359
  function wrapNextConfig(content, requestConfigPath, typescript) {
142
360
  if (content.includes('next-intl/plugin'))
@@ -179,8 +397,25 @@ function wrapNextConfig(content, requestConfigPath, typescript) {
179
397
  }
180
398
  return null;
181
399
  }
182
- /** Wrap `{children}` inside the root layout's <body> with <NextIntlClientProvider>. */
183
- function wrapRootLayout(content, typescript) {
400
+ /**
401
+ * True when next.config turns on Cache Components (`cacheComponents: true`,
402
+ * the default in create-next-app 16.4+, or `experimental.dynamicIO` before
403
+ * Next 16). Then request data — the cookies and headers our request config
404
+ * reads — may only be read inside <Suspense>, or `next build` fails with
405
+ * "Next.js encountered uncached or runtime data during prerendering".
406
+ */
407
+ function usesCacheComponents(nextConfig) {
408
+ return /\b(cacheComponents|dynamicIO)\s*:\s*true\b/.test(nextConfig);
409
+ }
410
+ /**
411
+ * Wrap `{children}` inside the root layout's <body> with <NextIntlClientProvider>.
412
+ *
413
+ * With `suspense` (Cache Components on), the whole <body> content is wrapped
414
+ * in <Suspense><NextIntlClientProvider>…, so every translated component —
415
+ * including a header or footer rendered by the layout itself — reads the
416
+ * locale inside a Suspense boundary.
417
+ */
418
+ function wrapRootLayout(content, typescript, options = {}) {
184
419
  if (content.includes('NextIntlClientProvider'))
185
420
  return content;
186
421
  let ast;
@@ -191,11 +426,16 @@ function wrapRootLayout(content, typescript) {
191
426
  return null;
192
427
  }
193
428
  let target = null;
429
+ let bodyContent = null;
194
430
  (0, ast_helpers_1.traverse)(ast, {
195
431
  JSXElement(p) {
196
432
  const name = p.node.openingElement.name;
197
433
  if (!ast_helpers_1.t.isJSXIdentifier(name, { name: 'body' }))
198
434
  return;
435
+ const { openingElement, closingElement } = p.node;
436
+ if (openingElement.end != null && closingElement?.start != null) {
437
+ bodyContent = { start: openingElement.end, end: closingElement.start };
438
+ }
199
439
  p.traverse({
200
440
  JSXExpressionContainer(inner) {
201
441
  if (ast_helpers_1.t.isIdentifier(inner.node.expression, { name: 'children' }) && inner.node.start != null && inner.node.end != null) {
@@ -209,6 +449,19 @@ function wrapRootLayout(content, typescript) {
209
449
  });
210
450
  if (!target)
211
451
  return null;
452
+ if (options.suspense && bodyContent) {
453
+ const { start, end } = bodyContent;
454
+ const importsSuspense = /import\s*\{[^}]*\bSuspense\b[^}]*\}\s*from\s*['"]react['"]/.test(content);
455
+ const imports = [
456
+ ...(importsSuspense ? [] : [`import { Suspense } from 'react';`]),
457
+ `import { NextIntlClientProvider } from 'next-intl';`,
458
+ ].join('\n');
459
+ return applySplices(content, [
460
+ insertTopLevel(ast, imports),
461
+ { at: start, insert: '<Suspense><NextIntlClientProvider>' },
462
+ { at: end, insert: '</NextIntlClientProvider></Suspense>' },
463
+ ]);
464
+ }
212
465
  const { start, end } = target;
213
466
  return applySplices(content, [
214
467
  insertTopLevel(ast, `import { NextIntlClientProvider } from 'next-intl';`),
@@ -262,6 +515,24 @@ writer = new writes_1.FinalizationWriter(workspace.path, dryRun)) {
262
515
  // the content's syntax always matches its extension and next.config points
263
516
  // at a file that exists.
264
517
  const requestDir = path.join(path.dirname(appDir), 'i18n');
518
+ const routing = await readRouting(workspace.path);
519
+ const locales = await availableLocales(workspace, options);
520
+ const sourceLocale = options.sourceLocale ?? 'en';
521
+ // 0. i18n/locales — the locale list the request config, proxy and layout share.
522
+ const localesFile = (await findFirst(requestDir, ['locales.ts', 'locales.js'])) ?? path.join(requestDir, `locales.${typescript ? 'ts' : 'js'}`);
523
+ const localesContent = await (0, file_utils_1.readFile)(localesFile).catch(() => null);
524
+ const ownsLocales = localesContent === null || localesContent.includes(LOCALES_MARKER);
525
+ if (!ownsLocales) {
526
+ warnings.push(`${toPosix(path.relative(root, localesFile))} already exists and was not generated by Babelize; left untouched. ` +
527
+ 'It must export sourceLocale, locales and localeDirection(locale).');
528
+ }
529
+ else {
530
+ const content = buildLocalesModule({ sourceLocale, locales, typescript: /\.ts$/.test(localesFile) });
531
+ if (content !== localesContent) {
532
+ await writer.write(localesFile, content);
533
+ configFileCreated = true;
534
+ }
535
+ }
265
536
  const existingRequest = await findFirst(requestDir, ['request.ts', 'request.tsx', 'request.js', 'request.jsx', 'request.mjs']);
266
537
  const requestFile = existingRequest ?? path.join(requestDir, `request.${typescript ? 'ts' : 'js'}`);
267
538
  const requestIsTs = /\.tsx?$/.test(requestFile);
@@ -276,12 +547,7 @@ writer = new writes_1.FinalizationWriter(workspace.path, dryRun)) {
276
547
  let messagesImportPath = toPosix(path.relative(requestDir, sampleLocale));
277
548
  if (!messagesImportPath.startsWith('.'))
278
549
  messagesImportPath = `./${messagesImportPath}`;
279
- const content = buildRequestConfig({
280
- sourceLocale: options.sourceLocale ?? 'en',
281
- locales: await availableLocales(workspace, options),
282
- messagesImportPath,
283
- typescript: requestIsTs,
284
- });
550
+ const content = buildRequestConfig({ sourceLocale, locales, messagesImportPath, typescript: requestIsTs, routing });
285
551
  if (content !== existingContent) {
286
552
  await writer.write(requestFile, content);
287
553
  configFileCreated = true;
@@ -290,6 +556,7 @@ writer = new writes_1.FinalizationWriter(workspace.path, dryRun)) {
290
556
  // 2. next.config — wrap with the next-intl plugin.
291
557
  const pluginPath = `./${toPosix(path.relative(root, requestFile))}`;
292
558
  const nextConfigPath = await findFirst(root, NEXT_CONFIG_FILES);
559
+ const cacheComponents = nextConfigPath ? usesCacheComponents(await (0, file_utils_1.readFile)(nextConfigPath)) : false;
293
560
  if (!nextConfigPath) {
294
561
  const created = `import createNextIntlPlugin from 'next-intl/plugin';\n\n` +
295
562
  `const withNextIntl = createNextIntlPlugin(${JSON.stringify(pluginPath)});\n\n` +
@@ -309,19 +576,65 @@ writer = new writes_1.FinalizationWriter(workspace.path, dryRun)) {
309
576
  configFileCreated = true;
310
577
  }
311
578
  }
312
- // 3. Root layout — NextIntlClientProvider so Client Components can use useTranslations().
579
+ // 3. proxy.ts (middleware.ts before Next 16) — a URL per language (#380).
580
+ if (routing === 'prefix') {
581
+ const proxyDir = path.dirname(appDir);
582
+ const existingProxy = await findFirst(proxyDir, PROXY_FILES);
583
+ const proxyContent = existingProxy ? await (0, file_utils_1.readFile)(existingProxy).catch(() => '') : null;
584
+ if (existingProxy && !proxyContent.includes(PROXY_MARKER)) {
585
+ warnings.push(`${toPosix(path.relative(root, existingProxy))} already exists, so locale URLs (/ja/…) were not set up. ` +
586
+ `Rewrite /<locale>/… to /… with the ${exports.LOCALE_HEADER} request header set to the locale (Babelize's generated proxy does this), ` +
587
+ 'or set "routing": "cookie" in .babelize/config.json to keep one URL for every language.');
588
+ }
589
+ else {
590
+ // Our earlier file keeps its name (middleware.ts still runs on Next 16).
591
+ const proxyFile = existingProxy
592
+ ?? path.join(proxyDir, `${(nextMajor(workspace.packageJson) ?? 16) >= 16 ? 'proxy' : 'middleware'}.${typescript ? 'ts' : 'js'}`);
593
+ const kind = path.basename(proxyFile).startsWith('proxy') ? 'proxy' : 'middleware';
594
+ const content = buildProxy({ kind, typescript: /\.ts$/.test(proxyFile) });
595
+ if (content !== proxyContent) {
596
+ await writer.write(proxyFile, content);
597
+ configFileCreated = true;
598
+ }
599
+ }
600
+ }
601
+ // 4. Root layout — NextIntlClientProvider so Client Components can use
602
+ // useTranslations(), and <html lang dir> from the active locale.
313
603
  const layoutPath = await findFirst(appDir, LAYOUT_FILES);
314
604
  if (!layoutPath) {
315
605
  warnings.push('No root layout found in app/: wrap your app in <NextIntlClientProvider> from next-intl.');
316
606
  }
317
607
  else {
318
608
  const content = await (0, file_utils_1.readFile)(layoutPath);
319
- const wrapped = wrapRootLayout(content, /\.tsx?$/.test(layoutPath));
609
+ const layoutIsTs = /\.tsx?$/.test(layoutPath);
610
+ let wrapped = wrapRootLayout(content, layoutIsTs, { suspense: cacheComponents });
611
+ const layoutName = toPosix(path.relative(root, layoutPath));
612
+ if (cacheComponents && content.includes('NextIntlClientProvider') && !/<Suspense\b/.test(content)) {
613
+ warnings.push(`next.config enables cacheComponents, and ${layoutName} renders NextIntlClientProvider outside <Suspense>. ` +
614
+ 'next-intl reads the locale from cookies and headers here, so wrap the <body> content in <Suspense> or next build fails.');
615
+ }
320
616
  if (wrapped === null) {
321
- warnings.push(`Could not find {children} inside <body> in ${toPosix(path.relative(root, layoutPath))}: ` +
617
+ warnings.push(`Could not find {children} inside <body> in ${layoutName}: ` +
322
618
  'wrap it in <NextIntlClientProvider> from next-intl so Client Components can translate.');
323
619
  }
324
- else if (wrapped !== content) {
620
+ // Cache Components can't read the locale outside <Suspense>, and <html> can't be inside one.
621
+ if (ownsLocales && !cacheComponents) {
622
+ let localesImport = toPosix(path.relative(path.dirname(layoutPath), localesFile)).replace(/\.(t|j)s$/, '');
623
+ if (!localesImport.startsWith('.'))
624
+ localesImport = `./${localesImport}`;
625
+ const located = setHtmlLocale(wrapped ?? content, layoutIsTs, localesImport);
626
+ if (located === null) {
627
+ warnings.push(`Could not set <html lang> and dir in ${layoutName}: use \`lang={await getLocale()}\` (next-intl/server) and ` +
628
+ `dir={localeDirection(locale)} from ${localesImport}, or right-to-left languages render left-to-right.`);
629
+ }
630
+ else {
631
+ wrapped = located;
632
+ }
633
+ }
634
+ else if (cacheComponents && locales.some(rtl_languages_1.isRTL)) {
635
+ warnings.push(`${layoutName}: set <html lang> and dir from the locale yourself (Cache Components is on); right-to-left languages need dir="rtl".`);
636
+ }
637
+ if (wrapped !== null && wrapped !== content) {
325
638
  await writer.write(layoutPath, wrapped);
326
639
  entryPointModified = true;
327
640
  }
@@ -43,6 +43,7 @@ const file_utils_1 = require("../../utils/file-utils");
43
43
  const types_1 = require("../../runtime/types");
44
44
  const StrategyFactory_1 = require("../../injection/StrategyFactory");
45
45
  const generator_1 = require("@babel/generator");
46
+ const source_scope_1 = require("../../utils/source-scope");
46
47
  /** The local name of `import X from 'i18next'` in a file, if it has one. */
47
48
  function i18nextDefaultImport(ast) {
48
49
  for (const node of ast.program.body) {
@@ -91,7 +92,7 @@ async function injectFormats(workspace, formatStrings, formatConfig, dryRun = fa
91
92
  const sourceFiles = [];
92
93
  for (const sourceDir of workspace.sourceDirs) {
93
94
  const dirPath = path.join(workspace.path, sourceDir);
94
- const files = await (0, file_utils_1.findFiles)(dirPath, types_1.SUPPORTED_EXTENSIONS, (0, types_1.workspaceExcludes)(workspace));
95
+ const files = (0, source_scope_1.filterToScope)(workspace, await (0, file_utils_1.findFiles)(dirPath, types_1.SUPPORTED_EXTENSIONS, (0, types_1.workspaceExcludes)(workspace)));
95
96
  sourceFiles.push(...files);
96
97
  }
97
98
  // Build a lookup of format strings by (relative file path, line)
@@ -225,7 +226,7 @@ async function injectFormats(workspace, formatStrings, formatConfig, dryRun = fa
225
226
  const htmlExtensions = ['.html', '.htm'];
226
227
  for (const sourceDir of workspace.sourceDirs) {
227
228
  const dirPath = path.join(workspace.path, sourceDir);
228
- const files = await (0, file_utils_1.findFiles)(dirPath, htmlExtensions, (0, types_1.workspaceExcludes)(workspace));
229
+ const files = (0, source_scope_1.filterToScope)(workspace, await (0, file_utils_1.findFiles)(dirPath, htmlExtensions, (0, types_1.workspaceExcludes)(workspace)));
229
230
  for (const filePath of files) {
230
231
  const relativePath = (0, file_utils_1.getRelativePath)(workspace.path, filePath);
231
232
  const fileStrings = stringsByFile.get(relativePath);
@@ -49,6 +49,7 @@ const file_utils_1 = require("../../utils/file-utils");
49
49
  const i18n_config_path_1 = require("../../utils/i18n-config-path");
50
50
  const i18next_icu_1 = require("../../utils/i18next-icu");
51
51
  const string_utils_1 = require("../../utils/string-utils");
52
+ const source_scope_1 = require("../../utils/source-scope");
52
53
  const ast_helpers_1 = require("../../utils/ast-helpers");
53
54
  /**
54
55
  * An arrow function that defines a component: assigned to a capitalized name
@@ -414,7 +415,7 @@ positions) {
414
415
  const sourceFiles = [];
415
416
  for (const sourceDir of workspace.sourceDirs) {
416
417
  const dirPath = path.join(workspace.path, sourceDir);
417
- const files = await (0, file_utils_1.findFiles)(dirPath, extensions, (0, types_2.workspaceExcludes)(workspace));
418
+ const files = (0, source_scope_1.filterToScope)(workspace, await (0, file_utils_1.findFiles)(dirPath, extensions, (0, types_2.workspaceExcludes)(workspace)));
418
419
  sourceFiles.push(...files);
419
420
  }
420
421
  // react-i18next projects get Babelize's config, which exports a module-level
@@ -1,18 +1,42 @@
1
1
  import type { ExtractedString, LocaleData, LocaleFile, NotInjectedString, WorkspaceInfo } from '../../runtime/types';
2
2
  import type { LockfileData } from '../lockfile/schema';
3
+ import { type MessageModule } from './message-modules';
3
4
  export interface AdoptedLocale {
5
+ /** Namespaced and modules layouts: `{ <namespace>: <that file's messages> }`. */
4
6
  data: LocaleData;
7
+ /** Flat layout: the file's content. */
5
8
  raw: string;
9
+ /** Namespaced and modules layouts: the locale's files, by namespace. */
10
+ parts?: Record<string, AdoptedPart>;
11
+ /** Modules: the locale's combining module (`index.ts`) as written. */
12
+ indexRaw?: string;
13
+ }
14
+ export interface AdoptedPart {
15
+ /** File name in the locale's folder (`auth.json`, `auth.ts`). */
16
+ file: string;
17
+ raw: string;
18
+ data: LocaleData;
19
+ /** Modules: where each string sits, to write a module like this one. */
20
+ module?: MessageModule;
6
21
  }
7
22
  /** The locale files as they are before the run (the translator writes to the same paths). */
8
23
  export declare function readAdoptedLocales(workspace: WorkspaceInfo, locales: string[]): Promise<Record<string, AdoptedLocale | null>>;
24
+ export declare function readAdoptedLocale(workspace: WorkspaceInfo, locale: string): Promise<AdoptedLocale | null>;
9
25
  /**
10
26
  * Record the translations already in the project's locale files in the
11
27
  * lockfile, so they are reused instead of re-translated. A file value wins
12
28
  * over the lockfile's (someone edited the file); a key whose source text
13
29
  * changed since the lockfile recorded it is left for re-translation.
14
30
  */
15
- export declare function seedLockfileFromLocaleFiles(lockfile: LockfileData, flatKeys: Record<string, string>, targets: Record<string, AdoptedLocale | null>): LockfileData;
31
+ export declare function seedLockfileFromLocaleFiles(lockfile: LockfileData, flatKeys: Record<string, string>, targets: Record<string, AdoptedLocale | null>, options?: {
32
+ /**
33
+ * Only replace translations the lockfile already recorded (files Babelize
34
+ * generated itself): a value it never recorded — a backup-translator
35
+ * draft, or a failed key — is retried as usual, and so is a recorded copy
36
+ * of the source text.
37
+ */
38
+ onlyOverRecorded?: boolean;
39
+ }): LockfileData;
16
40
  /** Keys of `source` missing (or empty) in each target file: the work for a run without a lockfile. */
17
41
  export declare function missingKeysByLocale(flatKeys: Record<string, string>, targets: Record<string, AdoptedLocale | null>): Record<string, string[]>;
18
42
  /**
@@ -20,8 +44,11 @@ export declare function missingKeysByLocale(flatKeys: Record<string, string>, ta
20
44
  * extra keys, non-string values) with `values` filled in, or — for a new
21
45
  * file — the source file's structure and order. Serialized like the source
22
46
  * file (indentation, trailing newline) and handed to hosts as exact content.
47
+ * `others` are the setup's other locales, whose modules can serve as the
48
+ * template for a new language's (they already import the source and say
49
+ * `satisfies`).
23
50
  */
24
- export declare function adoptedLocaleFile(workspace: WorkspaceInfo, locale: string, source: AdoptedLocale, values: Record<string, string>, existing: AdoptedLocale | null): LocaleFile;
51
+ export declare function adoptedLocaleFile(workspace: WorkspaceInfo, locale: string, source: AdoptedLocale, values: Record<string, string>, existing: AdoptedLocale | null, others?: Record<string, AdoptedLocale | null>): LocaleFile;
25
52
  /**
26
53
  * What the user needs to know after translating an adopted setup: where the
27
54
  * translations went, strings in the code that aren't wired up, and where a