Repository Public
1// Idempotency-Key per user intent: the key stays the same while the same request body is retried (network error,2// step-up retry, double click) and changes as soon as the body changes or the intent completed.34export function fingerprint(value: unknown): string {5 return JSON.stringify(sortKeys(value));6}7function sortKeys(value: unknown): unknown {8 if (Array.isArray(value)) return value.map(sortKeys);9 if (value && typeof value === "object") {10 const out: Record<string, unknown> = {};11 for (const k of Object.keys(value as object).sort()) {12 const v = (value as Record<string, unknown>)[k];13 if (v !== undefined) out[k] = sortKeys(v);14 }15 return out;16 }17 return value;18}1920export class IdempotencyIntent {21 private print: string | null = null;22 private key: string | null = null;23 constructor(private readonly generate: () => string = () => crypto.randomUUID()) {}2425 /** Key for this body: stable across retries of the same body, renewed when the body differs. */26 keyFor(body: unknown): string {27 const p = fingerprint(body);28 if (this.key === null || this.print !== p) {29 this.print = p;30 this.key = this.generate();31 }32 return this.key;33 }3435 /** Call once the server accepted the request: the next submission is a new intent. */36 complete(): void {37 this.print = null;38 this.key = null;39 }40}41