/** * scale-architecture.md §17–§18. The platform error envelope. * * The platform owns only the generic shape and its closed classification * axes. Concrete `kind` literals belong to the feature (or platform module) * that raises them; there is deliberately no union enumerating every feature * error, so a new feature never edits a central error type. */ export type ErrorCategory = | "transport" | "contract" | "validation" | "domain" | "application" | "platform"; export type ErrorSeverity = "info" | "warning" | "error" | "critical"; export type Retryability = "never" | "safe" | "policy"; export interface AppError { /** Stable machine-readable `owner.reason` kind, e.g. `payment.declined`. */ readonly kind: string; readonly category: ErrorCategory; readonly severity: ErrorSeverity; readonly retryability: Retryability; } export const ERROR_CATEGORIES: ReadonlySet = new Set([ "transport", "contract", "validation", "domain", "application", "platform", ]); export const ERROR_SEVERITIES: ReadonlySet = new Set([ "info", "warning", "error", "critical", ]); const RETRYABILITIES: ReadonlySet = new Set([ "never", "safe", "policy", ]); /** Bounded, low-cardinality `owner.reason` identifier. */ const ERROR_KIND = /^[a-z][a-z0-9-]{0,39}(?:\.[a-z][a-z0-9-]{0,39}){1,3}$/u; export function isErrorKind(value: unknown): value is string { return typeof value === "string" && ERROR_KIND.test(value); } /** * Structural recognition only: reads four own data fields and never invokes * accessors, so an untrusted object cannot run code while being classified. */ export function isAppError(value: unknown): value is AppError { if (value === null || typeof value !== "object") return false; const read = (key: string): unknown => { const descriptor = Object.getOwnPropertyDescriptor(value, key); return descriptor && "value" in descriptor ? descriptor.value : undefined; }; return ( isErrorKind(read("kind")) && ERROR_CATEGORIES.has(read("category") as ErrorCategory) && ERROR_SEVERITIES.has(read("severity") as ErrorSeverity) && RETRYABILITIES.has(read("retryability") as Retryability) ); } export function defineAppError( error: Envelope, ): Readonly { if (!isAppError(error)) { throw new TypeError("Invalid AppError envelope"); } return Object.freeze({ ...error }); }