Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : MacLustr Identity8 * File : sdk/typescript/src/errors.ts9 * Module : sdk10 * Repository : https://git.spboucher.ai/maclustr-identity11 * Project Website : https://identity.spboucher.ai12 * Created : 2026-12-0113 * Last Modified : 2026-12-0114 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: admin@spboucher.ai23 * Technical Contact: dev@spboucher.ai24 * Security/Admin : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142/** Typed errors. API errors mirror the envelope `{"error": {"type", "code", "message", "param", "request_id"}}`. */4344export interface ErrorDetails {45 status?: number;46 type?: string;47 code?: string;48 param?: string;49 requestId?: string;50 headers?: Record<string, string>;51 cause?: unknown;52}5354export class MacLustrIdentityError extends Error {55 /** HTTP status, or `undefined` when no response was received. */56 readonly status: number | undefined;57 /** Error family sent by the API, for example `invalid_request_error`. */58 readonly type: string;59 /** Machine-readable code, for example `resource_missing`. */60 readonly code: string;61 /** Offending request parameter, when the API names one. */62 readonly param: string | undefined;63 /** Value of the `Request-Id` response header: quote it when asking for support. */64 readonly requestId: string | undefined;65 readonly headers: Record<string, string>;6667 constructor(message: string, details: ErrorDetails = {}) {68 super(message);69 this.name = new.target.name;70 this.status = details.status;71 this.type = details.type ?? "api_error";72 this.code = details.code ?? "unknown_error";73 this.param = details.param;74 this.requestId = details.requestId;75 this.headers = details.headers ?? {};76 if (details.cause !== undefined) (this as { cause?: unknown }).cause = details.cause;77 Object.setPrototypeOf(this, new.target.prototype);78 }79}8081/**82 * 400, 411, 413, 422: the request itself is wrong; retrying it unchanged will fail again.83 * Notable codes: `invalid_cursor` (unknown `starting_after`), `payload_too_large` (413), `length_required` (411).84 */85export class InvalidRequestError extends MacLustrIdentityError {}86/** 401: missing, invalid, expired or revoked API key. */87export class AuthenticationError extends MacLustrIdentityError {}88/** 403: the key lacks a scope, the application is suspended, a compliance gate is closed, or the caller's network is not allowed (`forbidden_network`). */89export class PermissionError extends MacLustrIdentityError {}90/** 404: unknown object, or an object that belongs to another application or mode. */91export class NotFoundError extends MacLustrIdentityError {}92/** 409: state conflict or idempotency-key conflict. */93export class ConflictError extends MacLustrIdentityError {}94/** 429: too many requests (`rate_limited`, shared by every server process) or a quota (`daily_session_limit`). */95export class RateLimitError extends MacLustrIdentityError {96 /** Seconds to wait, from the `Retry-After` header when present. */97 readonly retryAfter: number | undefined;98 constructor(message: string, details: ErrorDetails & { retryAfter?: number } = {}) {99 super(message, details);100 this.retryAfter = details.retryAfter;101 }102}103/** 5xx: the service failed. `service_unavailable` (503) is a temporary saturation and carries `Retry-After`. */104export class ApiServerError extends MacLustrIdentityError {105 /** Seconds to wait, from the `Retry-After` header when present (503). */106 readonly retryAfter: number | undefined;107 constructor(message: string, details: ErrorDetails & { retryAfter?: number } = {}) {108 super(message, details);109 this.retryAfter = details.retryAfter;110 }111}112/** No response: DNS, TCP, TLS failure or timeout. Treat the identity service as unreachable and fail closed. */113export class ConnectionError extends MacLustrIdentityError {}114/** The webhook signature is missing, malformed, expired or does not match. Never process such a payload. */115export class SignatureVerificationError extends MacLustrIdentityError {}116117/** Builds the right error class from an HTTP response. */118export function errorFromResponse(status: number, body: unknown, headers: Record<string, string>): MacLustrIdentityError {119 const e = (body && typeof body === "object" && (body as { error?: unknown }).error) || {};120 const env = (typeof e === "object" && e ? e : {}) as Record<string, unknown>;121 const str = (v: unknown): string | undefined => (typeof v === "string" && v ? v : undefined);122 const details: ErrorDetails = {123 status,124 type: str(env.type),125 code: str(env.code),126 param: str(env.param),127 requestId: str(env.request_id) ?? headers["request-id"],128 headers,129 };130 const message = str(env.message) ?? `HTTP ${status}`;131 if (status === 401) return new AuthenticationError(message, details);132 if (status === 403) return new PermissionError(message, details);133 if (status === 404) return new NotFoundError(message, details);134 if (status === 409) return new ConflictError(message, details);135 if (status === 429) return new RateLimitError(message, { ...details, retryAfter: parseRetryAfter(headers["retry-after"]) });136 if (status >= 500) return new ApiServerError(message, { ...details, retryAfter: parseRetryAfter(headers["retry-after"]) });137 if (status >= 400) return new InvalidRequestError(message, details);138 return new MacLustrIdentityError(message, details);139}140141/** Parses `Retry-After` (delta seconds or HTTP date) into seconds. */142export function parseRetryAfter(value: string | undefined | null, now: number = Date.now()): number | undefined {143 if (!value) return undefined;144 const n = Number(value);145 if (Number.isFinite(n)) return Math.max(0, n);146 const t = Date.parse(value);147 return Number.isNaN(t) ? undefined : Math.max(0, (t - now) / 1000);148}149