PEP-217: Web Vitals пользователей и проверка веса JS в CI #206

Open
peppa-bot wants to merge 1 commits from task/pep-217 into main
32 changed files with 702 additions and 22 deletions

View File

@ -49,9 +49,14 @@ jobs:
- name: typecheck
if: (success() || failure()) && steps.install.outcome == 'success'
run: bash .gitea/peppa-check.sh typecheck
- name: build
- id: build
name: build
if: (success() || failure()) && steps.install.outcome == 'success'
run: bash .gitea/peppa-check.sh build
# PEP-217: weight of the first-load JS of every route against docs/bundle-baseline.json (+10 % fails).
- name: bundle
if: (success() || failure()) && steps.install.outcome == 'success' && steps.build.outcome == 'success'
run: bash .gitea/peppa-check.sh bundle
- name: test
if: (success() || failure()) && steps.install.outcome == 'success'
run: bash .gitea/peppa-check.sh test

View File

@ -51,9 +51,10 @@
## Решения
- Застрявшая задача (PEP-209): лечит `stuckTaskTick` — платформа сама на ревью/в «Готово», агенту — новый процесс (`restartAgent`: старый не вернёт MCP), не `sendToSession`. Новая причина задержки с повторами — `platformDelay` с `retryMin`/`retryAt`, суперадмину кнопки — `buttons: true`.
- Сообщения людям — только через `telegram_outbox`/`push_outbox`: ночная тишина 23–08 (PEP-208) стоит на их выборке; тестам и стенду `PEPPA_NIGHT_QUIET=off`.
- После правок `template/` — `scripts/push-template.sh` и `peppa ci connect <KEY>` старым проектам.
- Живой сайт — только `scripts/live-deploy.sh`; в живой копии коммиты запрещены хуком, агенты там не запускаются.
- Эталон (PEP-184, PM): подписка прогона — наименее загруженная свободная из общего пула; про подписку PM не спрашивать.
- Распознавание речи — свой faster-whisper (`<Dictate>`, MediaRecorder), не Web Speech API. Вход через Google: по почте учётки не склеиваем.
- Привязка Google к учётке с другим Google-only пользователем объединяет учётки (core/merge-users.ts `mergeUserInto`); с eGov/Gitea — отказ к админу (PEP-195).
- Язык голоса (PEP-131): `transcribeLanguage(cfg, locale)` — язык интерфейса говорящего; новый вызов `transcribe` передаёт его пятым аргументом. Казахский у Whisper ~25% ошибок слов.
- Правки `template/` — `scripts/push-template.sh`, старым проектам `peppa ci connect <KEY>`.
- Живой сайт — только `scripts/live-deploy.sh` (в живой копии коммиты запрещены).
- Эталон (PEP-184): подписка прогона — наименее загруженная свободная из общего пула.
- Речь — свой faster-whisper (`<Dictate>`), не Web Speech API. Google-вход: по почте учётки не склеиваем.
- Привязка Google к чужой Google-only учётке объединяет их (`mergeUserInto`); с eGov/Gitea — отказ к админу (PEP-195).
- Язык голоса (PEP-131): `transcribe` получает `transcribeLanguage(cfg, locale)` пятым аргументом.
- Вес JS (PEP-217): `node scripts/bundle-check.mjs [--update]` после build, эталон docs/bundle-baseline.json; словари en/kk в браузерный бандл не идут (`#dicts`, `registerDictionary`); Web Vitals — core/vitals.ts + observe.db.

View File

@ -8,6 +8,7 @@
"lint": "pnpm lint",
"typecheck": "pnpm -r typecheck",
"build": "pnpm --filter @peppa/web build",
"bundle": "node scripts/bundle-check.mjs",
"test": "pnpm --filter @peppa/testkit test"
}
}

View File

