@hirefinn/sdk 0.5.1 → 0.5.2

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/README.md CHANGED
@@ -21,15 +21,16 @@ npm install @hirefinn/sdk
21
21
  ```ts
22
22
  import { Finn, isPendingApproval, FinnError } from '@hirefinn/sdk';
23
23
 
24
- const finn = new Finn({ apiKey: process.env.FINN_API_KEY }); // finn_live_..., finn_test_... or an OAuth finn_oat_... token
25
- // Note: finn_test_... keys can read and build, but outward actions such as calls.create answer 403 `test_mode`.
24
+ const finn = new Finn({ apiKey: process.env.FINN_API_KEY }); // wsk_live_..., wsk_test_... or an OAuth wsk_oat_... token
25
+ // Older keys start with finn_live_..., finn_test_... or finn_oat_... and keep working.
26
+ // Note: test keys (wsk_test_... or finn_test_...) can read and build, but outward actions such as calls.create answer 403 `test_mode`.
26
27
 
27
28
  // List, retrieve
28
- const { data: finns } = await finn.finns.list({ limit: 20 });
29
+ const { data: assistants } = await finn.assistants.list({ limit: 20 });
29
30
  const call = await finn.calls.retrieve('b7e3c9a2-4d1f-4e8b-9a6c-2f5d8e1b3c70');
30
31
 
31
32
  // Place a call (gets an automatic Idempotency-Key, so it is safe to retry)
32
- const res = await finn.calls.create({ finn_id: finns[0]!.id, to_number: '4155550142', country_code: '1' });
33
+ const res = await finn.calls.create({ finn_id: assistants[0]!.id, to_number: '4155550142', country_code: '1' });
33
34
  if (isPendingApproval(res)) {
34
35
  // OAuth / MCP callers: outward and spending actions may wait for a person to approve them (HTTP 202)
35
36
  console.log('Approve it here:', res.approve_url);
@@ -56,8 +57,8 @@ for await (const e of finn.cases.listAllEvents('5c1e8f3a-9b2d-4a7e-8c6f-1d3b5a7e
56
57
  new Finn({
57
58
  apiKey, // default: process.env.FINN_API_KEY
58
59
  baseUrl, // default: https://api.hirefinn.ai/v1
59
- org, // Finn-Org header: which org a multi-org token acts in
60
- version, // Finn-Version header; default DEFAULT_FINN_VERSION ('2026-11-01'), null sends none
60
+ org, // X-Org-Id header (formerly Finn-Org): which org a multi-org token acts in
61
+ version, // Api-Version header (formerly Finn-Version); default DEFAULT_FINN_VERSION ('2026-11-01'), null sends none
61
62
  maxRetries: 2, // retries after the first attempt
62
63
  timeoutMs: 60_000, // per attempt
63
64
  fetch, // custom fetch (tests, proxies, older runtimes)
@@ -78,7 +79,7 @@ On Node and other server runtimes the SDK sends `User-Agent: finn-node/<version>
78
79
  | Property | Endpoints |
79
80
  |---|---|
80
81
  | `finn.calls` | `create`, `list`, `listAll`, `retrieve` |
81
- | `finn.finns` | `list`, `listAll`, `create`, `retrieve`, `update`, `delete`, `listKnowledgeBase`, `addKnowledgeBaseDocument`, `postCallAnalysis` |
82
+ | `finn.assistants` (`finn.finns` is a deprecated alias) | `list`, `listAll`, `create`, `retrieve`, `update`, `delete`, `listKnowledgeBase`, `addKnowledgeBaseDocument`, `postCallAnalysis` |
82
83
  | `finn.voices` | `list`, `listAll`, `retrieve` |
83
84
  | `finn.phoneNumbers` | `list`, `listAll`, `searchAvailable`, `rent`, `retrieve`, `release` |
84
85
  | `finn.audiences` | `list`, `listAll`, `create`, `retrieve`, `archive`, `listContacts`, `listAllContacts`, `addContacts`, `removeContact` |
