// PEP-324: a page opened before an update presses a button whose server action the new server doesn't // know (renamed, removed, or the actions key changed) — Next throws `UnrecognizedActionError`. Instead // of «Application error» and lost text, the page says FORGE was updated, keeps what the person typed // and reloads itself; after the reload the text goes back into the same fields. // Pure functions over a minimal DOM/storage shape — the browser glue is components/StaleActionGuard.tsx. const MESSAGE_RE = /Server Action "[^"]*" was not found on the server/; /** True for the «action not found on the server» error — as an Error, from another module copy, or as text. * `nextCheck` — `unstable_isUnrecognizedActionError` from `next/navigation` (passed in by the client * components: this module stays free of Next imports and testable under plain node). */ export function isStaleAction(err: unknown, nextCheck?: (e: unknown) => boolean): boolean { if (!err) return false; if (typeof err === "string") return MESSAGE_RE.test(err); try { if (nextCheck?.(err)) return true; } catch { /* fall through to the name/message check */ } const e = err as { name?: unknown; message?: unknown }; return e.name === "UnrecognizedActionError" || (typeof e.message === "string" && MESSAGE_RE.test(e.message)); } export const DRAFTS_KEY = "peppa.stale-drafts"; export const RELOAD_KEY = "peppa.stale-reload"; /** A second self-reload within this window means reloading did not help: show the button instead. */ export const RELOAD_GUARD_MS = 60_000; /** Fields of a form submitted this recently still go along: it may be the very submit that failed. */ export const SUBMIT_GRACE_MS = 15_000; /** Saved text older than this is not restored. */ export const DRAFTS_TTL_MS = 5 * 60_000; export const FIELD_MAX = 20_000; export interface StorageLike { getItem(key: string): string | null; setItem(key: string, value: string): void; removeItem(key: string): void; } /** The parts of an input/textarea the draft logic reads. */ export interface FieldLike { tagName: string; type?: string; name?: string; id?: string; value: string; form?: unknown; hasAttribute(name: string): boolean; } /** An id React generated (`useId`) differs from one page load to the next: not an address to come back to. */ const GENERATED_ID_RE = /^(:|«|_r_|_R_)/; /** Fields that hold a secret or a one-time code. Their text is never kept, whatever the field's type: * a project secret or a server key is typed into a textarea, not into a password field. */ const SECRET_NAME_RE = /secret|token|passw|credential|api_?key|^(code|value|key|pin|otp)$/i; /** A textarea or a text-like input — the fields a draft is kept for (not password, hidden, file…). */ export function isTextField(el: FieldLike): boolean { const tag = el.tagName.toUpperCase(); if (tag === "TEXTAREA") return true; return tag === "INPUT" && ["text", "search", "email", "url", "tel", ""].includes((el.type ?? "text").toLowerCase()); } /** * Where the text goes back after the reload; null — the text is not kept (password, hidden, file, * a secret, no address…). * The field's own lasting id first (`#answer-12`): on a page with a card per question the fields share * a name, and an answer typed for one question must never come back in another's field. Without such * an id — the name, but only while it is the only text field of that name on the page (`alone`). */ export function fieldKey(el: FieldLike, alone: (name: string) => boolean = () => true): string | null { if (!isTextField(el)) return null; if (el.hasAttribute("data-no-draft") || el.hasAttribute("readonly") || el.hasAttribute("disabled")) return null; if (SECRET_NAME_RE.test(el.name ?? "") || SECRET_NAME_RE.test(el.id ?? "")) return null; if (el.id && !GENERATED_ID_RE.test(el.id)) return `#${el.id}`; if (el.name && alone(el.name)) return el.name; return null; } interface Saved { path: string; at: number; fields: Record; } /** What the person typed on this page, in memory until an unknown action asks to keep it. */ export class DraftTracker { private typed = new Map(); private sent = new Map(); /** An `input` event on a field; `alone` — is it the only text field of that name on the page (see fieldKey). */ input(el: FieldLike, alone?: (name: string) => boolean) { const key = fieldKey(el, alone); if (!key) return; this.sent.delete(key); if (el.value) this.typed.set(key, { value: el.value.slice(0, FIELD_MAX), form: el.form ?? null }); else this.typed.delete(key); } /** A `submit` event: the form's fields move to «sent» — after a successful submit the form is * cleared and that text must not come back on a later reload. */ submit(form: unknown, now: number) { for (const [key, v] of this.typed) { if (v.form !== form) continue; this.sent.set(key, { value: v.value, at: now }); this.typed.delete(key); } } /** Fields to keep across the reload: everything typed plus what was submitted just now. */ snapshot(now: number): Record { const out: Record = {}; for (const [key, v] of this.sent) if (now - v.at <= SUBMIT_GRACE_MS) out[key] = v.value; for (const [key, v] of this.typed) out[key] = v.value; return out; } } export function saveDrafts(storage: StorageLike, path: string, fields: Record, now: number) { try { if (Object.keys(fields).length === 0) storage.removeItem(DRAFTS_KEY); else storage.setItem(DRAFTS_KEY, JSON.stringify({ path, at: now, fields } satisfies Saved)); } catch { /* storage full or blocked: the reload still helps */ } } /** Saved fields for this page (and forgets them); null when none, stale, or from another page. */ export function takeDrafts(storage: StorageLike, path: string, now: number): Record | null { let raw: string | null = null; try { raw = storage.getItem(DRAFTS_KEY); if (raw !== null) storage.removeItem(DRAFTS_KEY); } catch { return null; } if (!raw) return null; try { const saved = JSON.parse(raw) as Saved; if (saved.path !== path || !(now - saved.at <= DRAFTS_TTL_MS) || !saved.fields) return null; return saved.fields; } catch { return null; } } /** Put saved text back into empty fields; `find` resolves a field key, `set` writes so React sees it, * `alone` — as in fieldKey: text kept by name goes back only into the single field of that name. * Returns the keys not placed (their field is not on the page yet, or is not the same field). */ export function restoreDrafts(fields: Record, find: (key: string) => FieldLike | null, set: (el: FieldLike, value: string) => void, alone?: (name: string) => boolean): string[] { const left: string[] = []; for (const [key, value] of Object.entries(fields)) { const el = find(key); if (!el || fieldKey(el, alone) !== key) { left.push(key); continue; } if (!el.value) set(el, value); } return left; } /** May the page reload itself now? Records the reload; false when it already did within the guard window. */ export function claimReload(storage: StorageLike, now: number): boolean { try { const last = Number(storage.getItem(RELOAD_KEY) ?? 0); if (last && now - last >= 0 && now - last < RELOAD_GUARD_MS) return false; storage.setItem(RELOAD_KEY, String(now)); return true; } catch { // Without storage we cannot tell a loop from a first time: ask the person instead. return false; } } /** * An error caught by the pages' error boundary (app/error.tsx) still has to reach «Ошибки из прода». * Next prints a caught error with the `console.error` it took at startup — before ErrorReporter * wrapped it — so the reporter never hears it. Raise it the way the browser raises an uncaught error * (ErrorReporter listens to those); a browser without `reportError` — through the wrapped console. */ export function reportCaughtError(error: unknown, target: { reportError?: (e: unknown) => void; console: { error: (...args: unknown[]) => void } }) { if (typeof target.reportError === "function") target.reportError(error); else target.console.error(error); }