@hirefinn/sdk 0.0.0-stage → 0.2.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 (45) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +217 -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 +81 -0
  8. package/dist/cjs/core.js +300 -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 +13 -0
  14. package/dist/cjs/index.js +55 -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 +148 -0
  21. package/dist/cjs/types.js +2 -0
  22. package/dist/cjs/webhooks.d.ts +57 -0
  23. package/dist/cjs/webhooks.js +181 -0
  24. package/dist/esm/approval.d.ts +12 -0
  25. package/dist/esm/approval.js +16 -0
  26. package/dist/esm/client.d.ts +30 -0
  27. package/dist/esm/client.js +31 -0
  28. package/dist/esm/core.d.ts +81 -0
  29. package/dist/esm/core.js +294 -0
  30. package/dist/esm/errors.d.ts +90 -0
  31. package/dist/esm/errors.js +155 -0
  32. package/dist/esm/generated/openapi.d.ts +10729 -0
  33. package/dist/esm/generated/openapi.js +1 -0
  34. package/dist/esm/index.d.ts +13 -0
  35. package/dist/esm/index.js +8 -0
  36. package/dist/esm/package.json +1 -0
  37. package/dist/esm/pagination.d.ts +36 -0
  38. package/dist/esm/pagination.js +116 -0
  39. package/dist/esm/resources.d.ts +845 -0
  40. package/dist/esm/resources.js +377 -0
  41. package/dist/esm/types.d.ts +148 -0
  42. package/dist/esm/types.js +1 -0
  43. package/dist/esm/webhooks.d.ts +57 -0
  44. package/dist/esm/webhooks.js +140 -0
  45. package/package.json +53 -4