@@ -92,7 +93,7 @@ On Node and other server runtimes the SDK sends `User-Agent: finn-node/<version>
92
93
  | `finn.chat` | `listChannels`; `conversations.{list, listAll, start, retrieve, listMessages, listAllMessages, send}`; `contacts.{list, listAll, retrieve, update}` |
93
94
 
94
95
  The other operations (`finn.crm`, `finn.dialer`, `finn.webhooks`, `finn.organization`, `finn.sales` and more
95
- `finn.finns` methods) are generated from the spec: see [Coverage](#coverage).
96
+ `finn.assistants` methods) are generated from the spec: see [Coverage](#coverage).
96
97
 
97
98
  Methods return the response body exactly as the spec describes it (older voice endpoints wrap it in
98
99
  `{ success, data }`). Request and response types come from `src/generated/openapi.ts`; schemas are exported as
@@ -115,7 +116,7 @@ The SDK covers **165 of 165** operations in the spec (Finn API v1):
115
116
 
116
117
  | Property | Generated methods |
117
118
  |---|---|
118
- | `finn.finns` | `generate`, `getFlow`, `enableFlow`, `disableFlow`, `getSettings`, `getVariables`, `updateVariables`, `updateHandbook`, `updateSpeechSettings`, `updateDraft`, `duplicate`, `getShareLink`, `createShareLink`, `getStats`, `getOutcomes` |
119
+ | `finn.assistants` | `generate`, `getFlow`, `enableFlow`, `disableFlow`, `getSettings`, `getVariables`, `updateVariables`, `updateHandbook`, `updateSpeechSettings`, `updateDraft`, `duplicate`, `getShareLink`, `createShareLink`, `getStats`, `getOutcomes` |
119
120
  | `finn.agents` | `archive` |
120
121
  | `finn.chat` | `getAgent`, `updateAgent`, `testAgent` |
121
122
  | `finn.crm` | `getSetup`, `getFilterSchema`, `searchRecords`, `queryRecords`, `countRecords`, `countRecordsByStage`, `getRecord`, `updateRecord`, `getRecordTimeline`, `getStageGate`, `listRecordDocuments`, `listRecordFiles`, `attachFile`, `getFormsChecklist`, `listFormSubmissions`, `listFormDrafts`, `listForms`, `listFollowUps`, `listAllFollowUps`, `getFollowUpStats`, `getMyWork`, `listViews`, `saveView`, `getSummary`, `getStageCounts`, `getSpeed`, `listDuplicates`, `ask`, `addNote`, `createFollowUp`, `updateFollowUp`, `createRecord`, `setStageCheck`, `assignReferenceNo`, `setDocumentStatus`, `saveFormDraft`, `draftDocument`, `moveRecordStage`, `submitForm`, `createFormLink`, `createUploadLink`, `guessImportColumns`, `importRecords` |
@@ -125,8 +126,8 @@ The SDK covers **165 of 165** operations in the spec (Finn API v1):
125
126
  | `finn.sales` (experimental) | `listPlays`, `listPlayRuns`, `listProspects`, `runPlay`, `listDrafts`, `updateDraft`, `skipDraft`, `listThreads`, `getThread` |
126
127
  <!-- generated:coverage:end -->
127
128
 
128
- Generated methods are named after the spec's `operationId` without the area's noun (`getFinnFlow` is
129
- `finn.finns.getFlow`, `searchCrmRecords` is `finn.crm.searchRecords`). Path parameters come first, in path order,
129
+ Generated methods are named after the spec's `operationId` without the area's noun (`getAssistantFlow` is
130
+ `finn.assistants.getFlow`, `searchCrmRecords` is `finn.crm.searchRecords`). Path parameters come first, in path order,
130
131
  then the body, then the query, then `options`. List operations that page by `cursor` also get a `listAll...` helper.
131
132
 
132
133
  **`finn.sales` is experimental.** The Sales API (`/sales`) is switched off for every organization today, so its calls
@@ -232,6 +233,16 @@ try {
232
233
  `FinnConnectionError` (no HTTP answer), `FinnTimeoutError` (per-attempt timeout) and `FinnApprovalTimeoutError`
233
234
  (from `waitForApproval`) all extend `FinnSdkError`.
234
235
 
236
+ Some error codes were renamed with the `/assistants` path (`finn_not_found` is now `assistant_not_found`, and so on:
237
+ `RENAMED_ERROR_CODES`). `err.code` is what the API sent; `err.hasCode('finn_not_found')` matches either name, and
238
+ `err.legacyCode` gives the old one.
239
+
240
+ ### Neutral names
241
+
242
+ The same classes are also exported under neutral names, so `instanceof` works with either: `Client` (`Finn`),
243
+ `SdkError`, `ApiError`, `ApiConnectionError`, `ApiTimeoutError`, `ApprovalTimeoutError`, `WebhookVerificationError`,
244
+ and the types `ClientOptions`, `ErrorCode`, `FieldError`.
245
+
235
246
  ## Pagination
236
247
 
237
248
  `listAll(...)` returns a `Paginator`: an async iterator over items that fetches pages as needed. It handles each
@@ -1,16 +1,22 @@
1
1
  import { FinnCore, type FinnOptions } from './core.js';
2
- import { Agents, Approvals, Audiences, Calls, Cases, Chat, Contacts, Crm, Deployments, Dialer, DoNotCall, Finns, Organization, PhoneNumbers, Sales, Voices, Wallet, Webhooks, type WaitForApprovalOptions } from './resources.js';
2
+ import { Agents, Approvals, Assistants, Audiences, Calls, Cases, Chat, Contacts, Crm, Deployments, Dialer, DoNotCall, Organization, PhoneNumbers, Sales, Voices, Wallet, Webhooks, type WaitForApprovalOptions } from './resources.js';
3
3
  import type { ApprovalHold, Schemas } from './types.js';
4
4
  /**
5
- * The Finn API client.
5
+ * The API client. `Client` is the neutral name of the same class.
6
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 });
7
+ * import { Client } from '@hirefinn/sdk';
8
+ * const client = new Client({ apiKey: process.env.FINN_API_KEY });
9
+ * const { data } = await client.calls.list({ limit: 10 });
10
10
  */
11
11
  export declare class Finn extends FinnCore {
12
12
  readonly calls: Calls;
13
- readonly finns: Finns;
13
+ /** Assistants (voice agents): `/assistants`. */
14
+ readonly assistants: Assistants;
15
+ /**
16
+ * @deprecated Use {@link Finn.assistants}: the very same object (`client.finns === client.assistants`), kept so
17
+ * existing code runs. It calls `/assistants`, not the old `/finns` path.
18
+ */
19
+ readonly finns: Assistants;
14
20
  readonly voices: Voices;
15
21
  readonly phoneNumbers: PhoneNumbers;
16
22
  readonly audiences: Audiences;
@@ -40,3 +46,7 @@ export declare class Finn extends FinnCore {
40
46
  /** Polls an approval until it is decided (see approvals.wait). */
41
47
  waitForApproval(id: string, options?: WaitForApprovalOptions): Promise<ApprovalHold | Schemas['Approval']>;
42
48
  }
49
+ /** The neutral name of the API client: the same class as {@link Finn}, so `instanceof` works with either name. */
50
+ export declare const Client: typeof Finn;
51
+ /** The neutral name of the API client. */
52
+ export type Client = Finn;
@@ -1,20 +1,21 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Finn = void 0;
3
+ exports.Client = exports.Finn = void 0;
4
4
  const core_js_1 = require("./core.js");
5
5
  const resources_js_1 = require("./resources.js");
6
6
  /**
7
- * The Finn API client.
7
+ * The API client. `Client` is the neutral name of the same class.
8
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 });
9
+ * import { Client } from '@hirefinn/sdk';
10
+ * const client = new Client({ apiKey: process.env.FINN_API_KEY });
11
+ * const { data } = await client.calls.list({ limit: 10 });
12
12
  */
13
13
  class Finn extends core_js_1.FinnCore {
14
14
  constructor(options = {}) {
15
15
  super(options);
16
16
  this.calls = new resources_js_1.Calls(this);
17
- this.finns = new resources_js_1.Finns(this);
17
+ this.assistants = new resources_js_1.Assistants(this);
18
+ this.finns = this.assistants;
18
19
  this.voices = new resources_js_1.Voices(this);
19
20
  this.phoneNumbers = new resources_js_1.PhoneNumbers(this);
20
21
  this.audiences = new resources_js_1.Audiences(this);
@@ -38,3 +39,5 @@ class Finn extends core_js_1.FinnCore {
38
39
  }
39
40
  }
40
41
  exports.Finn = Finn;
42
+ /** The neutral name of the API client: the same class as {@link Finn}, so `instanceof` works with either name. */
43
+ exports.Client = Finn;
@@ -1,18 +1,30 @@
1
1
  import type { FinnResponse, HttpMethod, Operation, PathsFor, RequestArgs, RequestOptions, ResultOf } from './types.js';
2
2
  export declare const DEFAULT_BASE_URL = "https://api.hirefinn.ai/v1";
3
- export declare const SDK_VERSION = "0.5.1";
4
- /** The API version this SDK was built against, sent as Finn-Version unless `version` says otherwise. */
3
+ export declare const SDK_VERSION = "0.5.2";
4
+ /** The API version this SDK was built against, sent as Api-Version unless `version` says otherwise. */
5
5
  export declare const DEFAULT_FINN_VERSION = "2026-11-01";
6
+ /** The neutral name of {@link DEFAULT_FINN_VERSION}. */
7
+ export declare const DEFAULT_API_VERSION = "2026-11-01";
8
+ /**
9
+ * Request headers the API renamed: old name -> the name the SDK sends. The API still accepts the old names, but answers
10
+ * `400` when a request carries both names with different values, so the SDK only ever sends the new one: an old name
11
+ * passed in `defaultHeaders` or per-request `headers` is sent under its new name.
12
+ */
13
+ export declare const RENAMED_REQUEST_HEADERS: Readonly<Record<string, string>>;
6
14
  export interface FinnOptions {
7
- /** `finn_live_...` org key, `finn_test_...` test key, or an OAuth `finn_oat_...` token. Defaults to env FINN_API_KEY. */
15
+ /**
16
+ * `wsk_live_...` org key, `wsk_test_...` test key, or an OAuth `wsk_oat_...` token (older keys: `finn_live_...`,
17
+ * `finn_test_...`, `finn_oat_...`; both work). Sent as given. Defaults to env FINN_API_KEY.
18
+ */
8
19
  apiKey?: string;
9
20
  /** Defaults to `https://api.hirefinn.ai/v1`. */
