import { kindForStatus, safeValidationIssues, type FailureKind, type ValidationIssue, } from "../../contracts/errors.ts"; import { z } from "../../contracts/zod.ts"; /** * 1101 README 14.3. How this client reads the paired backend's Envelope * (clean-architecture-backend-template docs/web/http-contract.md §1, §2, §4) * for a V3 operation that declares `responseEnvelope: "ENVELOPE_V1"`. */ /** * 백엔드 1101/02-02. The paired backend drops a null field together with its * key (§1). The id keys are absent on an answer written before its request id * filter, so they are optional here too. */ const metaSchema = z .object({ requestId: z.string().regex(/^[A-Za-z0-9._:-]{1,128}$/).optional(), traceId: z.string().regex(/^[A-Za-z0-9._:-]{1,128}$/).optional(), correlationId: z.string().regex(/^[A-Za-z0-9._:-]{1,128}$/).optional(), }) .strip(); export const successEnvelopeSchema = z .object({ success: z.literal(true), // A missing `data` is the null the backend dropped. data: z.unknown().default(null), meta: metaSchema, }) .strict(); export const failureEnvelopeSchema = z .object({ success: z.literal(false), error: z .object({ code: z.string().regex(/^[A-Z0-9_]{1,64}$/), category: z.string().min(1).max(64).optional(), message: z.string().max(1_024).optional(), retryable: z.boolean().optional(), details: z.unknown().optional(), }) .strict(), meta: metaSchema, }) .strict(); export type EnvelopeError = Readonly<{ code: string; category?: string; message?: string; retryable?: boolean; details?: unknown; }>; export type EnvelopeRead = | Readonly<{ ok: true; value: Value }> | Readonly<{ ok: false }>; const ENVELOPE_INVALID: EnvelopeRead = Object.freeze({ ok: false }); /** The success `data`. A missing key is the null the backend dropped. */ export function readSuccessEnvelope(value: unknown): EnvelopeRead { const parsed = successEnvelopeSchema.safeParse(value); return parsed.success ? Object.freeze({ ok: true as const, value: parsed.data.data }) : ENVELOPE_INVALID; } /** The failure `error` object, as the backend sent it. */ export function readFailureEnvelope( value: unknown, ): EnvelopeRead { const parsed = failureEnvelopeSchema.safeParse(value); return parsed.success ? Object.freeze({ ok: true as const, value: parsed.data.error }) : ENVELOPE_INVALID; } /** * 1101/14.4. The 400, 409 and 422 codes the paired backend raises only before * it writes. Backend 5786126c, read code by code into the frontend contract * (docs/architecture/backend-api-and-server-state-contract.md 6.1); recheck * this table with that section when the backend SHA there moves. Only the * status and code together count. `reason` is the diagnostics name of an * idempotency refusal, named for what is wrong on this side. */ export type IdempotencyRefusalReason = | "IDEMPOTENT_REQUEST_MISMATCH" | "IDEMPOTENCY_KEY_RULE_MISMATCH"; const REFUSED_BEFORE_WRITE: Readonly< Record< string, Readonly<{ status: number; reason?: IdempotencyRefusalReason }> > > = Object.freeze({ // Request binding and validation, whatever the details: the field list, a // body that did not parse (`{cause}` or none), a page or sort parameter. VALIDATION_FAILED: Object.freeze({ status: 400 }), // `isValidIdempotencyKey` passed the key before sending, so the client and // server key rules disagree. IDEMPOTENCY_KEY_INVALID: Object.freeze({ status: 400, reason: "IDEMPOTENCY_KEY_RULE_MISMATCH", }), // The same key went out with another body. IDEMPOTENT_REQUEST_MISMATCH: Object.freeze({ status: 422, reason: "IDEMPOTENT_REQUEST_MISMATCH", }), }); function refusedBeforeWrite(code: string, status: number | undefined) { const refusal = Object.hasOwn(REFUSED_BEFORE_WRITE, code) ? REFUSED_BEFORE_WRITE[code] : undefined; return refusal !== undefined && refusal.status === status ? refusal : undefined; } export function idempotencyRefusalReason( code: string, status: number | undefined, ): IdempotencyRefusalReason | undefined { return refusedBeforeWrite(code, status)?.reason; } /** * 백엔드 1101/02-01 후속. A failure the form shows on its fields: a 422, or * the paired backend's 400 VALIDATION_FAILED whose details is the field list * (§4). This decides the kind and the issues only, not whether it applied. */ export function isFieldValidationFailure( status: number, error: EnvelopeError, ): boolean { return ( status === 422 || (status === 400 && error.code === "VALIDATION_FAILED" && Array.isArray(error.details)) ); } /** * The verdict the backend contract gives whatever the operation is, or * `undefined` when the operation's own classifier decides. * * - Not applied: a code in the table above. * - Maybe applied: every other 400, 409 and 422, including 409 * IDEMPOTENT_IN_FLIGHT (an earlier request with the key still runs); the * backend can raise them after a write and the code does not say which. * And 503 IDEMPOTENCY_UNAVAILABLE: §2 says to resend it with the same key, * which only an unknown result keeps. */ export function envelopeFailureEffect( status: number, error: EnvelopeError, ): "NOT_APPLIED" | "MAYBE_APPLIED" | undefined { if (refusedBeforeWrite(error.code, status) !== undefined) return "NOT_APPLIED"; return status === 400 || status === 409 || status === 422 || (status === 503 && error.code === "IDEMPOTENCY_UNAVAILABLE") ? "MAYBE_APPLIED" : undefined; } /** * §2. The one answer after which the backend asks for the same request again * with the same key: 503 IDEMPOTENCY_UNAVAILABLE, refused before the command * ran. A KEYED command may be resent on it automatically (runtime design * §8.3: only on a known answer that says resending is safe). */ export function invitesKeyedResend( status: number, error: EnvelopeError, ): boolean { return status === 503 && error.code === "IDEMPOTENCY_UNAVAILABLE"; } /** * Q-6.3-3b. A gateway 5xx/408/425 is a server outage, not a contract breach: * it keeps the SERVER_FAILURE retry rule. */ export function gatewayFailureOr(status: number, kind: FailureKind): FailureKind { return status >= 500 || status === 408 || status === 425 ? "SERVER_FAILURE" : kind; } /** The failure kind, code and field issues an unmapped problem reads as. */ export function envelopeFailureReading( status: number, error: EnvelopeError, ): Readonly<{ kind: FailureKind; code: string; validationIssues?: readonly ValidationIssue[]; }> { const fieldValidation = isFieldValidationFailure(status, error); return Object.freeze({ kind: fieldValidation ? "VALIDATION_REJECTED" : gatewayFailureOr(status, kindForStatus(status)), code: error.code, ...(fieldValidation ? { validationIssues: safeValidationIssues(error.details) } : {}), }); }