Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536import type { CheckOutcome } from "./engine";import type { CheckContext, CheckFn } from "./checkTypes";
const timedOut = Symbol("timed out");
/** Runs one check function with its context, under a time limit, and turns whatever it returns or throws into the outcome the engine understands. */export async function runCheckFunction(name: string, fn: CheckFn, context: CheckContext, timeoutMs: number): Promise<CheckOutcome> { const internal = (message: string): CheckOutcome => ({ ok: false, reason: "internal", message }); let timer: ReturnType<typeof setTimeout> | undefined; try { const finished = await Promise.race([ Promise.resolve(fn(context)), new Promise<typeof timedOut>((resolveTimer) => { timer = setTimeout(() => resolveTimer(timedOut), timeoutMs); }), ]); if (finished === timedOut) return { ok: false, reason: "timeout", message: `check ${name} did not finish within ${timeoutMs} ms` }; if (finished === undefined || finished === true) return { ok: true }; if (finished === false) return { ok: false, reason: "mismatch", message: `check ${name} returned false` }; if (typeof finished === "object" && finished !== null && typeof (finished as { ok?: unknown }).ok === "boolean") { const r = finished as { ok: boolean; reason?: unknown; message?: string; expected?: unknown; found?: unknown }; if (r.ok) return { ok: true }; return { ok: false, reason: r.reason === "pre-state" ? "pre-state" : "mismatch", message: r.message ?? `check ${name} failed`, ...(r.expected !== undefined ? { expected: r.expected } : {}), ...(r.found !== undefined ? { found: r.found } : {}) }; } return internal(`check ${name} returned something that is not a result (return nothing, true, false or { ok })`); } catch (err) { const e = err as { name?: string; message?: string; expected?: unknown; actual?: unknown }; if (e?.name === "AssertionError" || e?.name === "CheckFailed" || e?.name === "PreStateFailed") { return { ok: false, reason: e.name === "PreStateFailed" ? "pre-state" : "mismatch", message: e.message ?? "assertion failed", ...(e.expected !== undefined ? { expected: e.expected } : {}), ...(e.actual !== undefined ? { found: e.actual } : {}) }; } return internal(`check ${name} crashed: ${err instanceof Error ? err.message : String(err)}`); } finally { if (timer) clearTimeout(timer); }}