@@ -0,0 +1,300 @@
1
+ "use strict";
2
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
3
+ if (kind === "m") throw new TypeError("Private method is not writable");
4
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
5
+ 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");
6
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
7
+ };
8
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
9
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
10
+ 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");
11
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
12
+ };
13
+ var _FinnCore_apiKey, _FinnCore_fetch, _FinnCore_defaultHeaders, _FinnCore_sleep;
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.FinnCore = exports.IDEMPOTENT_WRITE_ROUTES = exports.AUTO_IDEMPOTENCY_ROUTES = exports.SDK_VERSION = exports.DEFAULT_BASE_URL = void 0;
16
+ exports.honoursIdempotencyKey = honoursIdempotencyKey;
17
+ exports.idempotencyKey = idempotencyKey;
18
+ const errors_js_1 = require("./errors.js");
19
+ exports.DEFAULT_BASE_URL = 'https://api.hirefinn.ai/v1';
20
+ exports.SDK_VERSION = '0.2.0';
21
+ /** Writes that get an automatic Idempotency-Key (when autoIdempotency is on). */
22
+ exports.AUTO_IDEMPOTENCY_ROUTES = new Set([
23
+ 'post /calls',
24
+ 'post /phone_numbers',
25
+ 'post /deployments',
26
+ 'post /deployments/inbound',
27
+ 'post /chat/conversations',
28
+ 'post /chat/conversations/{id}/messages',
29
+ 'post /agents',
30
+ 'post /agents/{id}/cases',
31
+ ]);
32
+ /**
33
+ * POST/PATCH routes where the API dedupes by Idempotency-Key (a retry with the same key and body replays the first
34
+ * answer). Only these writes are retried, and only when they carry a key: other routes ignore the header, so a retry
35
+ * after a timeout could create a second resource. `*` matches the rest of the path.
36
+ */
37
+ exports.IDEMPOTENT_WRITE_ROUTES = [
38
+ 'post /calls',
39
+ 'post /phone_numbers',
40
+ 'post /deployments',
41
+ 'post /deployments/inbound',
42
+ 'post /chat/conversations',
43
+ 'post /chat/conversations/{id}/messages',
44
+ 'post /agents',
45
+ 'post /agents/{id}/cases',
46
+ 'post /crm/*',
47
+ 'patch /crm/*',
48
+ 'post /sales/plays/{slug}/run',
49
+ 'post /sales/drafts/{id}/skip',
50
+ ];
51
+ const IDEMPOTENT_WRITE_MATCHERS = exports.IDEMPOTENT_WRITE_ROUTES.map((route) => {
52
+ const [method, path] = route.split(' ');
53
+ const body = path
54
+ .split('/')
55
+ .map((seg) => (seg === '*' ? '.+' : /^\{[^}]+\}$/.test(seg) ? '[^/]+' : seg.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')))
56
+ .join('/');
57
+ return { method: method.toUpperCase(), re: new RegExp(`^${body}/?$`) };
58
+ });
59
+ /** True when the API dedupes this write by Idempotency-Key. `path` may be a template or a filled-in path. */
60
+ function honoursIdempotencyKey(method, path) {
61
+ const m = method.toUpperCase();
62
+ const p = path.split('?')[0];
63
+ return IDEMPOTENT_WRITE_MATCHERS.some((x) => x.method === m && x.re.test(p));
64
+ }
65
+ const SAFE_TO_RETRY_METHODS = new Set(['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE']);
66
+ const RETRY_BASE_DELAY_MS = 500;
67
+ const RETRY_MAX_DELAY_MS = 8000;
68
+ /** A new random Idempotency-Key (a UUID v4). */
69
+ function idempotencyKey() {
70
+ const c = globalThis.crypto;
71
+ if (c && typeof c.randomUUID === 'function')
72
+ return c.randomUUID();
73
+ const bytes = new Uint8Array(16);
74
+ if (c && typeof c.getRandomValues === 'function')
75
+ c.getRandomValues(bytes);
76
+ else
77
+ for (let i = 0; i < 16; i += 1)
78
+ bytes[i] = Math.floor(Math.random() * 256);
79
+ bytes[6] = (bytes[6] & 0x0f) | 0x40;
80
+ bytes[8] = (bytes[8] & 0x3f) | 0x80;
81
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
82
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
83
+ }
84
+ function defaultSleep(ms, signal) {
85
+ return new Promise((resolve, reject) => {
86
+ if (signal?.aborted)
87
+ return reject(signal.reason ?? new Error('Aborted'));
88
+ const timer = setTimeout(() => {
89
+ signal?.removeEventListener('abort', onAbort);
90
+ resolve();
91
+ }, ms);
92
+ const onAbort = () => {
93
+ clearTimeout(timer);
94
+ reject(signal?.reason ?? new Error('Aborted'));
95
+ };
96
+ signal?.addEventListener('abort', onAbort, { once: true });
97
+ });
98
+ }
99
+ function readEnvKey() {
100
+ const proc = globalThis.process;
101
+ return proc?.env?.FINN_API_KEY;
102
+ }
103
+ class FinnCore {
104
+ constructor(options = {}) {
105
+ _FinnCore_apiKey.set(this, void 0);
106
+ _FinnCore_fetch.set(this, void 0);
107
+ _FinnCore_defaultHeaders.set(this, void 0);
108
+ _FinnCore_sleep.set(this, void 0);
109
+ const apiKey = options.apiKey ?? readEnvKey();
110
+ if (!apiKey) {
111
+ throw new errors_js_1.FinnSdkError('Missing API key: pass { apiKey } to new Finn() or set FINN_API_KEY.');
112
+ }
113
+ const f = options.fetch ?? globalThis.fetch;
114
+ if (typeof f !== 'function') {
115
+ throw new errors_js_1.FinnSdkError('No fetch available: use Node 18+ or pass { fetch } to new Finn().');
116
+ }
117
+ __classPrivateFieldSet(this, _FinnCore_apiKey, apiKey, "f");
118
+ __classPrivateFieldSet(this, _FinnCore_fetch, f, "f");
119
+ this.baseUrl = (options.baseUrl ?? exports.DEFAULT_BASE_URL).replace(/\/+$/, '');
120
+ this.org = options.org;
121
+ this.version = options.version;
122
+ this.maxRetries = options.maxRetries ?? 2;
123
+ this.timeoutMs = options.timeoutMs ?? 60000;
124
+ this.autoIdempotency = options.autoIdempotency ?? true;
125
+ this.maxRetryAfterMs = options.maxRetryAfterMs ?? 60000;
126
+ __classPrivateFieldSet(this, _FinnCore_defaultHeaders, { ...(options.defaultHeaders ?? {}) }, "f");
127
+ __classPrivateFieldSet(this, _FinnCore_sleep, options.sleep ?? defaultSleep, "f");
128
+ }
129
+ /**
130
+ * Calls any operation in the spec, fully typed.
131
+ *
132
+ * const call = await finn.request('get', '/calls/{call_uuid}', { path: { call_uuid } });
133
+ */
134
+ async request(method, path, ...args) {
135
+ const res = await this.requestWithResponse(method, path, ...args);
136
+ return res.data;
137
+ }
138
+ /** Same as request(), plus status, headers and request id. */
139
+ async requestWithResponse(method, path, ...args) {
140
+ const [params, options] = args;
141
+ return this.rawRequest({ method, path: path, pathParams: params?.path, query: params?.query, body: params?.body }, options);
142
+ }
143
+ /** Untyped escape hatch for endpoints newer than this SDK's spec. */
144
+ async rawRequest(req, options = {}) {
145
+ const method = req.method.toUpperCase();
146
+ const routeKey = `${method.toLowerCase()} ${req.path}`;
147
+ const url = this.buildUrl(req.path, req.pathParams, req.query);
148
+ let key;
149
+ if (typeof options.idempotencyKey === 'string')
150
+ key = options.idempotencyKey;
151
+ else if (options.idempotencyKey !== false && this.autoIdempotency && exports.AUTO_IDEMPOTENCY_ROUTES.has(routeKey)) {
152
+ key = idempotencyKey();
153
+ }
154
+ const headers = new Headers();
155
+ headers.set('Accept', 'application/json');
156
+ for (const [k, v] of Object.entries(__classPrivateFieldGet(this, _FinnCore_defaultHeaders, "f")))
157
+ headers.set(k, v);
158
+ const org = options.org ?? this.org;
159
+ if (org)
160
+ headers.set('Finn-Org', org);
161
+ const version = options.version ?? this.version;
162
+ if (version)
163
+ headers.set('Finn-Version', version);
164
+ if (key)
165
+ headers.set('Idempotency-Key', key);
166
+ let body;
167
+ if (req.body !== undefined && req.body !== null) {
168
+ if (typeof FormData !== 'undefined' && req.body instanceof FormData)
169
+ body = req.body;
170
+ else {
171
+ headers.set('Content-Type', 'application/json');
172
+ body = JSON.stringify(req.body);
173
+ }
174
+ }
175
+ for (const [k, v] of Object.entries(options.headers ?? {}))
176
+ headers.set(k, v);
177
+ headers.set('Authorization', `Bearer ${__classPrivateFieldGet(this, _FinnCore_apiKey, "f")}`);
178
+ // Idempotent methods always; a POST/PATCH only with a key on a route that dedupes by it.
179
+ const canRetry = SAFE_TO_RETRY_METHODS.has(method) || (headers.has('Idempotency-Key') && honoursIdempotencyKey(method, req.path));
180
+ const maxRetries = canRetry ? Math.max(0, options.maxRetries ?? this.maxRetries) : 0;
181
+ const timeoutMs = options.timeoutMs ?? this.timeoutMs;
182
+ for (let attempt = 0;; attempt += 1) {
183
+ let response;
184
+ try {
185
+ response = await this.fetchOnce(url, { method, headers, body }, timeoutMs, options.signal);
186
+ }
187
+ catch (err) {
188
+ if (options.signal?.aborted)
189
+ throw err;
190
+ const wrapped = err instanceof errors_js_1.FinnTimeoutError
191
+ ? err
192
+ : new errors_js_1.FinnConnectionError(`Could not reach the Finn API: ${err?.message ?? err}`, { cause: err });
193
+ if (attempt < maxRetries) {
194
+ await __classPrivateFieldGet(this, _FinnCore_sleep, "f").call(this, backoffMs(attempt), options.signal);
195
+ continue;
196
+ }
197
+ throw wrapped;
198
+ }
199
+ const parsed = await readBody(response);
200
+ if (response.ok) {
201
+ return {
202
+ data: parsed,
203
+ status: response.status,
204
+ headers: response.headers,
205
+ requestId: response.headers.get('x-request-id'),
206
+ idempotentReplayed: response.headers.get('idempotent-replayed') === 'true',
207
+ };
208
+ }
209
+ const error = errors_js_1.FinnError.fromResponse(response.status, response.headers, parsed, response.statusText);
210
+ if (attempt < maxRetries && isRetryable(error)) {
211
+ const wait = error.retryAfter != null ? error.retryAfter * 1000 : backoffMs(attempt);
212
+ if (wait > this.maxRetryAfterMs)
213
+ throw error;
214
+ await __classPrivateFieldGet(this, _FinnCore_sleep, "f").call(this, wait, options.signal);
215
+ continue;
216
+ }
217
+ throw error;
218
+ }
219
+ }
220
+ /** Builds the full URL: base + path with `{name}` filled in + query string. */
221
+ buildUrl(path, pathParams, query) {
222
+ const filled = path.replace(/\{([^}]+)\}/g, (_, name) => {
223
+ const value = pathParams?.[name];
224
+ if (value === undefined || value === null || value === '') {
225
+ throw new errors_js_1.FinnSdkError(`Missing path parameter "${name}" for ${path}`);
226
+ }
227
+ return encodeURIComponent(String(value));
228
+ });
229
+ const qs = new URLSearchParams();
230
+ for (const [k, v] of Object.entries(query ?? {})) {
231
+ if (v === undefined || v === null)
232
+ continue;
233
+ if (Array.isArray(v))
234
+ qs.set(k, v.map(String).join(','));
235
+ else if (v instanceof Date)
236
+ qs.set(k, v.toISOString());
237
+ else
238
+ qs.set(k, String(v));
239
+ }
240
+ const s = qs.toString();
241
+ return `${this.baseUrl}${filled.startsWith('/') ? '' : '/'}${filled}${s ? `?${s}` : ''}`;
242
+ }
243
+ async fetchOnce(url, init, timeoutMs, signal) {
244
+ const controller = new AbortController();
245
+ let timedOut = false;
246
+ const onAbort = () => controller.abort(signal?.reason);
247
+ if (signal?.aborted)
248
+ throw signal.reason ?? new Error('Aborted');
249
+ signal?.addEventListener('abort', onAbort, { once: true });
250
+ const timer = timeoutMs > 0 && Number.isFinite(timeoutMs)
251
+ ? setTimeout(() => {
252
+ timedOut = true;
253
+ controller.abort();
254
+ }, timeoutMs)
255
+ : undefined;
256
+ try {
257
+ return await __classPrivateFieldGet(this, _FinnCore_fetch, "f").call(this, url, { ...init, signal: controller.signal });
258
+ }
259
+ catch (err) {
260
+ if (timedOut)
261
+ throw new errors_js_1.FinnTimeoutError(`The request timed out after ${timeoutMs} ms.`, { cause: err });
262
+ throw err;
263
+ }
264
+ finally {
265
+ if (timer)
266
+ clearTimeout(timer);
267
+ signal?.removeEventListener('abort', onAbort);
268
+ }
269
+ }
270
+ }
271
+ exports.FinnCore = FinnCore;
272
+ _FinnCore_apiKey = new WeakMap(), _FinnCore_fetch = new WeakMap(), _FinnCore_defaultHeaders = new WeakMap(), _FinnCore_sleep = new WeakMap();
273
+ function isRetryable(error) {
274
+ if (error.status === 408 || error.status === 429)
275
+ return true;
276
+ if (error.status === 409)
277
+ return error.code === 'idempotency_in_progress';
278
+ return error.status === 502 || error.status === 503 || error.status === 504;
279
+ }
280
+ function backoffMs(attempt) {
281
+ const base = Math.min(RETRY_MAX_DELAY_MS, RETRY_BASE_DELAY_MS * 2 ** attempt);
282
+ return Math.round(base * (1 - Math.random() * 0.25));
283
+ }
284
+ async function readBody(response) {
285
+ if (response.status === 204 || response.status === 205)
286
+ return undefined;
287
+ const text = await response.text();
288
+ if (text === '')
289
+ return undefined;
290
+ const type = response.headers.get('content-type') ?? '';
291
+ if (type.includes('json') || /^[[{]/.test(text.trimStart())) {
292
+ try {
293
+ return JSON.parse(text);
294
+ }
295
+ catch {
296
+ return text;
297
+ }
298
+ }
299
+ return text;
300
+ }
@@ -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,165 @@
1
+ "use strict";
2
+ /**
3
+ * Errors thrown by the SDK.
4
+ *
5
+ * The API answers errors in one of three shapes, and FinnError reads all of them:
6
+ *
7
+ * - unified (newer endpoints: Agents, Chat, and errors raised by shared middleware on them):
8
+ * `{ "error": { "code", "message", "fields", "request_id", "doc_url" } }`
9
+ * - legacy (older /v1 endpoints): `{ "error": "<code>", "message": "...", ...extra }`
10
+ * - Operator pass-through (Cases, Approvals): `{ "code": "<code>", "message": "...", "details": ... }`
11
+ *
12
+ * Branch on `code`, never on `message`.
13
+ */
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.FinnApprovalTimeoutError = exports.FinnTimeoutError = exports.FinnConnectionError = exports.FinnError = exports.FinnSdkError = exports.codeForStatus = void 0;
16
+ exports.parseRetryAfterSeconds = parseRetryAfterSeconds;
17
+ const CODE_FOR_STATUS = {
18
+ 400: 'invalid_request',
19
+ 401: 'unauthorized',
20
+ 403: 'forbidden',
21
+ 404: 'not_found',
22
+ 409: 'conflict',
23
+ 413: 'payload_too_large',
24
+ 422: 'invalid_request',
25
+ 429: 'rate_limited',
26
+ 500: 'internal_error',
27
+ 502: 'unavailable',
28
+ 503: 'unavailable',
29
+ 504: 'unavailable',
30
+ };
31
+ /** The code an error gets when the body does not name one (mirrors the backend's codeForStatus). */
32
+ const codeForStatus = (status) => CODE_FOR_STATUS[status] ?? (status >= 500 ? 'internal_error' : 'invalid_request');
33
+ exports.codeForStatus = codeForStatus;
34
+ /** Base class for every error the SDK throws. */
35
+ class FinnSdkError extends Error {
36
+ constructor(message, options) {
37
+ super(message);
38
+ this.name = 'FinnSdkError';
39
+ if (options && 'cause' in options)
40
+ this.cause = options.cause;
41
+ }
42
+ }
43
+ exports.FinnSdkError = FinnSdkError;
44
+ /** The API answered with a 4xx or 5xx status. */
45
+ class FinnError extends FinnSdkError {
46
+ constructor(init) {
47
+ super(init.message);
48
+ this.name = 'FinnError';
49
+ this.status = init.status;
50
+ this.code = init.code;
51
+ this.requestId = init.requestId ?? null;
52
+ this.fields = init.fields ?? [];
53
+ this.docUrl = init.docUrl ?? null;
54
+ this.actionUrl = init.actionUrl ?? null;
55
+ this.requiredScope = init.requiredScope ?? null;
56
+ this.retryAfter = init.retryAfter ?? null;
57
+ this.details = init.details ?? {};
58
+ this.body = init.body;
59
+ this.headers = init.headers ?? new Headers();
60
+ }
61
+ /** Builds a FinnError from a failed response and its already-read body. */
62
+ static fromResponse(status, headers, body, statusText = '') {
63
+ const headerRequestId = headers.get('x-request-id');
64
+ const retryAfter = parseRetryAfterSeconds(headers.get('retry-after'));
65
+ const base = { status, headers, body, retryAfter };
66
+ const obj = isRecord(body) ? body : null;
67
+ // Unified: { error: { code, message, fields, request_id, doc_url } }
68
+ if (obj && isRecord(obj.error)) {
69
+ const e = obj.error;
70
+ const { error: _e, ...rest } = obj;
71
+ return new FinnError({
72
+ ...base,
73
+ code: str(e.code) ?? (0, exports.codeForStatus)(status),
74
+ message: str(e.message) ?? defaultMessage(status, statusText),
75
+ requestId: str(e.request_id) ?? headerRequestId,
76
+ fields: Array.isArray(e.fields) ? e.fields.filter(isFieldError) : [],
77
+ docUrl: str(e.doc_url),
78
+ actionUrl: str(e.action_url) ?? str(obj.action_url),
79
+ requiredScope: str(e.required_scope) ?? str(obj.required_scope),
80
+ details: rest,
81
+ });
82
+ }
83
+ // Legacy: { error: "<code>", message, ...extra }
84
+ if (obj && typeof obj.error === 'string') {
85
+ const { error, message, action_url, required_scope, request_id, ...rest } = obj;
86
+ return new FinnError({
87
+ ...base,
88
+ code: error || (0, exports.codeForStatus)(status),
89
+ message: str(message) ?? defaultMessage(status, statusText),
90
+ requestId: str(request_id) ?? headerRequestId,
91
+ actionUrl: str(action_url),
92
+ requiredScope: str(required_scope),
93
+ details: rest,
94
+ });
95
+ }
96
+ // Operator pass-through: { code, message, details }
97
+ if (obj && typeof obj.code === 'string') {
98
+ const { code, message, request_id, ...rest } = obj;
99
+ return new FinnError({
100
+ ...base,
101
+ code: code,
102
+ message: str(message) ?? defaultMessage(status, statusText),
103
+ requestId: str(request_id) ?? headerRequestId,
104
+ details: rest,
105
+ });
106
+ }
107
+ return new FinnError({
108
+ ...base,
109
+ code: (0, exports.codeForStatus)(status),
110
+ message: typeof body === 'string' && body.trim() && body.length < 500 ? body.trim() : defaultMessage(status, statusText),
111
+ requestId: headerRequestId,
112
+ });
113
+ }
114
+ }
115
+ exports.FinnError = FinnError;
116
+ /** The request never got an HTTP answer (DNS, connection reset, CORS, ...). */
117
+ class FinnConnectionError extends FinnSdkError {
118
+ constructor(message = 'Could not reach the Finn API.', options) {
119
+ super(message, options);
120
+ this.name = 'FinnConnectionError';
121
+ }
122
+ }
123
+ exports.FinnConnectionError = FinnConnectionError;
124
+ /** The request took longer than `timeoutMs`. */
125
+ class FinnTimeoutError extends FinnConnectionError {
126
+ constructor(message = 'The request to the Finn API timed out.', options) {
127
+ super(message, options);
128
+ this.name = 'FinnTimeoutError';
129
+ }
130
+ }
131
+ exports.FinnTimeoutError = FinnTimeoutError;
132
+ /** waitForApproval gave up before the approval reached a final status. */
133
+ class FinnApprovalTimeoutError extends FinnSdkError {
134
+ constructor(approvalId, lastStatus) {
135
+ super(`Approval ${approvalId} was still ${lastStatus ?? 'unknown'} when waitForApproval timed out.`);
136
+ this.name = 'FinnApprovalTimeoutError';
137
+ this.approvalId = approvalId;
138
+ this.lastStatus = lastStatus;
139
+ }
140
+ }
141
+ exports.FinnApprovalTimeoutError = FinnApprovalTimeoutError;
142
+ /** Retry-After as seconds: accepts delta-seconds or an HTTP date. */
143
+ function parseRetryAfterSeconds(value, now = Date.now()) {
144
+ if (value == null || value.trim() === '')
145
+ return null;
146
+ const v = value.trim();
147
+ if (/^\d+(\.\d+)?$/.test(v))
148
+ return Number(v);
149
+ const date = Date.parse(v);
150
+ if (Number.isNaN(date))
151
+ return null;
152
+ return Math.max(0, (date - now) / 1000);
153
+ }
154
+ function defaultMessage(status, statusText) {
155
+ return `Finn API request failed with status ${status}${statusText ? ` ${statusText}` : ''}.`;
156
+ }
157
+ function isRecord(v) {
158
+ return typeof v === 'object' && v !== null && !Array.isArray(v);
159
+ }
160
+ function str(v) {
161
+ return typeof v === 'string' && v !== '' ? v : null;
162
+ }
163
+ function isFieldError(v) {
164
+ return isRecord(v) && typeof v.field === 'string';
165
+ }