@hirefinn/sdk 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +177 -2
  3. package/dist/cjs/approval.d.ts +12 -0
  4. package/dist/cjs/approval.js +19 -0
  5. package/dist/cjs/client.d.ts +30 -0
  6. package/dist/cjs/client.js +35 -0
  7. package/dist/cjs/core.d.ts +69 -0
  8. package/dist/cjs/core.js +265 -0
  9. package/dist/cjs/errors.d.ts +90 -0
  10. package/dist/cjs/errors.js +165 -0
  11. package/dist/cjs/generated/openapi.d.ts +10729 -0
  12. package/dist/cjs/generated/openapi.js +2 -0
  13. package/dist/cjs/index.d.ts +11 -0
  14. package/dist/cjs/index.js +44 -0
  15. package/dist/cjs/package.json +1 -0
  16. package/dist/cjs/pagination.d.ts +36 -0
  17. package/dist/cjs/pagination.js +124 -0
  18. package/dist/cjs/resources.d.ts +845 -0
  19. package/dist/cjs/resources.js +395 -0
  20. package/dist/cjs/types.d.ts +144 -0
  21. package/dist/cjs/types.js +2 -0
  22. package/dist/esm/approval.d.ts +12 -0
  23. package/dist/esm/approval.js +16 -0
  24. package/dist/esm/client.d.ts +30 -0
  25. package/dist/esm/client.js +31 -0
  26. package/dist/esm/core.d.ts +69 -0
  27. package/dist/esm/core.js +260 -0
  28. package/dist/esm/errors.d.ts +90 -0
  29. package/dist/esm/errors.js +155 -0
  30. package/dist/esm/generated/openapi.d.ts +10729 -0
  31. package/dist/esm/generated/openapi.js +1 -0
  32. package/dist/esm/index.d.ts +11 -0
  33. package/dist/esm/index.js +7 -0
  34. package/dist/esm/package.json +1 -0
  35. package/dist/esm/pagination.d.ts +36 -0
  36. package/dist/esm/pagination.js +116 -0
  37. package/dist/esm/resources.d.ts +845 -0
  38. package/dist/esm/resources.js +377 -0
  39. package/dist/esm/types.d.ts +144 -0
  40. package/dist/esm/types.js +1 -0
  41. package/package.json +51 -4
