Skip to content

Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors

5.3 KB
Raw Blame
#!/usr/bin/env node
/**
 * Generate the per-section i18n namespace map and the section layout files.
 *
 * Why: `src/app/layout.tsx` used to pass the ENTIRE merged locale catalog
 * (~700 KB for `en`, 132 namespaces) to `NextIntlClientProvider`, which
 * serializes it into the RSC flight payload of every rendered page — 757-865 KB
 * of HTML even for the login and 404 pages. The fix splits the catalog per
 * route section: the root layout serves only the public surface, the
 * dashboard shell serves the chrome namespaces, and each section layout adds
 * exactly what its subtree's client components use.
 *
 * Outputs:
 *   - `src/i18n/routeNamespaces.generated.json` — the map (root/chrome/home/
 *     sections). Keep in sync by re-running this script; the unit test
 *     `tests/unit/i18n-route-namespaces.test.ts` fails on drift.
 *   - `src/app/(dashboard)/dashboard/<section>/layout.tsx` — a tiny provider
 *     layout per section (only created when missing; hand-edited files are
 *     left alone and reported).
 *
 * Usage: node scripts/i18n/generate-route-namespaces.mjs
 */

import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { analyzeRouteNamespaces, REPO_ROOT } from "./lib/routeNamespacesAnalyzer.mjs";

const __dirname = dirname(fileURLToPath(import.meta.url));
const MAP_PATH = join(REPO_ROOT, "src", "i18n", "routeNamespaces.generated.json");
const SECTIONS_ROOT = join(REPO_ROOT, "src", "app", "(dashboard)", "dashboard");
const HOME_ROUTE_ROOT = join(REPO_ROOT, "src", "app", "(dashboard)", "home");

const GENERATED_MARKER =
  "// GENERATED by scripts/i18n/generate-route-namespaces.mjs — do not edit by hand.";

/** "search-tools" → "SearchTools" (dir names may contain hyphens). */
function pascalCase(name) {
  return name
    .split("-")
    .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
    .join("");
}

function sectionLayoutSource(sectionDirName) {
  return `${GENERATED_MARKER}
import { SectionI18nProvider } from "@/i18n/SectionI18nProvider";
import sectionNamespaces from "@/i18n/routeNamespaces.generated.json";

/**
 * Per-section i18n provider — serves only the namespaces this section's
 * client components actually use (see scripts/i18n/generate-route-namespaces.mjs).
 */
export default function ${pascalCase(sectionDirName)}SectionLayout({ children }: { children: React.ReactNode }) {
  return (
    <SectionI18nProvider namespaces={sectionNamespaces.sections["${sectionDirName}"]}>
      {children}
    </SectionI18nProvider>
  );
}
`;
}

function homeRouteLayoutSource() {
  return `${GENERATED_MARKER}
import { SectionI18nProvider } from "@/i18n/SectionI18nProvider";
import sectionNamespaces from "@/i18n/routeNamespaces.generated.json";

/**
 * Home route (\`/home\`) i18n provider — the "home" set covers the home page,
 * the sponsor banners and the companion components under
 * \`src/app/(dashboard)/dashboard/\` that it renders. Without this layout the
 * route inherits the dashboard chrome provider, whose namespace set is missing
 * "home" and every banner namespace, so next-intl renders MISSING_MESSAGE
 * errors in production (#16321).
 */
export default function HomeRouteLayout({ children }: { children: React.ReactNode }) {
  return <SectionI18nProvider namespaces={sectionNamespaces.home}>{children}</SectionI18nProvider>;
}
`;
}

/** Ensure a provider layout exists; report a hand-edited file without one. */
function ensureProviderLayout(layoutPath, source, label, skippedNames) {
  if (existsSync(layoutPath)) {
    const existing = readFileSync(layoutPath, "utf8");
    if (!existing.includes("SectionI18nProvider")) skippedNames.push(label);
    return 0;
  }
  mkdirSync(dirname(layoutPath), { recursive: true });
  writeFileSync(layoutPath, source);
  return 1;
}

const analysis = analyzeRouteNamespaces();

// Map file: the source of truth consumed at runtime.
writeFileSync(MAP_PATH, `${JSON.stringify(analysis, null, 2)}\n`);

// Section layouts.
let created = 0;
const skippedNames = [];
for (const sectionDirName of Object.keys(analysis.sections)) {
  const layoutPath = join(SECTIONS_ROOT, sectionDirName, "layout.tsx");
  created += ensureProviderLayout(
    layoutPath,
    sectionLayoutSource(sectionDirName),
    sectionDirName,
    skippedNames
  );
}

// Home route layout. `/dashboard` redirects to `/home`, and `/home` renders the
// home page + sponsor banners, so it needs its own provider — without it the
// route falls back to chrome-only messages and renders MISSING_MESSAGE (#16321).
created += ensureProviderLayout(
  join(HOME_ROUTE_ROOT, "layout.tsx"),
  homeRouteLayoutSource(),
  "home",
  skippedNames
);

const sectionCount = Object.keys(analysis.sections).length;
console.log("map written: src/i18n/routeNamespaces.generated.json");
console.log(
  `root=${analysis.root.length} chrome=${analysis.chrome.length} home=${analysis.home.length} sections=${sectionCount}`
);
console.log(`provider layouts created: ${created} (sections: ${sectionCount} + home route)`);
if (skippedNames.length > 0) {
  console.log(
    `WARNING: pre-existing layouts without SectionI18nProvider: ${skippedNames.join(", ")}`
  );
}
for (const [name, ns] of Object.entries(analysis.sections)) {
  console.log(`  ${name}: ${ns.length} namespaces`);
}