Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : SPIDER — Universal Web Intelligence Engine8 * File : sdk/typescript/src/errors.ts9 * Module : Sdk10 * Repository : https://git.spboucher.ai/spider11 * Project Website : Not specified12 * Created : 2026-12-0413 * Last Modified : 2026-12-0414 *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: contact@spboucher.ai23 * Development : dev@spboucher.ai24 * Support : support@spboucher.ai25 * Security/Admin : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License : ISC34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243/** Typed errors of the SPIDER SDK. */4445export class SpiderError extends Error {46 constructor(message: string, options?: ErrorOptions) {47 super(message, options);48 this.name = new.target.name;49 }50}5152/** The request could not be completed (connection refused, reset, timeout) after the allowed retries. */53export class TransportError extends SpiderError {}5455/** `waitForJob` gave up before the job reached a terminal state (the job itself keeps running). */56export class JobTimeoutError extends SpiderError {57 constructor(readonly jobId: string, readonly lastStatus: string | null, readonly timeoutMs: number) {58 super(`job ${jobId} still ${lastStatus ?? "unknown"} after ${timeoutMs} ms`);59 }60}6162/** The bytes of an artifact do not match the SHA-256 announced by the server. */63export class ArtifactIntegrityError extends SpiderError {64 constructor(readonly artifactId: string, readonly expected: string | null, readonly actual: string) {65 super(`artifact ${artifactId}: expected sha256 ${expected ?? "<missing header>"}, got ${actual}`);66 }67}6869export type WebhookFailure =70 | "missing_header" | "bad_timestamp" | "timestamp_out_of_tolerance" | "unsupported_version" | "bad_signature"71 | "bad_payload";7273/** A webhook delivery failed verification. */74export class WebhookVerificationError extends SpiderError {75 constructor(readonly reason: WebhookFailure, message: string) {76 super(message);77 }78}7980export interface ApiErrorFields {81 status: number;82 code: string;83 message: string;84 details: unknown;85 requestId: string | null;86 retryAfterSeconds: number | null;87}8889/** An error answered by the API: `{"error": {code, message, details, request_id}}`. */90export class ApiError extends SpiderError {91 readonly status: number;92 readonly code: string;93 readonly details: unknown;94 readonly requestId: string | null;95 readonly retryAfterSeconds: number | null;9697 constructor(f: ApiErrorFields) {98 super(f.message);99 this.status = f.status;100 this.code = f.code;101 this.details = f.details;102 this.requestId = f.requestId;103 this.retryAfterSeconds = f.retryAfterSeconds;104 }105}106107/** 401 or 403. */108export class AuthError extends ApiError {}109/** 401: missing, invalid, expired or revoked API key. */110export class AuthenticationError extends AuthError {}111/** 403: the key lacks a scope, or the source is blocked by policy. */112export class PermissionDeniedError extends AuthError {}113/** 400 or 422: the request was refused before anything was created. */114export class ValidationError extends ApiError {}115/** 422 `mandatory_policy`: an attempt to disable robots.txt compliance or stop-on-access-denial. */116export class MandatoryPolicyError extends ValidationError {}117/** 404. */118export class NotFoundError extends ApiError {}119/** 409. */120export class ConflictError extends ApiError {}121/** 409 `idempotency_conflict`: the Idempotency-Key was already used with a different request. */122export class IdempotencyConflictError extends ConflictError {}123/** 429 `rate_limited` (after the allowed retries). */124export class RateLimitError extends ApiError {}125/** 429 `quota_exceeded`: a tenant quota is reached. */126export class QuotaExceededError extends RateLimitError {}127/** 5xx. */128export class ServerError extends ApiError {}129130function retryAfter(headers: Headers, details: unknown): number | null {131 const raw = headers.get("retry-after");132 if (raw !== null && /^\d+(\.\d+)?$/.test(raw.trim())) return Number(raw);133 if (details !== null && typeof details === "object") {134 const v = (details as Record<string, unknown>)["retry_after_s"];135 if (typeof v === "number" && Number.isFinite(v)) return Math.max(0, v);136 }137 return null;138}139140/** The typed error of a non-2xx response. `body` is the decoded JSON, or undefined. */141export function errorFromResponse(status: number, body: unknown, headers: Headers, text = ""): ApiError {142 const err = body !== null && typeof body === "object" ? (body as Record<string, unknown>)["error"] : undefined;143 let code = "http_error";144 let message = text.slice(0, 300) || `HTTP ${status}`;145 let details: unknown = null;146 let requestId: string | null = null;147 if (err !== null && typeof err === "object") {148 const e = err as Record<string, unknown>;149 code = typeof e["code"] === "string" && e["code"] ? e["code"] : "http_error";150 message = typeof e["message"] === "string" ? e["message"] : "";151 details = e["details"] ?? null;152 requestId = typeof e["request_id"] === "string" ? e["request_id"] : null;153 }154 const fields: ApiErrorFields = {155 status, code, message, details,156 requestId: requestId ?? headers.get("x-request-id"),157 retryAfterSeconds: retryAfter(headers, details),158 };159 if (status === 401) return new AuthenticationError(fields);160 if (status === 403) return new PermissionDeniedError(fields);161 if (status === 400 || status === 422) {162 return code === "mandatory_policy" ? new MandatoryPolicyError(fields) : new ValidationError(fields);163 }164 if (status === 404) return new NotFoundError(fields);165 if (status === 409) {166 return code === "idempotency_conflict" ? new IdempotencyConflictError(fields) : new ConflictError(fields);167 }168 if (status === 429) return code === "quota_exceeded" ? new QuotaExceededError(fields) : new RateLimitError(fields);169 if (status >= 500) return new ServerError(fields);170 return new ApiError(fields);171}172