@ -3,7 +3,7 @@
// 30 s it writes its heartbeat (the watchdog watches it like the bot and the web), every hour it
// deletes checks older than the retention (7 days). Monitors are rows in observe.db: the web and
// MCP change them, the service picks the change up on its next pass — no restart.
import { beat, observeTick, pruneObserve, seedMonitors, type ObserveProbes } from "@peppa/core";
import { beat, observeTick, pruneObserve, seedMonitors, vitalsAlertTick, type ObserveProbes } from "@peppa/core";
import type { Db } from "@peppa/db";
export interface ObserverOptions {
@ -19,6 +19,7 @@ export async function runObserver(db: Db, o: ObserverOptions = {}, signal?: Abor
log("observer started");
let lastBeat = 0;
let lastPrune = 0;
let lastVitals = 0;
while (!signal?.aborted) {
const now = Date.now();
if (now - lastBeat >= 30_000) {
@ -34,6 +35,11 @@ export async function runObserver(db: Db, o: ObserverOptions = {}, signal?: Abor
log(`observer: prune failed: ${(e as Error).message}`);
}
}
// PEP-217: slow pages (p75 of real users) → one warning per route and day in Bugsink.
if (now - lastVitals >= 600_000) {
lastVitals = now;
void vitalsAlertTick(db).catch((e: Error) => log(`observer: vitals failed: ${e.message}`));
}
// Not awaited: a slow check must not hold the others or the heartbeat.
void observeTick(db, { log, probes: o.probes }).catch((e: Error) => log(`observer: tick failed: ${e.message}`));
await new Promise((r) => setTimeout(r, o.tickMs ?? 1_000));

View File

@ -7,7 +7,8 @@ import { navCounts } from "@/lib/queries";
import { WordsProvider } from "@/components/Words";
import { Sidebar } from "@/components/Sidebar";
import { AttentionBadge } from "@/components/AttentionBadge";
import { CommandPalette } from "@/components/CommandPalette";
import { LazyCommandPalette as CommandPalette } from "@/components/Lazy";
import { WebVitals } from "@/components/WebVitals";
import { AgentsStrip, UsageStrip } from "@/components/Accounting";
import { VersionWatch } from "@/components/VersionWatch";
import { bootId } from "@/lib/boot";
@ -40,6 +41,8 @@ export default async function AppLayout({ children }: { children: ReactNode }) {
{children}
</div>
<CommandPalette />
{/* PEP-217: Web Vitals of real users. */}
<WebVitals mode={mode} />
{/* PEP-143: «Сообщить о проблеме» on every page. */}
<FeedbackButton />
</div>

View File

@ -2,7 +2,7 @@
import Link from "next/link";
import { notFound } from "next/navigation";
import { Activity, Pause, Play, Plus } from "lucide-react";
import { describeTarget, egovLoginSummary, isSuperadmin, listMonitorViews } from "@peppa/core";
import { describeTarget, egovLoginSummary, isBadVital, isSuperadmin, listMonitorViews, vitalsSummary, type VitalDevice, type VitalMetric } from "@peppa/core";
import { loadEnv } from "@peppa/shared";
import { AutoRefresh } from "@/components/AutoRefresh";
import { Hidden } from "@/components/cards";
@ -18,16 +18,21 @@ import { createMonitorAction, pauseMonitorAction } from "./actions";
export const dynamic = "force-dynamic";
const VITAL_COLUMNS: VitalMetric[] = ["LCP", "INP", "CLS", "TTFB"];
const fmtVital = (m: VitalMetric, v: number | null) => (v == null ? "—" : m === "CLS" ? v.toFixed(2) : v >= 1000 ? `${(v / 1000).toFixed(1)} s` : `${Math.round(v)} ms`);
export async function generateMetadata() {
const t = await getT();
return { title: t("Observability — Peppa FACTORY") };
}
export default async function Observability({ searchParams }: { searchParams: Promise<{ error?: string }> }) {
export default async function Observability({ searchParams }: { searchParams: Promise<{ error?: string; device?: string }> }) {
const user = await requireUser();
const t = await getT();
if (!(await isSuperadmin(db, user))) notFound();
const { error } = await searchParams;
const { error, device: deviceParam } = await searchParams;
const device: VitalDevice | undefined = deviceParam === "narrow" || deviceParam === "wide" ? deviceParam : undefined;
const vitals = vitalsSummary({ device });
const monitors = listMonitorViews();
const egov = await egovLoginSummary(db);
const web = loadEnv().PEPPA_WEB_URL;
@ -88,6 +93,42 @@ export default async function Observability({ searchParams }: { searchParams: Pr
</form>
</Disclosure>
</Section>
{/* PEP-217: what the browsers of real users measured over the last day. */}
<Section title={t("Скорость в браузере")} count={vitals.length}>
<p className="mb-2 text-sm text-muted-foreground">{t("Что измерили браузеры пользователей за сутки. Значение — p75: три из четырёх посещений не хуже него. Плохо: LCP больше 4 с, INP больше 500 мс.")}</p>
<div className="mb-2 flex gap-3 text-sm">
{([[undefined, t("Все экраны")], ["narrow", t("Узкий экран")], ["wide", t("Широкий экран")]] as const).map(([d, label]) => (
<Link key={label} href={d ? `/observability?device=${d}` : "/observability"} className={d === device ? "font-semibold" : "text-muted-foreground hover:underline"}>{label}</Link>
))}
</div>
{vitals.length === 0 ? (
<Empty>{t("Пока нет данных: браузеры пришлют их при следующих открытиях страниц.")}</Empty>
) : (
<Card className="overflow-x-auto py-2">
<table className="w-full text-sm">
<thead>
<tr className="text-left text-xs text-muted-foreground">
<th className="px-3 py-1 font-normal">{t("Страница")}</th>
<th className="px-3 py-1 text-right font-normal">{t("Посещений")}</th>
{VITAL_COLUMNS.map((c) => <th key={c} className="px-3 py-1 text-right font-normal">{c}</th>)}
</tr>
</thead>
<tbody>
{vitals.map((r) => (
<tr key={r.route} className="border-t">
<td className="px-3 py-1 font-mono text-xs">{r.route}</td>
<td className="px-3 py-1 text-right text-muted-foreground">{r.samples}</td>
{VITAL_COLUMNS.map((c) => (
<td key={c} className={`px-3 py-1 text-right ${isBadVital(c, r.p75[c], r.n[c]) ? "text-destructive" : ""}`}>{fmtVital(c, r.p75[c])}</td>
))}
</tr>
))}
</tbody>
</table>
</Card>
)}
</Section>
</div>
</Workspace>
);

View File

@ -0,0 +1,38 @@
// PEP-217: Web Vitals from the browser (WebVitals) → observe.db. No login (the login page counts
// too): a size cap and a per-IP limit like /api/client-errors. Nothing but a route without ids,
// the metric, the value, the screen kind and the mode is stored — no user, no keys, no address.
import { recordVital } from "@peppa/core";
const MAX_BYTES = 4 * 1024;
const PER_IP_PER_MIN = 30;
const MAX_ITEMS = 8;
const hits = new Map<string, { at: number; n: number }>();
function limited(ip: string, now = Date.now()): boolean {
const h = hits.get(ip);
if (!h || now - h.at >= 60_000) {
if (hits.size > 5000) hits.clear();
hits.set(ip, { at: now, n: 1 });
return false;
}
return ++h.n > PER_IP_PER_MIN;
}
export async function POST(req: Request) {
const ip = req.headers.get("cf-connecting-ip") ?? req.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ?? "local";
if (limited(ip)) return new Response(null, { status: 429 });
const raw = await req.text();
if (raw.length > MAX_BYTES) return new Response(null, { status: 413 });
let b: { route?: unknown; device?: unknown; mode?: unknown; metrics?: unknown };
try {
b = JSON.parse(raw) as typeof b;
} catch {
return new Response(null, { status: 400 });
}
if (!Array.isArray(b.metrics)) return new Response(null, { status: 400 });
let stored = 0;
for (const m of b.metrics.slice(0, MAX_ITEMS) as Array<{ metric?: unknown; value?: unknown }>) {
if (m && recordVital({ route: b.route, metric: m.metric, value: m.value, device: b.device, mode: b.mode })) stored++;
}
return new Response(null, { status: stored ? 204 : 400 });
}

View File

@ -2,7 +2,7 @@ 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 { dictionary, productName } from "@peppa/shared/i18n";
import { cn } from "@/lib/utils";
import { THEME_COOKIE } from "@/lib/theme";
import { getLocale, getT } from "@/lib/i18n";
@ -22,7 +22,7 @@ export default async function RootLayout({ children }: { children: ReactNode })
return (
<html lang={locale === "kk" ? "kk" : locale} className={cn(GeistSans.variable, GeistMono.variable, !light && "dark")}>
<body>
<I18nProvider locale={locale}>
<I18nProvider locale={locale} dict={locale === "ru" ? undefined : dictionary(locale)}>
<ErrorReporter />
{children}
</I18nProvider>

View File

@ -4,13 +4,16 @@
// `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 { LOCALE_LABELS, LOCALES, registerDictionary, translator, type Dict, 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 }) {
/** `dict` — the dictionary of `locale` (not for Russian): the browser bundle carries none (PEP-217). */
export function I18nProvider({ locale, dict, children }: { locale: Locale; dict?: Dict; children: ReactNode }) {
// Before the children render, on the server and on hydration alike; idempotent.
if (dict) registerDictionary(locale, dict);
return <LocaleContext.Provider value={locale}>{children}</LocaleContext.Provider>;
}

View File

@ -0,0 +1,10 @@
"use client";
// PEP-217: heavy client pieces that the first view does not need load on demand (next/dynamic,
// ssr off) — they stay out of the first-load JS of every route.
import dynamic from "next/dynamic";
/** Terminal of a runner (xterm.js and its styles): only when a terminal is opened. */
export const LazyRunnerTerminal = dynamic(() => import("@/components/RunnerTerminal").then((m) => m.RunnerTerminal), { ssr: false });
/** ⌘K palette and shortcuts: there is nothing to draw before the first key press. */
export const LazyCommandPalette = dynamic(() => import("@/components/CommandPalette").then((m) => m.CommandPalette), { ssr: false });

View File

@ -10,7 +10,7 @@ import { AgentSteps } from "@/components/AgentSteps";
import { AttachCommand, QuestionCard, SessionActions } from "@/components/cards";
import { ago, Key, StatusBadge } from "@/components/common";
import { LocalTime, ScrollIntoViewOnNarrow } from "@/components/LocalTime";
import { RunnerTerminal } from "@/components/RunnerTerminal";
import { LazyRunnerTerminal as RunnerTerminal } from "@/components/Lazy";
import { SessionUsageLine } from "@/components/Accounting";
import type { InboxItem } from "@/lib/queries";
import { SESSION_STATUS, TONE_BG, TONE_TEXT } from "@/lib/status";

View File

@ -0,0 +1,89 @@
"use client";
import { useEffect } from "react";
import { usePathname } from "next/navigation";
type Metric = "LCP" | "INP" | "CLS" | "TTFB";
/**
* PEP-217: Web Vitals of real users with a bare PerformanceObserver — no outside scripts.
* LCP, INP and CLS are final when the page goes to the background (or is left), TTFB is known at
* once. One beacon per page view to /api/client-vitals: route without ids is cut on the server,
* mode (Продакт/Инженер) comes from the layout, the screen kind from the window width.
*/
export function WebVitals({ mode }: { mode: "product" | "engineer" }) {
const pathname = usePathname();
useEffect(() => {
if (typeof PerformanceObserver === "undefined") return;
// A soft navigation inside the app has no LCP/TTFB of its own: only the first load is measured.
if ((window as { __peppaVitals?: boolean }).__peppaVitals) return;
(window as { __peppaVitals?: boolean }).__peppaVitals = true;
const route = pathname;
let lcp = 0;
let cls = 0;
let inp = 0;
const longest: number[] = [];
const observe = (type: string, cb: (e: PerformanceEntry[]) => void, extra: object = {}) => {
try {
const o = new PerformanceObserver((l) => cb(l.getEntries()));
o.observe({ type, buffered: true, ...extra } as PerformanceObserverInit);
return o;
} catch {
return null; // the browser does not know this entry type
}
};
observe("largest-contentful-paint", (es) => {
const last = es[es.length - 1] as PerformanceEntry | undefined;
if (last) lcp = last.startTime;
});
observe("layout-shift", (es) => {
for (const e of es as Array<PerformanceEntry & { value: number; hadRecentInput: boolean }>) if (!e.hadRecentInput) cls += e.value;
});
// INP: the slowest interaction (p98 of the worst ones, simplified to the 2nd worst after 50).
observe(
"event",
(es) => {
for (const e of es as Array<PerformanceEntry & { interactionId?: number }>) {
if (!e.interactionId) continue;
longest.push(e.duration);
longest.sort((a, b) => b - a);
longest.length = Math.min(longest.length, 10);
}
inp = longest.length > 50 ? longest[1]! : (longest[0] ?? 0);
},
{ durationThreshold: 40 },
);
let sent = false;
const flush = () => {
if (sent) return;
const metrics: Array<{ metric: Metric; value: number }> = [];
const nav = performance.getEntriesByType("navigation")[0] as PerformanceNavigationTiming | undefined;
if (nav && nav.responseStart > 0) metrics.push({ metric: "TTFB", value: nav.responseStart });
if (lcp > 0) metrics.push({ metric: "LCP", value: lcp });
metrics.push({ metric: "CLS", value: cls });
if (inp > 0) metrics.push({ metric: "INP", value: inp });
if (!metrics.length) return;
sent = true;
const body = JSON.stringify({ route, device: window.innerWidth < 768 ? "narrow" : "wide", mode, metrics });
try {
if (!navigator.sendBeacon?.("/api/client-vitals", new Blob([body], { type: "application/json" }))) {
void fetch("/api/client-vitals", { method: "POST", headers: { "Content-Type": "application/json" }, body, keepalive: true }).catch(() => {});
}
} catch {
/* measuring must never break the page */
}
};
const onHide = () => {
if (document.visibilityState === "hidden") flush();
};
document.addEventListener("visibilitychange", onHide);
window.addEventListener("pagehide", flush);
// A page left open for a long time still reports once.
const timer = setTimeout(flush, 60_000);
return () => {
// Never cleaned during soft navigation (the effect runs once per tab): nothing to undo.
void timer;
};
}, [pathname, mode]);
return null;
}

View File

@ -16,7 +16,7 @@ import { Input } from "@/components/ui/input";
import { ago, Disclosure, Empty, Key, linkify, StatusBadge } from "@/components/common";
import { AgentSteps } from "@/components/AgentSteps";
import { Dictate } from "@/components/Dictate";
import { RunnerTerminal } from "@/components/RunnerTerminal";
import { LazyRunnerTerminal as RunnerTerminal } from "@/components/Lazy";
import { SessionUsageLine } from "@/components/Accounting";
import { cn } from "@/lib/utils";
import { cleanText } from "@/lib/chat-text";

36
docs/bundle-baseline.json Normal file
View File

@ -0,0 +1,36 @@
{
"/": 215418,
"/_global-error": 175270,
"/_not-found": 188068,
"/chats": 212798,
"/chats/[chat]": 215334,
"/dashboard": 212798,
"/dashboard/delays": 212798,
"/feedback": 211322,
"/gitea": 211322,
"/help": 211322,
"/help/connect": 212105,
"/help/shortcuts": 215791,
"/hosts": 211322,
"/journal": 211322,
"/login": 198835,
"/mcp-guide": 190185,
"/oauth/authorize": 188350,
"/observability": 211729,
"/observability/[id]": 211729,
"/p/[key]": 219920,
"/p/[key]/accept": 212798,
"/p/[key]/plan/[epic]": 211322,
"/platform": 211322,
"/projects": 211322,
"/projects/new": 213018,
"/runners": 213298,
"/secrets": 211322,
"/settings": 216795,
"/subscriptions": 211729,
"/t/[key]": 215028,
"/team": 216804,
"/users": 211322,
"/users/merge": 211322,
"/welcome": 213529
}

View File

@ -0,0 +1,9 @@
## Решения
- **Хранилище**: `observe.db` (миграция user_version 2, таблица `web_vitals`), не основная БД: частые записи без внешних ключей, TTL 7 дней через `pruneObserve`. Миграции основной БД не нужны.
- **Приватность**: сервер режет маршрут (`/t/PEP-1` → `/t/:key`), пользователя, адреса и ключей не хранит; сбор — в `(app)`-раскладке, режим берётся оттуда.
- **Сбор**: одна отправка за загрузку вкладки при уходе на фон/`pagehide` (или через 60 с); мягкие переходы внутри приложения не меряются (у них нет своих LCP/TTFB). INP — самое долгое взаимодействие (упрощение).
- **Предупреждение**: `vitalsAlertTick` в observer раз в 10 минут; метка `vitals.warned:<маршрут>:<метрика>:<день>` в `observe_meta`; `level: warning` в событии Bugsink.
- **Вес JS**: считаем из `.next` — `entryJSFiles` страницы из `page_client-reference-manifest.js` + корневые файлы Next, gzip. Динамические чанки в первую загрузку не входят. Порог 10%, новые маршруты не роняют (предупреждение), эталон обновляется `node scripts/bundle-check.mjs --update`.
- **Словари**: `package.json → imports["#dicts"]` с условием `browser` отдаёт пустые словари; `I18nProvider` получает словарь языка читателя от сервера и вызывает `registerDictionary` до рендера детей. Русскому читателю не уходит ничего; английскому/казахскому словарь едет в RSC-ответе (сжимается транспортом) вместо бандла у всех. Итог: первая загрузка ~500 → ~210 КБ.
- **Ленивые**: `Lazy.tsx` — `LazyCommandPalette`, `LazyRunnerTerminal` (xterm.js уже грузился через `import()`, теперь и его обвязка со стилями). Markdown — свой лёгкий рендер, отдельно не выносился.
- **CI**: шаг `bundle` в `.gitea/workflows/ci.yml` после `build`, команда в `checks.bundle`; PR меняет `.gitea/` и `checks`, поэтому не мержится автоматически.

View File

@ -0,0 +1,9 @@
## Why
Мы не знали, как быстро Peppa работает у пользователей в браузере, и не замечали, когда первая загрузка страниц тяжелеет. Измерение показало: в каждую страницу уходило ~500 КБ JS (gzip), из них ~300 КБ — словари английского и казахского, нужные лишь части читателей.
## What Changes
- Браузер меряет LCP, INP, CLS, TTFB (`PerformanceObserver`, без внешних скриптов) и шлёт `sendBeacon` на `POST /api/client-vitals` (без входа, предел 30 запросов/мин на IP, ≤4 КБ).
- Хранение в `observe.db` (7 дней): маршрут без id, метрика, значение, узкий/широкий экран, режим. Сводка p75 за сутки — на `/observability`.
- Плохой p75 (LCP > 4 с, INP > 500 мс, ≥5 замеров) — одно предупреждение в Bugsink PEP-web на маршрут и метрику в сутки.
- Проверка `bundle` в CI: вес JS первой загрузки каждого маршрута против `docs/bundle-baseline.json`, рост >10% — красная.
- Тяжёлое — по требованию: палитра ⌘K и терминал (`next/dynamic`), словари en/kk не входят в браузерный бандл — сервер передаёт словарь языка читателя.

View File

@ -0,0 +1,35 @@
## ADDED Requirements
### Requirement: Скорость страниц у реальных пользователей видна
Peppa SHALL собирать Web Vitals (LCP, INP, CLS, TTFB) в браузере и показывать p75 по маршрутам за сутки суперадмину на `/observability`.
#### Scenario: Браузер присылает замеры
- **GIVEN** пользователь открыл страницу «/t/PEP-1» на телефоне
- **WHEN** вкладка уходит на фон
- **THEN** на `/api/client-vitals` уходит один запрос с метриками
- **AND** сохраняется маршрут «/t/:key», узкий экран и режим, без пользователя и ключей
#### Scenario: Некорректный замер
- **WHEN** приходит неизвестная метрика, отрицательное или слишком большое значение
- **THEN** замер не сохраняется, ответ 400
### Requirement: Медленные страницы — одно предупреждение в сутки
Peppa SHALL отправлять в Bugsink (PEP-web) предупреждение, когда p75 маршрута за сутки хуже предела (LCP > 4 с или INP > 500 мс, не меньше 5 замеров), не чаще раза в сутки на маршрут и метрику.
#### Scenario: Плохой p75
- **GIVEN** пять замеров LCP маршрута от 4,5 до 6 с
- **WHEN** срабатывает проверка
- **THEN** в Bugsink уходит одно предупреждение
- **AND** повторная проверка в тот же день ничего не шлёт
### Requirement: Вес JS первой загрузки под контролем CI
Проверка `bundle` SHALL падать, если вес JS первой загрузки маршрута вырос больше чем на 10% к `docs/bundle-baseline.json`.
#### Scenario: Маршрут потяжелел
- **GIVEN** эталон маршрута 200 КБ
- **WHEN** после сборки он весит 230 КБ
- **THEN** проверка красная с названием маршрута и ростом в процентах
#### Scenario: Вес в пределах
- **WHEN** рост не больше 10%
- **THEN** проверка зелёная

View File

@ -0,0 +1,12 @@
## 1. Сбор и хранение
- [x] 1.1 `core/vitals.ts`, таблица `web_vitals` в observe.db, маршрут без id
- [x] 1.2 `POST /api/client-vitals`, `WebVitals.tsx` в раскладке `(app)`
## 2. Сводка и предупреждения
- [x] 2.1 Блок «Скорость в браузере» на `/observability`, тексты ru/en/kk
- [x] 2.2 `vitalsAlertTick` в observer, предупреждение в Bugsink
## 3. Вес JS
- [x] 3.1 `scripts/bundle-check.mjs`, `docs/bundle-baseline.json`, `checks.bundle`, шаг CI
- [x] 3.2 Ленивые палитра и терминал, словари не в браузерном бандле (500 → 210 КБ)
## 4. Проверка
- [x] 4.1 Тест `web-vitals.test.ts`, lint, typecheck, build
- [ ] 4.2 Lighthouse вручную на доске, задаче и Главной — не сделано (нужен вход под учёткой)

View File

@ -0,0 +1,40 @@
# web-performance Specification
## Purpose
TBD - created by archiving change pep-217-web-vitals. Update Purpose after archive.
## Requirements
### Requirement: Скорость страниц у реальных пользователей видна
Peppa SHALL собирать Web Vitals (LCP, INP, CLS, TTFB) в браузере и показывать p75 по маршрутам за сутки суперадмину на `/observability`.
#### Scenario: Браузер присылает замеры
- **GIVEN** пользователь открыл страницу «/t/PEP-1» на телефоне
- **WHEN** вкладка уходит на фон
- **THEN** на `/api/client-vitals` уходит один запрос с метриками
- **AND** сохраняется маршрут «/t/:key», узкий экран и режим, без пользователя и ключей
#### Scenario: Некорректный замер
- **WHEN** приходит неизвестная метрика, отрицательное или слишком большое значение
- **THEN** замер не сохраняется, ответ 400
### Requirement: Медленные страницы — одно предупреждение в сутки
Peppa SHALL отправлять в Bugsink (PEP-web) предупреждение, когда p75 маршрута за сутки хуже предела (LCP > 4 с или INP > 500 мс, не меньше 5 замеров), не чаще раза в сутки на маршрут и метрику.
#### Scenario: Плохой p75
- **GIVEN** пять замеров LCP маршрута от 4,5 до 6 с
- **WHEN** срабатывает проверка
- **THEN** в Bugsink уходит одно предупреждение
- **AND** повторная проверка в тот же день ничего не шлёт
### Requirement: Вес JS первой загрузки под контролем CI
Проверка `bundle` SHALL падать, если вес JS первой загрузки маршрута вырос больше чем на 10% к `docs/bundle-baseline.json`.
#### Scenario: Маршрут потяжелел
- **GIVEN** эталон маршрута 200 КБ
- **WHEN** после сборки он весит 230 КБ
- **THEN** проверка красная с названием маршрута и ростом в процентах
#### Scenario: Вес в пределах
- **WHEN** рост не больше 10%
- **THEN** проверка зелёная

View File

@ -63,6 +63,8 @@ export interface ErrorContext {
platform?: "node" | "javascript";
request?: { url?: string; method?: string; userAgent?: string };
tags?: Record<string, string>;
/** PEP-217: a warning (slow pages) is not an error. */
level?: "error" | "warning";
/** Overrides for tests. */
release?: string | null;
environment?: string;
@ -89,7 +91,7 @@ export function errorEvent(e: unknown, ctx: ErrorContext, at = new Date()) {
event_id: randomBytes(16).toString("hex"),
timestamp: at.getTime() / 1000,
platform: ctx.platform ?? "node",
level: "error",
level: ctx.level ?? "error",
logger: ctx.service,
server_name: hostname(),
release: (ctx.release !== undefined ? ctx.release : peppaCommit()) ?? `peppa@${peppaVersion()}`,

View File

@ -102,3 +102,4 @@ export * from "./observe.ts";
export * from "./observe-checks.ts";
export * from "./accept-screen.ts";
export * from "./accept-digest.ts";
export * from "./vitals.ts";

View File

@ -158,7 +158,20 @@ const SCHEMA = [
`CREATE TABLE observe_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)`,
];
/** Each entry upgrades the file by one version (PRAGMA user_version). */
const MIGRATIONS: string[][] = [SCHEMA];
// PEP-217: browser Web Vitals of real users (route without ids, no user, no keys).
const VITALS_SCHEMA = [
`CREATE TABLE web_vitals (
id INTEGER PRIMARY KEY AUTOINCREMENT,
at TEXT NOT NULL,
route TEXT NOT NULL,
metric TEXT NOT NULL,
value REAL NOT NULL,
device TEXT NOT NULL,
mode TEXT NOT NULL
)`,
`CREATE INDEX web_vitals_at ON web_vitals (at)`,
];
const MIGRATIONS: string[][] = [SCHEMA, VITALS_SCHEMA];
const opened = new Map<string, DatabaseSync>();
@ -599,6 +612,7 @@ export function pruneObserve(now = new Date(), days = retentionDays()): number {
const db = observeDb();
const r = db.prepare("DELETE FROM monitor_checks WHERE at < ?").run(cut);
db.prepare("DELETE FROM monitor_incidents WHERE ended_at IS NOT NULL AND ended_at < ?").run(cut);
db.prepare("DELETE FROM web_vitals WHERE at < ?").run(cut);
return Number(r.changes);
}

122
packages/core/src/vitals.ts Normal file
View File

@ -0,0 +1,122 @@
// PEP-217: Web Vitals of real users (LCP, INP, CLS, TTFB) — what the browser measured on Peppa's
// own pages. Stored in observe.db (7 days), p75 per route for the last day on /observability,
// one warning in Bugsink (PEP-web) per route and metric per day when p75 is bad.
// glossary-ignore-file: the section is for the superadmin only.
import type { Db } from "@peppa/db";
import { observeDb } from "./observe.ts";
import { reportPlatformError } from "./error-report.ts";
export const VITAL_METRICS = ["LCP", "INP", "CLS", "TTFB"] as const;
export type VitalMetric = (typeof VITAL_METRICS)[number];
export type VitalDevice = "narrow" | "wide";
export type VitalMode = "product" | "engineer";
/** Bad p75 of a route: LCP > 4 s, INP > 500 ms (CLS > 0.25 is shown, not reported). */
export const VITAL_BAD: Record<VitalMetric, number> = { LCP: 4000, INP: 500, CLS: 0.25, TTFB: 1800 };
export const VITAL_WARN_METRICS: VitalMetric[] = ["LCP", "INP"];
/** Fewer samples than this do not make a verdict. */
export const VITAL_MIN_SAMPLES = 5;
const MAX_VALUE: Record<VitalMetric, number> = { LCP: 600_000, INP: 600_000, TTFB: 600_000, CLS: 100 };
const ID_SEGMENT = /^(\d+|[0-9a-f]{8,}|[A-Za-z]{2,10}-\d+)$/i;
const KEY_PARENTS = new Set(["p", "t", "chats"]);
/** A path without ids and keys: /t/PEP-12 → /t/:key, /runners/7 → /runners/:id. */
export function normalizeRoute(path: unknown): string | null {
if (typeof path !== "string") return null;
const clean = path.split(/[?#]/)[0]!.slice(0, 300);
if (!clean.startsWith("/")) return null;
const parts = clean.split("/").filter(Boolean).slice(0, 6);
const out = parts.map((seg, i) => {
if (i > 0 && KEY_PARENTS.has(parts[i - 1]!)) return ":key";
if (ID_SEGMENT.test(seg)) return ":id";
return seg.slice(0, 40).replace(/[^\w.\-~%]/g, "_");
});
return `/${out.join("/")}`;
}
export interface VitalInput {
route: unknown;
metric: unknown;
value: unknown;
device: unknown;
mode: unknown;
}
/** Stores one sample; false when the input is not a valid sample. */
export function recordVital(i: VitalInput, now = new Date()): boolean {
const route = normalizeRoute(i.route);
const metric = VITAL_METRICS.find((m) => m === i.metric);
const value = typeof i.value === "number" ? i.value : NaN;
if (!route || !metric || !Number.isFinite(value) || value < 0 || value > MAX_VALUE[metric]) return false;
const device: VitalDevice = i.device === "narrow" ? "narrow" : "wide";
const mode: VitalMode = i.mode === "engineer" ? "engineer" : "product";
observeDb()
.prepare("INSERT INTO web_vitals (at, route, metric, value, device, mode) VALUES (?, ?, ?, ?, ?, ?)")
.run(now.toISOString(), route, metric, value, device, mode);
return true;
}
/** Nearest-rank 75th percentile. */
export function p75(values: number[]): number | null {
if (!values.length) return null;
const s = [...values].sort((a, b) => a - b);
return s[Math.ceil(s.length * 0.75) - 1]!;
}
export interface RouteVitals {
route: string;
samples: number;
/** p75 per metric; null — no samples. */
p75: Record<VitalMetric, number | null>;
/** How many samples per metric. */
n: Record<VitalMetric, number>;
}
/** p75 per route over the last `hours` (default a day); the most visited routes first. */
export function vitalsSummary(o: { hours?: number; device?: VitalDevice; now?: Date } = {}): RouteVitals[] {
const now = o.now ?? new Date();
const since = new Date(now.getTime() - (o.hours ?? 24) * 3_600_000).toISOString();
const rows = (o.device
? observeDb().prepare("SELECT route, metric, value FROM web_vitals WHERE at >= ? AND device = ?").all(since, o.device)
: observeDb().prepare("SELECT route, metric, value FROM web_vitals WHERE at >= ?").all(since)) as { route: string; metric: VitalMetric; value: number }[];
const by = new Map<string, Record<VitalMetric, number[]>>();
for (const r of rows) {
const e = by.get(r.route) ?? { LCP: [], INP: [], CLS: [], TTFB: [] };
e[r.metric]?.push(r.value);
by.set(r.route, e);
}
const out: RouteVitals[] = [...by].map(([route, e]) => ({
route,
samples: Math.max(...VITAL_METRICS.map((m) => e[m].length)),
p75: { LCP: p75(e.LCP), INP: p75(e.INP), CLS: p75(e.CLS), TTFB: p75(e.TTFB) },
n: { LCP: e.LCP.length, INP: e.INP.length, CLS: e.CLS.length, TTFB: e.TTFB.length },
}));
return out.sort((a, b) => b.samples - a.samples || a.route.localeCompare(b.route));
}
export const isBadVital = (metric: VitalMetric, value: number | null, n: number) => value != null && n >= VITAL_MIN_SAMPLES && value > VITAL_BAD[metric];
/**
* Bad p75 → one warning to Bugsink per route and metric per day (observe_meta remembers it).
* Returns what was reported.
*/
export async function vitalsAlertTick(db: Db, now = new Date()): Promise<string[]> {
const meta = observeDb();
const day = now.toISOString().slice(0, 10);
const sent: string[] = [];
for (const r of vitalsSummary({ now })) {
for (const m of VITAL_WARN_METRICS) {
const v = r.p75[m];
if (!isBadVital(m, v, r.n[m])) continue;
const key = `vitals.warned:${r.route}:${m}:${day}`;
if (meta.prepare("SELECT 1 FROM observe_meta WHERE key = ?").get(key)) continue;
meta.prepare("INSERT OR IGNORE INTO observe_meta (key, value) VALUES (?, ?)").run(key, String(now.getTime()));
const text = `${m} p75 ${Math.round(v!)} ms (> ${VITAL_BAD[m]}) on ${r.route}, ${r.n[m]} samples in 24 h`;
await reportPlatformError(db, { name: `SlowPage ${m}`, message: text }, { service: "browser", kind: "web", platform: "javascript", where: r.route, level: "warning", tags: { vital: m } });
sent.push(`${r.route}:${m}`);
}
}
meta.prepare("DELETE FROM observe_meta WHERE key LIKE 'vitals.warned:%' AND key NOT LIKE ?").run(`%:${day}`);
return sent;
}

View File

@ -15,5 +15,11 @@
},
"dependencies": {
"zod": "4.6.7"
},
"imports": {
"#dicts": {
"browser": "./src/i18n/dicts-browser.ts",
"default": "./src/i18n/dicts.ts"
}
}
}

View File

@ -0,0 +1,5 @@
// PEP-217: in the browser bundle the dictionaries (≈1.2 MB, ~300 KB gzip) are NOT shipped to
// everyone. `package.json → imports["#dicts"]` points here for the `browser` condition; the page
// of an English/Kazakh reader gets its one dictionary from the server (registerDictionary).
export const en: Record<string, string> = {};
export const kk: Record<string, string> = {};

View File

@ -0,0 +1,4 @@
// The dictionaries for the server, the bot and the tests (PEP-217: the browser gets an empty
// stand-in, see dicts-browser.ts — it receives the dictionary of its language from the server).
export { en } from "./en/index.ts";
export { kk } from "./kk.ts";

View File

@ -87,4 +87,12 @@ export const observe: Dict = {
"другая причина": "other reason",
"Входы за сутки: {n}, неудачных {m} ({reasons})": "Logins in 24 h: {n}, failed {m} ({reasons})",
"Входы за сутки: {n}, неудачных нет": "Logins in 24 h: {n}, none failed",
"Скорость в браузере": "Speed in the browser",
"Что измерили браузеры пользователей за сутки. Значение — p75: три из четырёх посещений не хуже него. Плохо: LCP больше 4 с, INP больше 500 мс.": "What users' browsers measured over the last day. The value is p75: three of four visits are no worse. Bad: LCP over 4 s, INP over 500 ms.",
"Все экраны": "All screens",
"Узкий экран": "Narrow screen",
"Широкий экран": "Wide screen",
"Пока нет данных: браузеры пришлют их при следующих открытиях страниц.": "No data yet: browsers will send it when pages are opened.",
"Страница": "Page",
"Посещений": "Visits",
};

View File

@ -3,8 +3,7 @@
// `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";
import { en, kk } from "#dicts";
export const LOCALES = ["ru", "en", "kk"] as const;
export type Locale = (typeof LOCALES)[number];
@ -18,6 +17,17 @@ export type Dict = Record<string, string>;
const DICTS: Record<Locale, Dict> = { ru: {}, en, kk };
/**
* PEP-217: the browser bundle has no dictionaries; the server passes the one of the reader's
* language and the client provider registers it before anything is translated.
*/
export function registerDictionary(locale: Locale, dict: Dict): void {
if (DICTS[locale] === dict) return;
DICTS[locale] = dict;
compiled.delete(locale);
caches.delete(locale);
}
export function normalizeLocale(v: unknown): Locale {
return typeof v === "string" && (LOCALES as readonly string[]).includes(v) ? (v as Locale) : DEFAULT_LOCALE;
}

View File

@ -87,4 +87,12 @@ export const observe: Dict = {
"другая причина": "басқа себеп",
"Входы за сутки: {n}, неудачных {m} ({reasons})": "Тәулікте кіру: {n}, сәтсіз {m} ({reasons})",
"Входы за сутки: {n}, неудачных нет": "Тәулікте кіру: {n}, сәтсізі жоқ",
"Скорость в браузере": "Браузердегі жылдамдық",
"Что измерили браузеры пользователей за сутки. Значение — p75: три из четырёх посещений не хуже него. Плохо: LCP больше 4 с, INP больше 500 мс.": "Пайдаланушылар браузері тәулік бойы өлшегені. Мәні — p75: төрт кірудің үшеуі одан жаман емес. Жаман: LCP 4 с-тан, INP 500 мс-тан асса.",
"Все экраны": "Барлық экран",
"Узкий экран": "Тар экран",
"Широкий экран": "Кең экран",
"Пока нет данных: браузеры пришлют их при следующих открытиях страниц.": "Әзірге дерек жоқ: браузерлер беттер келесі ашылғанда жібереді.",
"Страница": "Бет",
"Посещений": "Кіру саны",
};

View File

@ -0,0 +1,72 @@
// PEP-217: Web Vitals of real users — what is stored (route without ids, no user), p75 per route
// for the last day, one Bugsink warning per route and metric per day.
import assert from "node:assert/strict";
import { join } from "node:path";
import { after, describe, test } from "node:test";
// helpers must load first: it sets the isolated test env that runner modules read on load.
import { core, db, project, runner, teardown } from "./helpers.ts";
import { MockBugsink } from "../src/mock-bugsink.ts";
process.env.PEPPA_OBSERVE_DB = join(process.env.PEPPA_HOME!, "vitals-observe.db");
const { createBugsinkClient } = await import("@peppa/bugsink");
const bugsink = await new MockBugsink().start();
const client = createBugsinkClient({ url: bugsink.url, token: bugsink.token, teamId: bugsink.teamId, publicUrl: bugsink.url });
process.env.BUGSINK_URL = bugsink.url;
after(async () => {
core.closeObserveDb();
await bugsink.stop();
await teardown();
});
const sample = (route: string, metric: string, value: number, device = "wide", at = new Date()) => core.recordVital({ route, metric, value, device, mode: "product" }, at);
describe("PEP-217: Web Vitals", () => {
test("Scenario: маршрут без идентификаторов", () => {
assert.equal(core.normalizeRoute("/t/PEP-217?tab=design"), "/t/:key");
assert.equal(core.normalizeRoute("/p/PEP/accept"), "/p/:key/accept");
assert.equal(core.normalizeRoute("/runners/42"), "/runners/:id");
assert.equal(core.normalizeRoute("/"), "/");
assert.equal(core.normalizeRoute("https://evil"), null);
});
test("Scenario: плохие значения не записываются", () => {
assert.equal(sample("/", "FOO", 10), false);
assert.equal(sample("/", "LCP", -1), false);
assert.equal(sample("/", "LCP", Number.NaN), false);
assert.equal(sample("/", "CLS", 5000), false);
assert.equal(core.vitalsSummary().length, 0);
});
test("Scenario: p75 по маршрутам за сутки, старое не считается", () => {
for (const v of [1000, 1200, 1400, 3000]) sample("/", "LCP", v);
sample("/", "INP", 120);
sample("/", "LCP", 99_000, "wide", new Date(Date.now() - 3 * 86_400_000));
const r = core.vitalsSummary();
const home = r.find((x) => x.route === "/")!;
assert.equal(home.p75.LCP, 1400);
assert.equal(home.n.LCP, 4);
assert.equal(home.p75.INP, 120);
assert.equal(core.vitalsSummary({ device: "narrow" }).length, 0);
assert.equal(core.p75([]), null);
});
test("Scenario: плохой p75 — одно предупреждение на маршрут в сутки", async () => {
const p = await project({ turns: [] });
process.env.PEPPA_PLATFORM_KEY = p.key;
core.resetErrorReporting();
const r = await runner.connectErrorTracking(db, await core.getProject(db, p.key), client, "http://peppa.test");
const web = r.sources.find((s) => s.kind === "web")!.bugsinkProjectId;
for (const v of [4500, 5000, 6000, 5200, 4800]) sample("/t/PEP-5", "LCP", v);
for (const v of [100, 100, 100, 100, 100]) sample("/p/PEP", "LCP", v);
for (let i = 0; i < 3; i++) sample("/chats", "INP", 900); // too few samples: no verdict
const before = bugsink.ingested.length;
const sent = await core.vitalsAlertTick(db);
assert.deepEqual(sent, ["/t/:key:LCP"]);
const got = bugsink.ingested.slice(before);
assert.equal(got.length, 1);
assert.equal(got[0]!.projectId, web);
assert.equal((got[0]!.event as ReturnType<typeof core.errorEvent>).level, "warning");
assert.deepEqual(await core.vitalsAlertTick(db), []);
});
});

89
scripts/bundle-check.mjs Normal file
View File

@ -0,0 +1,89 @@
#!/usr/bin/env node
// PEP-217: weight of the client JS of every route after `next build` (apps/web/.next).
// First load of a route = the chunks the route's page needs on the first visit (layout + page
// entries from its client-reference manifest, plus Next's root main files), gzip bytes.
// Lazy chunks (next/dynamic, import()) are not part of it — that is the point.
// node scripts/bundle-check.mjs compare with docs/bundle-baseline.json, exit 1 if a route grew > 10 %
// node scripts/bundle-check.mjs --update write the baseline (on purpose, in the PR that explains the growth)
// node scripts/bundle-check.mjs --report print the table only
import { existsSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
import { dirname, join, relative } from "node:path";
import { fileURLToPath } from "node:url";
import { gzipSync } from "node:zlib";
const root = join(dirname(fileURLToPath(import.meta.url)), "..");
const web = join(root, "apps/web");
const next = join(web, ".next");
const baselinePath = join(root, "docs/bundle-baseline.json");
export const LIMIT = 0.1;
const gz = new Map();
function size(file) {
if (!gz.has(file)) gz.set(file, gzipSync(readFileSync(join(next, file))).length);
return gz.get(file);
}
function manifests(dir, out = []) {
for (const n of readdirSync(dir)) {
const p = join(dir, n);
if (statSync(p).isDirectory()) manifests(p, out);
else if (n === "page_client-reference-manifest.js") out.push(p);
}
return out;
}
/** { route: gzip bytes of the first-load JS }. */
export function measure() {
if (!existsSync(join(next, "server/app"))) throw new Error("apps/web/.next не найден — сначала pnpm build");
const build = JSON.parse(readFileSync(join(next, "build-manifest.json"), "utf8"));
const common = [...(build.rootMainFiles ?? []), ...(build.polyfillFiles ?? [])].filter((f) => f.endsWith(".js"));
const out = {};
for (const m of manifests(join(next, "server/app"))) {
const src = readFileSync(m, "utf8");
const entry = /\["([^"]+)"\]\s*=\s*(\{.*\});?\s*$/s.exec(src);
if (!entry) continue;
const data = JSON.parse(entry[2]);
const files = data.entryJSFiles ?? {};
const pageKey = Object.keys(files).find((k) => /\/page$/.test(k)) ?? Object.keys(files).at(-1);
if (!pageKey) continue;
const route = "/" + relative(join(next, "server/app"), dirname(m)).split("/").filter((s) => !/^\(.*\)$/.test(s)).join("/");
const list = new Set([...common, ...files[pageKey]].filter((f) => f.endsWith(".js")));
out[route === "/" ? "/" : route.replace(/\/$/, "")] = [...list].reduce((a, f) => a + size(f), 0);
}
return Object.fromEntries(Object.entries(out).sort(([a], [b]) => a.localeCompare(b)));
}
/** Routes that grew more than `limit` against the baseline; new routes are listed apart. */
export function compare(now, base, limit = LIMIT) {
const grew = [];
const added = [];
for (const [route, bytes] of Object.entries(now)) {
const was = base[route];
if (was == null) added.push(route);
else if (bytes > was * (1 + limit)) grew.push({ route, was, now: bytes, pct: ((bytes / was - 1) * 100) });
}
return { grew, added };
}
const kb = (n) => `${(n / 1024).toFixed(1)} КБ`;
if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
const now = measure();
const mode = process.argv[2];
if (mode === "--update") {
writeFileSync(baselinePath, JSON.stringify(now, null, 2) + "\n");
console.log(`bundle: эталон записан — маршрутов ${Object.keys(now).length}, docs/bundle-baseline.json`);
process.exit(0);
}
const base = existsSync(baselinePath) ? JSON.parse(readFileSync(baselinePath, "utf8")) : {};
for (const [r, b] of Object.entries(now)) console.log(`${r.padEnd(40)} ${kb(b).padStart(10)}${base[r] ? ` (эталон ${kb(base[r])})` : ""}`);
if (mode === "--report") process.exit(0);
const { grew, added } = compare(now, base);
if (added.length) console.log(`bundle: новые маршруты без эталона: ${added.join(", ")} — обновите эталон: node scripts/bundle-check.mjs --update`);
if (grew.length) {
for (const g of grew) console.error(`bundle: ${g.route} вырос на ${g.pct.toFixed(1)}% (${kb(g.was)} → ${kb(g.now)}), предел ${LIMIT * 100}%`);
console.error("bundle: вынесите тяжёлое в dynamic import или, если рост нужен, обновите эталон: node scripts/bundle-check.mjs --update");
process.exit(1);
}
console.log("bundle: вес JS первой загрузки в пределах эталона");
}

View File

@ -70,6 +70,7 @@ step() { # <name> <command...>
step lint pnpm lint
step typecheck pnpm -r typecheck
[ "$BUILD" = 1 ] && step "web build" pnpm --filter @peppa/web build
[ "$BUILD" = 1 ] && step "bundle" node scripts/bundle-check.mjs
for i in $(seq 1 "$REPEAT"); do
step "e2e $i/$REPEAT" pnpm --filter @peppa/testkit test
done