@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.
- package/LICENSE +21 -0
- package/README.md +177 -2
- package/dist/cjs/approval.d.ts +12 -0
- package/dist/cjs/approval.js +19 -0
- package/dist/cjs/client.d.ts +30 -0
- package/dist/cjs/client.js +35 -0
- package/dist/cjs/core.d.ts +69 -0
- package/dist/cjs/core.js +265 -0
- package/dist/cjs/errors.d.ts +90 -0
- package/dist/cjs/errors.js +165 -0
- package/dist/cjs/generated/openapi.d.ts +10729 -0
- package/dist/cjs/generated/openapi.js +2 -0
- package/dist/cjs/index.d.ts +11 -0
- package/dist/cjs/index.js +44 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/pagination.d.ts +36 -0
- package/dist/cjs/pagination.js +124 -0
- package/dist/cjs/resources.d.ts +845 -0
- package/dist/cjs/resources.js +395 -0
- package/dist/cjs/types.d.ts +144 -0
- package/dist/cjs/types.js +2 -0
- package/dist/esm/approval.d.ts +12 -0
- package/dist/esm/approval.js +16 -0
- package/dist/esm/client.d.ts +30 -0
- package/dist/esm/client.js +31 -0
- package/dist/esm/core.d.ts +69 -0
- package/dist/esm/core.js +260 -0
- package/dist/esm/errors.d.ts +90 -0
- package/dist/esm/errors.js +155 -0
- package/dist/esm/generated/openapi.d.ts +10729 -0
- package/dist/esm/generated/openapi.js +1 -0
- package/dist/esm/index.d.ts +11 -0
- package/dist/esm/index.js +7 -0
- package/dist/esm/package.json +1 -0
- package/dist/esm/pagination.d.ts +36 -0
- package/dist/esm/pagination.js +116 -0
- package/dist/esm/resources.d.ts +845 -0
- package/dist/esm/resources.js +377 -0
- package/dist/esm/types.d.ts +144 -0
- package/dist/esm/types.js +1 -0
- package/package.json +51 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Finn (hirefinn.ai)
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,178 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Finn TypeScript SDK
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Typed client for the [Finn](https://hirefinn.ai) public API (`https://api.hirefinn.ai/v1`).
|
|
4
|
+
Types are generated from the API's OpenAPI spec; the client is a thin hand-written layer over `fetch` with
|
|
5
|
+
retries, idempotency keys, typed errors, pagination and approval helpers. No runtime dependencies.
|
|
6
|
+
|
|
7
|
+
- Node 18+ and modern browsers (anything with `fetch`)
|
|
8
|
+
- ESM and CommonJS, with `.d.ts` types
|
|
9
|
+
|
|
10
|
+
> Status: pre-release (0.1.0). MIT licensed (see `LICENSE`).
|
|
11
|
+
|
|
12
|
+
## Install
|
|
13
|
+
|
|
14
|
+
```sh
|
|
15
|
+
npm install @hirefinn/sdk
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## Quickstart
|
|
19
|
+
|
|
20
|
+
```ts
|
|
21
|
+
import { Finn, isPendingApproval, FinnError } from '@hirefinn/sdk';
|
|
22
|
+
|
|
23
|
+
const finn = new Finn({ apiKey: process.env.FINN_API_KEY }); // finn_live_..., finn_test_... or an OAuth finn_oat_... token
|
|
24
|
+
|
|
25
|
+
// List, retrieve
|
|
26
|
+
const { data: finns } = await finn.finns.list({ limit: 20 });
|
|
27
|
+
const call = await finn.calls.retrieve('b7e3c9a2-4d1f-4e8b-9a6c-2f5d8e1b3c70');
|
|
28
|
+
|
|
29
|
+
// Place a call (gets an automatic Idempotency-Key, so it is safe to retry)
|
|
30
|
+
const res = await finn.calls.create({ finn_id: finns[0]!.id, to_number: '4155550142', country_code: '1' });
|
|
31
|
+
if (isPendingApproval(res)) {
|
|
32
|
+
// OAuth / MCP callers: outward and spending actions may wait for a person to approve them (HTTP 202)
|
|
33
|
+
console.log('Approve it here:', res.approve_url);
|
|
34
|
+
const outcome = await finn.waitForApproval(res.approval_id); // polls GET /approvals/{id}
|
|
35
|
+
console.log(outcome.status); // succeeded | failed | declined | expired
|
|
36
|
+
} else {
|
|
37
|
+
console.log('Dialing', res.data.call_uuid);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// Every page, lazily
|
|
41
|
+
for await (const c of finn.calls.listAll({ status: 'completed' })) {
|
|
42
|
+
console.log(c.call_uuid);
|
|
43
|
+
}
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
## Client options
|
|
47
|
+
|
|
48
|
+
```ts
|
|
49
|
+
new Finn({
|
|
50
|
+
apiKey, // default: process.env.FINN_API_KEY
|
|
51
|
+
baseUrl, // default: https://api.hirefinn.ai/v1
|
|
52
|
+
org, // Finn-Org header: which org a multi-org token acts in
|
|
53
|
+
version, // Finn-Version header: pins the API version, e.g. '2026-11-01'
|
|
54
|
+
maxRetries: 2, // retries after the first attempt
|
|
55
|
+
timeoutMs: 60_000, // per attempt
|
|
56
|
+
fetch, // custom fetch (tests, proxies, older runtimes)
|
|
57
|
+
autoIdempotency: true,
|
|
58
|
+
maxRetryAfterMs: 60_000,
|
|
59
|
+
defaultHeaders: {},
|
|
60
|
+
});
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Every method also takes a last `options` argument that overrides these per call:
|
|
64
|
+
`{ idempotencyKey, org, version, maxRetries, timeoutMs, signal, headers }`.
|
|
65
|
+
|
|
66
|
+
## Resources
|
|
67
|
+
|
|
68
|
+
| Property | Endpoints |
|
|
69
|
+
|---|---|
|
|
70
|
+
| `finn.calls` | `create`, `list`, `listAll`, `retrieve` |
|
|
71
|
+
| `finn.finns` | `list`, `listAll`, `create`, `retrieve`, `update`, `delete`, `listKnowledgeBase`, `addKnowledgeBaseDocument`, `postCallAnalysis` |
|
|
72
|
+
| `finn.voices` | `list`, `listAll`, `retrieve` |
|
|
73
|
+
| `finn.phoneNumbers` | `list`, `listAll`, `searchAvailable`, `rent`, `retrieve`, `release` |
|
|
74
|
+
| `finn.audiences` | `list`, `listAll`, `create`, `retrieve`, `archive`, `listContacts`, `listAllContacts`, `addContacts`, `removeContact` |
|
|
75
|
+
| `finn.deployments` (campaigns) | `list`, `listAll`, `createOutbound`, `createInbound`, `retrieve`, `stop`, `stopInbound`, `analytics` |
|
|
76
|
+
| `finn.wallet` | `retrieve`, `listTransactions`, `listAllTransactions` |
|
|
77
|
+
| `finn.doNotCall` | `list`, `listAll`, `add`, `remove` |
|
|
78
|
+
| `finn.contacts` (CRM records) | `list`, `listAll`, `create`, `retrieve`, `update`, `timeline`, `timelineAll`, `addNote`, `listKinds`, `listFields` |
|
|
79
|
+
| `finn.cases` | `list`, `listAll`, `retrieve`, `listEvents`, `start` |
|
|
80
|
+
| `finn.approvals` | `list`, `listAll`, `retrieve`, `decide`, `approve`, `reject`, `wait` |
|
|
81
|
+
| `finn.agents` | `list`, `listAll`, `create`, `draft`, `retrieve`, `saveDraft`, `validate`, `test`, `publish`, `driveTest` |
|
|
82
|
+
| `finn.chat` | `listChannels`; `conversations.{list, listAll, start, retrieve, listMessages, listAllMessages, send}`; `contacts.{list, listAll, retrieve, update}` |
|
|
83
|
+
|
|
84
|
+
Methods return the response body exactly as the spec describes it (older voice endpoints wrap it in
|
|
85
|
+
`{ success, data }`). Request and response types come from `src/generated/openapi.ts`; schemas are exported as
|
|
86
|
+
`Schemas`, e.g. `Schemas['Call']`.
|
|
87
|
+
|
|
88
|
+
Anything in the spec is also reachable through the typed generic call:
|
|
89
|
+
|
|
90
|
+
```ts
|
|
91
|
+
const res = await finn.request('get', '/calls/{call_uuid}', { path: { call_uuid } });
|
|
92
|
+
const full = await finn.requestWithResponse('get', '/wallet'); // { data, status, headers, requestId, idempotentReplayed }
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
and endpoints newer than the SDK through `finn.rawRequest({ method, path, pathParams, query, body })`.
|
|
96
|
+
|
|
97
|
+
## Retries
|
|
98
|
+
|
|
99
|
+
Network errors, `408`, `429`, `500`, `502`, `503`, `504` and `409 idempotency_in_progress` are retried up to
|
|
100
|
+
`maxRetries` times, with exponential backoff (0.5 s, 1 s, 2 s ... up to 8 s, with jitter). A `Retry-After` header
|
|
101
|
+
is honoured; one longer than `maxRetryAfterMs` throws instead of waiting.
|
|
102
|
+
|
|
103
|
+
`GET`, `PUT` and `DELETE` are always retried. `POST` and `PATCH` are retried **only when the request carries an
|
|
104
|
+
`Idempotency-Key`**, so a retry can never place a call or spend credits twice.
|
|
105
|
+
|
|
106
|
+
## Idempotency keys
|
|
107
|
+
|
|
108
|
+
These writes get a fresh `Idempotency-Key` automatically, reused across their retries:
|
|
109
|
+
`calls.create`, `phoneNumbers.rent`, `deployments.createOutbound`, `deployments.createInbound`,
|
|
110
|
+
`chat.conversations.start`, `chat.conversations.send`, `agents.create`, `cases.start`.
|
|
111
|
+
|
|
112
|
+
```ts
|
|
113
|
+
import { idempotencyKey } from '@hirefinn/sdk';
|
|
114
|
+
|
|
115
|
+
const key = idempotencyKey(); // store it with your job
|
|
116
|
+
await finn.calls.create(body, { idempotencyKey: key }); // same key + same body within 24 h = same answer
|
|
117
|
+
await finn.finns.create(body, { idempotencyKey: idempotencyKey() }); // opt in on any other write
|
|
118
|
+
await finn.calls.create(body, { idempotencyKey: false }); // opt out
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
## Errors
|
|
122
|
+
|
|
123
|
+
Every API error throws a `FinnError`, whichever of the API's error shapes it answered with:
|
|
124
|
+
|
|
125
|
+
```ts
|
|
126
|
+
try {
|
|
127
|
+
await finn.calls.create(body);
|
|
128
|
+
} catch (err) {
|
|
129
|
+
if (err instanceof FinnError) {
|
|
130
|
+
err.status; // 402
|
|
131
|
+
err.code; // 'insufficient_credits' (branch on this, not on message)
|
|
132
|
+
err.message;
|
|
133
|
+
err.requestId; // X-Request-Id, for support
|
|
134
|
+
err.fields; // [{ field, code, message }] on validation errors
|
|
135
|
+
err.actionUrl; // dashboard page that fixes it, when sent
|
|
136
|
+
err.requiredScope; // on 403 insufficient_scope
|
|
137
|
+
err.retryAfter; // seconds, on 429
|
|
138
|
+
err.details; // other fields from the body
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
`FinnConnectionError` (no HTTP answer), `FinnTimeoutError` (per-attempt timeout) and `FinnApprovalTimeoutError`
|
|
144
|
+
(from `waitForApproval`) all extend `FinnSdkError`.
|
|
145
|
+
|
|
146
|
+
## Pagination
|
|
147
|
+
|
|
148
|
+
`listAll(...)` returns a `Paginator`: an async iterator over items that fetches pages as needed. It handles each
|
|
149
|
+
list style the API uses (cursor, offset, page and `before`).
|
|
150
|
+
|
|
151
|
+
```ts
|
|
152
|
+
for await (const agent of finn.agents.listAll()) { ... }
|
|
153
|
+
for await (const page of finn.calls.listAll({ limit: 200 }).pages()) { ... }
|
|
154
|
+
const first500 = await finn.contacts.listAll().toArray(500);
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
## Regenerating from the spec
|
|
158
|
+
|
|
159
|
+
The spec is vendored at `spec/openapi.json`; the generated types at `src/generated/openapi.ts` are committed.
|
|
160
|
+
|
|
161
|
+
```sh
|
|
162
|
+
npm run generate # from spec/openapi.json
|
|
163
|
+
npm run generate -- ./path/to/openapi.json # from a file (also copied into spec/)
|
|
164
|
+
npm run generate -- https://host/openapi.json # from a URL (also copied into spec/)
|
|
165
|
+
BACKEND=../hirefinn-web-app-backend npm run spec:pull # from the backend repo's prod branch
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
Then `npm run typecheck && npm test`. New endpoints are reachable at once through `finn.request(...)`; add a
|
|
169
|
+
resource method in `src/resources.ts` for the ones worth a name.
|
|
170
|
+
|
|
171
|
+
## Development
|
|
172
|
+
|
|
173
|
+
```sh
|
|
174
|
+
npm install
|
|
175
|
+
npm run typecheck
|
|
176
|
+
npm test
|
|
177
|
+
npm run build # dist/esm + dist/cjs
|
|
178
|
+
```
|
|
@@ -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,19 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.isPendingApproval = isPendingApproval;
|
|
4
|
+
/**
|
|
5
|
+
* True when a write was held for a person to approve (HTTP 202 `{ status: 'pending_approval', approval_id, ... }`).
|
|
6
|
+
* Outward and spending actions from OAuth and MCP callers can answer this instead of doing the work.
|
|
7
|
+
*
|
|
8
|
+
* const res = await finn.calls.create({ ... });
|
|
9
|
+
* if (isPendingApproval(res)) {
|
|
10
|
+
* console.log('Approve at', res.approve_url);
|
|
11
|
+
* const outcome = await finn.waitForApproval(res.approval_id);
|
|
12
|
+
* }
|
|
13
|
+
*/
|
|
14
|
+
function isPendingApproval(value) {
|
|
15
|
+
if (typeof value !== 'object' || value === null)
|
|
16
|
+
return false;
|
|
17
|
+
const v = value;
|
|
18
|
+
return v.status === 'pending_approval' && typeof v.approval_id === 'string';
|
|
19
|
+
}
|
|
@@ -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,35 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.Finn = void 0;
|
|
4
|
+
const core_js_1 = require("./core.js");
|
|
5
|
+
const resources_js_1 = require("./resources.js");
|
|
6
|
+
/**
|
|
7
|
+
* The Finn API client.
|
|
8
|
+
*
|
|
9
|
+
* import { Finn } from '@hirefinn/sdk';
|
|
10
|
+
* const finn = new Finn({ apiKey: process.env.FINN_API_KEY });
|
|
11
|
+
* const { data } = await finn.calls.list({ limit: 10 });
|
|
12
|
+
*/
|
|
13
|
+
class Finn extends core_js_1.FinnCore {
|
|
14
|
+
constructor(options = {}) {
|
|
15
|
+
super(options);
|
|
16
|
+
this.calls = new resources_js_1.Calls(this);
|
|
17
|
+
this.finns = new resources_js_1.Finns(this);
|
|
18
|
+
this.voices = new resources_js_1.Voices(this);
|
|
19
|
+
this.phoneNumbers = new resources_js_1.PhoneNumbers(this);
|
|
20
|
+
this.audiences = new resources_js_1.Audiences(this);
|
|
21
|
+
this.deployments = new resources_js_1.Deployments(this);
|
|
22
|
+
this.wallet = new resources_js_1.Wallet(this);
|
|
23
|
+
this.doNotCall = new resources_js_1.DoNotCall(this);
|
|
24
|
+
this.contacts = new resources_js_1.Contacts(this);
|
|
25
|
+
this.cases = new resources_js_1.Cases(this);
|
|
26
|
+
this.approvals = new resources_js_1.Approvals(this);
|
|
27
|
+
this.agents = new resources_js_1.Agents(this);
|
|
28
|
+
this.chat = new resources_js_1.Chat(this);
|
|
29
|
+
}
|
|
30
|
+
/** Polls an approval until it is decided (see approvals.wait). */
|
|
31
|
+
waitForApproval(id, options) {
|
|
32
|
+
return this.approvals.wait(id, options);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
exports.Finn = Finn;
|
|
@@ -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
|
+
}
|
package/dist/cjs/core.js
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
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.AUTO_IDEMPOTENCY_ROUTES = exports.SDK_VERSION = exports.DEFAULT_BASE_URL = void 0;
|
|
16
|
+
exports.idempotencyKey = idempotencyKey;
|
|
17
|
+
const errors_js_1 = require("./errors.js");
|
|
18
|
+
exports.DEFAULT_BASE_URL = 'https://api.hirefinn.ai/v1';
|
|
19
|
+
exports.SDK_VERSION = '0.1.0';
|
|
20
|
+
/** Writes that get an automatic Idempotency-Key (when autoIdempotency is on). */
|
|
21
|
+
exports.AUTO_IDEMPOTENCY_ROUTES = new Set([
|
|
22
|
+
'post /calls',
|
|
23
|
+
'post /phone_numbers',
|
|
24
|
+
'post /deployments',
|
|
25
|
+
'post /deployments/inbound',
|
|
26
|
+
'post /chat/conversations',
|
|
27
|
+
'post /chat/conversations/{id}/messages',
|
|
28
|
+
'post /agents',
|
|
29
|
+
'post /agents/{id}/cases',
|
|
30
|
+
]);
|
|
31
|
+
const SAFE_TO_RETRY_METHODS = new Set(['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE']);
|
|
32
|
+
const RETRY_BASE_DELAY_MS = 500;
|
|
33
|
+
const RETRY_MAX_DELAY_MS = 8000;
|
|
34
|
+
/** A new random Idempotency-Key (a UUID v4). */
|
|
35
|
+
function idempotencyKey() {
|
|
36
|
+
const c = globalThis.crypto;
|
|
37
|
+
if (c && typeof c.randomUUID === 'function')
|
|
38
|
+
return c.randomUUID();
|
|
39
|
+
const bytes = new Uint8Array(16);
|
|
40
|
+
if (c && typeof c.getRandomValues === 'function')
|
|
41
|
+
c.getRandomValues(bytes);
|
|
42
|
+
else
|
|
43
|
+
for (let i = 0; i < 16; i += 1)
|
|
44
|
+
bytes[i] = Math.floor(Math.random() * 256);
|
|
45
|
+
bytes[6] = (bytes[6] & 0x0f) | 0x40;
|
|
46
|
+
bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
|
47
|
+
const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
|
|
48
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
49
|
+
}
|
|
50
|
+
function defaultSleep(ms, signal) {
|
|
51
|
+
return new Promise((resolve, reject) => {
|
|
52
|
+
if (signal?.aborted)
|
|
53
|
+
return reject(signal.reason ?? new Error('Aborted'));
|
|
54
|
+
const timer = setTimeout(() => {
|
|
55
|
+
signal?.removeEventListener('abort', onAbort);
|
|
56
|
+
resolve();
|
|
57
|
+
}, ms);
|
|
58
|
+
const onAbort = () => {
|
|
59
|
+
clearTimeout(timer);
|
|
60
|
+
reject(signal?.reason ?? new Error('Aborted'));
|
|
61
|
+
};
|
|
62
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
function readEnvKey() {
|
|
66
|
+
const proc = globalThis.process;
|
|
67
|
+
return proc?.env?.FINN_API_KEY;
|
|
68
|
+
}
|
|
69
|
+
class FinnCore {
|
|
70
|
+
constructor(options = {}) {
|
|
71
|
+
_FinnCore_apiKey.set(this, void 0);
|
|
72
|
+
_FinnCore_fetch.set(this, void 0);
|
|
73
|
+
_FinnCore_defaultHeaders.set(this, void 0);
|
|
74
|
+
_FinnCore_sleep.set(this, void 0);
|
|
75
|
+
const apiKey = options.apiKey ?? readEnvKey();
|
|
76
|
+
if (!apiKey) {
|
|
77
|
+
throw new errors_js_1.FinnSdkError('Missing API key: pass { apiKey } to new Finn() or set FINN_API_KEY.');
|
|
78
|
+
}
|
|
79
|
+
const f = options.fetch ?? globalThis.fetch;
|
|
80
|
+
if (typeof f !== 'function') {
|
|
81
|
+
throw new errors_js_1.FinnSdkError('No fetch available: use Node 18+ or pass { fetch } to new Finn().');
|
|
82
|
+
}
|
|
83
|
+
__classPrivateFieldSet(this, _FinnCore_apiKey, apiKey, "f");
|
|
84
|
+
__classPrivateFieldSet(this, _FinnCore_fetch, f, "f");
|
|
85
|
+
this.baseUrl = (options.baseUrl ?? exports.DEFAULT_BASE_URL).replace(/\/+$/, '');
|
|
86
|
+
this.org = options.org;
|
|
87
|
+
this.version = options.version;
|
|
88
|
+
this.maxRetries = options.maxRetries ?? 2;
|
|
89
|
+
this.timeoutMs = options.timeoutMs ?? 60000;
|
|
90
|
+
this.autoIdempotency = options.autoIdempotency ?? true;
|
|
91
|
+
this.maxRetryAfterMs = options.maxRetryAfterMs ?? 60000;
|
|
92
|
+
__classPrivateFieldSet(this, _FinnCore_defaultHeaders, { ...(options.defaultHeaders ?? {}) }, "f");
|
|
93
|
+
__classPrivateFieldSet(this, _FinnCore_sleep, options.sleep ?? defaultSleep, "f");
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Calls any operation in the spec, fully typed.
|
|
97
|
+
*
|
|
98
|
+
* const call = await finn.request('get', '/calls/{call_uuid}', { path: { call_uuid } });
|
|
99
|
+
*/
|
|
100
|
+
async request(method, path, ...args) {
|
|
101
|
+
const res = await this.requestWithResponse(method, path, ...args);
|
|
102
|
+
return res.data;
|
|
103
|
+
}
|
|
104
|
+
/** Same as request(), plus status, headers and request id. */
|
|
105
|
+
async requestWithResponse(method, path, ...args) {
|
|
106
|
+
const [params, options] = args;
|
|
107
|
+
return this.rawRequest({ method, path: path, pathParams: params?.path, query: params?.query, body: params?.body }, options);
|
|
108
|
+
}
|
|
109
|
+
/** Untyped escape hatch for endpoints newer than this SDK's spec. */
|
|
110
|
+
async rawRequest(req, options = {}) {
|
|
111
|
+
const method = req.method.toUpperCase();
|
|
112
|
+
const routeKey = `${method.toLowerCase()} ${req.path}`;
|
|
113
|
+
const url = this.buildUrl(req.path, req.pathParams, req.query);
|
|
114
|
+
let key;
|
|
115
|
+
if (typeof options.idempotencyKey === 'string')
|
|
116
|
+
key = options.idempotencyKey;
|
|
117
|
+
else if (options.idempotencyKey !== false && this.autoIdempotency && exports.AUTO_IDEMPOTENCY_ROUTES.has(routeKey)) {
|
|
118
|
+
key = idempotencyKey();
|
|
119
|
+
}
|
|
120
|
+
const headers = new Headers();
|
|
121
|
+
headers.set('Accept', 'application/json');
|
|
122
|
+
for (const [k, v] of Object.entries(__classPrivateFieldGet(this, _FinnCore_defaultHeaders, "f")))
|
|
123
|
+
headers.set(k, v);
|
|
124
|
+
const org = options.org ?? this.org;
|
|
125
|
+
if (org)
|
|
126
|
+
headers.set('Finn-Org', org);
|
|
127
|
+
const version = options.version ?? this.version;
|
|
128
|
+
if (version)
|
|
129
|
+
headers.set('Finn-Version', version);
|
|
130
|
+
if (key)
|
|
131
|
+
headers.set('Idempotency-Key', key);
|
|
132
|
+
let body;
|
|
133
|
+
if (req.body !== undefined && req.body !== null) {
|
|
134
|
+
if (typeof FormData !== 'undefined' && req.body instanceof FormData)
|
|
135
|
+
body = req.body;
|
|
136
|
+
else {
|
|
137
|
+
headers.set('Content-Type', 'application/json');
|
|
138
|
+
body = JSON.stringify(req.body);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
for (const [k, v] of Object.entries(options.headers ?? {}))
|
|
142
|
+
headers.set(k, v);
|
|
143
|
+
headers.set('Authorization', `Bearer ${__classPrivateFieldGet(this, _FinnCore_apiKey, "f")}`);
|
|
144
|
+
const canRetry = SAFE_TO_RETRY_METHODS.has(method) || headers.has('Idempotency-Key');
|
|
145
|
+
const maxRetries = canRetry ? Math.max(0, options.maxRetries ?? this.maxRetries) : 0;
|
|
146
|
+
const timeoutMs = options.timeoutMs ?? this.timeoutMs;
|
|
147
|
+
for (let attempt = 0;; attempt += 1) {
|
|
148
|
+
let response;
|
|
149
|
+
try {
|
|
150
|
+
response = await this.fetchOnce(url, { method, headers, body }, timeoutMs, options.signal);
|
|
151
|
+
}
|
|
152
|
+
catch (err) {
|
|
153
|
+
if (options.signal?.aborted)
|
|
154
|
+
throw err;
|
|
155
|
+
const wrapped = err instanceof errors_js_1.FinnTimeoutError
|
|
156
|
+
? err
|
|
157
|
+
: new errors_js_1.FinnConnectionError(`Could not reach the Finn API: ${err?.message ?? err}`, { cause: err });
|
|
158
|
+
if (attempt < maxRetries) {
|
|
159
|
+
await __classPrivateFieldGet(this, _FinnCore_sleep, "f").call(this, backoffMs(attempt), options.signal);
|
|
160
|
+
continue;
|
|
161
|
+
}
|
|
162
|
+
throw wrapped;
|
|
163
|
+
}
|
|
164
|
+
const parsed = await readBody(response);
|
|
165
|
+
if (response.ok) {
|
|
166
|
+
return {
|
|
167
|
+
data: parsed,
|
|
168
|
+
status: response.status,
|
|
169
|
+
headers: response.headers,
|
|
170
|
+
requestId: response.headers.get('x-request-id'),
|
|
171
|
+
idempotentReplayed: response.headers.get('idempotent-replayed') === 'true',
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
const error = errors_js_1.FinnError.fromResponse(response.status, response.headers, parsed, response.statusText);
|
|
175
|
+
if (attempt < maxRetries && isRetryable(error)) {
|
|
176
|
+
const wait = error.retryAfter != null ? error.retryAfter * 1000 : backoffMs(attempt);
|
|
177
|
+
if (wait > this.maxRetryAfterMs)
|
|
178
|
+
throw error;
|
|
179
|
+
await __classPrivateFieldGet(this, _FinnCore_sleep, "f").call(this, wait, options.signal);
|
|
180
|
+
continue;
|
|
181
|
+
}
|
|
182
|
+
throw error;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
/** Builds the full URL: base + path with `{name}` filled in + query string. */
|
|
186
|
+
buildUrl(path, pathParams, query) {
|
|
187
|
+
const filled = path.replace(/\{([^}]+)\}/g, (_, name) => {
|
|
188
|
+
const value = pathParams?.[name];
|
|
189
|
+
if (value === undefined || value === null || value === '') {
|
|
190
|
+
throw new errors_js_1.FinnSdkError(`Missing path parameter "${name}" for ${path}`);
|
|
191
|
+
}
|
|
192
|
+
return encodeURIComponent(String(value));
|
|
193
|
+
});
|
|
194
|
+
const qs = new URLSearchParams();
|
|
195
|
+
for (const [k, v] of Object.entries(query ?? {})) {
|
|
196
|
+
if (v === undefined || v === null)
|
|
197
|
+
continue;
|
|
198
|
+
if (Array.isArray(v))
|
|
199
|
+
qs.set(k, v.map(String).join(','));
|
|
200
|
+
else if (v instanceof Date)
|
|
201
|
+
qs.set(k, v.toISOString());
|
|
202
|
+
else
|
|
203
|
+
qs.set(k, String(v));
|
|
204
|
+
}
|
|
205
|
+
const s = qs.toString();
|
|
206
|
+
return `${this.baseUrl}${filled.startsWith('/') ? '' : '/'}${filled}${s ? `?${s}` : ''}`;
|
|
207
|
+
}
|
|
208
|
+
async fetchOnce(url, init, timeoutMs, signal) {
|
|
209
|
+
const controller = new AbortController();
|
|
210
|
+
let timedOut = false;
|
|
211
|
+
const onAbort = () => controller.abort(signal?.reason);
|
|
212
|
+
if (signal?.aborted)
|
|
213
|
+
throw signal.reason ?? new Error('Aborted');
|
|
214
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
215
|
+
const timer = timeoutMs > 0 && Number.isFinite(timeoutMs)
|
|
216
|
+
? setTimeout(() => {
|
|
217
|
+
timedOut = true;
|
|
218
|
+
controller.abort();
|
|
219
|
+
}, timeoutMs)
|
|
220
|
+
: undefined;
|
|
221
|
+
try {
|
|
222
|
+
return await __classPrivateFieldGet(this, _FinnCore_fetch, "f").call(this, url, { ...init, signal: controller.signal });
|
|
223
|
+
}
|
|
224
|
+
catch (err) {
|
|
225
|
+
if (timedOut)
|
|
226
|
+
throw new errors_js_1.FinnTimeoutError(`The request timed out after ${timeoutMs} ms.`, { cause: err });
|
|
227
|
+
throw err;
|
|
228
|
+
}
|
|
229
|
+
finally {
|
|
230
|
+
if (timer)
|
|
231
|
+
clearTimeout(timer);
|
|
232
|
+
signal?.removeEventListener('abort', onAbort);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
exports.FinnCore = FinnCore;
|
|
237
|
+
_FinnCore_apiKey = new WeakMap(), _FinnCore_fetch = new WeakMap(), _FinnCore_defaultHeaders = new WeakMap(), _FinnCore_sleep = new WeakMap();
|
|
238
|
+
function isRetryable(error) {
|
|
239
|
+
if (error.status === 408 || error.status === 429)
|
|
240
|
+
return true;
|
|
241
|
+
if (error.status === 409)
|
|
242
|
+
return error.code === 'idempotency_in_progress';
|
|
243
|
+
return error.status === 500 || error.status === 502 || error.status === 503 || error.status === 504;
|
|
244
|
+
}
|
|
245
|
+
function backoffMs(attempt) {
|
|
246
|
+
const base = Math.min(RETRY_MAX_DELAY_MS, RETRY_BASE_DELAY_MS * 2 ** attempt);
|
|
247
|
+
return Math.round(base * (1 - Math.random() * 0.25));
|
|
248
|
+
}
|
|
249
|
+
async function readBody(response) {
|
|
250
|
+
if (response.status === 204 || response.status === 205)
|
|
251
|
+
return undefined;
|
|
252
|
+
const text = await response.text();
|
|
253
|
+
if (text === '')
|
|
254
|
+
return undefined;
|
|
255
|
+
const type = response.headers.get('content-type') ?? '';
|
|
256
|
+
if (type.includes('json') || /^[[{]/.test(text.trimStart())) {
|
|
257
|
+
try {
|
|
258
|
+
return JSON.parse(text);
|
|
259
|
+
}
|
|
260
|
+
catch {
|
|
261
|
+
return text;
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
return text;
|
|
265
|
+
}
|