PEP-98: i18n core — dictionaries, localizeText, user locale, web provider, bot and push localization, i18n-check

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Асель 2026-11-15 14:25:03 +05:00
parent ec79b0bfab
commit 355c5b19b2
21 changed files with 705 additions and 34 deletions

View File

@ -2,7 +2,8 @@
// alerts) to the paired chat and turns button presses / replies into answers delivered
// back into the agent session. Telegram is an adapter over the DB, not a remote shell:
// it can only answer a specific pending question or resume/stop the session it is about.
import { reportPlatformError } from "@peppa/core";
import { reportPlatformError, telegramChatLocale } from "@peppa/core";
import { localizeText } from "@peppa/shared/i18n";
import {
accountUsageForUser,
describeUsage,
@ -146,11 +147,38 @@ export function createBot(o: BotOptions) {
const ownBots = new Map<number, OwnBot>();
const ownByChat = new Map<number, OwnBot>();
const pick = (chatId?: unknown): TelegramApi => via.getStore()?.api ?? (typeof chatId === "number" ? ownByChat.get(chatId)?.api : undefined) ?? o.api;
// ── PEP-98: messages go out in the reader's language ─────────────────────────────
// Texts are rendered in Russian everywhere (core, runner, this file); right before the Bot API
// call the text, caption and button labels are translated for the chat's user.
const readerChat = new AsyncLocalStorage<number>();
const localizeParams = async (params: Record<string, unknown>): Promise<Record<string, unknown>> => {
const chatId = typeof params.chat_id === "number" ? params.chat_id : readerChat.getStore();
if (chatId == null) return params;
const locale = await telegramChatLocale(db, chatId).catch(() => "ru" as const);
if (locale === "ru") return params;
const tr = (v: unknown) => (typeof v === "string" ? localizeText(locale, v) : v);
const out: Record<string, unknown> = { ...params, text: tr(params.text), caption: tr(params.caption) };
if (params.text === undefined) delete out.text;
if (params.caption === undefined) delete out.caption;
const markup = params.reply_markup as { inline_keyboard?: { text: string }[][]; keyboard?: ({ text: string } | string)[][] } | undefined;
if (markup && typeof markup === "object") {
const btn = <B,>(b: B): B => (typeof b === "string" ? (tr(b) as B) : b && typeof b === "object" && "text" in b ? ({ ...b, text: tr((b as { text: string }).text) } as B) : b);
out.reply_markup = {
...markup,
...(markup.inline_keyboard ? { inline_keyboard: markup.inline_keyboard.map((row) => row.map(btn)) } : {}),
...(markup.keyboard ? { keyboard: markup.keyboard.map((row) => row.map(btn)) } : {}),
};
}
return out;
};
/** The same surface as TelegramApi, routed to the right bot per call. */
const api = {
call: <T>(method: string, params: Record<string, unknown> = {}, timeoutMs?: number) => pick(params.chat_id).call<T>(method, params, timeoutMs),
sendMessage: (chatId: number, text: string, extra: Record<string, unknown> = {}) => pick(chatId).sendMessage(chatId, text, extra),
answerCallbackQuery: (id: string, text?: string) => pick().answerCallbackQuery(id, text),
call: async <T,>(method: string, params: Record<string, unknown> = {}, timeoutMs?: number) => pick(params.chat_id).call<T>(method, await localizeParams(params), timeoutMs),
sendMessage: async (chatId: number, text: string, extra: Record<string, unknown> = {}) => {
const p = await localizeParams({ ...extra, chat_id: chatId, text });
return pick(chatId).sendMessage(chatId, p.text as string, p);
},
answerCallbackQuery: async (id: string, text?: string) => pick().answerCallbackQuery(id, text === undefined ? undefined : ((await localizeParams({ text })).text as string)),
getFile: (fileId: string) => pick().getFile(fileId),
downloadFile: (filePath: string) => pick().downloadFile(filePath),
getMe: () => o.api.getMe(),
@ -695,6 +723,13 @@ export function createBot(o: BotOptions) {
}
async function handleUpdate(u: TgUpdate): Promise<void> {
// PEP-98: the person who sent the update reads the toasts and replies without a chat_id.
const reader = u.callback_query?.from?.id ?? u.message?.from?.id ?? u.message?.chat?.id;
if (reader != null) return readerChat.run(reader, () => handleUpdateIn(u));
return handleUpdateIn(u);
}
async function handleUpdateIn(u: TgUpdate): Promise<void> {
const botUserId = via.getStore()?.userId;
if (!(await claimUpdate(db, u.update_id, botUserId))) return;
try {

View File

@ -65,6 +65,7 @@ import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { asWebActor, requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
import { getT } from "@/lib/i18n";
const str = (f: FormData, k: string) => String(f.get(k) ?? "").trim();
const back = (f: FormData) => str(f, "back") || "/";
@ -75,7 +76,9 @@ async function attempt(f: FormData, fn: () => Promise<string | void>): Promise<n
try {
target = (await fn()) || target;
} catch (e) {
const msg = e instanceof PeppaError ? e.message : `Ошибка: ${(e as Error).message}`;
const t = await getT();
// PEP-98: core errors are rendered Russian text — translate them for the reader.
const msg = e instanceof PeppaError ? t.text(e.message) : t("Ошибка: {message}", { message: (e as Error).message });
const [path, query] = target.split("?");
const params = new URLSearchParams(query);
params.set("error", msg.slice(0, 300));

View File

@ -3,6 +3,8 @@ import { cookies } from "next/headers";
import { NextResponse, type NextRequest } from "next/server";
import { EGOV_COOKIE, egovCookieOptions, safeNext, sessionCookie } from "@/lib/auth";
import { db } from "@/lib/db";
import { adoptLocale, localeCookieOptions } from "@/lib/i18n";
import { LOCALE_COOKIE } from "@peppa/shared/i18n";
/** Finishes a signed eGov flow: logs in by the IIN (PEP-71: registers an unknown one), or links it to the current account. */
export async function POST(req: NextRequest) {
@ -22,6 +24,9 @@ export async function POST(req: NextRequest) {
const res = done({ redirect: safeNext(next) });
const c = sessionCookie(r.user.id);
res.cookies.set(c.name, c.value, c.options);
// PEP-98: the language picked on the login page sticks to the account (or the account's wins).
const lang = await adoptLocale(r.user.id, req.cookies.get(LOCALE_COOKIE)?.value);
if (lang) res.cookies.set(LOCALE_COOKIE, lang, localeCookieOptions);
return res;
} catch (e) {
return done({ error: e instanceof PeppaError ? e.message : "Не удалось войти через eGov" }, 400);

View File

@ -3,6 +3,8 @@ import { cookies } from "next/headers";
import { NextResponse, type NextRequest } from "next/server";
import { GOOGLE_COOKIE, googleCookieOptions, publicOrigin, safeNext, sessionCookie } from "@/lib/auth";
import { db } from "@/lib/db";
import { adoptLocale, localeCookieOptions } from "@/lib/i18n";
import { LOCALE_COOKIE } from "@peppa/shared/i18n";
/** Google redirects here (PEP-90): checks state against the browser's cookie, then logs in, registers or links. */
export async function GET(req: NextRequest) {
@ -25,6 +27,9 @@ export async function GET(req: NextRequest) {
const res = done(next);
const c = sessionCookie(r.user.id);
res.cookies.set(c.name, c.value, c.options);
// PEP-98: the language picked on the login page sticks to the account (or the account's wins).
const lang = await adoptLocale(r.user.id, req.cookies.get(LOCALE_COOKIE)?.value);
if (lang) res.cookies.set(LOCALE_COOKIE, lang, localeCookieOptions);
return res;
} catch (e) {
return done("/login", e instanceof PeppaError ? e.message : "Не удалось войти через Google");

View File

@ -2,6 +2,8 @@ import { consumeLoginLink } from "@peppa/core";
import { NextResponse, type NextRequest } from "next/server";
import { publicOrigin, sessionCookie } from "@/lib/auth";
import { db } from "@/lib/db";
import { adoptLocale, localeCookieOptions } from "@/lib/i18n";
import { LOCALE_COOKIE } from "@peppa/shared/i18n";
/** One-time admin login link from `peppa web login-link`. */
export async function GET(req: NextRequest) {
@ -11,5 +13,8 @@ export async function GET(req: NextRequest) {
const res = NextResponse.redirect(`${origin}/`);
const c = sessionCookie(uid);
res.cookies.set(c.name, c.value, c.options);
// PEP-98: the language picked on the login page sticks to the account (or the account's wins).
const lang = await adoptLocale(uid, req.cookies.get(LOCALE_COOKIE)?.value);
if (lang) res.cookies.set(LOCALE_COOKIE, lang, localeCookieOptions);
return res;
}

View File

@ -2,21 +2,30 @@ import type { ReactNode } from "react";
import { cookies } from "next/headers";
import { GeistSans } from "geist/font/sans";
import { GeistMono } from "geist/font/mono";
import { productName } from "@peppa/shared/i18n";
import { cn } from "@/lib/utils";
import { THEME_COOKIE } from "@/lib/theme";
import { getLocale, getT } from "@/lib/i18n";
import { ErrorReporter } from "@/components/ErrorReporter";
import { I18nProvider } from "@/components/I18n";
import "./app.css";
export const metadata = { title: "Peppa", description: "Софтвейр-фабрика: проекты, стори и агенты", icons: { icon: "/icon.svg" } };
export async function generateMetadata() {
const t = await getT();
return { title: productName(t.locale), description: t("Софтвейр-фабрика: проекты, стори и агенты"), icons: { icon: "/icon.svg" } };
}
export default async function RootLayout({ children }: { children: ReactNode }) {
// Dark by default; the cookie is read on the server so a light choice renders without a dark flash.
const light = (await cookies()).get(THEME_COOKIE)?.value === "light";
const locale = await getLocale();
return (
<html lang="ru" className={cn(GeistSans.variable, GeistMono.variable, !light && "dark")}>
<html lang={locale === "kk" ? "kk" : locale} className={cn(GeistSans.variable, GeistMono.variable, !light && "dark")}>
<body>
<ErrorReporter />
{children}
<I18nProvider locale={locale}>
<ErrorReporter />
{children}
</I18nProvider>
</body>
</html>
);

View File

@ -0,0 +1,19 @@
"use server";
import { forgetChatLocales, setUserLocale } from "@peppa/core";
import { LOCALE_COOKIE, normalizeLocale } from "@peppa/shared/i18n";
import { cookies } from "next/headers";
import { currentUser } from "@/lib/auth";
import { db } from "@/lib/db";
import { localeCookieOptions } from "@/lib/i18n";
/** PEP-98: language switcher — cookie for everyone, plus the user's setting when logged in. */
export async function setLanguage(value: string): Promise<void> {
const locale = normalizeLocale(value);
(await cookies()).set(LOCALE_COOKIE, locale, localeCookieOptions);
const user = await currentUser();
if (user) {
await setUserLocale(db, user.id, locale);
forgetChatLocales();
}
}

View File

@ -0,0 +1,53 @@
"use client";
// Interface language in client components (PEP-98): the root layout passes the locale,
// `useT()` gives a translator over the bundled dictionaries.
import { createContext, useContext, useMemo, useTransition, type ReactNode } from "react";
import { useRouter } from "next/navigation";
import { LOCALE_LABELS, LOCALES, translator, type Locale, type Translator } from "@peppa/shared/i18n";
import { setLanguage } from "@/app/locale-actions";
import { cn } from "@/lib/utils";
const LocaleContext = createContext<Locale>("ru");
export function I18nProvider({ locale, children }: { locale: Locale; children: ReactNode }) {
return <LocaleContext.Provider value={locale}>{children}</LocaleContext.Provider>;
}
export function useLocale(): Locale {
return useContext(LocaleContext);
}
export function useT(): Translator {
const locale = useLocale();
return useMemo(() => translator(locale), [locale]);
}
/** RU / EN / KZ: saves the cookie (and the user's choice when logged in), then re-renders. */
export function LanguageSwitcher({ className }: { className?: string }) {
const current = useLocale();
const t = useT();
const router = useRouter();
const [pending, start] = useTransition();
return (
<div role="group" aria-label={t("Язык интерфейса")} className={cn("inline-flex rounded-md border p-0.5", className)}>
{LOCALES.map((l) => (
<button
key={l}
type="button"
disabled={pending}
aria-pressed={l === current}
onClick={() =>
start(async () => {
await setLanguage(l);
router.refresh();
})
}
className={cn("rounded px-2 py-0.5 font-mono text-xs transition-colors", l === current ? "bg-primary text-primary-foreground" : "text-muted-foreground hover:text-foreground")}
>
{LOCALE_LABELS[l]}
</button>
))}
</div>
);
}

View File

@ -7,6 +7,8 @@ import { Brand } from "@/components/Brand";
import { ThemeToggle } from "@/components/ThemeToggle";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { useT } from "@/components/I18n";
import { m } from "@peppa/shared/i18n";
interface Item {
href: string;
@ -21,45 +23,46 @@ interface Item {
}
const ITEMS: Item[] = [
{ href: "/", label: "Главная", icon: House, match: (p) => p === "/", count: "questions" },
{ href: "/chats", label: "Чаты", icon: MessagesSquare, match: (p) => p.startsWith("/chats") },
{ href: "/projects", label: "Проекты", icon: FolderKanban, match: (p) => p.startsWith("/projects") || p.startsWith("/p/") || p.startsWith("/t/") },
{ href: "/runners", label: "Работа агентов", icon: Bot, match: (p) => p.startsWith("/runners"), count: "waitingRunners" },
{ href: "/team", label: "Команда", icon: Contact, match: (p) => p.startsWith("/team"), desktopOnly: true },
{ href: "/welcome", label: "О Пеппе", icon: Sparkles, match: (p) => p.startsWith("/welcome"), desktopOnly: true },
{ href: "/help", label: "Помощь", icon: LifeBuoy, match: (p) => p.startsWith("/help") },
{ href: "/subscriptions", label: "Подписки", icon: KeyRound, match: (p) => p.startsWith("/subscriptions"), admin: true },
{ href: "/secrets", label: "Секреты", icon: ShieldCheck, match: (p) => p.startsWith("/secrets"), admin: true },
{ href: "/hosts", label: "Хосты", icon: Server, match: (p) => p.startsWith("/hosts"), admin: true },
{ href: "/journal", label: "Журнал", icon: ScrollText, match: (p) => p.startsWith("/journal"), admin: true },
{ href: "/platform", label: "Платформа", icon: Megaphone, match: (p) => p.startsWith("/platform"), admin: true },
{ href: "/users", label: "Пользователи", icon: Users, match: (p) => p.startsWith("/users"), admin: true },
{ href: "/settings", label: "Настройки", icon: Settings, match: (p) => p.startsWith("/settings") },
{ href: "/", label: m("Главная"), icon: House, match: (p) => p === "/", count: "questions" },
{ href: "/chats", label: m("Чаты"), icon: MessagesSquare, match: (p) => p.startsWith("/chats") },
{ href: "/projects", label: m("Проекты"), icon: FolderKanban, match: (p) => p.startsWith("/projects") || p.startsWith("/p/") || p.startsWith("/t/") },
{ href: "/runners", label: m("Работа агентов"), icon: Bot, match: (p) => p.startsWith("/runners"), count: "waitingRunners" },
{ href: "/team", label: m("Команда"), icon: Contact, match: (p) => p.startsWith("/team"), desktopOnly: true },
{ href: "/welcome", label: m("О Пеппе"), icon: Sparkles, match: (p) => p.startsWith("/welcome"), desktopOnly: true },
{ href: "/help", label: m("Помощь"), icon: LifeBuoy, match: (p) => p.startsWith("/help") },
{ href: "/subscriptions", label: m("Подписки"), icon: KeyRound, match: (p) => p.startsWith("/subscriptions"), admin: true },
{ href: "/secrets", label: m("Секреты"), icon: ShieldCheck, match: (p) => p.startsWith("/secrets"), admin: true },
{ href: "/hosts", label: m("Хосты"), icon: Server, match: (p) => p.startsWith("/hosts"), admin: true },
{ href: "/journal", label: m("Журнал"), icon: ScrollText, match: (p) => p.startsWith("/journal"), admin: true },
{ href: "/platform", label: m("Платформа"), icon: Megaphone, match: (p) => p.startsWith("/platform"), admin: true },
{ href: "/users", label: m("Пользователи"), icon: Users, match: (p) => p.startsWith("/users"), admin: true },
{ href: "/settings", label: m("Настройки"), icon: Settings, match: (p) => p.startsWith("/settings") },
];
const COUNT_TITLE = { questions: "вопросов ждут тебя", waitingRunners: "раннеров ждут тебя" };
const COUNT_TITLE = { questions: m("{n} вопросов ждут тебя"), waitingRunners: m("{n} раннеров ждут тебя") };
/** Left panel on desktop; on phones a top bar plus a bottom tab bar (PEP-38): sections with «ждут тебя» counters, theme, user. */
export function Sidebar({ login, avatarUrl, counts, superadmin = false }: { login: string; avatarUrl: string | null; counts: Record<"questions" | "waitingRunners", number>; superadmin?: boolean }) {
const path = usePathname();
const t = useT();
return (
<header className="sticky top-0 z-30 flex h-14 items-center gap-2 border-b bg-sidebar px-3 md:h-dvh md:flex-col md:items-stretch md:gap-1 md:border-r md:border-b-0 md:px-3 md:py-4">
<Link href="/" className="flex shrink-0 items-center gap-2 rounded-md px-1 text-foreground hover:no-underline md:mb-4 md:px-2">
<Brand />
<span className="hidden font-mono text-[11px] text-muted-foreground md:inline">фабрика</span>
<span className="hidden font-mono text-[11px] text-muted-foreground md:inline">{t("фабрика")}</span>
</Link>
{/* PEP-52: the palette listens for clicks on [data-open-palette]. */}
<button
type="button"
data-open-palette
title="Поиск и команды (⌘K)"
title={t("Поиск и команды (⌘K)")}
className="ml-auto flex items-center gap-2 rounded-md border bg-background/60 px-2 py-1.5 text-sm text-muted-foreground transition-colors hover:text-foreground md:mb-2 md:ml-0"
>
<Search className="size-4" />
<span className="hidden md:inline">Поиск</span>
<span className="hidden md:inline">{t("Поиск")}</span>
<kbd className="ml-auto hidden rounded border bg-muted px-1 font-mono text-[10px] md:inline">⌘K</kbd>
</button>
<nav
aria-label="Разделы"
aria-label={t("Разделы")}
className="fixed inset-x-0 bottom-0 z-30 grid grid-cols-6 border-t bg-sidebar/95 pb-[env(safe-area-inset-bottom)] backdrop-blur md:static md:flex md:flex-col md:gap-0.5 md:border-0 md:bg-transparent md:pb-0 md:backdrop-blur-none"
>
{ITEMS.filter((i) => !i.admin || superadmin).map((i) => {
@ -77,9 +80,9 @@ export function Sidebar({ login, avatarUrl, counts, superadmin = false }: { logi
)}
>
<i.icon className={cn("size-5 md:size-4", active && "text-primary")} />
<span>{i.label}</span>
<span>{t(i.label)}</span>
{n > 0 && (
<span title={`${n} ${COUNT_TITLE[i.count!]}`} className="absolute top-1 left-[calc(50%+6px)] min-w-4 rounded-full bg-primary px-1 text-center font-mono text-[10px] font-semibold leading-4 text-primary-foreground tabular-nums md:static md:ml-auto md:min-w-5 md:px-1.5 md:text-[11px] md:leading-5">
<span title={t(COUNT_TITLE[i.count!], { n })} className="absolute top-1 left-[calc(50%+6px)] min-w-4 rounded-full bg-primary px-1 text-center font-mono text-[10px] font-semibold leading-4 text-primary-foreground tabular-nums md:static md:ml-auto md:min-w-5 md:px-1.5 md:text-[11px] md:leading-5">
{n}
</span>
)}
@ -92,7 +95,7 @@ export function Sidebar({ login, avatarUrl, counts, superadmin = false }: { logi
<span className="hidden min-w-0 flex-1 truncate text-sm md:block" title={login}>{login}</span>
<ThemeToggle />
<form action="/logout" method="post">
<Button variant="ghost" size="icon-sm" aria-label="Выйти" title="Выйти">
<Button variant="ghost" size="icon-sm" aria-label={t("Выйти")} title={t("Выйти")}>
<LogOut />
</Button>
</form>

View File

@ -3,15 +3,17 @@
import { Moon, Sun } from "lucide-react";
import { Button } from "@/components/ui/button";
import { THEME_COOKIE } from "@/lib/theme";
import { useT } from "@/components/I18n";
/** Dark ⇄ light; the choice lives in a cookie for a year (the root layout reads it). */
export function ThemeToggle() {
const t = useT();
const toggle = () => {
const dark = document.documentElement.classList.toggle("dark");
document.cookie = `${THEME_COOKIE}=${dark ? "dark" : "light"}; path=/; max-age=31536000; samesite=lax`;
};
return (
<Button variant="ghost" size="icon-sm" onClick={toggle} aria-label="Сменить тему" title="Сменить тему">
<Button variant="ghost" size="icon-sm" onClick={toggle} aria-label={t("Сменить тему")} title={t("Сменить тему")}>
<Sun className="hidden dark:block" />
<Moon className="dark:hidden" />
</Button>

38
apps/web/lib/i18n.ts Normal file
View File

@ -0,0 +1,38 @@
// Interface language on the server (PEP-98): the user's choice, else the cookie, else (only
// before login) the browser's Accept-Language, else Russian.
import { getUserLocaleSetting, setUserLocale } from "@peppa/core";
import { isLocale, LOCALE_COOKIE, localeFromAcceptLanguage, translator, type Locale, type Translator } from "@peppa/shared/i18n";
import { cookies, headers } from "next/headers";
import { cache } from "react";
import { currentUser } from "./auth";
import { db } from "./db";
export const getLocale = cache(async (): Promise<Locale> => {
const cookie = (await cookies()).get(LOCALE_COOKIE)?.value;
const user = await currentUser();
if (user) {
const own = await getUserLocaleSetting(db, user.id);
if (own) return own;
return isLocale(cookie) ? cookie : "ru";
}
if (isLocale(cookie)) return cookie;
return localeFromAcceptLanguage((await headers()).get("accept-language")) ?? "ru";
});
/** Translator for the current request: `const t = await getT(); t("Проекты")`. */
export async function getT(): Promise<Translator> {
return translator(await getLocale());
}
export const localeCookieOptions = { sameSite: "lax" as const, path: "/", maxAge: 365 * 86400 };
/**
* After login: a language picked on the login page (cookie) becomes the user's if they have
* none yet; otherwise the user's language goes into the cookie. Returns the cookie to set.
*/
export async function adoptLocale(userId: number, cookieValue: string | undefined): Promise<Locale | null> {
const own = await getUserLocaleSetting(db, userId);
if (own) return own === cookieValue ? null : own;
if (isLocale(cookieValue)) await setUserLocale(db, userId, cookieValue);
return null;
}

View File

@ -30,3 +30,16 @@
## Название
`ru`: «Пеппа» / «Peppa»; `en`: «Peppa FACTORY» (заголовок страницы, марка входа, бот).
## Как переводить (соглашения для кода)
- Серверный компонент / server action: `const t = await getT()` (`@/lib/i18n`); клиентский:
`const t = useT()` (`@/components/I18n`). `t("Текст {x}", { x })`.
- Константы уровня модуля (подписи, меню, статусы): `m("Текст")` из `@peppa/shared/i18n`,
перевод при показе `t(label)`.
- Множественное число: `t.n(n, "{n} стори", "{n} стори", "{n} стори")` (ключи — формы one/few/many).
- Текст, пришедший из core/БД (ошибки, события, сообщения): `t.text(value)`.
- Даты/числа: `intlLocale(t.locale)` вместо `"ru-RU"`.
- core/runner/bot: тексты пользователю — `m("… {x} …", { x })` (рендерит тот же русский текст);
тексты агентам (промпты, правила) не переводятся — `// i18n-ignore`.
- Словарь: `packages/shared/src/i18n/en/<раздел>.ts`, ключ — точная русская строка.
- Проверка: `node scripts/i18n-check.ts` (`--summary` — по файлам).

View File

@ -6,6 +6,7 @@ export * from "./tasks.ts";
export * from "./sessions.ts";
export * from "./rules.ts";
export * from "./settings.ts";
export * from "./locale.ts";
export * from "./runners.ts";
export * from "./hosts.ts";
export * from "./telegram.ts";

View File

@ -0,0 +1,50 @@
// User interface language (PEP-98): `settings` `user.locale:<id>`, no column. Missing = Russian.
import { chats, projects, users, type Db } from "@peppa/db";
import { isLocale, normalizeLocale, type Locale } from "@peppa/shared/i18n";
import { eq } from "drizzle-orm";
import { deleteSetting, getSetting, setSetting } from "./settings.ts";
const key = (userId: number) => `user.locale:${userId}`;
/** The language the user picked, or null when never chosen. */
export async function getUserLocaleSetting(db: Db, userId: number): Promise<Locale | null> {
const v = await getSetting<string>(db, key(userId));
return isLocale(v) ? v : null;
}
export async function getUserLocale(db: Db, userId: number): Promise<Locale> {
return normalizeLocale(await getUserLocaleSetting(db, userId));
}
export async function setUserLocale(db: Db, userId: number, locale: Locale | null): Promise<void> {
if (locale == null) await deleteSetting(db, key(userId));
else if (isLocale(locale)) await setSetting(db, key(userId), locale);
else throw new Error("Неизвестный язык");
}
const chatCache = new Map<number, { locale: Locale; at: number }>();
/** Language of the reader of a Telegram chat: the paired user, or for a linked group the user who linked it; Russian otherwise. */
export async function telegramChatLocale(db: Db, chatId: number, now = Date.now()): Promise<Locale> {
const hit = chatCache.get(chatId);
if (hit && now - hit.at < 60_000) return hit.locale;
const [u] = await db.select({ id: users.id }).from(users).where(eq(users.telegramChatId, chatId));
let userId: number | null = u?.id ?? null;
if (userId == null) {
// A linked group (PEP-62): the language of the user who linked it, else the project owner.
const [g] = await db
.select({ by: chats.tgLinkedBy, owner: projects.ownerId, master: chats.userId })
.from(chats)
.leftJoin(projects, eq(projects.id, chats.projectId))
.where(eq(chats.tgChatId, chatId));
userId = g ? (g.by ?? g.owner ?? g.master ?? null) : null;
}
const locale = userId != null ? await getUserLocale(db, userId) : "ru";
chatCache.set(chatId, { locale, at: now });
return locale;
}
/** Forget cached chat languages (after the user changes theirs). */
export function forgetChatLocales(): void {
chatCache.clear();
}

View File

@ -8,6 +8,8 @@ import type { Question } from "./tasks.ts";
import type { User } from "./users.ts";
import { enqueuePush, type PushPayload } from "./webpush.ts";
import { addMasterMessage } from "./chats.ts";
import { getUserLocale } from "./locale.ts";
import { localizeText } from "@peppa/shared/i18n";
/** Telegram HTML → plain text for the web chat. */
export function htmlToText(html: string): string {
@ -190,7 +192,10 @@ export async function deliverToUser(db: Db, user: User, d: Delivery, prefs?: Not
});
}
if (ch.push && d.push && !quiet) {
out.push = await enqueuePush(db, user.id, { dedupeKey: d.pushKey ?? d.dedupeKey, payload: { ...d.push, sound: d.push.sound ?? p.sound }, urgency: d.urgency });
// PEP-98: push text in the user's language (Telegram is translated by the bot when sent).
const locale = await getUserLocale(db, user.id);
const push = locale === "ru" ? d.push : { ...d.push, title: localizeText(locale, d.push.title), body: localizeText(locale, d.push.body) };
out.push = await enqueuePush(db, user.id, { dedupeKey: d.pushKey ?? d.dedupeKey, payload: { ...push, sound: d.push.sound ?? p.sound }, urgency: d.urgency });
}
return out;
}

View File

@ -5,7 +5,8 @@
"type": "module",
"exports": {
".": "./src/index.ts",
"./palette": "./src/palette.ts"
"./palette": "./src/palette.ts",
"./i18n": "./src/i18n/index.ts"
},
"scripts": {
"typecheck": "tsc -p ."

View File

@ -0,0 +1,58 @@
import type { Dict } from "../index.ts";
/** Shared words: navigation, statuses, buttons, generic errors. */
export const common: Dict = {
Пеппа: "Peppa FACTORY",
"Софтвейр-фабрика: проекты, стори и агенты": "Software factory: projects, stories and agents",
"Язык интерфейса": "Interface language",
"Ошибка: {message}": "Error: {message}",
"Неизвестный язык": "Unknown language",
// Glossary — reuse these words: стори → story, эпик → epic, раннер → runner, агент → agent,
// PM → PM, подписка → subscription, вопрос → question, ревью → review, «Принять» → «Accept».
Бэклог: "Backlog",
"В работе": "In progress",
Ревью: "Review",
Готово: "Done",
"в работе": "in progress",
бэклог: "backlog",
ревью: "review",
готово: "done",
Принять: "Accept",
Отмена: "Cancel",
Сохранить: "Save",
Удалить: "Delete",
Изменить: "Edit",
Закрыть: "Close",
Стори: "Story",
стори: "story",
Эпик: "Epic",
Эпики: "Epics",
Раннер: "Runner",
Раннеры: "Runners",
Агент: "Agent",
"Не найдено": "Not found",
"Нет доступа": "No access",
// Navigation (Sidebar)
Главная: "Home",
Чаты: "Chats",
Проекты: "Projects",
"Работа агентов": "Agent work",
Команда: "Team",
"О Пеппе": "About Peppa",
Помощь: "Help",
Подписки: "Subscriptions",
Секреты: "Secrets",
Хосты: "Hosts",
Журнал: "Journal",
Платформа: "Platform",
Пользователи: "Users",
Настройки: "Settings",
"{n} вопросов ждут тебя": "{n} questions waiting for you",
"{n} раннеров ждут тебя": "{n} runners waiting for you",
фабрика: "factory",
"Поиск и команды (⌘K)": "Search and commands (⌘K)",
Поиск: "Search",
Разделы: "Sections",
Выйти: "Log out",
"Сменить тему": "Toggle theme",
};

View File

@ -0,0 +1,6 @@
// English dictionary (PEP-98), split by area so parts can be edited independently.
// Keys are the Russian strings exactly as in the code; values may reorder {placeholders}.
import type { Dict } from "../index.ts";
import { common } from "./common.ts";
export const en: Dict = { ...common };

View File

@ -0,0 +1,250 @@
// Interface language (PEP-98). Dictionary keys are the Russian strings themselves (templates
// with {name} placeholders): Russian needs no dictionary, a missing translation shows Russian.
// `t` translates a known key; `localizeText` translates text that was already rendered from a
// template somewhere else (core/runner messages, errors, notifications) by reverse matching.
// Pure module: used by the server, the bot and client components.
import { en } from "./en/index.ts";
import { kk } from "./kk.ts";
export const LOCALES = ["ru", "en", "kk"] as const;
export type Locale = (typeof LOCALES)[number];
export const DEFAULT_LOCALE: Locale = "ru";
/** Cookie with the chosen language. */
export const LOCALE_COOKIE = "peppa_lang";
/** Switcher labels. */
export const LOCALE_LABELS: Record<Locale, string> = { ru: "RU", en: "EN", kk: "KZ" };
export type Dict = Record<string, string>;
const DICTS: Record<Locale, Dict> = { ru: {}, en, kk };
export function normalizeLocale(v: unknown): Locale {
return typeof v === "string" && (LOCALES as readonly string[]).includes(v) ? (v as Locale) : DEFAULT_LOCALE;
}
export const isLocale = (v: unknown): v is Locale => typeof v === "string" && (LOCALES as readonly string[]).includes(v);
/** Best language from an Accept-Language header (null when nothing matches). */
export function localeFromAcceptLanguage(header: string | null | undefined): Locale | null {
if (!header) return null;
const langs = header
.split(",")
.map((p) => {
const [tag, ...params] = p.trim().split(";");
const q = params.map((x) => x.trim()).find((x) => x.startsWith("q="));
return { tag: (tag ?? "").toLowerCase(), q: q ? Number(q.slice(2)) || 0 : 1 };
})
.filter((x) => x.tag)
.sort((a, b) => b.q - a.q);
for (const { tag } of langs) {
const base = tag.split("-")[0];
if (base === "ru") return "ru";
if (base === "en") return "en";
if (base === "kk" || base === "kz") return "kk";
}
return null;
}
/** Substitutes {name} placeholders. */
export function fill(s: string, vars?: Record<string, unknown>): string {
if (!vars) return s;
return s.replace(/\{(\w+)\}/g, (all, k: string) => (k in vars && vars[k] != null ? String(vars[k]) : all));
}
/** The dictionary entry for `key` in `locale`, or undefined (kk falls back to Russian). */
function entry(locale: Locale, key: string): string | undefined {
return DICTS[locale][key];
}
/** Translates a Russian key (a template) into `locale` and fills the placeholders. */
export function t(locale: Locale, key: string, vars?: Record<string, unknown>): string {
return fill(entry(locale, key) ?? key, vars);
}
/**
* Marks a Russian template for the dictionary check and renders it in Russian (as before).
* Used where the text is produced without knowing the reader (core, runner); the delivery
* layer translates it with `localizeText`.
*/
export const m = (key: string, vars?: Record<string, unknown>): string => fill(key, vars);
/** Russian plural form: one (1, 21), few (2–4, 22), many (5, 11, 25). */
export function ruPlural<T>(n: number, one: T, few: T, many: T): T {
const a = Math.abs(n) % 100;
const b = a % 10;
if (a > 10 && a < 20) return many;
if (b === 1) return one;
if (b >= 2 && b <= 4) return few;
return many;
}
/**
* Plural-aware translation: Russian forms are the keys; English uses the `one` entry for
* n = 1 and the `many` entry otherwise. `{n}` is filled with the number.
*/
export function tn(locale: Locale, n: number, one: string, few: string, many: string, vars?: Record<string, unknown>): string {
const v = { n, ...vars };
if (locale === "ru" || (locale === "kk" && entry("kk", many) === undefined)) return fill(ruPlural(n, one, few, many), v);
return t(locale, n === 1 ? one : many, v);
}
/** A translator bound to a locale — what pages and components use. */
export interface Translator {
(key: string, vars?: Record<string, unknown>): string;
locale: Locale;
n: (n: number, one: string, few: string, many: string, vars?: Record<string, unknown>) => string;
/** Translates already rendered Russian text (see localizeText). */
text: (text: string | null | undefined) => string;
}
export function translator(locale: Locale): Translator {
const fn = ((key: string, vars?: Record<string, unknown>) => t(locale, key, vars)) as Translator;
fn.locale = locale;
fn.n = (n, one, few, many, vars) => tn(locale, n, one, few, many, vars);
fn.text = (text) => localizeText(locale, text ?? "");
return fn;
}
// ---- Reverse matching of rendered text --------------------------------------------------
interface Template {
re: RegExp;
names: string[];
out: string;
weight: number;
}
const CYR = /[А-Яа-яЁё]/;
const compiled = new Map<Locale, { byHead: Map<string, Template[]>; loose: Template[] }>();
const caches = new Map<Locale, Map<string, string>>();
const CACHE_MAX = 5000;
const escapeRe = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
function compile(locale: Locale) {
let c = compiled.get(locale);
if (c) return c;
c = { byHead: new Map(), loose: [] };
for (const [key, out] of Object.entries(DICTS[locale])) {
if (!key.includes("{")) continue;
const parts = key.split(/\{(\w+)\}/);
const names: string[] = [];
let src = "^";
let weight = 0;
for (let i = 0; i < parts.length; i++) {
if (i % 2) {
names.push(parts[i]!);
src += "([\\s\\S]+?)";
} else {
src += escapeRe(parts[i]!);
weight += parts[i]!.length;
}
}
if (weight < 2) continue; // "{a} {b}" would match anything
const tpl: Template = { re: new RegExp(src + "$"), names, out, weight };
const head = parts[0]!.slice(0, 2);
if (head.length === 2) {
const list = c.byHead.get(head) ?? [];
list.push(tpl);
c.byHead.set(head, list);
} else c.loose.push(tpl);
}
for (const list of c.byHead.values()) list.sort((a, b) => b.weight - a.weight);
c.loose.sort((a, b) => b.weight - a.weight);
compiled.set(locale, c);
return c;
}
function matchTemplate(locale: Locale, s: string, depth: number): string | undefined {
const c = compile(locale);
const lists = [c.byHead.get(s.slice(0, 2)) ?? [], c.loose];
for (const list of lists) {
for (const tpl of list) {
const mt = tpl.re.exec(s);
if (!mt) continue;
const vars: Record<string, string> = {};
tpl.names.forEach((name, i) => {
const v = mt[i + 1]!;
vars[name] = depth < 2 ? (piece(locale, v, depth + 1) ?? v) : v;
});
return fill(tpl.out, vars);
}
}
return undefined;
}
/** Exact entry or a template match; undefined when nothing fits. */
function piece(locale: Locale, s: string, depth = 0): string | undefined {
if (!CYR.test(s)) return undefined;
const exact = entry(locale, s);
if (exact !== undefined) return exact;
return matchTemplate(locale, s, depth);
}
/** Leading/trailing decoration around a phrase: whitespace, emoji, bullets, dashes, punctuation. */
const EDGE = /^([^А-Яа-яЁёA-Za-z0-9«"(<{]*)([\s\S]*?)([\s.:;,!?…)»"]*)$/u;
function phrase(locale: Locale, s: string): string {
const direct = piece(locale, s);
if (direct !== undefined) return direct;
const mt = EDGE.exec(s);
if (mt && (mt[1] || mt[3])) {
const core = mt[2]!;
const inner = piece(locale, core);
if (inner !== undefined) return mt[1] + inner + mt[3];
// "Стори готова." → key "Стори готова." handled above; try keeping the trailing dot in the key
if (mt[3]) {
const withTail = piece(locale, core + mt[3].trimEnd());
if (withTail !== undefined) return mt[1] + withTail + mt[3].slice(mt[3].trimEnd().length);
}
}
return s;
}
function line(locale: Locale, s: string): string {
if (!CYR.test(s)) return s;
const whole = phrase(locale, s);
if (whole !== s) return whole;
// Telegram HTML: translate the text between tags one by one.
if (s.includes("<")) {
const segs = s.split(/(<[^>]+>)/);
if (segs.length > 1) return segs.map((seg) => (seg.startsWith("<") ? seg : phrase(locale, seg))).join("");
}
// "Label: value" and "a · b" pieces.
for (const sep of [" · ", " — ", ": "]) {
if (s.includes(sep)) {
const out = s
.split(sep)
.map((p) => phrase(locale, p))
.join(sep);
if (out !== s) return out;
}
}
return s;
}
/**
* Translates already rendered Russian text into `locale`: the whole text, then line by line,
* then the pieces between HTML tags. Unknown text stays as it is.
*/
export function localizeText(locale: Locale, text: string): string {
if (locale === "ru" || !text || !CYR.test(text)) return text;
let cache = caches.get(locale);
if (!cache) caches.set(locale, (cache = new Map()));
const hit = cache.get(text);
if (hit !== undefined) return hit;
let out = phrase(locale, text);
if (out === text) out = text.includes("\n") ? text.split("\n").map((l) => line(locale, l)).join("\n") : line(locale, text);
if (cache.size >= CACHE_MAX) cache.clear();
cache.set(text, out);
return out;
}
/** BCP 47 tag for Intl / toLocaleString in `locale`. */
export const intlLocale = (locale: Locale) => (locale === "en" ? "en-GB" : locale === "kk" ? "kk-KZ" : "ru-RU");
/** Product name in `locale`. */
export const productName = (locale: Locale) => (locale === "en" ? "Peppa FACTORY" : "Peppa");
/** All keys of the English dictionary (for the coverage check). */
export const dictionary = (locale: Locale): Dict => DICTS[locale];

View File

@ -0,0 +1,4 @@
import type { Dict } from "./index.ts";
/** Kazakh — filled in PEP-99; until then every string falls back to Russian. */
export const kk: Dict = {};

106
scripts/i18n-check.ts Normal file
View File

@ -0,0 +1,106 @@
#!/usr/bin/env node
// PEP-98: dictionary coverage. Every key marked in code — `t("…")`, `m("…")`, `t.n(n, "…", "…", "…")`,
// `tn(locale, n, …)` — must have an English translation; in the strict areas (web, bot) every
// Cyrillic string literal and JSX text must be such a key. Exemptions: `// i18n-ignore` on the
// line or the line above, `// i18n-ignore-file` anywhere in the file.
// node scripts/i18n-check.ts — check, exit 1 on problems
// node scripts/i18n-check.ts --summary — counts per file only
import { readdirSync, readFileSync, statSync } from "node:fs";
import { join, relative } from "node:path";
import ts from "typescript";
import { dictionary } from "../packages/shared/src/i18n/index.ts";
const root = new URL("..", import.meta.url).pathname;
const STRICT = ["apps/web/app", "apps/web/components", "apps/web/lib", "apps/bot/src"];
const KEYS_ONLY = ["packages/core/src", "packages/runner/src", "packages/mcp/src", "packages/shared/src"];
const CYR = /[А-Яа-яЁё]/;
function files(dir: string): string[] {
const out: string[] = [];
const abs = join(root, dir);
for (const name of readdirSync(abs)) {
if (name === "node_modules" || name.startsWith(".")) continue;
const p = join(abs, name);
if (statSync(p).isDirectory()) out.push(...files(relative(root, p)));
else if (/\.(ts|tsx)$/.test(name) && !name.endsWith(".d.ts") && !p.includes("/i18n/")) out.push(p);
}
return out;
}
const en = dictionary("en");
const missing = new Map<string, string>(); // key → first place
const loose: { where: string; text: string }[] = [];
function calleeName(e: ts.Expression): string {
if (ts.isIdentifier(e)) return e.text;
if (ts.isPropertyAccessExpression(e)) return `${calleeName(e.expression)}.${e.name.text}`;
return "";
}
const KEY_CALLS = /^(t|m|tr)$|\.(t|m)$/;
const PLURAL_CALLS = /^(tn)$|\.n$|^t\.n$/;
function check(file: string, strict: boolean) {
const src = readFileSync(file, "utf8");
if (!CYR.test(src) || src.includes("i18n-ignore-file")) return;
const lines = src.split("\n");
const sf = ts.createSourceFile(file, src, ts.ScriptTarget.Latest, true, file.endsWith("x") ? ts.ScriptKind.TSX : ts.ScriptKind.TS);
const rel = relative(root, file);
const ignored = (node: ts.Node) => {
const line = sf.getLineAndCharacterOfPosition(node.getStart()).line;
return (lines[line] ?? "").includes("i18n-ignore") || (lines[line - 1] ?? "").includes("i18n-ignore");
};
const keyArgs = new Set<ts.Node>();
const visitCalls = (node: ts.Node) => {
if (ts.isCallExpression(node)) {
const name = calleeName(node.expression);
const lit = node.arguments.filter((a) => ts.isStringLiteral(a) || ts.isNoSubstitutionTemplateLiteral(a));
if (KEY_CALLS.test(name) && lit[0]) keyArgs.add(lit[0]);
else if (PLURAL_CALLS.test(name)) lit.forEach((a) => keyArgs.add(a));
}
ts.forEachChild(node, visitCalls);
};
visitCalls(sf);
for (const k of keyArgs) {
const text = (k as ts.StringLiteral).text;
if (CYR.test(text) && en[text] === undefined && !missing.has(text)) missing.set(text, `${rel}:${sf.getLineAndCharacterOfPosition(k.getStart()).line + 1}`);
}
if (!strict) return;
const visit = (node: ts.Node) => {
let text: string | null = null;
if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) text = node.text;
else if (ts.isTemplateExpression(node)) text = node.getText();
else if (ts.isJsxText(node)) text = node.text.trim();
if (text && CYR.test(text) && !keyArgs.has(node) && !ignored(node)) {
// Import paths and type-only positions never are user text.
if (!ts.isImportDeclaration(node.parent) && !ts.isLiteralTypeNode(node.parent)) {
loose.push({ where: `${rel}:${sf.getLineAndCharacterOfPosition(node.getStart()).line + 1}`, text: text.slice(0, 80) });
}
if (ts.isTemplateExpression(node)) return;
}
ts.forEachChild(node, visit);
};
visit(sf);
}
for (const d of STRICT) for (const f of files(d)) check(f, true);
for (const d of KEYS_ONLY) for (const f of files(d)) check(f, false);
if (process.argv.includes("--summary")) {
const per = new Map<string, number>();
for (const l of loose) {
const f = l.where.replace(/:\d+$/, "");
per.set(f, (per.get(f) ?? 0) + 1);
}
for (const [f, n] of [...per].sort((a, b) => b[1] - a[1])) console.log(`${String(n).padStart(4)} ${f}`);
console.log(`untranslated literals: ${loose.length}; keys without English: ${missing.size}`);
process.exit(0);
}
for (const [k, where] of missing) console.log(`нет перевода: ${where} «${k}»`);
for (const l of loose) console.log(`не через словарь: ${l.where} «${l.text}»`);
if (missing.size || loose.length) {
console.log(`\ni18n-check: ${missing.size} ключей без перевода, ${loose.length} строк не через словарь`);
process.exit(1);
}
console.log("i18n-check: ok");