10
21
  baseUrl?: string;
11
- /** Org to act in (Finn-Org header). Needed only for tokens that can use more than one org. */
22
+ /** Org to act in (X-Org-Id header, formerly Finn-Org). Needed only for tokens that can use more than one org. */
12
23
  org?: string;
13
24
  /**
14
- * Pins the API version (Finn-Version header), a date such as `2026-11-01`. Defaults to DEFAULT_FINN_VERSION, the
15
- * version this SDK was built against; `null` sends no header (the key's pinned version, else the current one).
25
+ * Pins the API version (Api-Version header, formerly Finn-Version), a date such as `2026-11-01`. Defaults to
26
+ * DEFAULT_FINN_VERSION, the version this SDK was built against; `null` sends no header (the key's pinned version,
27
+ * else the current one).
16
28
  */
17
29
  version?: string | null;
18
30
  /**
package/dist/cjs/core.js CHANGED
@@ -12,14 +12,30 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
12
12
  };
13
13
  var _FinnCore_apiKey, _FinnCore_fetch, _FinnCore_defaultHeaders, _FinnCore_sleep;
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.FinnCore = exports.DEFAULT_MAX_RETRY_WAIT_MS = exports.IDEMPOTENT_WRITE_ROUTES = exports.AUTO_IDEMPOTENCY_ROUTES = exports.DEFAULT_FINN_VERSION = exports.SDK_VERSION = exports.DEFAULT_BASE_URL = void 0;
15
+ exports.FinnCore = exports.DEFAULT_MAX_RETRY_WAIT_MS = exports.IDEMPOTENT_WRITE_ROUTES = exports.AUTO_IDEMPOTENCY_ROUTES = exports.RENAMED_REQUEST_HEADERS = exports.DEFAULT_API_VERSION = exports.DEFAULT_FINN_VERSION = exports.SDK_VERSION = exports.DEFAULT_BASE_URL = void 0;
16
16
  exports.honoursIdempotencyKey = honoursIdempotencyKey;
17
17
  exports.idempotencyKey = idempotencyKey;
18
18
  const errors_js_1 = require("./errors.js");
19
19
  exports.DEFAULT_BASE_URL = 'https://api.hirefinn.ai/v1';
20
- exports.SDK_VERSION = '0.5.1';
21
- /** The API version this SDK was built against, sent as Finn-Version unless `version` says otherwise. */
20
+ exports.SDK_VERSION = '0.5.2';
21
+ /** The API version this SDK was built against, sent as Api-Version unless `version` says otherwise. */
22
22
  exports.DEFAULT_FINN_VERSION = '2026-11-01';