@@ -0,0 +1,69 @@
1
+ import type { FinnResponse, HttpMethod, Operation, PathsFor, RequestArgs, RequestOptions, ResultOf } from './types.js';
2
+ export declare const DEFAULT_BASE_URL = "https://api.hirefinn.ai/v1";
3
+ export declare const SDK_VERSION = "0.1.0";
4
+ export interface FinnOptions {
5
+ /** `finn_live_...` org key, `finn_test_...` test key, or an OAuth `finn_oat_...` token. Defaults to env FINN_API_KEY. */
6
+ apiKey?: string;
7
+ /** Defaults to `https://api.hirefinn.ai/v1`. */
8
+ baseUrl?: string;
9
+ /** Org to act in (Finn-Org header). Needed only for tokens that can use more than one org. */
10
+ org?: string;
11
+ /** Pins the API version (Finn-Version header), a date such as `2026-11-01`. */
12
+ version?: string;
13
+ /** Retries after the first attempt, on network errors, 408, 429 and 5xx. Default 2. */
14
+ maxRetries?: number;
15
+ /** Timeout per attempt in milliseconds. Default 60000. */
16
+ timeoutMs?: number;
17
+ /** A fetch implementation. Defaults to the global fetch (Node 18+, browsers). */
18
+ fetch?: typeof fetch;
19
+ /**
20
+ * Send a generated Idempotency-Key on spending and outward writes (place a call, rent a number, deploy, start or
21
+ * send a chat, create an agent, start a case) when the caller did not pass one, so they can be retried safely.
22
+ * Default true.
23
+ */
24
+ autoIdempotency?: boolean;
25
+ /** Longest Retry-After the SDK will wait out; a longer one throws instead. Default 60000 ms. */
26
+ maxRetryAfterMs?: number;
27
+ /** Headers sent on every request. */
28
+ defaultHeaders?: Record<string, string>;
29
+ /** Replaces the wait between retries (for tests). */
30
+ sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
31
+ }
32
+ /** Writes that get an automatic Idempotency-Key (when autoIdempotency is on). */
33
+ export declare const AUTO_IDEMPOTENCY_ROUTES: ReadonlySet<string>;
34
+ /** A new random Idempotency-Key (a UUID v4). */
35
+ export declare function idempotencyKey(): string;
36
+ /** Untyped request input, for paths the spec does not have yet. */
37
+ export interface RawRequest {
38
+ method: HttpMethod | Uppercase<HttpMethod>;
39
+ /** Path below the base URL, e.g. `/calls/{call_uuid}` or `/calls/abc`. */
40
+ path: string;
41
+ /** Values for `{name}` placeholders in `path`. */
42
+ pathParams?: Record<string, string | number>;
43
+ query?: Record<string, unknown>;
44
+ body?: unknown;
45
+ }
46
+ export declare class FinnCore {
47
+ #private;
48
+ readonly baseUrl: string;
49
+ readonly org: string | undefined;
50
+ readonly version: string | undefined;
51
+ readonly maxRetries: number;
52
+ readonly timeoutMs: number;
53
+ readonly autoIdempotency: boolean;
54
+ readonly maxRetryAfterMs: number;
55
+ constructor(options?: FinnOptions);
56
+ /**
57
+ * Calls any operation in the spec, fully typed.
58
+ *
59
+ * const call = await finn.request('get', '/calls/{call_uuid}', { path: { call_uuid } });
60
+ */
61
+ request<M extends HttpMethod, P extends PathsFor<M>>(method: M, path: P, ...args: RequestArgs<Operation<P, M>>): Promise<ResultOf<P, M, Operation<P, M>>>;
62
+ /** Same as request(), plus status, headers and request id. */
63
+ requestWithResponse<M extends HttpMethod, P extends PathsFor<M>>(method: M, path: P, ...args: RequestArgs<Operation<P, M>>): Promise<FinnResponse<ResultOf<P, M, Operation<P, M>>>>;
64
+ /** Untyped escape hatch for endpoints newer than this SDK's spec. */
65
+ rawRequest<T = unknown>(req: RawRequest, options?: RequestOptions): Promise<FinnResponse<T>>;
66
+ /** Builds the full URL: base + path with `{name}` filled in + query string. */
67
+ buildUrl(path: string, pathParams?: Record<string, string | number>, query?: Record<string, unknown>): string;
68
+ private fetchOnce;
69
+ }
@@ -0,0 +1,260 @@
1
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
2
+ if (kind === "m") throw new TypeError("Private method is not writable");
3
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
4
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
5
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
6
+ };
7
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
8
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
9
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
+ };
12
+ var _FinnCore_apiKey, _FinnCore_fetch, _FinnCore_defaultHeaders, _FinnCore_sleep;
13
+ import { FinnConnectionError, FinnError, FinnSdkError, FinnTimeoutError } from './errors.js';
14
+ export const DEFAULT_BASE_URL = 'https://api.hirefinn.ai/v1';
15
+ export const SDK_VERSION = '0.1.0';
16
+ /** Writes that get an automatic Idempotency-Key (when autoIdempotency is on). */
17
+ export const AUTO_IDEMPOTENCY_ROUTES = new Set([
18
+ 'post /calls',
19
+ 'post /phone_numbers',
20
+ 'post /deployments',
21
+ 'post /deployments/inbound',
22
+ 'post /chat/conversations',
23
+ 'post /chat/conversations/{id}/messages',
24
+ 'post /agents',
25
+ 'post /agents/{id}/cases',
26
+ ]);
27
+ const SAFE_TO_RETRY_METHODS = new Set(['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE']);
28
+ const RETRY_BASE_DELAY_MS = 500;
29
+ const RETRY_MAX_DELAY_MS = 8000;
30
+ /** A new random Idempotency-Key (a UUID v4). */
31
+ export function idempotencyKey() {
32
+ const c = globalThis.crypto;
33
+ if (c && typeof c.randomUUID === 'function')
34
+ return c.randomUUID();
35
+ const bytes = new Uint8Array(16);
36
+ if (c && typeof c.getRandomValues === 'function')
37
+ c.getRandomValues(bytes);
38
+ else
39
+ for (let i = 0; i < 16; i += 1)
40
+ bytes[i] = Math.floor(Math.random() * 256);
41
+ bytes[6] = (bytes[6] & 0x0f) | 0x40;
42
+ bytes[8] = (bytes[8] & 0x3f) | 0x80;
43
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
44
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
45
+ }
46
+ function defaultSleep(ms, signal) {
47
+ return new Promise((resolve, reject) => {
48
+ if (signal?.aborted)
49
+ return reject(signal.reason ?? new Error('Aborted'));
50
+ const timer = setTimeout(() => {
51
+ signal?.removeEventListener('abort', onAbort);
52
+ resolve();
53
+ }, ms);
54
+ const onAbort = () => {
55
+ clearTimeout(timer);
56
+ reject(signal?.reason ?? new Error('Aborted'));
57
+ };
58
+ signal?.addEventListener('abort', onAbort, { once: true });
59
+ });
60
+ }
61
+ function readEnvKey() {
62
+ const proc = globalThis.process;
63
+ return proc?.env?.FINN_API_KEY;
64
+ }
65
+ export class FinnCore {
66
+ constructor(options = {}) {
67
+ _FinnCore_apiKey.set(this, void 0);
68
+ _FinnCore_fetch.set(this, void 0);
69
+ _FinnCore_defaultHeaders.set(this, void 0);
70
+ _FinnCore_sleep.set(this, void 0);
71
+ const apiKey = options.apiKey ?? readEnvKey();
72
+ if (!apiKey) {
73
+ throw new FinnSdkError('Missing API key: pass { apiKey } to new Finn() or set FINN_API_KEY.');
74
+ }
75
+ const f = options.fetch ?? globalThis.fetch;
76
+ if (typeof f !== 'function') {
77
+ throw new FinnSdkError('No fetch available: use Node 18+ or pass { fetch } to new Finn().');
78
+ }
79
+ __classPrivateFieldSet(this, _FinnCore_apiKey, apiKey, "f");
80
+ __classPrivateFieldSet(this, _FinnCore_fetch, f, "f");
81
+ this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, '');
82
+ this.org = options.org;
83
+ this.version = options.version;
84
+ this.maxRetries = options.maxRetries ?? 2;
85
+ this.timeoutMs = options.timeoutMs ?? 60000;
86
+ this.autoIdempotency = options.autoIdempotency ?? true;
87
+ this.maxRetryAfterMs = options.maxRetryAfterMs ?? 60000;
88
+ __classPrivateFieldSet(this, _FinnCore_defaultHeaders, { ...(options.defaultHeaders ?? {}) }, "f");
89
+ __classPrivateFieldSet(this, _FinnCore_sleep, options.sleep ?? defaultSleep, "f");
90
+ }
91
+ /**
92
+ * Calls any operation in the spec, fully typed.
93
+ *
94
+ * const call = await finn.request('get', '/calls/{call_uuid}', { path: { call_uuid } });
95
+ */
96
+ async request(method, path, ...args) {
97
+ const res = await this.requestWithResponse(method, path, ...args);
98
+ return res.data;
99
+ }
100
+ /** Same as request(), plus status, headers and request id. */
101
+ async requestWithResponse(method, path, ...args) {
102
+ const [params, options] = args;
103
+ return this.rawRequest({ method, path: path, pathParams: params?.path, query: params?.query, body: params?.body }, options);
104
+ }
105
+ /** Untyped escape hatch for endpoints newer than this SDK's spec. */
106
+ async rawRequest(req, options = {}) {
107
+ const method = req.method.toUpperCase();
108
+ const routeKey = `${method.toLowerCase()} ${req.path}`;
109
+ const url = this.buildUrl(req.path, req.pathParams, req.query);
110
+ let key;
111
+ if (typeof options.idempotencyKey === 'string')
112
+ key = options.idempotencyKey;
113
+ else if (options.idempotencyKey !== false && this.autoIdempotency && AUTO_IDEMPOTENCY_ROUTES.has(routeKey)) {
114
+ key = idempotencyKey();
115
+ }
116
+ const headers = new Headers();
117
+ headers.set('Accept', 'application/json');
118
+ for (const [k, v] of Object.entries(__classPrivateFieldGet(this, _FinnCore_defaultHeaders, "f")))
119
+ headers.set(k, v);
120
+ const org = options.org ?? this.org;
121
+ if (org)
122
+ headers.set('Finn-Org', org);
123
+ const version = options.version ?? this.version;
124
+ if (version)
125
+ headers.set('Finn-Version', version);
126
+ if (key)
127
+ headers.set('Idempotency-Key', key);
128
+ let body;
129
+ if (req.body !== undefined && req.body !== null) {
130
+ if (typeof FormData !== 'undefined' && req.body instanceof FormData)
131
+ body = req.body;
132
+ else {
133
+ headers.set('Content-Type', 'application/json');
134
+ body = JSON.stringify(req.body);
135
+ }
136
+ }
137
+ for (const [k, v] of Object.entries(options.headers ?? {}))
138
+ headers.set(k, v);
139
+ headers.set('Authorization', `Bearer ${__classPrivateFieldGet(this, _FinnCore_apiKey, "f")}`);
140
+ const canRetry = SAFE_TO_RETRY_METHODS.has(method) || headers.has('Idempotency-Key');
141
+ const maxRetries = canRetry ? Math.max(0, options.maxRetries ?? this.maxRetries) : 0;
142
+ const timeoutMs = options.timeoutMs ?? this.timeoutMs;
143
+ for (let attempt = 0;; attempt += 1) {
144
+ let response;
145
+ try {
146
+ response = await this.fetchOnce(url, { method, headers, body }, timeoutMs, options.signal);
147
+ }
148
+ catch (err) {
149
+ if (options.signal?.aborted)
150
+ throw err;
151
+ const wrapped = err instanceof FinnTimeoutError
152
+ ? err
153
+ : new FinnConnectionError(`Could not reach the Finn API: ${err?.message ?? err}`, { cause: err });
154
+ if (attempt < maxRetries) {
155
+ await __classPrivateFieldGet(this, _FinnCore_sleep, "f").call(this, backoffMs(attempt), options.signal);
156
+ continue;
157
+ }
158
+ throw wrapped;
159
+ }
160
+ const parsed = await readBody(response);
161
+ if (response.ok) {
162
+ return {
163
+ data: parsed,
164
+ status: response.status,
165
+ headers: response.headers,
166
+ requestId: response.headers.get('x-request-id'),
167
+ idempotentReplayed: response.headers.get('idempotent-replayed') === 'true',
168
+ };
169
+ }
170
+ const error = FinnError.fromResponse(response.status, response.headers, parsed, response.statusText);
171
+ if (attempt < maxRetries && isRetryable(error)) {
172
+ const wait = error.retryAfter != null ? error.retryAfter * 1000 : backoffMs(attempt);
173
+ if (wait > this.maxRetryAfterMs)
174
+ throw error;
175
+ await __classPrivateFieldGet(this, _FinnCore_sleep, "f").call(this, wait, options.signal);
176
+ continue;
177
+ }
178
+ throw error;
179
+ }
180
+ }
181
+ /** Builds the full URL: base + path with `{name}` filled in + query string. */
182
+ buildUrl(path, pathParams, query) {
183
+ const filled = path.replace(/\{([^}]+)\}/g, (_, name) => {
184
+ const value = pathParams?.[name];
185
+ if (value === undefined || value === null || value === '') {
186
+ throw new FinnSdkError(`Missing path parameter "${name}" for ${path}`);
187
+ }
188
+ return encodeURIComponent(String(value));
189
+ });
190
+ const qs = new URLSearchParams();
191
+ for (const [k, v] of Object.entries(query ?? {})) {
192
+ if (v === undefined || v === null)
193
+ continue;
194
+ if (Array.isArray(v))
195
+ qs.set(k, v.map(String).join(','));
196
+ else if (v instanceof Date)
197
+ qs.set(k, v.toISOString());
198
+ else
199
+ qs.set(k, String(v));
200
+ }
201
+ const s = qs.toString();
202
+ return `${this.baseUrl}${filled.startsWith('/') ? '' : '/'}${filled}${s ? `?${s}` : ''}`;
203
+ }
204
+ async fetchOnce(url, init, timeoutMs, signal) {
205
+ const controller = new AbortController();
206
+ let timedOut = false;
207
+ const onAbort = () => controller.abort(signal?.reason);
208
+ if (signal?.aborted)
209
+ throw signal.reason ?? new Error('Aborted');
210
+ signal?.addEventListener('abort', onAbort, { once: true });
211
+ const timer = timeoutMs > 0 && Number.isFinite(timeoutMs)
212
+ ? setTimeout(() => {
213
+ timedOut = true;
214
+ controller.abort();
215
+ }, timeoutMs)
216
+ : undefined;
217
+ try {
218
+ return await __classPrivateFieldGet(this, _FinnCore_fetch, "f").call(this, url, { ...init, signal: controller.signal });
219
+ }
220
+ catch (err) {
221
+ if (timedOut)
222
+ throw new FinnTimeoutError(`The request timed out after ${timeoutMs} ms.`, { cause: err });
223
+ throw err;
224
+ }
225
+ finally {
226
+ if (timer)
227
+ clearTimeout(timer);
228
+ signal?.removeEventListener('abort', onAbort);
229
+ }
230
+ }
231
+ }
232
+ _FinnCore_apiKey = new WeakMap(), _FinnCore_fetch = new WeakMap(), _FinnCore_defaultHeaders = new WeakMap(), _FinnCore_sleep = new WeakMap();
233
+ function isRetryable(error) {
234
+ if (error.status === 408 || error.status === 429)
235
+ return true;
236
+ if (error.status === 409)
237
+ return error.code === 'idempotency_in_progress';
238
+ return error.status === 500 || error.status === 502 || error.status === 503 || error.status === 504;
239
+ }
240
+ function backoffMs(attempt) {
241
+ const base = Math.min(RETRY_MAX_DELAY_MS, RETRY_BASE_DELAY_MS * 2 ** attempt);
242
+ return Math.round(base * (1 - Math.random() * 0.25));
243
+ }
244
+ async function readBody(response) {
245
+ if (response.status === 204 || response.status === 205)
246
+ return undefined;
247
+ const text = await response.text();
248
+ if (text === '')
249
+ return undefined;
250
+ const type = response.headers.get('content-type') ?? '';
251
+ if (type.includes('json') || /^[[{]/.test(text.trimStart())) {
252
+ try {
253
+ return JSON.parse(text);
254
+ }
255
+ catch {
256
+ return text;
257
+ }
258
+ }
259
+ return text;
260
+ }
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Errors thrown by the SDK.
3
+ *
4
+ * The API answers errors in one of three shapes, and FinnError reads all of them:
5
+ *
6
+ * - unified (newer endpoints: Agents, Chat, and errors raised by shared middleware on them):
7
+ * `{ "error": { "code", "message", "fields", "request_id", "doc_url" } }`
8
+ * - legacy (older /v1 endpoints): `{ "error": "<code>", "message": "...", ...extra }`
9
+ * - Operator pass-through (Cases, Approvals): `{ "code": "<code>", "message": "...", "details": ... }`
10
+ *
11
+ * Branch on `code`, never on `message`.
12
+ */
13
+ export interface FinnFieldError {
14
+ /** Dotted path into the body or query, e.g. `variables.first_name` or `limit`. */
15
+ field: string;
16
+ code: string;
17
+ message: string;
18
+ }
19
+ /** The shared error codes. Endpoints may also answer resource-specific codes such as `finn_not_found`. */
20
+ export type FinnErrorCode = 'invalid_request' | 'invalid_cursor' | 'unauthorized' | 'api_key_required' | 'invalid_api_key' | 'insufficient_scope' | 'forbidden' | 'not_found' | 'conflict' | 'idempotency_in_progress' | 'payload_too_large' | 'idempotency_key_reused' | 'rate_limited' | 'internal_error' | 'unavailable' | (string & {});
21
+ /** The code an error gets when the body does not name one (mirrors the backend's codeForStatus). */
22
+ export declare const codeForStatus: (status: number) => string;
23
+ /** Base class for every error the SDK throws. */
24
+ export declare class FinnSdkError extends Error {
25
+ constructor(message: string, options?: {
26
+ cause?: unknown;
27
+ });
28
+ }
29
+ /** The API answered with a 4xx or 5xx status. */
30
+ export declare class FinnError extends FinnSdkError {
31
+ /** HTTP status. */
32
+ readonly status: number;
33
+ /** Stable error code. */
34
+ readonly code: FinnErrorCode;
35
+ /** Matches the `X-Request-Id` response header; quote it to support. */
36
+ readonly requestId: string | null;
37
+ /** Per-field problems (unified shape only; `[]` otherwise). */
38
+ readonly fields: FinnFieldError[];
39
+ /** Link to the error's documentation, when the API sent one. */
40
+ readonly docUrl: string | null;
41
+ /** Dashboard page that fixes the problem (`compliance_required`, `insufficient_credits`, ...), when sent. */
42
+ readonly actionUrl: string | null;
43
+ /** The scope the key lacks, on `403 insufficient_scope`. */
44
+ readonly requiredScope: string | null;
45
+ /** Seconds the API asked us to wait (Retry-After), when sent. */
46
+ readonly retryAfter: number | null;
47
+ /** Extra fields from legacy and Operator bodies (`details`, `deployment_id`, `required_credits`, ...). */
48
+ readonly details: Record<string, unknown>;
49
+ /** The parsed response body (or raw text when it was not JSON). */
50
+ readonly body: unknown;
51
+ /** Response headers. */
52
+ readonly headers: Headers;
53
+ constructor(init: {
54
+ status: number;
55
+ code: string;
56
+ message: string;
57
+ requestId?: string | null;
58
+ fields?: FinnFieldError[];
59
+ docUrl?: string | null;
60
+ actionUrl?: string | null;
61
+ requiredScope?: string | null;
62
+ retryAfter?: number | null;
63
+ details?: Record<string, unknown>;
64
+ body?: unknown;
65
+ headers?: Headers;
66
+ });
67
+ /** Builds a FinnError from a failed response and its already-read body. */
68
+ static fromResponse(status: number, headers: Headers, body: unknown, statusText?: string): FinnError;
69
+ }
70
+ /** The request never got an HTTP answer (DNS, connection reset, CORS, ...). */
71
+ export declare class FinnConnectionError extends FinnSdkError {
72
+ constructor(message?: string, options?: {
73
+ cause?: unknown;
74
+ });
75
+ }
76
+ /** The request took longer than `timeoutMs`. */
77
+ export declare class FinnTimeoutError extends FinnConnectionError {
78
+ constructor(message?: string, options?: {
79
+ cause?: unknown;
80
+ });
81
+ }
82
+ /** waitForApproval gave up before the approval reached a final status. */
83
+ export declare class FinnApprovalTimeoutError extends FinnSdkError {
84
+ readonly approvalId: string;
85
+ /** The last status seen. */
86
+ readonly lastStatus: string | null;
87
+ constructor(approvalId: string, lastStatus: string | null);
88
+ }
89
+ /** Retry-After as seconds: accepts delta-seconds or an HTTP date. */
90
+ export declare function parseRetryAfterSeconds(value: string | null, now?: number): number | null;
@@ -0,0 +1,155 @@
1
+ /**
2
+ * Errors thrown by the SDK.
3
+ *
4
+ * The API answers errors in one of three shapes, and FinnError reads all of them:
5
+ *
6
+ * - unified (newer endpoints: Agents, Chat, and errors raised by shared middleware on them):
7
+ * `{ "error": { "code", "message", "fields", "request_id", "doc_url" } }`
8
+ * - legacy (older /v1 endpoints): `{ "error": "<code>", "message": "...", ...extra }`
9
+ * - Operator pass-through (Cases, Approvals): `{ "code": "<code>", "message": "...", "details": ... }`
10
+ *
11
+ * Branch on `code`, never on `message`.
12
+ */
13
+ const CODE_FOR_STATUS = {
14
+ 400: 'invalid_request',
15
+ 401: 'unauthorized',
16
+ 403: 'forbidden',
17
+ 404: 'not_found',
18
+ 409: 'conflict',
19
+ 413: 'payload_too_large',
20
+ 422: 'invalid_request',
21
+ 429: 'rate_limited',
22
+ 500: 'internal_error',
23
+ 502: 'unavailable',
24
+ 503: 'unavailable',
25
+ 504: 'unavailable',
26
+ };
27
+ /** The code an error gets when the body does not name one (mirrors the backend's codeForStatus). */
28
+ export const codeForStatus = (status) => CODE_FOR_STATUS[status] ?? (status >= 500 ? 'internal_error' : 'invalid_request');
29
+ /** Base class for every error the SDK throws. */
30
+ export class FinnSdkError extends Error {
31
+ constructor(message, options) {
32
+ super(message);
33
+ this.name = 'FinnSdkError';
34
+ if (options && 'cause' in options)
35
+ this.cause = options.cause;
36
+ }
37
+ }
38
+ /** The API answered with a 4xx or 5xx status. */
39
+ export class FinnError extends FinnSdkError {
40
+ constructor(init) {
41
+ super(init.message);
42
+ this.name = 'FinnError';
43
+ this.status = init.status;
44
+ this.code = init.code;
45
+ this.requestId = init.requestId ?? null;
46
+ this.fields = init.fields ?? [];
47
+ this.docUrl = init.docUrl ?? null;
48
+ this.actionUrl = init.actionUrl ?? null;
49
+ this.requiredScope = init.requiredScope ?? null;
50
+ this.retryAfter = init.retryAfter ?? null;
51
+ this.details = init.details ?? {};
52
+ this.body = init.body;
53
+ this.headers = init.headers ?? new Headers();
54
+ }
55
+ /** Builds a FinnError from a failed response and its already-read body. */
56
+ static fromResponse(status, headers, body, statusText = '') {
57
+ const headerRequestId = headers.get('x-request-id');
58
+ const retryAfter = parseRetryAfterSeconds(headers.get('retry-after'));
59
+ const base = { status, headers, body, retryAfter };
60
+ const obj = isRecord(body) ? body : null;
61
+ // Unified: { error: { code, message, fields, request_id, doc_url } }
62
+ if (obj && isRecord(obj.error)) {
63
+ const e = obj.error;
64
+ const { error: _e, ...rest } = obj;
65
+ return new FinnError({
66
+ ...base,
67
+ code: str(e.code) ?? codeForStatus(status),
68
+ message: str(e.message) ?? defaultMessage(status, statusText),
69
+ requestId: str(e.request_id) ?? headerRequestId,
70
+ fields: Array.isArray(e.fields) ? e.fields.filter(isFieldError) : [],
71
+ docUrl: str(e.doc_url),
72
+ actionUrl: str(e.action_url) ?? str(obj.action_url),
73
+ requiredScope: str(e.required_scope) ?? str(obj.required_scope),
74
+ details: rest,
75
+ });
76
+ }
77
+ // Legacy: { error: "<code>", message, ...extra }
78
+ if (obj && typeof obj.error === 'string') {
79
+ const { error, message, action_url, required_scope, request_id, ...rest } = obj;
80
+ return new FinnError({
81
+ ...base,
82
+ code: error || codeForStatus(status),
83
+ message: str(message) ?? defaultMessage(status, statusText),
84
+ requestId: str(request_id) ?? headerRequestId,
85
+ actionUrl: str(action_url),
86
+ requiredScope: str(required_scope),
87
+ details: rest,
88
+ });
89
+ }
90
+ // Operator pass-through: { code, message, details }
91
+ if (obj && typeof obj.code === 'string') {
92
+ const { code, message, request_id, ...rest } = obj;
93
+ return new FinnError({
94
+ ...base,
95
+ code: code,
96
+ message: str(message) ?? defaultMessage(status, statusText),
97
+ requestId: str(request_id) ?? headerRequestId,
98
+ details: rest,
99
+ });
100
+ }
101
+ return new FinnError({
102
+ ...base,
103
+ code: codeForStatus(status),
104
+ message: typeof body === 'string' && body.trim() && body.length < 500 ? body.trim() : defaultMessage(status, statusText),
105
+ requestId: headerRequestId,
106
+ });
107
+ }
108
+ }
109
+ /** The request never got an HTTP answer (DNS, connection reset, CORS, ...). */
110
+ export class FinnConnectionError extends FinnSdkError {
111
+ constructor(message = 'Could not reach the Finn API.', options) {
112
+ super(message, options);
113
+ this.name = 'FinnConnectionError';
114
+ }
115
+ }
116
+ /** The request took longer than `timeoutMs`. */
117
+ export class FinnTimeoutError extends FinnConnectionError {
118
+ constructor(message = 'The request to the Finn API timed out.', options) {
119
+ super(message, options);
120
+ this.name = 'FinnTimeoutError';
121
+ }
122
+ }
123
+ /** waitForApproval gave up before the approval reached a final status. */
124
+ export class FinnApprovalTimeoutError extends FinnSdkError {
125
+ constructor(approvalId, lastStatus) {
126
+ super(`Approval ${approvalId} was still ${lastStatus ?? 'unknown'} when waitForApproval timed out.`);
127
+ this.name = 'FinnApprovalTimeoutError';
128
+ this.approvalId = approvalId;
129
+ this.lastStatus = lastStatus;
130
+ }
131
+ }
132
+ /** Retry-After as seconds: accepts delta-seconds or an HTTP date. */
133
+ export function parseRetryAfterSeconds(value, now = Date.now()) {
134
+ if (value == null || value.trim() === '')
135
+ return null;
136
+ const v = value.trim();
137
+ if (/^\d+(\.\d+)?$/.test(v))
138
+ return Number(v);
139
+ const date = Date.parse(v);
140
+ if (Number.isNaN(date))
141
+ return null;
142
+ return Math.max(0, (date - now) / 1000);
143
+ }
144
+ function defaultMessage(status, statusText) {
145
+ return `Finn API request failed with status ${status}${statusText ? ` ${statusText}` : ''}.`;
146
+ }
147
+ function isRecord(v) {
148
+ return typeof v === 'object' && v !== null && !Array.isArray(v);
149
+ }
150
+ function str(v) {
151
+ return typeof v === 'string' && v !== '' ? v : null;
152
+ }
153
+ function isFieldError(v) {
154
+ return isRecord(v) && typeof v.field === 'string';
155
+ }