import type { Outcome, Problem } from "./contract/common.ts"; import { refsErrorMessage, type RefsErrorCode } from "./contract/errors.ts"; export function raise(code: RefsErrorCode, description: string): never { throw new Error(refsErrorMessage(code, description)); } export function ok(): Outcome; export function ok(value: T): Outcome; export function ok(value?: T): Outcome { return { ok: true, value }; } export function problem(code: Problem["code"], message: string, field?: string): { ok: false; problem: Problem } { return { ok: false, problem: field ? { code, message, field } : { code, message } }; } export function invalid(message: string, field?: string): { ok: false; problem: Problem } { return problem("invalid", message, field); } export function conflict(message: string, field?: string): { ok: false; problem: Problem } { return problem("conflict", message, field); } /** The first failed check as an `invalid` outcome on its field, or null when every check passed. Each check runs once. */ export function firstInvalid(checks: Readonly>): { ok: false; problem: Problem } | null { const failed = Object.entries(checks).find(([, message]) => message !== undefined); return failed ? invalid(failed[1]!, failed[0]) : null; }