@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,181 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.FinnWebhookVerificationError = exports.DEFAULT_WEBHOOK_TOLERANCE_SECONDS = exports.WEBHOOK_EVENT_HEADER = exports.WEBHOOK_SIGNATURE_HEADER = void 0;
37
+ exports.parseSignatureHeader = parseSignatureHeader;
38
+ exports.timingSafeEqual = timingSafeEqual;
39
+ exports.signWebhookPayload = signWebhookPayload;
40
+ exports.verifyWebhook = verifyWebhook;
41
+ const errors_js_1 = require("./errors.js");
42
+ /**
43
+ * Webhook signature checks.
44
+ *
45
+ * Finn signs every delivery with `X-Finn-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256(secret, "<t>.<raw body>")>`
46
+ * and names the event in `X-Finn-Event`. verifyWebhook() checks the signature in constant time and refuses
47
+ * deliveries whose timestamp is too far from now, so a captured request cannot be replayed later.
48
+ */
49
+ /** Header that carries the signature. */
50
+ exports.WEBHOOK_SIGNATURE_HEADER = 'X-Finn-Signature';
51
+ /** Header that carries the event name. */
52
+ exports.WEBHOOK_EVENT_HEADER = 'X-Finn-Event';
53
+ /** Default largest gap, in seconds, between the signed timestamp and now. */
54
+ exports.DEFAULT_WEBHOOK_TOLERANCE_SECONDS = 300;
55
+ /** The delivery's signature is missing, malformed, wrong or too old. Answer the request with a 400. */
56
+ class FinnWebhookVerificationError extends errors_js_1.FinnSdkError {
57
+ constructor(message) {
58
+ super(message);
59
+ this.name = 'FinnWebhookVerificationError';
60
+ }
61
+ }
62
+ exports.FinnWebhookVerificationError = FinnWebhookVerificationError;
63
+ /** Splits `t=...,v1=...` into its timestamp and v1 signatures. */
64
+ function parseSignatureHeader(header) {
65
+ let timestamp = NaN;
66
+ const signatures = [];
67
+ for (const part of header.split(',')) {
68
+ const i = part.indexOf('=');
69
+ if (i <= 0)
70
+ continue;
71
+ const k = part.slice(0, i).trim();
72
+ const v = part.slice(i + 1).trim();
73
+ if (k === 't' && /^\d+$/.test(v))
74
+ timestamp = Number(v);
75
+ else if (k === 'v1' && v)
76
+ signatures.push(v.toLowerCase());
77
+ }
78
+ return { timestamp, signatures };
79
+ }
80
+ function readHeader(headers) {
81
+ if (!headers)
82
+ return null;
83
+ if (typeof headers.get === 'function')
84
+ return headers.get(exports.WEBHOOK_SIGNATURE_HEADER);
85
+ const want = exports.WEBHOOK_SIGNATURE_HEADER.toLowerCase();
86
+ for (const [k, v] of Object.entries(headers)) {
87
+ if (k.toLowerCase() === want)
88
+ return Array.isArray(v) ? (v[0] ?? null) : (v ?? null);
89
+ }
90
+ return null;
91
+ }
92
+ async function subtleCrypto() {
93
+ const c = globalThis.crypto;
94
+ if (c?.subtle)
95
+ return c.subtle;
96
+ // Node 18 without the global: fall back to node:crypto. The specifier is a variable so bundlers leave it alone.
97
+ const name = 'node:crypto';
98
+ const mod = (await Promise.resolve(`${name}`).then(s => __importStar(require(s))));
99
+ return mod.webcrypto.subtle;
100
+ }
101
+ const encoder = new TextEncoder();
102
+ function hexToBytes(hex) {
103
+ if (hex.length === 0 || hex.length % 2 !== 0 || !/^[0-9a-f]+$/.test(hex))
104
+ return null;
105
+ const out = new Uint8Array(hex.length / 2);
106
+ for (let i = 0; i < out.length; i += 1)
107
+ out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
108
+ return out;
109
+ }
110
+ /** Compares two byte arrays in time that depends only on their length. */
111
+ function timingSafeEqual(a, b) {
112
+ if (a.length !== b.length)
113
+ return false;
114
+ let diff = 0;
115
+ for (let i = 0; i < a.length; i += 1)
116
+ diff |= a[i] ^ b[i];
117
+ return diff === 0;
118
+ }
119
+ /** Hex HMAC-SHA256 of `<timestamp>.<payload>`, the way Finn signs deliveries. */
120
+ async function signWebhookPayload(secret, timestamp, payload) {
121
+ const mac = await hmac(secret, timestamp, payload);
122
+ return Array.from(mac, (b) => b.toString(16).padStart(2, '0')).join('');
123
+ }
124
+ async function hmac(secret, timestamp, payload) {
125
+ const subtle = await subtleCrypto();
126
+ const key = await subtle.importKey('raw', encoder.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
127
+ const body = typeof payload === 'string' ? encoder.encode(payload) : payload;
128
+ const prefix = encoder.encode(`${timestamp}.`);
129
+ const data = new Uint8Array(prefix.length + body.length);
130
+ data.set(prefix, 0);
131
+ data.set(body, prefix.length);
132
+ return new Uint8Array(await subtle.sign('HMAC', key, data));
133
+ }
134
+ /**
135
+ * Checks a webhook delivery and returns its parsed body. Throws FinnWebhookVerificationError when the signature is
136
+ * missing, malformed or wrong, or the timestamp is more than `toleranceSeconds` (default 300) away from now.
137
+ *
138
+ * app.post('/finn-webhook', express.raw({ type: 'application/json' }), async (req, res) => {
139
+ * const event = await verifyWebhook({ payload: req.body, headers: req.headers, secret: process.env.FINN_WEBHOOK_SECRET! });
140
+ * ...
141
+ * });
142
+ */
143
+ async function verifyWebhook(options) {
144
+ const { payload } = options;
145
+ if (typeof payload !== 'string' && !(payload instanceof Uint8Array)) {
146
+ throw new FinnWebhookVerificationError('payload must be the raw request body (a string or bytes), not parsed JSON: re-serialising changes the bytes that were signed.');
147
+ }
148
+ const secrets = (typeof options.secret === 'string' ? [options.secret] : [...options.secret]).filter((s) => !!s);
149
+ if (secrets.length === 0)
150
+ throw new FinnWebhookVerificationError('Missing webhook signing secret.');
151
+ const header = options.header ?? readHeader(options.headers);
152
+ if (!header)
153
+ throw new FinnWebhookVerificationError(`Missing ${exports.WEBHOOK_SIGNATURE_HEADER} header.`);
154
+ const { timestamp, signatures } = parseSignatureHeader(header);
155
+ if (!Number.isFinite(timestamp) || signatures.length === 0) {
156
+ throw new FinnWebhookVerificationError(`Malformed ${exports.WEBHOOK_SIGNATURE_HEADER} header: expected t=<unix>,v1=<hex>.`);
157
+ }
158
+ const tolerance = options.toleranceSeconds ?? exports.DEFAULT_WEBHOOK_TOLERANCE_SECONDS;
159
+ const now = options.now ?? Math.floor(Date.now() / 1000);
160
+ if (Math.abs(now - timestamp) > tolerance) {
161
+ throw new FinnWebhookVerificationError('Webhook timestamp is outside the tolerance window.');
162
+ }
163
+ const given = signatures.map(hexToBytes).filter((b) => b !== null);
164
+ let ok = false;
165
+ for (const secret of secrets) {
166
+ const expected = await hmac(secret, timestamp, payload);
167
+ // Check every pair, so the time taken does not reveal which one matched.
168
+ for (const sig of given)
169
+ if (timingSafeEqual(expected, sig))
170
+ ok = true;
171
+ }
172
+ if (!ok)
173
+ throw new FinnWebhookVerificationError('Webhook signature does not match.');
174
+ const text = typeof payload === 'string' ? payload : new TextDecoder().decode(payload);
175
+ try {
176
+ return JSON.parse(text);
177
+ }
178
+ catch {
179
+ throw new FinnWebhookVerificationError('Webhook body is not valid JSON.');
180
+ }
181
+ }
@@ -0,0 +1,12 @@
1
+ import type { PendingApproval } from './types.js';
2
+ /**
3
+ * True when a write was held for a person to approve (HTTP 202 `{ status: 'pending_approval', approval_id, ... }`).
4
+ * Outward and spending actions from OAuth and MCP callers can answer this instead of doing the work.
5
+ *
6
+ * const res = await finn.calls.create({ ... });
7
+ * if (isPendingApproval(res)) {
8
+ * console.log('Approve at', res.approve_url);
9
+ * const outcome = await finn.waitForApproval(res.approval_id);
10
+ * }
11
+ */
12
+ export declare function isPendingApproval(value: unknown): value is PendingApproval;
@@ -0,0 +1,16 @@
1
+ /**
2
+ * True when a write was held for a person to approve (HTTP 202 `{ status: 'pending_approval', approval_id, ... }`).
3
+ * Outward and spending actions from OAuth and MCP callers can answer this instead of doing the work.
4
+ *
5
+ * const res = await finn.calls.create({ ... });
6
+ * if (isPendingApproval(res)) {
7
+ * console.log('Approve at', res.approve_url);
8
+ * const outcome = await finn.waitForApproval(res.approval_id);
9
+ * }
10
+ */
11
+ export function isPendingApproval(value) {
12
+ if (typeof value !== 'object' || value === null)
13
+ return false;
14
+ const v = value;
15
+ return v.status === 'pending_approval' && typeof v.approval_id === 'string';
16
+ }
@@ -0,0 +1,30 @@
1
+ import { FinnCore, type FinnOptions } from './core.js';
2
+ import { Agents, Approvals, Audiences, Calls, Cases, Chat, Contacts, Deployments, DoNotCall, Finns, PhoneNumbers, Voices, Wallet, type WaitForApprovalOptions } from './resources.js';
3
+ import type { ApprovalHold, Schemas } from './types.js';
4
+ /**
5
+ * The Finn API client.
6
+ *
7
+ * import { Finn } from '@hirefinn/sdk';
8
+ * const finn = new Finn({ apiKey: process.env.FINN_API_KEY });
9
+ * const { data } = await finn.calls.list({ limit: 10 });
10
+ */
11
+ export declare class Finn extends FinnCore {
12
+ readonly calls: Calls;
13
+ readonly finns: Finns;
14
+ readonly voices: Voices;
15
+ readonly phoneNumbers: PhoneNumbers;
16
+ readonly audiences: Audiences;
17
+ /** Campaigns: outbound and inbound deployments of a Finn. */
18
+ readonly deployments: Deployments;
19
+ readonly wallet: Wallet;
20
+ readonly doNotCall: DoNotCall;
21
+ /** CRM records (contacts and other record kinds). */
22
+ readonly contacts: Contacts;
23
+ readonly cases: Cases;
24
+ readonly approvals: Approvals;
25
+ readonly agents: Agents;
26
+ readonly chat: Chat;
27
+ constructor(options?: FinnOptions);
28
+ /** Polls an approval until it is decided (see approvals.wait). */
29
+ waitForApproval(id: string, options?: WaitForApprovalOptions): Promise<ApprovalHold | Schemas['Approval']>;
30
+ }
@@ -0,0 +1,31 @@
1
+ import { FinnCore } from './core.js';
2
+ import { Agents, Approvals, Audiences, Calls, Cases, Chat, Contacts, Deployments, DoNotCall, Finns, PhoneNumbers, Voices, Wallet, } from './resources.js';
3
+ /**
4
+ * The Finn API client.
5
+ *
6
+ * import { Finn } from '@hirefinn/sdk';
7
+ * const finn = new Finn({ apiKey: process.env.FINN_API_KEY });
8
+ * const { data } = await finn.calls.list({ limit: 10 });
9
+ */
10
+ export class Finn extends FinnCore {
11
+ constructor(options = {}) {
12
+ super(options);
13
+ this.calls = new Calls(this);
14
+ this.finns = new Finns(this);
15
+ this.voices = new Voices(this);
16
+ this.phoneNumbers = new PhoneNumbers(this);
17
+ this.audiences = new Audiences(this);
18
+ this.deployments = new Deployments(this);
19
+ this.wallet = new Wallet(this);
20
+ this.doNotCall = new DoNotCall(this);
21
+ this.contacts = new Contacts(this);
22
+ this.cases = new Cases(this);
23
+ this.approvals = new Approvals(this);
24
+ this.agents = new Agents(this);
25
+ this.chat = new Chat(this);
26
+ }
27
+ /** Polls an approval until it is decided (see approvals.wait). */
28
+ waitForApproval(id, options) {
29
+ return this.approvals.wait(id, options);
30
+ }
31
+ }
@@ -0,0 +1,81 @@
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.2.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
+ /**
14
+ * Retries after the first attempt, on network errors, 408, 429, 502, 503 and 504. Only GET/HEAD/OPTIONS/PUT/DELETE
15
+ * are retried freely; a POST or PATCH is retried only when it carries an Idempotency-Key and its route dedupes by
16
+ * that key (IDEMPOTENT_WRITE_ROUTES). Default 2.
17
+ */
18
+ maxRetries?: number;
19
+ /** Timeout per attempt in milliseconds. Default 60000. */
20
+ timeoutMs?: number;
21
+ /** A fetch implementation. Defaults to the global fetch (Node 18+, browsers). */
22
+ fetch?: typeof fetch;
23
+ /**
24
+ * Send a generated Idempotency-Key on spending and outward writes (place a call, rent a number, deploy, start or
25
+ * send a chat, create an agent, start a case) when the caller did not pass one, so they can be retried safely.
26
+ * Default true.
27
+ */
28
+ autoIdempotency?: boolean;
29
+ /** Longest Retry-After the SDK will wait out; a longer one throws instead. Default 60000 ms. */
30
+ maxRetryAfterMs?: number;
31
+ /** Headers sent on every request. */
32
+ defaultHeaders?: Record<string, string>;
33
+ /** Replaces the wait between retries (for tests). */
34
+ sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
35
+ }
36
+ /** Writes that get an automatic Idempotency-Key (when autoIdempotency is on). */
37
+ export declare const AUTO_IDEMPOTENCY_ROUTES: ReadonlySet<string>;
38
+ /**
39
+ * POST/PATCH routes where the API dedupes by Idempotency-Key (a retry with the same key and body replays the first
40
+ * answer). Only these writes are retried, and only when they carry a key: other routes ignore the header, so a retry
41
+ * after a timeout could create a second resource. `*` matches the rest of the path.
42
+ */
43
+ export declare const IDEMPOTENT_WRITE_ROUTES: readonly string[];
44
+ /** True when the API dedupes this write by Idempotency-Key. `path` may be a template or a filled-in path. */
45
+ export declare function honoursIdempotencyKey(method: string, path: string): boolean;
46
+ /** A new random Idempotency-Key (a UUID v4). */
47
+ export declare function idempotencyKey(): string;
48
+ /** Untyped request input, for paths the spec does not have yet. */
49
+ export interface RawRequest {
50
+ method: HttpMethod | Uppercase<HttpMethod>;
51
+ /** Path below the base URL, e.g. `/calls/{call_uuid}` or `/calls/abc`. */
52
+ path: string;
53
+ /** Values for `{name}` placeholders in `path`. */
54
+ pathParams?: Record<string, string | number>;
55
+ query?: Record<string, unknown>;
56
+ body?: unknown;
57
+ }
58
+ export declare class FinnCore {
59
+ #private;
60
+ readonly baseUrl: string;
61
+ readonly org: string | undefined;
62
+ readonly version: string | undefined;
63
+ readonly maxRetries: number;
64
+ readonly timeoutMs: number;
65
+ readonly autoIdempotency: boolean;
66
+ readonly maxRetryAfterMs: number;
67
+ constructor(options?: FinnOptions);
68
+ /**
69
+ * Calls any operation in the spec, fully typed.
70
+ *
71
+ * const call = await finn.request('get', '/calls/{call_uuid}', { path: { call_uuid } });
72
+ */
73
+ request<M extends HttpMethod, P extends PathsFor<M>>(method: M, path: P, ...args: RequestArgs<Operation<P, M>>): Promise<ResultOf<P, M, Operation<P, M>>>;
74
+ /** Same as request(), plus status, headers and request id. */
75
+ 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>>>>;
76
+ /** Untyped escape hatch for endpoints newer than this SDK's spec. */
77
+ rawRequest<T = unknown>(req: RawRequest, options?: RequestOptions): Promise<FinnResponse<T>>;
78
+ /** Builds the full URL: base + path with `{name}` filled in + query string. */
79
+ buildUrl(path: string, pathParams?: Record<string, string | number>, query?: Record<string, unknown>): string;
80
+ private fetchOnce;
81
+ }
@@ -0,0 +1,294 @@
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.2.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
+ /**
28
+ * POST/PATCH routes where the API dedupes by Idempotency-Key (a retry with the same key and body replays the first
29
+ * answer). Only these writes are retried, and only when they carry a key: other routes ignore the header, so a retry
30
+ * after a timeout could create a second resource. `*` matches the rest of the path.
31
+ */
32
+ export const IDEMPOTENT_WRITE_ROUTES = [
33
+ 'post /calls',
34
+ 'post /phone_numbers',
35
+ 'post /deployments',
36
+ 'post /deployments/inbound',
37
+ 'post /chat/conversations',
38
+ 'post /chat/conversations/{id}/messages',
39
+ 'post /agents',
40
+ 'post /agents/{id}/cases',
41
+ 'post /crm/*',
42
+ 'patch /crm/*',
43
+ 'post /sales/plays/{slug}/run',
44
+ 'post /sales/drafts/{id}/skip',
45
+ ];
46
+ const IDEMPOTENT_WRITE_MATCHERS = IDEMPOTENT_WRITE_ROUTES.map((route) => {
47
+ const [method, path] = route.split(' ');
48
+ const body = path
49
+ .split('/')
50
+ .map((seg) => (seg === '*' ? '.+' : /^\{[^}]+\}$/.test(seg) ? '[^/]+' : seg.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')))
51
+ .join('/');
52
+ return { method: method.toUpperCase(), re: new RegExp(`^${body}/?$`) };
53
+ });
54
+ /** True when the API dedupes this write by Idempotency-Key. `path` may be a template or a filled-in path. */
55
+ export function honoursIdempotencyKey(method, path) {
56
+ const m = method.toUpperCase();
57
+ const p = path.split('?')[0];
58
+ return IDEMPOTENT_WRITE_MATCHERS.some((x) => x.method === m && x.re.test(p));
59
+ }
60
+ const SAFE_TO_RETRY_METHODS = new Set(['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE']);
61
+ const RETRY_BASE_DELAY_MS = 500;
62
+ const RETRY_MAX_DELAY_MS = 8000;
63
+ /** A new random Idempotency-Key (a UUID v4). */
64
+ export function idempotencyKey() {
65
+ const c = globalThis.crypto;
66
+ if (c && typeof c.randomUUID === 'function')
67
+ return c.randomUUID();
68
+ const bytes = new Uint8Array(16);
69
+ if (c && typeof c.getRandomValues === 'function')
70
+ c.getRandomValues(bytes);
71
+ else
72
+ for (let i = 0; i < 16; i += 1)
73
+ bytes[i] = Math.floor(Math.random() * 256);
74
+ bytes[6] = (bytes[6] & 0x0f) | 0x40;
75
+ bytes[8] = (bytes[8] & 0x3f) | 0x80;
76
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
77
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
78
+ }
79
+ function defaultSleep(ms, signal) {
80
+ return new Promise((resolve, reject) => {
81
+ if (signal?.aborted)
82
+ return reject(signal.reason ?? new Error('Aborted'));
83
+ const timer = setTimeout(() => {
84
+ signal?.removeEventListener('abort', onAbort);
85
+ resolve();
86
+ }, ms);
87
+ const onAbort = () => {
88
+ clearTimeout(timer);
89
+ reject(signal?.reason ?? new Error('Aborted'));
90
+ };
91
+ signal?.addEventListener('abort', onAbort, { once: true });
92
+ });
93
+ }
94
+ function readEnvKey() {
95
+ const proc = globalThis.process;
96
+ return proc?.env?.FINN_API_KEY;
97
+ }
98
+ export class FinnCore {
99
+ constructor(options = {}) {
100
+ _FinnCore_apiKey.set(this, void 0);
101
+ _FinnCore_fetch.set(this, void 0);
102
+ _FinnCore_defaultHeaders.set(this, void 0);
103
+ _FinnCore_sleep.set(this, void 0);
104
+ const apiKey = options.apiKey ?? readEnvKey();
105
+ if (!apiKey) {
106
+ throw new FinnSdkError('Missing API key: pass { apiKey } to new Finn() or set FINN_API_KEY.');
107
+ }
108
+ const f = options.fetch ?? globalThis.fetch;
109
+ if (typeof f !== 'function') {
110
+ throw new FinnSdkError('No fetch available: use Node 18+ or pass { fetch } to new Finn().');
111
+ }
112
+ __classPrivateFieldSet(this, _FinnCore_apiKey, apiKey, "f");
113
+ __classPrivateFieldSet(this, _FinnCore_fetch, f, "f");
114
+ this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, '');
115
+ this.org = options.org;
116
+ this.version = options.version;
117
+ this.maxRetries = options.maxRetries ?? 2;
118
+ this.timeoutMs = options.timeoutMs ?? 60000;
119
+ this.autoIdempotency = options.autoIdempotency ?? true;
120
+ this.maxRetryAfterMs = options.maxRetryAfterMs ?? 60000;
121
+ __classPrivateFieldSet(this, _FinnCore_defaultHeaders, { ...(options.defaultHeaders ?? {}) }, "f");
122
+ __classPrivateFieldSet(this, _FinnCore_sleep, options.sleep ?? defaultSleep, "f");
123
+ }
124
+ /**
125
+ * Calls any operation in the spec, fully typed.
126
+ *
127
+ * const call = await finn.request('get', '/calls/{call_uuid}', { path: { call_uuid } });
128
+ */
129
+ async request(method, path, ...args) {
130
+ const res = await this.requestWithResponse(method, path, ...args);
131
+ return res.data;
132
+ }
133
+ /** Same as request(), plus status, headers and request id. */
134
+ async requestWithResponse(method, path, ...args) {
135
+ const [params, options] = args;
136
+ return this.rawRequest({ method, path: path, pathParams: params?.path, query: params?.query, body: params?.body }, options);
137
+ }
138
+ /** Untyped escape hatch for endpoints newer than this SDK's spec. */
139
+ async rawRequest(req, options = {}) {
140
+ const method = req.method.toUpperCase();
141
+ const routeKey = `${method.toLowerCase()} ${req.path}`;
142
+ const url = this.buildUrl(req.path, req.pathParams, req.query);
143
+ let key;
144
+ if (typeof options.idempotencyKey === 'string')
145
+ key = options.idempotencyKey;
146
+ else if (options.idempotencyKey !== false && this.autoIdempotency && AUTO_IDEMPOTENCY_ROUTES.has(routeKey)) {
147
+ key = idempotencyKey();
148
+ }
149
+ const headers = new Headers();
150
+ headers.set('Accept', 'application/json');
151
+ for (const [k, v] of Object.entries(__classPrivateFieldGet(this, _FinnCore_defaultHeaders, "f")))
152
+ headers.set(k, v);
153
+ const org = options.org ?? this.org;
154
+ if (org)
155
+ headers.set('Finn-Org', org);
156
+ const version = options.version ?? this.version;
157
+ if (version)
158
+ headers.set('Finn-Version', version);
159
+ if (key)
160
+ headers.set('Idempotency-Key', key);
161
+ let body;
162
+ if (req.body !== undefined && req.body !== null) {
163
+ if (typeof FormData !== 'undefined' && req.body instanceof FormData)
164
+ body = req.body;
165
+ else {
166
+ headers.set('Content-Type', 'application/json');
167
+ body = JSON.stringify(req.body);
168
+ }
169
+ }
170
+ for (const [k, v] of Object.entries(options.headers ?? {}))
171
+ headers.set(k, v);
172
+ headers.set('Authorization', `Bearer ${__classPrivateFieldGet(this, _FinnCore_apiKey, "f")}`);
173
+ // Idempotent methods always; a POST/PATCH only with a key on a route that dedupes by it.
174
+ const canRetry = SAFE_TO_RETRY_METHODS.has(method) || (headers.has('Idempotency-Key') && honoursIdempotencyKey(method, req.path));
175
+ const maxRetries = canRetry ? Math.max(0, options.maxRetries ?? this.maxRetries) : 0;
176
+ const timeoutMs = options.timeoutMs ?? this.timeoutMs;
177
+ for (let attempt = 0;; attempt += 1) {
178
+ let response;
179
+ try {
180
+ response = await this.fetchOnce(url, { method, headers, body }, timeoutMs, options.signal);
181
+ }
182
+ catch (err) {
183
+ if (options.signal?.aborted)
184
+ throw err;
185
+ const wrapped = err instanceof FinnTimeoutError
186
+ ? err
187
+ : new FinnConnectionError(`Could not reach the Finn API: ${err?.message ?? err}`, { cause: err });
188
+ if (attempt < maxRetries) {
189
+ await __classPrivateFieldGet(this, _FinnCore_sleep, "f").call(this, backoffMs(attempt), options.signal);
190
+ continue;
191
+ }
192
+ throw wrapped;
193
+ }
194
+ const parsed = await readBody(response);
195
+ if (response.ok) {
196
+ return {
197
+ data: parsed,
198
+ status: response.status,
199
+ headers: response.headers,
200
+ requestId: response.headers.get('x-request-id'),
201
+ idempotentReplayed: response.headers.get('idempotent-replayed') === 'true',
202
+ };
203
+ }
204
+ const error = FinnError.fromResponse(response.status, response.headers, parsed, response.statusText);
205
+ if (attempt < maxRetries && isRetryable(error)) {
206
+ const wait = error.retryAfter != null ? error.retryAfter * 1000 : backoffMs(attempt);
207
+ if (wait > this.maxRetryAfterMs)
208
+ throw error;
209
+ await __classPrivateFieldGet(this, _FinnCore_sleep, "f").call(this, wait, options.signal);
210
+ continue;
211
+ }
212
+ throw error;
213
+ }
214
+ }
215
+ /** Builds the full URL: base + path with `{name}` filled in + query string. */
216
+ buildUrl(path, pathParams, query) {
217
+ const filled = path.replace(/\{([^}]+)\}/g, (_, name) => {
218
+ const value = pathParams?.[name];
219
+ if (value === undefined || value === null || value === '') {
220
+ throw new FinnSdkError(`Missing path parameter "${name}" for ${path}`);
221
+ }
222
+ return encodeURIComponent(String(value));
223
+ });
224
+ const qs = new URLSearchParams();
225
+ for (const [k, v] of Object.entries(query ?? {})) {
226
+ if (v === undefined || v === null)
227
+ continue;
228
+ if (Array.isArray(v))
229
+ qs.set(k, v.map(String).join(','));
230
+ else if (v instanceof Date)
231
+ qs.set(k, v.toISOString());
232
+ else
233
+ qs.set(k, String(v));
234
+ }
235
+ const s = qs.toString();
236
+ return `${this.baseUrl}${filled.startsWith('/') ? '' : '/'}${filled}${s ? `?${s}` : ''}`;
237
+ }
238
+ async fetchOnce(url, init, timeoutMs, signal) {
239
+ const controller = new AbortController();
240
+ let timedOut = false;
241
+ const onAbort = () => controller.abort(signal?.reason);
242
+ if (signal?.aborted)
243
+ throw signal.reason ?? new Error('Aborted');
244
+ signal?.addEventListener('abort', onAbort, { once: true });
245
+ const timer = timeoutMs > 0 && Number.isFinite(timeoutMs)
246
+ ? setTimeout(() => {
247
+ timedOut = true;
248
+ controller.abort();
249
+ }, timeoutMs)
250
+ : undefined;
251
+ try {
252
+ return await __classPrivateFieldGet(this, _FinnCore_fetch, "f").call(this, url, { ...init, signal: controller.signal });
253
+ }
254
+ catch (err) {
255
+ if (timedOut)
256
+ throw new FinnTimeoutError(`The request timed out after ${timeoutMs} ms.`, { cause: err });
257
+ throw err;
258
+ }
259
+ finally {
260
+ if (timer)
261
+ clearTimeout(timer);
262
+ signal?.removeEventListener('abort', onAbort);
263
+ }
264
+ }
265
+ }
266
+ _FinnCore_apiKey = new WeakMap(), _FinnCore_fetch = new WeakMap(), _FinnCore_defaultHeaders = new WeakMap(), _FinnCore_sleep = new WeakMap();
267
+ function isRetryable(error) {
268
+ if (error.status === 408 || error.status === 429)
269
+ return true;
270
+ if (error.status === 409)
271
+ return error.code === 'idempotency_in_progress';
272
+ return error.status === 502 || error.status === 503 || error.status === 504;
273
+ }
274
+ function backoffMs(attempt) {
275
+ const base = Math.min(RETRY_MAX_DELAY_MS, RETRY_BASE_DELAY_MS * 2 ** attempt);
276
+ return Math.round(base * (1 - Math.random() * 0.25));
277
+ }
278
+ async function readBody(response) {
279
+ if (response.status === 204 || response.status === 205)
280
+ return undefined;
281
+ const text = await response.text();
282
+ if (text === '')
283
+ return undefined;
284
+ const type = response.headers.get('content-type') ?? '';
285
+ if (type.includes('json') || /^[[{]/.test(text.trimStart())) {
286
+ try {
287
+ return JSON.parse(text);
288
+ }
289
+ catch {
290
+ return text;
291
+ }
292
+ }
293
+ return text;
294
+ }