23
+ /** The neutral name of {@link DEFAULT_FINN_VERSION}. */
24
+ exports.DEFAULT_API_VERSION = exports.DEFAULT_FINN_VERSION;
25
+ /**
26
+ * Request headers the API renamed: old name -> the name the SDK sends. The API still accepts the old names, but answers
27
+ * `400` when a request carries both names with different values, so the SDK only ever sends the new one: an old name
28
+ * passed in `defaultHeaders` or per-request `headers` is sent under its new name.
29
+ */
30
+ exports.RENAMED_REQUEST_HEADERS = Object.freeze({
31
+ 'finn-version': 'Api-Version',
32
+ 'finn-org': 'X-Org-Id',
33
+ });
34
+ /** Sets a header, sending a renamed one (Finn-Version, Finn-Org) under its new name. */
35
+ function setHeader(headers, name, value) {
36
+ const renamed = exports.RENAMED_REQUEST_HEADERS[name.toLowerCase()];
37
+ headers.set(renamed ?? name, value);
38
+ }
23
39
  // Browsers own the User-Agent header, so it is only set on server runtimes.
24
40
  const IS_NODE = typeof globalThis.process?.versions?.node === 'string';
25
41
  /** Writes that get an automatic Idempotency-Key (when autoIdempotency is on). */
