@intelligence-cloud/sdk 0.2.0 → 0.3.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/CHANGELOG.md CHANGED
@@ -1,5 +1,52 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.0 (2026-12-01)
4
+
5
+ The TypeScript SDK matches the Python reference for 0.3.0.
6
+
7
+ ### What changed for callers
8
+
9
+ - **Bad input never reaches the network.** Every helper of `client.accounts` and `client.conversations` checks its arguments, types included, before it signs in or sends anything. A 40-day window, `limit: 500` or `alerts({ status })` throw `InvalidRequestError` with no request made, even with the network down, and cost no sign-in. `teams`, `userIds` and `phrases` may be any iterable and are read once.
10
+ - **Token renewal never resends a refresh token that may have been used.** It is sent again only after a 429 or a failure where the request provably never left this machine; after a 5xx, a failure after the request left, or an unreadable answer the client signs in instead. Sending a used refresh token ends every session of the login. Which `fetch` failures count as "never left" is written in the README ("Retries"): the codes `ENOTFOUND`, `EAI_AGAIN`, `ECONNREFUSED`, `ENETUNREACH`, `EHOSTUNREACH`, `UND_ERR_CONNECT_TIMEOUT`, `ERR_INVALID_URL` and the TLS certificate refusals; everything else may have left.
11
+ - **`new Client({ deadline: 120 })`** bounds one API request, with its sign-in, renewal, retries and waits; when the time left cannot cover the next wait it stops at once (`RateLimitError`, `NetworkError` kind `"timeout"`, or the last 5xx). Each attempt is aborted after `timeout` or the time left. `clock` and `sleep` replace the clock and the wait in tests.
12
+ - **One retry policy, written down** (README "Retries"). 0.2.0 did not retry sign-in at all: network failures and 5xx are now retried on sign-in too, and on token renewal when the request never left. A 429 whose `Retry-After` is longer than the wait limit throws `RateLimitError` at once with `retryAfter` (a sign-in 429 with `Retry-After: 120` used to wait 60 seconds and then fail). User creation keeps retrying with its idempotency key.
13
+ - **One error tree in every SDK language** (README "Errors"). New `NetworkError` (an `ApiError` with status 0; `kind`, `requestSent`; the underlying error is not attached). `ConnectorTimeoutError` is a `ConnectorError`; `FrontlineRequiredError` is a `WrongLoginError`. `AccountError.find(ErrorClass)` returns the first error of that class in the cause chain: a clashing line is `AccountError` → `ExtensionMappingError` → `ConflictError`. `AccountError<T>` carries the helper's result type.
14
+ - **Events: store by call id and upsert.** A later After Call delivery for the same call can carry newer data. `Deduplicator.seen(event)` only checks whether this exact delivery (event type, location, call id and the SHA-256 of the canonical JSON body) was remembered; `Deduplicator.remember(event)` records it and is called after your durable write, so a delivery whose storage failed is processed when it is retried. Both take an event, a parsed body or the raw body; a plain id is refused. `upsertKey(event)` (also `Deduplicator.upsertKey`) returns the call id (or alert id) to store under. The keys are the same text as the Python SDK's for the same event. The README receiver sections and the Next.js examples follow this order: parse, answer 2xx if seen, upsert, remember, answer 2xx; on a storage failure answer 5xx without remembering.
15
+ - **First Alert payload is not final.** `parseFirstAlertEvent` accepts any id of letters, digits, `-` and `_` up to 128 characters, kept as sent (it used to accept only UUIDs and lower-case them); the first of `alert_id`, `alert.id`, `id` that is present decides, and a top-level `alert_id` that is not a string is an error; `raw` holds the whole payload.
16
+ - **`@intelligence-cloud/sdk/testing`**: a supported fake API for your tests and CI (ESM and CommonJS, with types; not part of the main bundle). `FakeAPI.client({ role })`, fictional seed data (`seedCustomer`, `seedCalls`), failure knobs (`connectorOutcome`, `failNext` for each HTTP and network failure, `failWrite`, `networkDown`, `rateLimit`, `expireAccessTokens`), a request log and `authLog`, refresh-token reuse that ends every session as on the platform, and strict refusal of requests the published spec does not define, including query value types, enums and formats, and the JSON types of top-level body fields. README "Testing your code" lists the whole supported surface and its examples run as a test.
17
+ - **Review round: stricter and safer.** A path argument of `..`, `.` or one with `/`, `\\`, `?`, `#`, `%`, whitespace or a control character, or over 128 characters, is refused before any request (a `..` used to rewrite the URL). Free text and numbers must be real strings of at most 200 characters. Delivery keys hash the RFC 8785 (JSON Canonicalization Scheme) text of the projected event; lone surrogates, repeated object keys, non-UTF-8 bytes and non-finite numbers are refused (also by both parsers); integers beyond 2^53 collapse by rule. The After Call parser refuses exactly a missing or wrongly typed required field. Retry-After counts only as `[0-9]{1,9}(.[0-9]+)?` seconds. A failed `fetch` counts as "never left" only when its errno code comes with `syscall` `connect` or `getaddrinfo`. Account helpers refuse a bad argument before they join the write queue. A Customer object is checked against one live read of the company's locations (and re-read in full, in place, when it differs), group and rule ids come from a live listing of each team a helper uses them on, a Customer carrying another company's location is refused, and `Customer.refreshedAt` says when it was last checked. Every error class carries a `Symbol.for` brand, so `instanceof` works between the ESM and CommonJS copies of the package. `@intelligence-cloud/sdk/testing` type-checks under `moduleResolution` node, node16 and bundler (`typesVersions`). The fake: formats and enums are checked as the spec states them (`netsapiens` is the only connector type), `failNext` answers before the platform acts unless `afterProcessing: true`, the request log and every printed form mask keys and passwords. Request counts for a Customer object grow by the live reads (the table in the README).
18
+ - **Final check.** Helpers that write check for the groups they need on a live listing before their first write (`addBaseManager`, `addIntegrationUser`, `changeLicense` to a Base Manager, `moveUser` of a manager, `setAlerts`), as in Python: a missing group is an `InvalidRequestError` with no write. Unknown events are keyed `unknown:<hash>`. Bodies nested more than 64 levels, and `call.id`, `location_id` and alert ids that are not plain ids, are refused (nothing is trimmed). The path pattern refuses C1 controls and U+FEFF and counts code points. Every top-level body field is type-checked against the spec before sending (enums are left to the API, so a new connector type needs no SDK release). Sign-in is not retried after a failure that may have left. A deadline with less than 5 ms left stops before sending. The fake masks webhook paths in its log and reads `2.5e1` as a float.
19
+ - **Closing round.** Request counts equal the Python SDK's in every row (no connector-type list read before a connector write, a team read in the same call is not listed again, `licenseReport` reads the location list once); a connector type no list names is passed to the API, which judges it. Shared vectors version 3 (six files) are asserted entry by entry, including path arguments; a body that carries a bad `alert_id` is refused, not treated as an unknown event.
20
+ - **Connect failures.** A refused connection to `localhost` (Node's AggregateError, whose attempts carry the syscall) is now read as "never left": `requestSent` is false, sign-in is retried and a refresh token is sent again. The fake's `failNext({ network })` kinds produce the error shapes Node's fetch gives (connect: ECONNREFUSED with syscall connect; read_timeout: HeadersTimeoutError; write_timeout: SocketError; new `reset`: ECONNRESET). The README says the samples use top-level `await`.
21
+ - **Developer round (ported from the Python SDK).** Testing module: `client({ asUser })` signs in as a seeded person (calls, alerts, tasks and Insights Hub follow their license and teams; two clients for one login share its sessions), `seedCustomer()` returns `people`, `seedCalls({ recording, topics })`, `connectorOutcome` applies to connection attempts made after it is set, `settleConnector`, `failNext({ signIn })`, `requests` logs every request with its `answer`, `authLog` logs every sign-in and renewal attempt, non-strict mode lets an unlisted connector type through. Lines must be the whole value `\+?[0-9*#]{1,32}`. `addBaseUser` and `addBaseManager` report all of the person's teams. `conversations.teams()` lists teams first (name order) and Management last. `isOlder(event, stored)` and the receiver flow parse, seen, compare, upsert, remember (equal timestamps: the later arrival wins). A connector found still settling when a helper runs again is checked again and restarted once. The result types are also exported under the Python names (`AlertActivation`, `NoManagerTeam`, `LineSyncReport`, `TeamLines`, `LineDiff`, `RemovalSummary`, `OffboardSummary`). README: "Upgrading from 0.2", `sleep` and `clock` as test hooks, `setAlerts` and the ten-team total in the request table. Shared vectors version 4: `fake_behaviour_vectors.json` (21 scenarios) and `line_vectors.json`.
22
+ - Connector waits count the check intervals as well as the clock, so a replaced `sleep` (tests) cannot spin for the whole timeout.
23
+ - README: "Retries" with worst-case blocking time and the fetch failure mapping, "Testing your code", "Running helpers from more than one process" (with Node recipes), "How many requests" (pinned by a test, the same numbers as the Python SDK), the error tree, the examples table. SDK documentation links point to the SDK pages (https://docs.intelligence.cloud/sdk/, /sdk/quick-start, /sdk/reference, /sdk/events, /sdk/configuration, /sdk/downloads, /sdk/testing); API links stay https://docs.intelligence.cloud/api and https://docs.intelligence.cloud/reference. The examples ship in the source download, not the npm package, and the README says so.
24
+ - Examples use one fictional customer, Riverbend Auto Group, and the variables `IC_ADMIN_EMAIL` / `IC_ADMIN_PASSWORD` and `IC_USER_EMAIL` / `IC_USER_PASSWORD`. `examples/node/create-customer.mjs` read a result field that does not exist (`skipped`); it now reads `noManager`.
25
+ - `Conversations.window()` is marked internal.
26
+
27
+ ### Breaking changes
28
+
29
+ | 0.2.0 | 0.3.0 |
30
+ |---|---|
31
+ | `Deduplicator.isDuplicate(id)` (and `seen(id)`) checked and recorded in one call, keyed on the call id | Removed, with no alias: `seen(event)` checks, `remember(event)` records after your write. A plain id throws `InvalidRequestError` |
32
+ | A custom `DedupStore` had `checkAndAdd(key)` | It needs `has(key)` and `add(key)` (both may be async) |
33
+ | `ConnectorTimeoutError` was not a `ConnectorError` | It is: a `catch` on `ConnectorError` now catches timeouts too (test `ConnectorTimeoutError` first to tell them apart) |
34
+ | `FrontlineRequiredError` derived from `IntelligenceCloudError` only | It is a `WrongLoginError` |
35
+ | A network failure threw `ApiError` (status 0) holding the underlying error as `cause` | It throws `NetworkError` (still an `ApiError`, status 0) with no `cause` |
36
+ | Sign-in was not retried | Network failures and 5xx are retried on sign-in |
37
+ | No overall time limit | `deadline: 120` seconds per API request (sign-in, renewal, retries and waits included); raise it for long Retry-After waits |
38
+ | A sign-in 429 always waited `loginRateLimitWait` once | It waits only when `Retry-After` fits in that limit; otherwise it throws at once |
39
+ | A refresh was retried after a 5xx or any network failure | Only after a 429 or a failure where the request never left |
40
+ | A path argument could be any string (`..` rewrote the URL) | Ids of at most 128 characters without `/`, `?`, `#`, `%`, whitespace, and not `.` or `..` |
41
+ | Delivery keys hashed a JavaScript-specific canonical text | The RFC 8785 text of the projected event (the same key in every SDK language); non-I-JSON bodies are refused |
42
+ | `Retry-After` accepted any number or a date | Only `[0-9]{1,9}(.[0-9]+)?` seconds; anything else is absent |
43
+ | The After Call parser required `call.id`, `location_id` and a `1.` version | It refuses exactly a missing or wrongly typed required field; a string `call_date` or `timestamp` that is not a date is accepted |
44
+ | An id inside an app link could be any string | Links carry only ids of letters, digits, `-` and `_`; `reference()` refuses others and briefs with such an id get `link: null` |
45
+ | `parseFirstAlertEvent` refused non-UUID ids and lower-cased ids | Ids of letters, digits, `-` and `_` (at most 128), kept as sent |
46
+ | Conversation and account helpers signed in before checking arguments | They check first; with a bad argument no request is sent (your mocks may see fewer requests) |
47
+ | `AccountError.result` was `unknown` | `AccountError<T>`: typed as the helper's result |
48
+ | The examples read `IC_DATA_EMAIL` and `IC_DATA_PASSWORD` | `IC_USER_EMAIL` and `IC_USER_PASSWORD` |
49
+
3
50
  ## 0.2.0 (2026-11-29)
4
51
 
5
52
  Two new layers. `client.accounts` replaces `client.workflows`; `client.conversations` is new. Every generated resource method and every `client.intelligence` helper keeps its name and behaviour. The TypeScript SDK now matches the Python reference.
package/README.md CHANGED
@@ -1,13 +1,13 @@
1
1
  # Intelligence Cloud SDK for TypeScript
2
2
 
3
- `@intelligence-cloud/sdk` 0.2.0. The partner API for Node.js 20+ and Next.js server code (route handlers, server actions).
3
+ `@intelligence-cloud/sdk` 0.3.0 (changes: `CHANGELOG.md`). The partner API for Node.js 20+ and Next.js server code (route handlers, server actions).
4
4
 
5
5
  - **Customers** (administrator login): the account layer, `client.accounts`, creates and maintains a customer on Base User and Base Manager licenses, beside one method per API operation (companies, locations, users, products, connectors, First Alert rules, Insights Hub).
6
6
  - **Conversations** (a user's own login): the conversation layer, `client.conversations`, gives a signed-in person their own calls, tasks and alerts; `client.intelligence` reads calls, transcripts, recording links, alerts, tasks and insights; and the After Call and First Alert webhooks.
7
7
 
8
8
  Zero runtime dependencies (uses the global `fetch`). ESM and CommonJS builds with full types.
9
9
 
10
- The API reference is at https://docs.intelligence.cloud/reference.html; the source of truth is https://docs.intelligence.cloud/openapi.yaml.
10
+ SDK documentation: overview https://docs.intelligence.cloud/sdk/, quick start https://docs.intelligence.cloud/sdk/quick-start, every helper https://docs.intelligence.cloud/sdk/reference, events https://docs.intelligence.cloud/sdk/events, client options and errors https://docs.intelligence.cloud/sdk/configuration, downloads and versions https://docs.intelligence.cloud/sdk/downloads, testing https://docs.intelligence.cloud/sdk/testing. The API itself: the guide https://docs.intelligence.cloud/api and the API reference https://docs.intelligence.cloud/reference, built from https://docs.intelligence.cloud/openapi.yaml.
11
11
 
12
12
  ## Install
13
13
 
@@ -17,11 +17,11 @@ npm install @intelligence-cloud/sdk
17
17
 
18
18
  The package holds only the compiled SDK and pulls in no dependencies.
19
19
 
20
- Alternative, from the source download: it includes a packed build, `intelligence-cloud-sdk-0.2.0.tgz`.
20
+ Alternative, from the source download: it includes a packed build, `intelligence-cloud-sdk-0.3.0.tgz`.
21
21
 
22
22
  ```bash
23
23
  unzip typescript.zip -d vendor-src # creates vendor-src/typescript
24
- npm install ./vendor-src/typescript/intelligence-cloud-sdk-0.2.0.tgz # from your project
24
+ npm install ./vendor-src/typescript/intelligence-cloud-sdk-0.3.0.tgz # from your project
25
25
  ```
26
26
 
27
27
  ```ts
@@ -29,6 +29,8 @@ import { Client } from "@intelligence-cloud/sdk"; // ESM
29
29
  const { Client } = require("@intelligence-cloud/sdk"); // CommonJS
30
30
  ```
31
31
 
32
+ The fake API for your tests is a separate entry, `@intelligence-cloud/sdk/testing` (ESM and CommonJS, with types); the main entry does not contain it. See "Testing your code".
33
+
32
34
  To rebuild from source: `npm install && npm run build && npm pack` in the SDK folder (the dev tools stay in that folder). `npm run generate` regenerates the types and operation table from `openapi.yaml` (download it from https://docs.intelligence.cloud/openapi.yaml and pass its path: `node scripts/generate.mjs openapi.yaml`).
33
35
 
34
36
  ## Credentials
@@ -40,19 +42,22 @@ Use one client per credential:
40
42
  | Client | Login | For |
41
43
  |---|---|---|
42
44
  | Admin (`IC_ADMIN_EMAIL`, `IC_ADMIN_PASSWORD` in the examples) | a reseller admin login (`reseller_admin`) | `client.accounts`, `client.companies`, `client.users`, … |
43
- | Data (`IC_DATA_EMAIL`, `IC_DATA_PASSWORD` in the examples) | a frontline login (`frontline_user`), a person's own or an integration user mapped to the lines you need | `client.conversations` and `client.intelligence` (calls, alerts, tasks, insights) |
45
+ | Data (`IC_USER_EMAIL`, `IC_USER_PASSWORD` in the examples) | a frontline login (`frontline_user`), a person's own or an integration user mapped to the lines you need | `client.conversations` and `client.intelligence` (calls, alerts, tasks, insights) |
44
46
 
45
47
  Admin logins get empty lists from the conversation-data endpoints by design. The intelligence helpers check the role once and throw `FrontlineRequiredError` instead of returning nothing; `client.conversations` throws `WrongLoginError`, and `client.accounts` throws it for a user login.
46
48
 
47
49
  ```ts
48
50
  const ic = new Client({
49
- email: process.env.IC_DATA_EMAIL!,
50
- password: process.env.IC_DATA_PASSWORD!,
51
+ email: process.env.IC_USER_EMAIL!,
52
+ password: process.env.IC_USER_PASSWORD!,
51
53
  // baseUrl: "https://app.intelligence.cloud/api/v1", (default; https only, plain http for localhost only)
52
54
  // timeout: 30, (seconds)
53
55
  // tokenStore: new FileTokenStore("/var/lib/my-app/ic-tokens.json"), (default: memory)
54
56
  // loginRateLimitWait: 60, (seconds to wait once on a sign-in 429; 0 throws at once)
55
57
  // keepUnknownFields: false, (true keeps fields the reference doesn't list yet)
58
+ // deadline: 120, (seconds one API request may take in all: sign-in, renewal, retries and waits included; see "Retries")
59
+ // maxRetries: 3,
60
+ // sleep, clock: test hooks (see below)
56
61
  // maskNumbers: true, (client.conversations shows caller numbers as their last four digits; false shows them in full)
57
62
  // appUrl: "https://app.intelligence.cloud", (links on call and alert briefs; https only)
58
63
  // userAgent: "riverbend-bi-sync/1.0",
@@ -61,14 +66,16 @@ const ic = new Client({
61
66
 
62
67
  If you pass your own `fetch`, keep certificate verification on.
63
68
 
69
+ Two options are **test hooks**: `sleep` (default a `setTimeout` wait, in milliseconds) is called for every wait (retries, Retry-After, connector checks), and `clock` (default `performance.now`, milliseconds) is read for the deadline. Pass your own to run waits instantly or drive time in a test (`@intelligence-cloud/sdk/testing` passes a no-op `sleep`). `timeout` is the per-attempt HTTP timeout; it is not the connector settle timeout, which `ConnectorSpec.timeout` sets (default 600 seconds).
70
+
64
71
  `keepUnknownFields: true` passes on response fields the reference doesn't list yet, so you can use a new field before you update the SDK. It applies to the customer-lifecycle (admin) reads: `/me`, sign-in and every conversation-data read (calls, transcripts, alerts, tasks, insights) always keep only the documented fields, and the one-time sign-in link is never passed on.
65
72
 
66
73
  ### How the client signs in
67
74
 
68
75
  - It signs in on the first call and keeps the access and refresh tokens in its token store.
69
76
  - It renews the access token before it expires and once after a 401. Refresh tokens are **single use**: the SDK marks the old one spent before sending it and stores the new pair before using it. Renewals are serialised, so concurrent calls share one refresh.
70
- - Sign-in is rate limited. On a 429 at sign-in the client waits `loginRateLimitWait` seconds (60) once; set it to 0 inside a web request to fail at once.
71
- - A rate-limited renewal (429) waits and retries the same refresh token; it never falls back to a sign-in. Any `Retry-After` over 60 seconds is not waited on: the client throws `RateLimitError` (`retryAfter` in seconds).
77
+ - Sign-in is rate limited (5 a minute). On a 429 at sign-in the client waits `Retry-After` once, but only when it fits in `loginRateLimitWait` (60 seconds): a longer one throws `RateLimitError` at once with `retryAfter`. Set `loginRateLimitWait` to 0 inside a web request to fail at once. Sign-in is also retried after a failure that never left or a 5xx, but not after a timeout or reset once the request was sent (see "Retries").
78
+ - A refresh token is sent again **only** after a 429 or a failure where the request provably never left this machine. After a 5xx, a failure after the request left, or an unreadable answer the client signs in instead: sending a used refresh token ends every session of the login. See "Retries" for which failures count as "never left".
72
79
  - An integration user with MFA on gets `MfaRequiredError`: "Integration users need MFA off for their company. API keys arrive in December 2026."
73
80
  - A sign-in with an expired password throws `PasswordExpiredError`: a person must set a new password for the integration user in the app; then update your secret store.
74
81
 
@@ -90,10 +97,23 @@ The client signs in and renews inside `withLock`, and re-reads the store first,
90
97
 
91
98
  ## Quick start: conversation intelligence
92
99
 
100
+ The samples in this README use top-level `await`. That needs an ES module project (`"type": "module"` in `package.json`, or a `.mjs` file); otherwise wrap them in an async function. In a CommonJS project:
101
+
102
+ ```js
103
+ const { Client } = require("@intelligence-cloud/sdk");
104
+
105
+ async function main() {
106
+ const ic = new Client({ email: process.env.IC_USER_EMAIL, password: process.env.IC_USER_PASSWORD });
107
+ await ic.requireFrontline();
108
+ // ... the rest of the sample
109
+ }
110
+ main().catch((e) => { console.error(e); process.exit(1); });
111
+ ```
112
+
93
113
  ```ts
94
114
  import { Client } from "@intelligence-cloud/sdk";
95
115
 
96
- const ic = new Client({ email: process.env.IC_DATA_EMAIL!, password: process.env.IC_DATA_PASSWORD! });
116
+ const ic = new Client({ email: process.env.IC_USER_EMAIL!, password: process.env.IC_USER_PASSWORD! });
97
117
  await ic.requireFrontline();
98
118
 
99
119
  const since = new Date(Date.now() - 24 * 3600 * 1000);
@@ -185,35 +205,50 @@ Each processed call at the location is POSTed to the URL (`type: "end_of_call_su
185
205
  - Answer 2xx within 2 seconds and do the work after responding. Redirects count as failures.
186
206
  - Answer 2xx to event types you don't handle (`isUnknownEvent`) and ignore them. Answer 400 only for a body that isn't JSON, 413 for a body over 256 KB, 404 for a wrong token.
187
207
  - Treat the event as a notification: read the call with `getCall(event.call.id)` before you write anything from it into another system. A 404 means drop it.
188
- - Three attempts in all, then the delivery is dropped. Expect duplicates (retries, calls with several legs): upsert on `call.id`.
208
+ - Three attempts in all, then the delivery is dropped.
209
+ - **Store by call id and upsert.** The same call can arrive again (retries, calls with several legs), and **a later delivery can carry newer data**: it replaces the earlier one. Store each delivery durably under `upsertKey(event)` (the call id) before acknowledging. Never drop a delivery because its call id was seen before.
210
+ - **Check, compare, store, remember.** `Deduplicator.seen(event)` only checks whether this exact delivery was remembered; `remember(event)` records it and is called **after** your durable write. In order: parse, then if `seen(event)` answer 2xx, then load what is stored under `upsertKey(event)`, then if `isOlder(event, stored)` call `remember(event)` and answer 2xx without storing, else upsert, then `remember(event)`, then answer 2xx. If the write fails, answer 5xx and do not remember: the sender's retry is then processed. `isOlder(event, stored)` compares the events' own `timestamp` fields (`stored` is the stored event, its body or its timestamp; false when either has none). **Ordering relies on the event's timestamp; when two deliveries carry the same timestamp, the later arrival wins.** Without the comparison, a v1 that failed to store and is retried after v2 was stored would overwrite newer data with older. An exact re-delivery is the same event type, location and call id with the same content (a SHA-256 of the canonical JSON body, because the payload carries no version marker); a later delivery with newer data is not seen. **Limits of the check.** Two identical deliveries that arrive at the same moment can both be "not seen" (neither is remembered yet): that is harmless because storing is an upsert. A delivery that differs from an earlier one only in a field the published event does not list is treated as a duplicate, because unlisted fields are dropped before the key is made. `seen` and `remember` take an event, a parsed body or the raw request body (which must be I-JSON: valid UTF-8, no lone surrogates, no repeated key in one object, only finite numbers; the parsers refuse anything else); a plain id is refused (`InvalidRequestError`), because an id alone cannot tell newer data apart.
211
+ - The default store is **in memory and per process**: with more than one worker or process it misses deliveries the others remembered. Pass a shared store with `has(key)` and `add(key)` (both may be async), for example over a key-value store your workers share: `new Deduplicator({ store: { has: async (k) => (await kv.exists("ic:" + k)) === 1, add: async (k) => void (await kv.set("ic:" + k, "1", { expiresIn: 86400 })) } })`, where `kv` is your own client.
189
212
 
190
213
  ```ts
191
- import { Deduplicator, isUnknownEvent, parseAfterCallEvent } from "@intelligence-cloud/sdk";
214
+ import { Deduplicator, isOlder, isUnknownEvent, parseAfterCallEvent, upsertKey } from "@intelligence-cloud/sdk";
192
215
 
193
216
  const dedup = new Deduplicator(); // in-memory LRU; pass { store } for a shared store (a database or cache)
194
217
 
195
218
  const event = parseAfterCallEvent(rawBody); // WebhookPayloadError (400) / PayloadTooLargeError (413)
196
219
  if (isUnknownEvent(event)) return; // a type you don't handle: answer 2xx
197
- if (!event.is_test && !(await dedup.isDuplicate(event.call.id))) {
198
- queue.push(event.call.id); // read the call later with getCall(event.call.id)
220
+ if (event.is_test || (await dedup.seen(event))) return; // an exact re-delivery you already stored: answer 2xx
221
+ try {
222
+ const stored = await db.get(upsertKey(event)); // what you stored for this call, or null
223
+ if (stored && isOlder(event, stored.timestamp)) {
224
+ await dedup.remember(event); // an older delivery arriving late: keep the newer data
225
+ return; // answer 2xx
226
+ }
227
+ await db.upsert(upsertKey(event), event); // durable, keyed on the call id: newer data replaces older
228
+ } catch {
229
+ return new Response(null, { status: 503 }); // not remembered: the sender's retry is processed
199
230
  }
231
+ await dedup.remember(event); // only after the write
232
+ // answer 2xx; read the call later with getCall(event.call.id)
200
233
  ```
201
234
 
202
- `parseAfterCallEvent(body, { maxBytes })` refuses bodies over `MAX_EVENT_BYTES` (262144). `Deduplicator.isDuplicate(id)` is true for a repeat (the same name and meaning in the Python and PHP SDKs; the older `seen` still works). `examples/after-call-sample.json` is a sample event: post it to your receiver locally, e.g. `curl -X POST http://localhost:3000/api/ic-webhook/$IC_WEBHOOK_TOKEN -H 'Content-Type: application/json' -d @examples/after-call-sample.json`.
235
+ `parseAfterCallEvent(body, { maxBytes })` refuses bodies over `MAX_EVENT_BYTES` (262144). The in-memory store keeps the last 10,000 delivery keys. The key is a SHA-256 of the RFC 8785 (JSON Canonicalization Scheme) text of the event as projected onto the published fields: numbers are IEEE-754 doubles written as in JavaScript, so integers beyond 2^53 collapse to the nearest double by rule, in every SDK language; the key is the same text in the Python and PHP SDKs for the same event (shared test vectors pin it). `examples/after-call-sample.json` is a sample event: post it to your receiver locally, e.g. `curl -X POST http://localhost:3000/api/ic-webhook/$IC_WEBHOOK_TOKEN -H 'Content-Type: application/json' -d @examples/after-call-sample.json`.
203
236
 
204
- The Next.js route handler in `examples/nextjs/app/api/ic-webhook/[token]/route.ts` shows the whole receiver: path token, size cap, parse, de-duplicate, respond, then read the call with `after()`.
237
+ The Next.js route handler in `examples/nextjs/app/api/ic-webhook/[token]/route.ts` shows the whole receiver: path token, size cap, parse, check, compare with what is stored, upsert, remember, respond, then read the call with `after()`.
205
238
 
206
239
  ## Receiving the First Alert webhook
207
240
 
208
241
  Webhooks are how your integration hears about new calls and alerts: the After Call webhook for every call, the First Alert webhook for each alert as it fires. Subscribe to them; don't poll the API for new data.
209
242
 
210
- The First Alert webhook posts the alert that fired: the alert id, the rule, the location, the call and the time. Read only the alert id, answer 2xx at once, then fetch the alert and its call with a frontline integration user in every alert group:
243
+ The First Alert webhook posts the alert that fired: the alert id, the rule, the location, the call and the time. **The First Alert payload is not final yet.** `parseFirstAlertEvent` returns a `FirstAlertEvent`: `alertId` (letters, digits, `-` and `_`, at most 128 characters, kept as sent, under `alert_id`, else `alert.id`, else `id`; the first present decides, and anything else is refused), and `rule`, `locationId`, `callId` and `timestamp` when the delivery carries them in the shapes known today; `raw` holds the whole payload. Take the alert id, answer 2xx at once, then fetch the alert and its call with a login that is in every alert group:
211
244
 
212
245
  ```ts
213
- const alertId = alertIdFrom(await request.text()); // parseFirstAlertEvent(body).alertId; see examples/nextjs/app/api/ic-alert-webhook/[token]/route.ts
214
- if (alertId && !(await alertDedup.isDuplicate(alertId))) { // a second Deduplicator, keyed on the alert id
246
+ const event = parseFirstAlertEvent(await request.text()); // WebhookPayloadError (400): no valid alert id
247
+ if (!(await alertDedup.seen(event))) { // a second Deduplicator
248
+ await alertQueue.put(event.alertId); // durable; answer 5xx if this fails
249
+ await alertDedup.remember(event); // after the write
215
250
  after(async () => {
216
- const alert = await ic.getAlert(alertId, { withCall: true }); // null when this login can't see it
251
+ const alert = await ic.getAlert(event.alertId, { withCall: true }); // null when this login can't see it
217
252
  if (alert?.id && alert.call_id) await pageOnCallManager(alert.id, alert.call_id); // ids only
218
253
  });
219
254
  }
@@ -223,7 +258,10 @@ If your receiver was unavailable, read the window you missed once and skip alert
223
258
 
224
259
  ```ts
225
260
  for await (const a of ic.iterAlerts({ dateFrom: new Date(wentDown.getTime() - 30 * 60_000), dateTo: cameBack })) {
226
- if (a.id && !(await alertDedup.isDuplicate(a.id))) await handleAlert(a.id);
261
+ if (a.id && !handled.has(a.id)) { // your own store of handled alert ids
262
+ handled.add(a.id);
263
+ await handleAlert(a.id);
264
+ }
227
265
  }
228
266
  ```
229
267
 
@@ -243,7 +281,7 @@ const phoneSystem = ConnectorSpec.netsapiens("https://pbx.example.com/ns-api/v2"
243
281
 
244
282
  const customer = await admin.accounts.createCustomer({
245
283
  companyId: savedCompanyId, // null the first time; store customer.companyId and pass it on re-runs
246
- companyName: "Riverbend Dental",
284
+ companyName: "Riverbend Auto Group",
247
285
  admin: { email: "pat.lee@example.com", firstName: "Pat", lastName: "Lee", phoneNumber: "+15555550100" },
248
286
  team: { name: "Riverbend - Main", street: "1 River Rd", city: "Springfield", state: "IL", country: "US", zipcode: "62701", vertical: "<vertical id or key>" },
249
287
  connector: phoneSystem, // used for the team and for Management
@@ -254,7 +292,7 @@ const team = customer.teams[0]!;
254
292
 
255
293
  await admin.accounts.addBaseUser(customer, { email: "sam.ortiz@example.com", firstName: "Sam", lastName: "Ortiz" }, { team, line: "2101" });
256
294
  await admin.accounts.addBaseManager(customer, { email: "dana.cho@example.com", firstName: "Dana", lastName: "Cho" }, { teams: [team], line: "2001" });
257
- await admin.accounts.activateAlerts(customer); // once each team has a manager in its alert groups
295
+ await admin.accounts.activateAlerts(customer); // every team; a team with no manager is listed in the result
258
296
  ```
259
297
 
260
298
  Optional settings go in one options object as the last argument; names are the camelCase form of the field names in the other SDKs.
@@ -284,15 +322,27 @@ Optional settings go in one options object as the last argument; names are the c
284
322
  | `changeLicense(customer, userId, to, { teams?, line? })` | `"base_manager"` or `"base_user"`, moving their own line between the team and Management | `Member` |
285
323
  | `moveUser(customer, userId, { fromTeam, toTeam })` | Moves a Base User's membership and line, or swaps one of a manager's teams; call history stays with the old team | `Member` |
286
324
  | `changeLine(customer, userId, old, new)` | A Base User's line: their mapping and the team's lists (a line another Base User still holds stays listed). A manager's own line at Management only | `Member` |
287
- | `removeUser(customer, userId, { keepLines? })` | Clears groups and lines, then deactivates; `notes` names teams left with no manager in an alert group (alerts are not changed) | summary |
288
- | `activateAlerts(customer, { team? })` | Switches alerts on where each alert group has a manager | `{ switchedOn, noManager }` (noManager: teams whose alert groups have no manager, with those groups) |
325
+ | `removeUser(customer, userId, { keepLines? })` | Clears groups and lines, then deactivates; `notes` names teams left with no manager in an alert group (alerts are not changed) | `RemovalSummary` (`userId`, `license`, `releasedLines`, `deactivated`, `notes`) |
326
+ | `activateAlerts(customer, { team? })` | Switches alerts on for every team | `AlertActivation` (`switchedOn`, `noManager`: `NoManagerTeam[]`, the teams whose alert groups have no manager, with those groups) |
289
327
  | `sendInvitations(customer, { userIds? })` | Sends invitations not yet sent or expired; re-sends to `userIds` | user ids |
290
328
  | `listMembers(customer, { license?, team? })` | Everyone, with license (`base_user`, `base_manager`, `integration`, `other`), teams and lines | `Member[]` |
291
- | `licenseReport(customer)` | People by license and the number of teams (Management not counted) | counts and members |
292
- | `syncLines(customer, { dryRun? })` | Makes every line list match the people. Someone with After Call and one line who reads back as `other` keeps their line and is listed under `other` | changes |
293
- | `offboardCustomer(customer, { deactivateCompany? })` | Pauses webhooks, stops every connector, deactivates integration users and the company | summary |
329
+ | `licenseReport(customer)` | People by license and the number of teams (Management not counted) | `LicenseReport` (`baseUser`, `baseManager`, `integration`, `other`, `teams`, `members`) |
330
+ | `syncLines(customer, { dryRun? })` | Makes every line list match the people. Someone with After Call and one line who reads back as `other` keeps their line and is listed under `other` | `LineSyncReport` (`teams`: `TeamLines` by location id, `applied`) |
331
+ | `offboardCustomer(customer, { deactivateCompany? })` | Pauses webhooks, stops every connector, deactivates integration users and the company | `OffboardSummary` |
332
+
333
+ The results have the same field names in every SDK (camelCase here). A `Member` lists **every** team the person is on after the call, not only the teams named in it. A line (extension or number) must be the whole value `+?[0-9*#]{1,32}`: `"21 10"` or `"21-10"` throws `InvalidRequestError` before any request.
294
334
 
295
- Every helper that takes `customer` also takes a company id. `team` is a `Team`, its location id or its name. Lines need a **running** connector: a refused mapping throws `AccountError` whose `.cause` is `ExtensionMappingError`, and no invitation is sent. An extension belongs to one location only: a clash throws `ConflictError` with the message "Extension is already monitored at another location."
335
+ Every helper that takes `customer` also takes a company id. `team` is a `Team`, its location id or its name. Lines need a **running** connector: a refused mapping throws `AccountError` whose `.cause` is `ExtensionMappingError`, and no invitation is sent. An extension belongs to one location only. A line another location already holds reaches you as **`AccountError` → `ExtensionMappingError` → `ConflictError`** (message "Extension is already monitored at another location.", the clashing numbers on `.extensions`). Use `AccountError.find` instead of walking the chain:
336
+
337
+ ```ts
338
+ try {
339
+ await admin.accounts.addBaseUser(customer, person, { team, line: "2101" });
340
+ } catch (err) {
341
+ if (!(err instanceof AccountError)) throw err;
342
+ const clash = err.find(ConflictError); // undefined when the stop had another cause
343
+ if (clash) console.log("already captured at another location:", clash.extensions);
344
+ }
345
+ ```
296
346
 
297
347
  A customer built with 0.1.x is not converted: `getCustomer` lists what its layout is missing in `pending`.
298
348
 
@@ -309,12 +359,13 @@ for (const brief of await me.conversations.calls()) { // today, newest fir
309
359
  const history = await me.conversations.callerHistory("5555550142", { limit: 5 });
310
360
  const detail = await me.conversations.brief(callId); // summary, key points, tasks, sentiment, topics, alerts
311
361
  const tasks = await me.conversations.openTasks();
312
- const board = await me.conversations.teamView(teamId); // for a manager: counts, alerts, open tasks, briefs
362
+ const myTeam = (await me.conversations.teams()).find((t) => t.kind === "team")!; // teams first, Management last
363
+ const board = await me.conversations.teamView(myTeam); // for a manager: counts, alerts, open tasks, briefs
313
364
  ```
314
365
 
315
366
  | Helper | Returns | Limits |
316
367
  |---|---|---|
317
- | `me()`, `teams()` | Who is signed in and the teams they can see. `me().lines` is `null`: the API gives a user login no way to read its own lines | |
368
+ | `me()`, `teams()` | Who is signed in and the teams they can see: `kind === "team"` first in name order, Management last. `me().lines` is `null`: the API gives a user login no way to read its own lines | |
318
369
  | `calls({ day?, since?, until?, team?, number?, search?, limit? = 50 })` | `CallBrief[]`, newest first; default today | window at most 31 days, `limit` at most 200 |
319
370
  | `brief(callId)` | One `CallBrief` with key points, tasks, topics and the alerts it raised (read from one page of that day's alerts, so a day with more than 100 alerts can miss some) | no transcript, no recording |
320
371
  | `transcript(callId)` | The transcript of one call | one call per request |
@@ -378,6 +429,28 @@ What the SDK does for you on these:
378
429
  - The connector dry run and the webhook tests return only `success` and the HTTP status.
379
430
  - `client.intelligence` holds the read helpers; the same methods are also on the client itself. `client.accounts` and `client.conversations` are the two layers above.
380
431
 
432
+ ## Retries
433
+
434
+ One policy, the same in every SDK:
435
+
436
+ | Situation | What the client does |
437
+ |---|---|
438
+ | Network failure (no connection, timeout) or 5xx on a read, update, delete, or user create (which carries an idempotency key, reused on every try) | Retries up to `maxRetries` (3) times with exponential backoff and jitter: about 0.5, 1 and 2 seconds plus up to half again |
439
+ | Sign-in | Retried after a failure that provably never left, after a 5xx, and after a 429 whose `Retry-After` is within the wait limit (it waits once). A timeout, a reset or any failure **after** the request was sent is **not** retried: the error is thrown |
440
+ | Token renewal | The refresh token is sent again **only** after a 429 (the server did not use it) or after a failure where the request provably never left this machine (see below). Any other outcome (a 5xx, a failure after the request left, an unreadable answer) may have used it: it is never resent, and the client signs in instead |
441
+ | Network failure or 5xx on any other create | Not retried: the error is thrown, so nothing is created twice |
442
+ | 429 with `Retry-After` within the limit (60 s; for sign-in, `loginRateLimitWait`, default 60 s) | Waits `Retry-After` (backoff when absent or not plain seconds), then retries; sign-in waits once |
443
+ | 429 with `Retry-After` above the limit | Throws `RateLimitError` at once with `retryAfter` set; it never waits first and then fails |
444
+ | 401 on a request | Renews the token once and retries |
445
+
446
+ **Which fetch failures "never left".** Node's `fetch` reports a failure as a `TypeError("fetch failed")` whose `cause` carries a code. The SDK treats a failure as *never left this machine* only when every code found says so. An errno-style code (`ENOTFOUND`, `EAI_AGAIN`, `EAI_FAIL`, `ECONNREFUSED`, `ENETUNREACH`, `EHOSTUNREACH`, `ETIMEDOUT`) counts only when its `syscall` is `connect` or `getaddrinfo`, because the same codes also come from an established socket after the request was written (`syscall` `read` or `write`). Always counted: `UND_ERR_CONNECT_TIMEOUT` (no connection made in time), `ERR_INVALID_URL` and the TLS certificate refusals (`CERT_HAS_EXPIRED`, `DEPTH_ZERO_SELF_SIGNED_CERT`, `SELF_SIGNED_CERT_IN_CHAIN`, `UNABLE_TO_VERIFY_LEAF_SIGNATURE`, `UNABLE_TO_GET_ISSUER_CERT_LOCALLY`, `ERR_TLS_CERT_ALTNAME_INVALID`), all of which stop before the request is written. Everything else *may have left*: an errno-style code without that syscall, a reset or closed socket (`ECONNRESET`, `EPIPE`, `UND_ERR_SOCKET`), a timeout after the connection was made (`UND_ERR_HEADERS_TIMEOUT`, `UND_ERR_BODY_TIMEOUT`, `ETIMEDOUT`, and the SDK's own per-attempt timeout), a body that cannot be read, a failure with no code, or a mix of codes. When in doubt it is "may have left". `NetworkError.requestSent` is `false` only in the first case.
447
+
448
+ **Bounds.** One API request, including the sign-in or token renewal it needs and every retry and wait, never runs past **`deadline`** (default **120 seconds**). When the time left cannot cover the next wait, the client stops at once: `RateLimitError` (with `retryAfter`) after a 429, `NetworkError` with `kind` `"timeout"` after network failures, or the last 5xx as an `ApiError`. Each attempt is aborted after `timeout` (30 s) or the time left, whichever is less. Helpers that make many requests (`createCustomer`) apply the deadline to each request. Connector settle waits are not counted: they have their own `timeout` (600 s). Inside a web request, pass a smaller `deadline` (for example 10), `loginRateLimitWait: 0` and `maxRetries: 1`.
449
+
450
+ **Retry-After** counts only as plain decimal seconds, `[0-9]{1,9}` with an optional fraction (`5`, `1.5`); a date, a sign, an exponent, a space or a number of ten digits is treated as absent. `RateLimitError.retryAfter` is a number of seconds.
451
+
452
+ **Checks first.** Every helper of both layers checks its arguments, types included, before it signs in or sends anything, and before it joins the write queue (the generated methods check the JSON type of every top-level body field against the spec the same way), so a bad argument is refused at once rather than after earlier helpers finish. Bad input throws `InvalidRequestError` with no request made, so it costs no sign-in. An id that goes into a URL (a company, user, call, alert or location id) must be a non-empty string of at most 128 characters (counted as code points) that is not `.` or `..` and has no `/`, `\`, `?`, `#`, `%`, whitespace (nothing is trimmed: a leading or trailing space or newline is refused) or control character (including U+0080 to U+009F and U+FEFF); free text and numbers must be real strings of at most 200 characters. Lists passed as `teams`, `userIds` or `phrases` may be any iterable and are read once.
453
+
381
454
  ## Filters and validation
382
455
 
383
456
  The API ignores parameters it doesn't know and returns unfiltered data. The SDK accepts only the documented filters and checks them **before** sending:
@@ -389,27 +462,31 @@ The API ignores parameters it doesn't know and returns unfiltered data. The SDK
389
462
 
390
463
  ## Errors
391
464
 
465
+ The error tree is the same in every SDK language:
466
+
392
467
  ```
393
468
  IntelligenceCloudError
394
- ├── ApiError (status, code, message, requestId, operationId, serverMessage)
395
- │ ├── AuthError 401 (MfaRequiredError: MFA on; PasswordExpiredError: password expired)
396
- │ ├── NotFoundError 404, also for records outside your login's scope
397
- │ ├── ConflictError 409 (extensions: the refused extensions on a number conflict; code company_name_conflict)
398
- │ ├── ValidationError 400, 422
399
- │ └── RateLimitError 429 after retries (retryAfter in seconds)
400
- ├── InvalidRequestError bad input, refused by the SDK before sending (FilterError is an alias)
401
- ├── WrongLoginError an account helper with a user login, or a conversation helper with an administrator login
402
- ├── FrontlineRequiredError conversation data requested with an admin login (client.intelligence)
403
- ├── AccountError an account helper stopped part-way (step, result, cause); run it again
404
- ├── ConnectorError connector ended in error (stateReason)
405
- ├── ConnectorTimeoutError a new connector did not settle in time
406
- ├── ExtensionMappingError a helper could not map a user's numbers (userId, cause)
407
- └── WebhookPayloadError body isn't a JSON object, or a malformed After Call or First Alert event (400)
408
- └── PayloadTooLargeError body over 256 KB (413)
469
+ ├─ ApiError (status, code, serverMessage, requestId, operationId)
470
+ │ ├─ AuthError (401: sign-in failed, or the token could not be renewed)
471
+ │ │ ├─ MfaRequiredError (the integration user's company has MFA on)
472
+ │ │ └─ PasswordExpiredError
473
+ │ ├─ NotFoundError (404: not found, or outside what this login can see)
474
+ │ ├─ ConflictError (409: duplicate, already active or inactive, extension held elsewhere; .extensions)
475
+ │ ├─ ValidationError (400, 422)
476
+ │ ├─ RateLimitError (429; .retryAfter)
477
+ │ └─ NetworkError (status 0; .kind transport | timeout | decoding; .requestSent; the underlying error is not attached)
478
+ ├─ InvalidRequestError (bad input, refused before sending; FilterError is an alias)
479
+ ├─ WrongLoginError (the other kind of login is needed; the message says which)
480
+ │ └─ FrontlineRequiredError (client.intelligence asked for conversation data with an admin login)
481
+ ├─ ConnectorError (a connector ended in error; .stateReason)
482
+ │ └─ ConnectorTimeoutError (a new connector did not settle in time)
483
+ ├─ ExtensionMappingError (numbers not mapped; .userId, .cause)
484
+ ├─ AccountError (an account helper stopped part-way; .step, .result, .cause, .find(ErrorClass))
485
+ └─ WebhookPayloadError (a webhook body is not JSON or is malformed: answer 400)
486
+ └─ PayloadTooLargeError (over 256 KB: answer 413)
409
487
  ```
410
488
 
411
- - 429 and 5xx are retried up to 3 times with backoff and jitter, honouring `Retry-After` up to 60 seconds (a longer `Retry-After` is thrown at once). A `POST` is retried on 5xx only when it carries an `Idempotency-Key`.
412
- - The API's different error shapes are normalised into `status`, `code` and `requestId`. The exception text (`message`) never carries the server's error text, which can echo phone numbers or names: it reads e.g. `HTTP 422 VALIDATION_ERROR (request_id …)`. The server's text is on `serverMessage`.
489
+ - The API's different error shapes are normalised into `status`, `code` and `requestId`. The exception text (`message`) never carries the server's error text, which can echo phone numbers or names: it reads e.g. `HTTP 422 VALIDATION_ERROR (request_id …)`. The server's text is on `serverMessage`; keep it out of logs.
413
490
  - Log `status`, `code` and `requestId`, not exception text or response bodies.
414
491
  - The text of a 409 on number mappings is replaced with "Extension is already monitored at another location." and `extensions` lists the requested extensions that were refused.
415
492
  - Show your own messages to end users.
@@ -426,6 +503,171 @@ try {
426
503
  }
427
504
  ```
428
505
 
506
+ ## Testing your code
507
+
508
+ The samples here use top-level `await` too: use an ES module project (`"type": "module"`) or wrap them in an async function, as shown under Quick start.
509
+
510
+ `@intelligence-cloud/sdk/testing` is a supported fake API: run your code and CI with no account and no network. `api.client({ role: "admin" | "user", ...options })` returns a real `Client` wired to it.
511
+
512
+ ```js
513
+ import assert from "node:assert/strict";
514
+ import { AccountError, ValidationError } from "@intelligence-cloud/sdk";
515
+ import { FakeAPI } from "@intelligence-cloud/sdk/testing";
516
+
517
+ const person = { email: "sam.ortiz@example.com", firstName: "Sam", lastName: "Ortiz" };
518
+
519
+ export async function testAddsABaseUser() {
520
+ const api = new FakeAPI();
521
+ const seeded = await api.seedCustomer(); // "Riverbend Auto Group": fictional data
522
+ const admin = api.client({ role: "admin" });
523
+ const team = seeded.customer.teams[0];
524
+ const member = await admin.accounts.addBaseUser(seeded.customer, person, { team, line: "2109" });
525
+ assert.equal(member.license, "base_user");
526
+ assert.ok(api.writes.some(([method, path]) => method === "POST" && path === `/companies/${seeded.companyId}/users`));
527
+ assert.equal(api.faNumbers(team.locationId).at(-1), "2109");
528
+ const start = api.requests.length;
529
+ await admin.accounts.addBaseUser(seeded.customer, person, { team, line: "2109" });
530
+ assert.deepEqual(api.writesSince(start), []); // safe to re-run
531
+ }
532
+
533
+ export async function testReadsTodaysCalls() {
534
+ const api = new FakeAPI();
535
+ const ids = api.seedCalls(3);
536
+ const briefs = await api.client({ role: "user" }).conversations.calls();
537
+ assert.deepEqual(briefs.map((b) => b.id), ids);
538
+ assert.ok(briefs[0].callerNumber.startsWith("***"));
539
+ }
540
+
541
+ export async function testResumesAfterAStop() {
542
+ const api = new FakeAPI();
543
+ const seeded = await api.seedCustomer();
544
+ const admin = api.client({ role: "admin" });
545
+ const team = seeded.customer.teams[0];
546
+ api.failWrite(2); // the second write of the next call fails
547
+ const err = await admin.accounts.addBaseUser(seeded.customer, person, { team, line: "2109" }).catch((e) => e);
548
+ assert.ok(err instanceof AccountError && err.find(ValidationError));
549
+ const again = await admin.accounts.addBaseUser(seeded.customer, person, { team, line: "2109" });
550
+ assert.equal(again.userId, err.result.userId); // running it again continues
551
+ }
552
+ ```
553
+
554
+ | `FakeAPI` | Does |
555
+ |---|---|
556
+ | `new FakeAPI({ connectorOutcome = "active", role = "admin", strict = true })` | A new, empty fake |
557
+ | `client({ role?, asUser?, ...clientOptions })` | A real `Client` (role "admin" or "user"); waits do not sleep unless you pass `sleep`. `fetch` is refused. `asUser` (role "user"): the id or email of a seeded person, so their calls, alerts, tasks and Insights Hub access follow their license and teams; clients for the same person share that login's sessions |
558
+ | `await seedCustomer({ teams = 1, people = true })` | Riverbend Auto Group through the account layer: teams, Management, two Base Users per team, one manager. Returns `SeededCustomer` (`customer`, `companyId`, `baseUsers`, `managers`, `people`: `SeededPerson` with `userId`, `email`, `license`, `teams`, `lines`) |
559
+ | `seedCalls(n = 3, { locationId, day, alerts = true, tasks = true, recording = false, topics = false })` | Fictional calls with details, tasks and alerts (555-01xx numbers), each reaching a seeded Base User's line in turn. `recording: true` adds a recording link (example.com, expires in two hours); `topics: true` fills topic volumes and rising topics. Returns the call ids, newest first |
560
+ | `connectorOutcome` | `"active"`, `"connected"`, `"error"` or `"stuck"` (never settles) for connection attempts made after it is set (a connector created or restarted later); it does not change connectors already waiting |
561
+ | `settleConnector(connectorIdOrLocation, outcome = "active")` | Settle connectors that are waiting: the one with this id, or every waiting one at this location ("active", "connected" or "error") |
562
+ | `failNext({ status, network, signIn, method, path, retryAfter, afterProcessing })` | The next matching request fails once: the next sign-in answers `signIn: "mfa_required"`, `"password_expired"` or `"invalid_credentials"`; or an HTTP status, or `network: "connect"` (never left), `"read_timeout"`, `"write_timeout"` or `"reset"` (the request may have left) or `"undecodable"` (an answer that cannot be read). Each raises the error Node's fetch gives for that failure; `requestSent` is false only for "connect". A status answers **before** the platform acts (a renewal's refresh token is not used); with `afterProcessing: true` the platform acts first (the token is rotated), as a gateway error after processing would. A network failure other than "connect" on a renewal has used its token |
563
+ | `failWrite(nth = 1, status = 400)`, `networkDown(down = true)`, `rateLimit(count = 1, retryAfter = 1)`, `expireAccessTokens()` | Simpler knobs: the nth write fails; no network; 429s; every access token expires (the next call renews) |
564
+ | `requests`, `writes`, `writesSince(start)`, `count(method, pathRegex)`, `resetLog()`, `authLog` | The request log: **every** request the fake received, including those a knob answered, each with `answer` (the HTTP status, or `"network:connect"` and the like), so retries can be counted. Sign-in and renewal attempts are in `authLog` ("login", "refresh", and "refresh_reused" when a used refresh token was sent again, which ends every session of that login, as on the platform) |
565
+ | `products(uid, lid)`, `numbers(uid, connectorId?)`, `faNumbers(lid)`, `ihNumbers(lid)`, `groupMembers(lid, name)` | State to assert on |
566
+
567
+ That table is the whole supported surface; anything else on `FakeAPI` starts with an underscore (or is the client's wiring) and may change.
568
+
569
+ **Strict mode** (`strict: true`) answers with the API's error shape when a request is not what the published spec defines: an unknown path or method (404); an unknown query parameter, or a query value of the wrong type (whole number, true/false), outside its enum or range, or not in its format (uuid, date-time) (400); a body missing a required top-level field, carrying a top-level field the spec does not define, or with a top-level value of the wrong JSON type, outside its enum or not in its format, including each item of a top-level list (422). Formats are the ones the spec names: a whole number is `-?(0|[1-9][0-9]*)`, a date is `YYYY-MM-DD` and a real calendar day, a date-time has seconds, a `T` and `Z` or `±HH:MM` and a real calendar time, a uuid is all lower case or all upper case with hyphens. The spec lists only `netsapiens` as a connector type, so strict mode refuses any other (`strict: false` lets one through). It does **not** check nested objects, rules that join several fields, or how the platform searches and sorts, and it can only refuse what the spec states. Code that passes against it still needs one run against a test company before release.
570
+
571
+ ## Upgrading from 0.2
572
+
573
+ - **Connectors in account helpers:** a connector that does not settle, or ends in error, arrives as `AccountError` (step `"connectors"`) whose cause is `ConnectorTimeoutError` or `ConnectorError`, once everything else is built. A 0.2-style `catch (e instanceof ConnectorTimeoutError)` around `addTeam` no longer catches it:
574
+
575
+ ```ts
576
+ try {
577
+ await admin.accounts.addTeam(customer, team, connector);
578
+ } catch (err) {
579
+ if (!(err instanceof AccountError)) throw err;
580
+ if (err.find(ConnectorTimeoutError)) { // still settling: run addTeam again later
581
+ // ...
582
+ } else if (err.find(ConnectorError)) { // ended in error: check stateReason, fix the key, run again
583
+ // ...
584
+ } else throw err;
585
+ }
586
+ ```
587
+
588
+ The settle timeout is `ConnectorSpec.timeout` (600 s). The client's `timeout` and the `{ timeout }` option of the low-level `connectors.createConnector`, `reactivateConnector` and `deactivateConnector` methods apply only to those methods and HTTP attempts.
589
+ - `Deduplicator.isDuplicate` is gone: `seen(event)` checks, `remember(event)` records after your write (see "Receiving the After Call webhook").
590
+ - A line with a space or a dash is refused before sending; `conversations.teams()` lists Management last.
591
+ - See `CHANGELOG.md` for every breaking change.
592
+
593
+ ## Running helpers from more than one process
594
+
595
+ Within one client, the helpers that write run one at a time (each waits for the one before). Across clients and processes nothing serialises them: account helpers read, merge and write whole lists, so two of them changing the same customer at once can each read the old list and write back their own version, and one change is lost; two runs of `createCustomer` for a new customer can create it twice. Run at most one account helper per customer at a time. On one machine, a lock file is enough:
596
+
597
+ ```js
598
+ import { open, unlink } from "node:fs/promises";
599
+
600
+ export async function withCustomerLock(companyId, fn) {
601
+ const path = `/tmp/ic-customer-${companyId}.lock`;
602
+ for (;;) {
603
+ try {
604
+ const handle = await open(path, "wx"); // fails while another process holds the lock
605
+ await handle.close();
606
+ break;
607
+ } catch (err) {
608
+ if (err.code !== "EEXIST") throw err;
609
+ await new Promise((r) => setTimeout(r, 200)); // wait for the other process
610
+ }
611
+ }
612
+ try {
613
+ return await fn();
614
+ } finally {
615
+ await unlink(path);
616
+ }
617
+ }
618
+
619
+ await withCustomerLock(companyId, () => admin.accounts.addBaseUser(companyId, person, { team, line: "2101" }));
620
+ ```
621
+
622
+ A process that dies while holding the file leaves it behind: delete a lock file older than your longest helper run. Across several machines, use your own database with a lock table keyed by company id: insert the row if it is missing, then lock that row inside a transaction that wraps the helper call. The statements are ordinary SQL (`INSERT ... ON CONFLICT DO NOTHING` or your database's insert-if-missing, then `SELECT ... FOR UPDATE`); `db.transaction` stands for your client's transaction wrapper:
623
+
624
+ ```js
625
+ // create table customer_locks (company_id text primary key)
626
+ export async function withCustomerLock(db, companyId, fn) {
627
+ return db.transaction(async (tx) => {
628
+ await tx.run("INSERT INTO customer_locks (company_id) VALUES (?) ON CONFLICT (company_id) DO NOTHING", [companyId]); // insert if missing
629
+ await tx.run("SELECT company_id FROM customer_locks WHERE company_id = ? FOR UPDATE", [companyId]); // waits for any other holder
630
+ return fn(); // the row stays locked until the transaction ends
631
+ });
632
+ }
633
+ ```
634
+
635
+ Keep the helper call short enough for your transaction timeout. For a new customer, lock on a key you already have (your own account id) until `createCustomer` returns and you have stored `companyId`.
636
+
637
+ ## How many requests
638
+
639
+ Measured against `@intelligence-cloud/sdk/testing` with a fresh client (one `GET /me` included, sign-in not counted); a test pins these numbers. The published limits are **5 requests a second per user, bursts of 20, and 50,000 a day per company**.
640
+
641
+ | Helper | 1-team customer | 10-team customer |
642
+ |---|---|---|
643
+ | `createCustomer` (first run, one team) | 34 | 34 |
644
+ | `addTeam` (the 2nd team; the 10th team) | n/a | 23; 23 (241 for all ten teams) |
645
+ | `createCustomer`, re-run | 18 | 18 |
646
+ | `addBaseUser` (customer passed as a company id) | 36 | 90 |
647
+ | `addBaseManager` (on every team, Customer object) | 32 | 158 |
648
+ | `activateAlerts` (Customer object; company id), rules off before the call | 15; 21 | 105; 120 |
649
+ | `setAlerts` (both phrase alerts, Customer object) | 8 | 62 |
650
+ | `syncLines` (Customer object; company id) | 11; 19 | 65; 100 |
651
+ | `licenseReport` (Customer object; company id) | 8; 16 | 35; 70 |
652
+ | `calls` (one page) | 2 | 2 |
653
+ | `brief` | 3 | 3 |
654
+
655
+ A helper given a company id reads the whole layout first (for a 1-team customer 9 requests: the company, its locations, and each location's groups, rules and connectors, plus the domains); given a `Customer` object it reads only the location list it checks the object against (1 request), plus the groups and rules of each team whose ids it uses (2 per team), so a stale object cannot send a write to the wrong group or rule (a helper that needs a group the team no longer has stops with `InvalidRequestError` before its first write), and passing the object saves 8 requests on a 1-team customer and 35 on a 10-team one for `syncLines` and `licenseReport`. **Worked total:** setting up a ten-team customer end to end with a `Customer` object (create, nine `addTeam`, both phrase alerts, one manager per team, three Base Users per team, activate) takes **2,497 requests**, about **8.3 minutes** at 5 requests a second (a test pins it). If a team was added or stopped elsewhere the object is refreshed in place (`refreshedAt` says when it was last checked). The counts assume a freshly seeded customer with two Base Users per team and one manager, alert rules off before `activateAlerts`, a connector that settles at its first check, and the customer passed as an object to `addTeam`. **Each further 10 seconds a new connector takes to settle adds one request per connector** (one status check). At 5 a second a 10-team `addBaseManager` takes about 30 seconds; the client's retries absorb short 429 bursts.
656
+
657
+ ## Examples
658
+
659
+ The examples are in the source download and the source repository, not in the npm package. Each uses the fictional customer Riverbend Auto Group.
660
+
661
+ | File | Shows | Sign-in |
662
+ |---|---|---|
663
+ | `examples/node/basic.mjs` | Sign in, count calls, read one | user |
664
+ | `examples/node/create-customer.mjs` | Create a customer, add a Base User and a Base Manager, switch the alerts on (dry run unless `--apply`; phrase lists from the files in `IC_THREAT_PHRASES_FILE` and `IC_UPSET_PHRASES_FILE`, optional) | administrator |
665
+ | `examples/node/my-day.mjs` | A person's day: today's call briefs, open tasks and alerts, with masked numbers and no content in logs | user (the person's own login) |
666
+ | `examples/nextjs` | An After Call and a First Alert receiver (parse, check, upsert, remember, respond) and a calls page | user (worker) |
667
+ | `examples/after-call-sample.json` | A sample After Call event for local tests | none |
668
+
669
+ Administrator examples read `IC_ADMIN_EMAIL` and `IC_ADMIN_PASSWORD`; the others read `IC_USER_EMAIL` and `IC_USER_PASSWORD`.
670
+
429
671
  ## Secrets
430
672
 
431
673
  Never log access or refresh tokens, passwords, phone-system keys, webhook URLs or recording links. The SDK logs nothing and never returns the one-time sign-in link the API can include when a user is created. A connector's key is sent once and never kept: it is hidden from `JSON.stringify`, `console.log` and `String()` on `ConnectorSpec`, and it is not in any error message. A `RecordingLink` hides its URL the same way.