@@ -169,13 +185,13 @@ class FinnCore {
169
185
  if (IS_NODE)
170
186
  headers.set('User-Agent', `finn-node/${exports.SDK_VERSION}`);
171
187
  for (const [k, v] of Object.entries(__classPrivateFieldGet(this, _FinnCore_defaultHeaders, "f")))
172
- headers.set(k, v);
188
+ setHeader(headers, k, v);
173
189
  const org = options.org ?? this.org;
174
190
  if (org)
175
- headers.set('Finn-Org', org);
191
+ headers.set('X-Org-Id', org);
176
192
  const version = options.version ?? this.version;
177
193
  if (version)
178
- headers.set('Finn-Version', version);
194
+ headers.set('Api-Version', version);
179
195
  if (key)
180
196
  headers.set('Idempotency-Key', key);
181
197
  let body;
@@ -188,7 +204,7 @@ class FinnCore {
188
204
  }
189
205
  }
190
206
  for (const [k, v] of Object.entries(options.headers ?? {}))
191
- headers.set(k, v);
207
+ setHeader(headers, k, v);
192
208
  headers.set('Authorization', `Bearer ${__classPrivateFieldGet(this, _FinnCore_apiKey, "f")}`);
193
209
  // Idempotent methods always; a POST/PATCH only with a key on a route that dedupes by it.
194
210
  const canRetry = SAFE_TO_RETRY_METHODS.has(method) || (headers.has('Idempotency-Key') && honoursIdempotencyKey(method, req.path));
@@ -16,8 +16,17 @@ export interface FinnFieldError {
16
16
  code: string;
17
17
  message: string;
18
18
  }
19
- /** The shared error codes. Endpoints may also answer resource-specific codes such as `finn_not_found`. */
19
+ /** The shared error codes. Endpoints may also answer resource-specific codes such as `assistant_not_found`. */
20
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
+ /**
22
+ * Error codes the API renamed: old code -> its neutral successor. The new paths (`/assistants`, ...) answer the neutral
23
+ * code; the old paths answered the old one. {@link FinnError.hasCode} matches either name.
24
+ */
25
+ export declare const RENAMED_ERROR_CODES: Readonly<Record<string, string>>;
26
+ /** The neutral name of an error code: `finn_not_found` -> `assistant_not_found`; any other code as it is. */
27
+ export declare const neutralErrorCode: (code: string) => string;
28
+ /** The old name of a renamed error code: `assistant_not_found` -> `finn_not_found`; null when it was never renamed. */
29
+ export declare const legacyErrorCode: (code: string) => string | null;
21
30
  /** The code an error gets when the body does not name one (mirrors the backend's codeForStatus). */
22
31
  export declare const codeForStatus: (status: number) => string;
23
32
  /** Base class for every error the SDK throws. */
@@ -30,8 +39,13 @@ export declare class FinnSdkError extends Error {
30
39
  export declare class FinnError extends FinnSdkError {
31
40
  /** HTTP status. */
32
41
  readonly status: number;
33
- /** Stable error code. */
42
+ /** Stable error code, as the API sent it (neutral names such as `assistant_not_found` on the current paths). */
34
43
  readonly code: FinnErrorCode;
44
+ /**
45
+ * The old name of a renamed code (`finn_not_found` for `assistant_not_found`, see RENAMED_ERROR_CODES), else null.
46
+ * For code that still compares against the old names; prefer {@link FinnError.hasCode}.
47
+ */
48
+ readonly legacyCode: string | null;
35
49
  /** Matches the `X-Request-Id` response header; quote it to support. */
36
50
  readonly requestId: string | null;
37
51
  /** Per-field problems (unified shape, and legacy bodies that name fields as a string list; `[]` otherwise). */
@@ -64,6 +78,11 @@ export declare class FinnError extends FinnSdkError {
64
78
  body?: unknown;
65
79
  headers?: Headers;
66
80
  });
81
+ /**
82
+ * True when this error's code is `code`, by its old or its neutral name: `hasCode('finn_not_found')` and
83
+ * `hasCode('assistant_not_found')` both match either answer.
84
+ */
85
+ hasCode(code: string): boolean;
67
86
  /** Builds a FinnError from a failed response and its already-read body. */
68
87
  static fromResponse(status: number, headers: Headers, body: unknown, statusText?: string): FinnError;
69
88
  }
@@ -88,3 +107,22 @@ export declare class FinnApprovalTimeoutError extends FinnSdkError {
88
107
  }
89
108
  /** Retry-After as seconds: accepts delta-seconds or an HTTP date. */
90
109
  export declare function parseRetryAfterSeconds(value: string | null, now?: number): number | null;
110
+ /** The neutral name of {@link FinnSdkError}. */
111
+ export declare const SdkError: typeof FinnSdkError;
112
+ export type SdkError = FinnSdkError;
113
+ /** The neutral name of {@link FinnError}. */
114
+ export declare const ApiError: typeof FinnError;
115
+ export type ApiError = FinnError;
116
+ /** The neutral name of {@link FinnConnectionError}. */
117
+ export declare const ApiConnectionError: typeof FinnConnectionError;
118
+ export type ApiConnectionError = FinnConnectionError;
119
+ /** The neutral name of {@link FinnTimeoutError}. */
120
+ export declare const ApiTimeoutError: typeof FinnTimeoutError;
121
+ export type ApiTimeoutError = FinnTimeoutError;
122
+ /** The neutral name of {@link FinnApprovalTimeoutError}. */
123
+ export declare const ApprovalTimeoutError: typeof FinnApprovalTimeoutError;
124
+ export type ApprovalTimeoutError = FinnApprovalTimeoutError;
125
+ /** The neutral name of {@link FinnErrorCode}. */
126
+ export type ErrorCode = FinnErrorCode;
127
+ /** The neutral name of {@link FinnFieldError}. */
128
+ export type FieldError = FinnFieldError;
@@ -12,7 +12,7 @@
12
12
  * Branch on `code`, never on `message`.
13
13
  */
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.FinnApprovalTimeoutError = exports.FinnTimeoutError = exports.FinnConnectionError = exports.FinnError = exports.FinnSdkError = exports.codeForStatus = void 0;
15
+ exports.ApprovalTimeoutError = exports.ApiTimeoutError = exports.ApiConnectionError = exports.ApiError = exports.SdkError = exports.FinnApprovalTimeoutError = exports.FinnTimeoutError = exports.FinnConnectionError = exports.FinnError = exports.FinnSdkError = exports.codeForStatus = exports.legacyErrorCode = exports.neutralErrorCode = exports.RENAMED_ERROR_CODES = void 0;
16
16
  exports.parseRetryAfterSeconds = parseRetryAfterSeconds;
17
17
  const CODE_FOR_STATUS = {
18
18
  400: 'invalid_request',
@@ -28,6 +28,30 @@ const CODE_FOR_STATUS = {
28
28
  503: 'unavailable',
29
29
  504: 'unavailable',
30
30
  };
31
+ /**
32
+ * Error codes the API renamed: old code -> its neutral successor. The new paths (`/assistants`, ...) answer the neutral
33
+ * code; the old paths answered the old one. {@link FinnError.hasCode} matches either name.
34
+ */
35
+ exports.RENAMED_ERROR_CODES = Object.freeze({
36
+ finn_not_found: 'assistant_not_found',
37
+ finn_in_use: 'assistant_in_use',
38
+ finn_paused: 'assistant_paused',
39
+ finn_not_draft: 'assistant_not_draft',
40
+ finn_not_yours: 'assistant_not_yours',
41
+ invalid_finn_id: 'invalid_assistant_id',
42
+ invalid_finn_version: 'invalid_api_version',
43
+ });
44
+ const LEGACY_FOR_NEUTRAL = Object.freeze(Object.fromEntries(Object.entries(exports.RENAMED_ERROR_CODES).map(([old, neutral]) => [neutral, old])));
45
+ /** The neutral name of an error code: `finn_not_found` -> `assistant_not_found`; any other code as it is. */
46
+ const neutralErrorCode = (code) => Object.hasOwn(exports.RENAMED_ERROR_CODES, code) ? exports.RENAMED_ERROR_CODES[code] : code;
47
+ exports.neutralErrorCode = neutralErrorCode;
48
+ /** The old name of a renamed error code: `assistant_not_found` -> `finn_not_found`; null when it was never renamed. */
49
+ const legacyErrorCode = (code) => Object.hasOwn(LEGACY_FOR_NEUTRAL, code)
50
+ ? LEGACY_FOR_NEUTRAL[code]
51
+ : Object.hasOwn(exports.RENAMED_ERROR_CODES, code)
52
+ ? code
53
+ : null;
54
+ exports.legacyErrorCode = legacyErrorCode;
31
55
  /** The code an error gets when the body does not name one (mirrors the backend's codeForStatus). */
32
56
  const codeForStatus = (status) => CODE_FOR_STATUS[status] ?? (status >= 500 ? 'internal_error' : 'invalid_request');
33
57
  exports.codeForStatus = codeForStatus;
@@ -48,6 +72,7 @@ class FinnError extends FinnSdkError {
48
72
  this.name = 'FinnError';
49
73
  this.status = init.status;
50
74
  this.code = init.code;
75
+ this.legacyCode = (0, exports.legacyErrorCode)(init.code);
51
76
  this.requestId = init.requestId ?? null;
52
77
  this.fields = init.fields ?? [];
53
78
  this.docUrl = init.docUrl ?? null;
@@ -58,6 +83,13 @@ class FinnError extends FinnSdkError {
58
83
  this.body = init.body;
59
84
  this.headers = init.headers ?? new Headers();
60
85
  }
86
+ /**
87
+ * True when this error's code is `code`, by its old or its neutral name: `hasCode('finn_not_found')` and
88
+ * `hasCode('assistant_not_found')` both match either answer.
89
+ */
90
+ hasCode(code) {
91
+ return (0, exports.neutralErrorCode)(this.code) === (0, exports.neutralErrorCode)(code);
92
+ }
61
93
  /** Builds a FinnError from a failed response and its already-read body. */
62
94
  static fromResponse(status, headers, body, statusText = '') {
63
95
  const headerRequestId = headers.get('x-request-id');
@@ -174,3 +206,14 @@ function legacyFields(v, code, message) {
174
206
  function isFieldError(v) {
175
207
  return isRecord(v) && typeof v.field === 'string';
176
208
  }
209
+ // Neutral names of the error classes: the same classes, so `instanceof` works with either name.
210
+ /** The neutral name of {@link FinnSdkError}. */
211
+ exports.SdkError = FinnSdkError;
212
+ /** The neutral name of {@link FinnError}. */
213
+ exports.ApiError = FinnError;
214
+ /** The neutral name of {@link FinnConnectionError}. */
215
+ exports.ApiConnectionError = FinnConnectionError;
216
+ /** The neutral name of {@link FinnTimeoutError}. */
217
+ exports.ApiTimeoutError = FinnTimeoutError;
218
+ /** The neutral name of {@link FinnApprovalTimeoutError}. */
219
+ exports.ApprovalTimeoutError = FinnApprovalTimeoutError;