@isnap/sdk 2.3.0 → 2.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/CHANGELOG.md +65 -40
  2. package/README.md +360 -167
  3. package/dist/client.d.ts +35 -49
  4. package/dist/client.d.ts.map +1 -1
  5. package/dist/client.js +44 -58
  6. package/dist/client.js.map +1 -1
  7. package/dist/config.d.ts +6 -6
  8. package/dist/config.js +6 -6
  9. package/dist/generated/openapi.d.ts +403 -14
  10. package/dist/internal/sleep.d.ts +2 -2
  11. package/dist/internal/sleep.js +5 -5
  12. package/dist/internal/sleep.js.map +1 -1
  13. package/dist/resources/apps.d.ts +11 -18
  14. package/dist/resources/apps.d.ts.map +1 -1
  15. package/dist/resources/apps.js +11 -18
  16. package/dist/resources/apps.js.map +1 -1
  17. package/dist/resources/area-codes.d.ts +5 -6
  18. package/dist/resources/area-codes.d.ts.map +1 -1
  19. package/dist/resources/area-codes.js +5 -6
  20. package/dist/resources/area-codes.js.map +1 -1
  21. package/dist/resources/attachments.d.ts +51 -17
  22. package/dist/resources/attachments.d.ts.map +1 -1
  23. package/dist/resources/attachments.js +42 -22
  24. package/dist/resources/attachments.js.map +1 -1
  25. package/dist/resources/byod.d.ts +14 -4
  26. package/dist/resources/byod.d.ts.map +1 -1
  27. package/dist/resources/byod.js +14 -4
  28. package/dist/resources/byod.js.map +1 -1
  29. package/dist/resources/chats.d.ts +30 -22
  30. package/dist/resources/chats.d.ts.map +1 -1
  31. package/dist/resources/chats.js +29 -21
  32. package/dist/resources/chats.js.map +1 -1
  33. package/dist/resources/lines.d.ts +240 -266
  34. package/dist/resources/lines.d.ts.map +1 -1
  35. package/dist/resources/lines.js +240 -266
  36. package/dist/resources/lines.js.map +1 -1
  37. package/dist/resources/lookup.d.ts +10 -13
  38. package/dist/resources/lookup.d.ts.map +1 -1
  39. package/dist/resources/lookup.js +10 -13
  40. package/dist/resources/lookup.js.map +1 -1
  41. package/dist/resources/macos-sessions.d.ts +42 -36
  42. package/dist/resources/macos-sessions.d.ts.map +1 -1
  43. package/dist/resources/macos-sessions.js +24 -22
  44. package/dist/resources/macos-sessions.js.map +1 -1
  45. package/dist/resources/messages.d.ts +35 -25
  46. package/dist/resources/messages.d.ts.map +1 -1
  47. package/dist/resources/messages.js +30 -19
  48. package/dist/resources/messages.js.map +1 -1
  49. package/dist/resources/preorders.d.ts +42 -47
  50. package/dist/resources/preorders.d.ts.map +1 -1
  51. package/dist/resources/preorders.js +42 -47
  52. package/dist/resources/preorders.js.map +1 -1
  53. package/dist/resources/trial.d.ts +30 -21
  54. package/dist/resources/trial.d.ts.map +1 -1
  55. package/dist/resources/trial.js +30 -21
  56. package/dist/resources/trial.js.map +1 -1
  57. package/dist/resources/webhooks.d.ts +39 -22
  58. package/dist/resources/webhooks.d.ts.map +1 -1
  59. package/dist/resources/webhooks.js +39 -22
  60. package/dist/resources/webhooks.js.map +1 -1
  61. package/dist/retry.d.ts +9 -10
  62. package/dist/retry.d.ts.map +1 -1
  63. package/dist/retry.js +11 -12
  64. package/dist/retry.js.map +1 -1
  65. package/dist/types.d.ts +10 -0
  66. package/dist/types.d.ts.map +1 -1
  67. package/dist/version.d.ts +1 -1
  68. package/dist/version.d.ts.map +1 -1
  69. package/dist/version.js +13 -37
  70. package/dist/version.js.map +1 -1
  71. package/dist/webhooks/parse.d.ts +10 -9
  72. package/dist/webhooks/parse.d.ts.map +1 -1
  73. package/dist/webhooks/parse.js +14 -13
  74. package/dist/webhooks/parse.js.map +1 -1
  75. package/dist/webhooks/types.d.ts +74 -110
  76. package/dist/webhooks/types.d.ts.map +1 -1
  77. package/dist/webhooks/types.js.map +1 -1
  78. package/dist/webhooks/verify.d.ts +27 -29
  79. package/dist/webhooks/verify.d.ts.map +1 -1
  80. package/dist/webhooks/verify.js +29 -35
  81. package/dist/webhooks/verify.js.map +1 -1
  82. package/examples/handle-webhook.ts +146 -0
  83. package/examples/paginate-messages.ts +54 -0
  84. package/examples/send-message.ts +37 -0
  85. package/examples/upload-attachment.ts +91 -0
  86. package/package.json +4 -8
package/CHANGELOG.md CHANGED
@@ -1,52 +1,77 @@
1
1
  # Changelog
2
2
 
3
- All notable changes to `@isnap/sdk` will be documented in this file. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). Pre-1.0 versions may introduce breaking changes between 0.x → 0.(x+1) minor bumps.
3
+ All notable changes to `@isnap/sdk` are documented in this file. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the package follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
4
4
 
5
- ## [Unreleased]
5
+ ## [2.3.1]
6
+
7
+ Documentation, type declarations and package metadata. The compiled code is the code of 2.3.0, apart from the version string: no method changes behavior.
8
+
9
+ ### Changed
10
+ - The type declarations and their JSDoc describe the API as it is when this release is built. Those published in 2.2.0 predated API `2.26.0`.
11
+ - **A test line is billed like a rented line** (API `2.27.0`). `lines.convertToTest()` does not stop billing: the test line stays billed, like a two-way rented line, on the same billing dates (`anniversary_at` and `billing_anchor_at` are kept), and `Line.monthly_price` is no longer `0` for it. `lines.convertFromTest()` therefore leaves the billing unchanged. `lines.convertToTest()` refuses an inbound-only line (`ConflictError`, 409 `test_line_not_inbound_only`: make it two-way with `setVariant` first) and a line with a pending cancellation (409 `line_cancellation_pending`: call `uncancel` first). After `lines.terminate()` of a test line, the line's `cancel_at` holds the time it ended. A line transferred to a wholesale partner carries the transfer time as `activated_at`. No SDK code changes: the generated types and the JSDoc carry the new wording.
12
+ - **`lines.assign()`, `lines.convertToTest()` and `lines.convertFromTest()` are for wholesale partners only** (API `2.26.0`). Any other account is a `PaymentRequiredError` (402 `checkout_required`) and nothing is taken or converted, with or without `as_test_line`. `lines.transferOwnership()` of a shared line or a test line to an account that is not a wholesale partner is a `ConflictError` (409 `line_recipient_not_wholesale`). `lines.terminate()` ends a test line once no trial uses it, and is a `ConflictError` (409 `test_line_in_use`) until then. No SDK code changes: the existing error classes carry these refusals.
13
+ - **Pre-orders and the first payment**. The JSDoc of `preOrders.confirm`, `preOrders.get` and `preOrders.cancel` describes the pre-order of a direct account: `confirm()` returns it in `awaiting_payment` with `stripe_client_secret`, nothing is built until the first month is paid, and `cancel()` is free in `draft` and `awaiting_payment`. A wholesale partner's pre-order goes to `provisioning` at confirm, as before. No SDK code changes.
14
+ - **Rate limits are counted per account** for an API key, and per network address for a trial key. The README and the JSDoc say so. An account can have different limits.
15
+ - `lines.release` can be refused with `ConflictError` (409 `purchase_payment_in_progress`) while the first payment of a purchase is running. The `binding.released` event documents the reasons `reclaimed`, `moved`, `owner_contact` and `pool_removed`. No SDK code changes.
16
+ - `README.md` documents `lines.createInvite` and its default of no automatic retry.
17
+ - The four example scripts ship in the package, in `examples/`, and import `@isnap/sdk` like consumer code.
18
+ - `homepage` points to the documentation at `https://docs.isnap.ai`, and `bugs` to `support@isnap.ai`. The `repository` field is removed.
19
+
20
+ ### Fixed
21
+ - `README.md` is rewritten from the behavior of the code. It no longer states the key prefix `sk_live_`, the request fields `service` and `attachment_ids`, retries on every `429` and `5xx`, that a repeated call is deduplicated by default, or a period after `webhooks.rotateSecret` during which the previous secret still signs deliveries.
22
+ - JSDoc corrected where it disagreed with the code. `attachments.upload` throws an `APIError` with status 413 for a file larger than 5 GB, not a `BadRequestError`, and its timeout applies to any attachment that is not `ready`. After `webhooks.rotateSecret`, every delivery is signed with the new secret only. `chats.markRead` marks every unread inbound message of the chat. `lines.release` gives back a reserved line only. `lines.cancel` and `lines.setAnniversary` are for wholesale partners only. `lines.updateConfig` lets a BYOD line raise its five message limits. `byod.pair` is a `NotFoundError` (404 `no_slot_available`) when every slot is used. `trial.status`, `chats.shareContactCard`, and `lines.assign` with `as_test_line` say when to call them with `maxRetries: 0`. A `preOrders.cancel` or a `preOrders.confirm` that loses a race with another confirm or cancel of the same pre-order is a `ConflictError` (409). Pointers to operations that an API key cannot call are removed.
23
+ - `ErrorIssue.path` is documented as what it is at run time, an array of strings and numbers. Its declared type, `string`, is unchanged in this release.
24
+ - Examples: the key prefix is `isnap_live_` or `isnap_test_`, `messages.list` yields the newest message first, `upload-attachment.ts` reads the attachment every 2 seconds for up to 2 minutes and handles `upload_timeout`, and `handle-webhook.ts` records an event only once its work has succeeded and no longer logs the `data` of an event.
25
+
26
+ ## [2.3.0]
27
+
28
+ ### Added
29
+ - `client.lines.createInvite(id, { exclude? })` (`POST /v1/lines/{id}/invites`): pick a phone number for one visitor of an inbound-first line and issue the 7-character code the visitor's text must carry (at least 2 digits, valid only on that number, never expiring, usable more than once). It resolves with a `LineInvite` (`{ id, line_id, phone_number, code, created_at }`, `phone_number` in E.164); the body type is exported as `CreateLineInviteBody`. `exclude` lists up to 50 E.164 numbers the pick must avoid. Show the number only together with its code. The call is not idempotent by design: every call issues a new invite. It is not retried by default (`maxRetries: 0`, overridable per call with `opts.maxRetries`): it sits in a page render, a `line_pool_exhausted` does not clear within the backoff, and a retry after a lost response would issue a second invite. Refusals: `ServiceUnavailableError` (503 `line_pool_exhausted` when no number can take an invite now, `quota_state_unavailable`, `invite_code_unavailable`), `ConflictError` (409 `not_inbound_first_line`, `line_not_active`), `NotFoundError` (404) for a line of another account, `PermissionDeniedError` (403) for a line-scoped key outside its list. `MIN_API_VERSION` rises from `2.24.0` to `2.47.0`, the API version that added the endpoint.
30
+
31
+ ## [2.2.0] and earlier
32
+
33
+ The changes of releases 0.1.0, 1.3.0, 1.4.0, 2.0.0, 2.1.0 and 2.2.0. An entry that belongs to one release names it.
6
34
 
7
35
  ### Added
8
- - Initial public surface targeting iSnap API contract `v1.0.0`.
9
- - `ISnapClient` with retries (jittered exponential backoff on 429/5xx), per-attempt timeout, auto-`Idempotency-Key` for mutating verbs, header injection, abortable requests.
36
+ - Initial public surface.
37
+ - `ISnapClient` with automatic retries (on a connection failure, a timeout, a `500`, a `503` and a `429` that is a `RateLimitError`, with exponential backoff and jitter), a timeout per attempt, an automatic `Idempotency-Key` on `POST`, `PATCH`, `PUT` and `DELETE` calls, extra headers per call, and cancellation with an `AbortSignal`.
10
38
  - Resource classes: `messages`, `chats`, `lines`, `lookup`, `attachments`, `webhooks`, `byod`, `trial`.
11
- - `attachments.upload()` — transparent 3-step (POST register → presigned R2 PUT → poll until `ready`) with 5 GB cap and four typed failure modes.
12
- - Cursor pagination as `AsyncIterable` with optional `AbortSignal` on `messages.list`, `webhooks.deliveries`, `webhooks.events`.
13
- - Webhook helpers: `verifyWebhook` (HMAC-SHA256 + 5min replay window + multi-secret rotation), `parseWebhookEvent`, prefix-based type guards (`isMessageEvent`, `isReactionEvent`, `isLineEvent`, `isTypingIndicatorEvent`, `isTrialEvent`, `isPreOrderEvent`, `isBindingEvent`, `isAdminEvent`).
14
- - Webhook event-type aliases re-synced with the backend catalog (additive, MINOR): `MessageEventType` gains `message.fallback_triggered` (iMessage→SMS/RCS degradation) and `LineEventType` gains `line.capability_changed`; two new families ship complete — `BindingEventType`/`BindingEvent`/`isBindingEvent` (`binding.released`, shared-plan contact-binding release) and `AdminEventType`/`AdminEvent`/`isAdminEvent` (`webhook.test`, the suspended-state probe). All eight aliases are now locked to the generated `WebhookEventName` enum by a compile-time parity assertion (`src/webhooks/catalog-parity.test.ts`), so a future catalog change — including a brand-new family — fails `bun run typecheck` instead of silently stranding consumers who cast `event.event_type as MessageEventType` for exhaustiveness. Runtime narrowing is unchanged: the guards already prefix-matched every one of these.
15
- - `client.macosSessions` — the wholesale partner's tenancy verbs over a rented hosted macOS session (contract §2.16, WHA-3066): `rent()`, `cancel(id)`, `uncancel(id)`, all returning the `MacosSession` shape (`{ id, rented, anniversary_at, cancel_at, status, created_at }`). `rent()` takes no arguments — one call rents one session — and throws `ConflictError` (`409 no_macos_session_in_stock`) when nothing is free, which is a state rather than a transient failure and is not worth retrying on a timer.
16
- - Webhook family `macos_session.*` (contract §4.3.8, WHA-3066): the `MacosSessionEventType` alias, the `MacosSessionEvent` interface, the `isMacosSessionEvent` prefix guard, and the family's membership in the `WebhookEvent` union — shipped complete in one change, so the compile-time parity check (`webhooks/catalog-parity.test.ts`) and the runtime guard-routing cases cover it from the first release that carries it. It fires on the ACCOUNT, not on a line: a rented session has no line, so the payload carries no `line_id`.
17
- - Error hierarchy mirroring contract §6: `APIError` + 13 subclasses, all carrying `status`, `code`, `traceId`, `requestId`. Connection failures surface as `APIConnectionError` with native `Error.cause`.
18
- - Generated TypeScript types (`src/generated/openapi.d.ts`) compiled from the backend's frozen `openapi.json`.
19
- - `maxRetryDelayMs` client option (default `60_000`) — ceiling on how long a single retry may sleep. A 429 whose `retry_after` exceeds it is rethrown as `RateLimitError` (with `retryAfter` intact) instead of slept through, so a day-scale `Retry-After` such as the trial rebind cap can no longer park a call for hours. The exponential-backoff branch is clamped to the same ceiling.
20
- - Wholesale + test-line methods on `client.lines`: `mintShared(body?)` (`POST /v1/lines/shared`) mints a fresh **billable** shared wholesale line — wholesale-partner only in v1, so a direct customer is rejected with `PaymentRequiredError` (402) and a scoped API key with `PermissionDeniedError` (403); `convertToTest(id)` / `convertFromTest(id)` (`POST /v1/lines/{id}/convert-to-test` / `convert-from-test`) flip a line between billable and test. Every `mintShared()` call mints a new line — the auto `Idempotency-Key` only dedupes that one call's internal retries; a caller-level retry must reuse `opts.idempotencyKey`.
21
- - System probes on the client itself: `client.version()` (`GET /v1/version`) and `client.health()` (`GET /v1/health`). `health()` takes the **bare-body** path — `/v1/health` is the one endpoint that returns no `{success,data}` envelope — and resolves a degraded `503` as data instead of throwing, so a status check reads `status`/`checks` without a `try`/`catch`. Named to be unmistakable from the per-line `client.lines.health(id)`: this one is the global backend probe on the client.
22
- - `client.lines.setVariant(id, { inbound_only })` — `POST /v1/lines/{id}/variant` (contract §2.4, WHA-3336): move a **rental** line between the INBOUND product and the TWO-WAY product **keeping the same phone number**, the same hardware and the same device session. `inbound_only` is not receive-only — the line converses normally and simply cannot OPEN a conversation, and once a handle has messaged it the exchange is unrestricted in both directions for good. Idempotent **on the value**, not on a key: asking for the variant the line already has resolves with the line and writes nothing, so a retry after a timeout is safe and is not a second change; it is not a toggle, state the value you want. Refusals are `ConflictError` (409) with `not_a_rental_line`, `line_not_active` or `variant_bound_to_stripe_price` (the line carries an iSnap Stripe subscription whose price IS its variant — change the subscription instead), and a line the caller does not own is a masked `NotFoundError` (404).
23
- - Webhook event `line.variant_changed` (contract §4.3.3, WHA-3336) on the `LineEventType` alias: `data` carries `{ line, from, to, changed_at }`, where `from` / `to` are the old and new `inbound_only` and `line` already holds the new value. It fires on the change only, and on any operator door that reuses the same service function — which is the case a partner cannot poll for. Added to the alias rather than left to the prefix guard because `LineEventType` is locked to the generated `WebhookEventName` enum by the compile-time parity assertion, so a catalogue addition that skipped it would fail `bun run typecheck`.
24
- - `client.lines.setVariant(id, { inbound_only, effective? })` gains the optional `effective: 'now' | 'next_anchor'` (contract §2.4, WHA-3344). It is **optional and absent means `'now'`**, so every existing `setVariant(id, { inbound_only })` call is unchanged — deliberately typed `effective?` rather than carrying an OpenAPI `default`, because `openapi-typescript@7` renders a property with a `default` as REQUIRED and would have stopped those calls compiling. `'next_anchor'` stores the change against the line's next billing anchor and moves nothing today: `inbound_only` keeps its current value, so the line keeps serving the product it is being billed for, and the resolved `Line` carries `pending_variant: { inbound_only, effective_at }`. Use it for a **downgrade**, so the customer keeps the two-way product through the month they have already bought; use the default for an upgrade. `body.not_before` (optional ISO instant, `next_anchor` only, default now) is the earliest instant the change may take effect: iSnap resolves it to the FIRST anchor occurrence at or after it, applying the anchor's own day-of-month clamp. A monthly customer needs nothing here; a QUARTERLY or ANNUAL customer does, because without it the change lands on the next anchor and takes back capability they have already paid for. State the floor and read `pending_variant.effective_at` for the answer — never reproduce the clamp client-side. A past instant is `BadRequestError` (400 `not_before_in_the_past`), refused rather than clamped. ⚠️ **Adopt `effective` / `not_before` only against a deployment that has them**: iSnap STRIPS unknown request properties instead of rejecting them, so an early call gets no 400 — it gets the field dropped and an immediate downgrade. Check `client.version()` first, and read `pending_variant` on the 200. Scheduling is idempotent on the PENDING value the way an immediate change is on the live one — re-scheduling the change already pending resolves with the line and the date it was already given — while a DIFFERENT pending change is `ConflictError` (409 `variant_change_already_pending`). An immediate change does **not** withdraw a scheduled one: they are separate acts.
25
- - `client.lines.cancelVariantChange(id)` — `DELETE /v1/lines/{id}/variant` (contract §2.4, WHA-3344): call off the change waiting for the anchor. The line's live `inbound_only` is never touched, so the only effect is that `pending_variant` becomes `null`. A line with no pending change is `NotFoundError` (404 `no_pending_variant_change`), which includes a change the anchor has already applied; losing the race to the anchor mid-request is `ConflictError` (409 `variant_change_already_applied`), so the two are distinguishable from the code alone. It succeeds on a suspended or cancelled line — withdrawing an instruction must never be blocked by the state that made it moot.
26
- - `Line.pending_variant` — `{ inbound_only, effective_at } | null` on every `Line` (contract §2.4, WHA-3344). **Not a second spelling of `inbound_only`**: that field is what the line IS and what the send gate enforces today, this is what it WILL be and on which date. Test the object against `null`, never `pending_variant.inbound_only` for truthiness — `false` there is a scheduled UPGRADE, a meaningful value and not an absence.
27
- - Webhook events `line.variant_scheduled` and `line.variant_unscheduled` (contract §4.3.3, WHA-3344) on the `LineEventType` alias: both carry the same three fields, `data.line_id`, `data.inbound_only` (the value the line WILL take, or would have taken) and `data.effective_at`, so a console mirrors the pending state with one code path in both directions instead of polling. They announce the PENDING state, not the change — the change still arrives as `line.variant_changed`, which now carries those SAME three flat fields on BOTH producers plus `data.scheduled` (always present, `false` from the partner's own immediate call and `true` when the anchor applied a scheduled one) beside the original `data.line` / `data.from` / `data.to` / `data.changed_at`. So one accessor reads a line's variant across all three events. A change DROPPED at the anchor (the line was cancelled, suspended or released, or the partner made it themselves meanwhile) fires nothing — do not treat a missing `line.variant_changed` at the expected instant as a delivery failure; re-read the line.
28
- - `coverage.test.ts` guard: for every `/v1` operation in the published `openapi.json`, asserts an SDK wrapper exists (or is listed as deliberately un-wrapped, each with a reason). The expected set is derived from the spec, not hand-written, so a newly published endpoint reddens the suite until it is wrapped.
29
- - `verifyWebhook` verifies the **Standard Webhooks** headers (`webhook-id` / `webhook-timestamp` / `webhook-signature`, WHA-3648) whenever `webhook-signature` is present, and falls back to the `X-iSnap-Signature` / `X-iSnap-Timestamp` scheme otherwise (additive, MINOR — `1.4.0`). Every iSnap delivery now carries both header sets over the same body, so existing callers keep working unchanged; the same secret string (`whsec_…`, or a legacy `whs_…`) and the same `[newSecret, oldSecret]` rotation array work on both paths, and the tolerance applies to both. When the standard header is present it decides: a wrong standard signature is rejected even if the legacy one would pass. The Standard Webhooks key is the base64 decoding of the secret without its prefix, which is what every official Standard Webhooks library derives from the same `whsec_` string.
30
- - **Every webhook event carries your own tags** (WHA-3655, additive, MINOR — `2.1.0`): `WebhookPartnerMetadata` (`{ metadata, line_metadata }`, both `Record<string, unknown> | null`) is now part of `data` on `WebhookEventBase` and on every family's event type. `data.metadata` is your metadata on the event's primary resource (the line for `line.*`, the message for `message.*`, the reacted-to message for `reaction.*`, the rented session for `macos_session.*`, the trial for `trial.*`, the pre-order for `pre_order.*`; always `null` for `typing_indicator.*`, `binding.*` and `webhook.*`), and `data.line_metadata` is your metadata on the line the event is tied to (the same object as `metadata` on `line.*`). Both keys are always present, `null` when untagged, and are a snapshot taken at emission, so a retry or a replay carries the same value. Attribute an event to your own records from its payload alone, with no second call.
31
- - `client.macosSessions.get(id)` (`GET /v1/macos-sessions/{id}`) and `client.macosSessions.update(id, { metadata })` (`PATCH /v1/macos-sessions/{id}`), plus `client.macosSessions.rent({ metadata })`: a rented session now takes your metadata, returned on `MacosSession.metadata` and cleared when the session is released. `update` merges: a key you send overwrites, a key sent as `null` is deleted. The one-argument `rent(opts)` form is unchanged, and the call shapes are told apart by the `metadata` key.
32
- - `client.trial.get(trialId)` (`GET /v1/trial/{trial_id}`) and `client.trial.update(trialId, { metadata })` (`PATCH /v1/trial/{trial_id}`), plus `metadata` on `client.trial.init({ … })` and on `TrialInitData`: the owner's read of one trial (`Trial`) and the verb that tags it, with the same merge rule. Authenticated as the trial's owner, like `revoke`.
33
- - `client.preOrders.create({ …, metadata })`: a pre-order takes your metadata, read back on `PreOrder.metadata` and echoed on every `pre_order.*` webhook. It is not copied onto the line the pre-order produces; `preOrders.update` (below) changes it after creation.
34
- - Metadata on every resource that takes it (lines, messages, BYOD pairing, pre-orders, macOS sessions, trials) is now capped at 20 keys and 8192 bytes serialized; a request over the cap is a `BadRequestError` (400), and a PATCH whose merged result breaks it is `400 metadata_too_large`.
35
- - `client.preOrders.update(id, { metadata })` (`PATCH /v1/pre-orders/{id}`, WHA-3684, additive, MINOR — `2.2.0`): change a pre-order's tags after creation, for example when it is re-assigned to another of your customers before delivery, or to backfill a pre-order placed before you tagged. `update` merges like `macosSessions.update` and `trial.update`: a key you send overwrites, a key sent as `null` is deleted, every other key is kept. It is accepted in every status, `fulfilled` and `cancelled` included, and resolves with the same `PreOrder` that `get` returns. Every `pre_order.*` webhook emitted afterwards carries the new tags as `data.metadata`, and an event already emitted keeps its original tags on every retry and replay. The tags are still not copied onto the line the pre-order produces. A pre-order placed by another account is a `NotFoundError` (404). The body type is exported as `PatchPreOrderBody`. `MIN_API_VERSION` rises from `2.0.0` to `2.24.0`, the API version that added the endpoint.
36
- - `client.lines.createInvite(id, { exclude? })` (`POST /v1/lines/{id}/invites`, WHA-3999, additive, MINOR — `2.3.0`): pick a phone number for one visitor of an inbound-first line and issue the 7-character code the visitor's text must carry (at least 2 digits, valid only on that number, never expiring, usable more than once). Resolves with a `LineInvite` (`{ id, line_id, phone_number, code, created_at }`, `phone_number` in E.164); the body type is exported as `CreateLineInviteBody`. `exclude` lists up to 50 E.164 numbers the pick must avoid. Show the number only together with its code. The call is not idempotent by design: every call issues a new invite. It is not retried by default (`maxRetries: 0`, overridable per call with `opts.maxRetries`): it sits in a page render, a `line_pool_exhausted` does not clear within the backoff, and a retry after a lost response would issue a second invite. Refusals: `ServiceUnavailableError` (503 `line_pool_exhausted` when no number can take an invite now, `quota_state_unavailable`, `invite_code_unavailable`), `ConflictError` (409 `not_inbound_first_line`, `line_not_active`), `NotFoundError` (404) for a line of another account, `PermissionDeniedError` (403) for a line-scoped key outside its list. `MIN_API_VERSION` rises from `2.24.0` to `2.47.0`, the API version that added the endpoint.
39
+ - `attachments.upload()`: registers the attachment, uploads the bytes and waits until the attachment is `ready`, in one call. A file larger than 5 GB is refused. Its failures are an `APIError`, told apart by `code`.
40
+ - Cursor pagination as an `AsyncIterable`, with an optional `AbortSignal`, on `messages.list`, `chats.list`, `webhooks.deliveries` and `webhooks.events`.
41
+ - Webhook helpers: `verifyWebhook` (HMAC-SHA256 signature, a 300-second timestamp tolerance, one secret or an array of secrets), `parseWebhookEvent`, and type guards that match on the prefix of the event type (`isMessageEvent`, `isReactionEvent`, `isLineEvent`, `isTypingIndicatorEvent`, `isTrialEvent`, `isPreOrderEvent`, `isBindingEvent`, `isAdminEvent`).
42
+ - Webhook event type aliases brought in line with the event types of the API: `MessageEventType` gains `message.fallback_triggered` and `LineEventType` gains `line.capability_changed`. Two families are new: `BindingEventType`, `BindingEvent` and `isBindingEvent` (`binding.released`), and `AdminEventType`, `AdminEvent` and `isAdminEvent` (`webhook.test`). The aliases are checked at compile time against the event names of the generated types. Run-time narrowing is unchanged: the guards already matched these events by prefix.
43
+ - `client.macosSessions`, for wholesale partners: `rent()`, `cancel(id)` and `uncancel(id)`, which resolve with a `MacosSession` (`{ id, rented, anniversary_at, cancel_at, status, created_at }`). One `rent()` call rents one session. It throws `ConflictError` (409 `no_macos_session_in_stock`) when no session is free.
44
+ - Webhook family `macos_session.*`: the `MacosSessionEventType` alias, the `MacosSessionEvent` interface, the `isMacosSessionEvent` guard, and the family's place in the `WebhookEvent` union. Their `data` has no `line_id`.
45
+ - Error classes: `APIError` and 12 subclasses, which carry `status`, `code`, `traceId` and `requestId`. A connection failure is an `APIConnectionError`: it extends `Error`, has none of these properties, and keeps the original error in `cause`. A webhook verification failure is a `WebhookSignatureError`.
46
+ - TypeScript types generated from the OpenAPI document of the API.
47
+ - `maxRetryDelayMs` client option (default `60000`): the longest wait the SDK accepts before one retry. A `429` whose `retry_after` exceeds it is thrown as a `RateLimitError` immediately, with `retryAfter` set, in place of a wait. The exponential backoff is capped at the same value.
48
+ - Methods on `client.lines` for wholesale partners: `mintShared(body?)` (`POST /v1/lines/shared`) creates a billable shared line. Any other account is a `PaymentRequiredError` (402), and a line-scoped API key is a `PermissionDeniedError` (403). Every `mintShared()` call creates a new line: the automatic `Idempotency-Key` covers only the automatic retries of one call, and a retry made by the caller must pass the same `opts.idempotencyKey`. `convertToTest(id)` and `convertFromTest(id)` (`POST /v1/lines/{id}/convert-to-test` and `convert-from-test`) convert a rented line to a test line and back.
49
+ - `client.version()` (`GET /v1/version`) and `client.health()` (`GET /v1/health`), on the client itself. `health()` resolves on a `200` and on a degraded `503`, so a status check reads `status` and `checks` without a `try`/`catch`. `client.lines.health(id)` is a different method: the health of one line.
50
+ - `client.lines.setVariant(id, { inbound_only })` (`POST /v1/lines/{id}/variant`): move a rented line between inbound-only and two-way, on the same phone number. An inbound-only line can message a contact only after that contact wrote to it. Asking for the value the line already has resolves with the line and changes nothing, so a retry is safe. Refusals are a `ConflictError` (409) with `not_a_rental_line`, `line_not_active` or `variant_bound_to_stripe_price` (the line has a subscription of its own). A line you do not own is a `NotFoundError` (404).
51
+ - Webhook event `line.variant_changed` on the `LineEventType` alias: `data` carries `{ line, from, to, changed_at }`, where `from` and `to` are the old and new `inbound_only` and `line` holds the new value.
52
+ - `client.lines.setVariant(id, { inbound_only, effective? })` gains the optional `effective`: `'now'` or `'next_anchor'`. Absent means `'now'`, so existing calls are unchanged. `'next_anchor'` stores the change for the line's next billing anchor: `inbound_only` keeps its value, and the resolved `Line` carries `pending_variant: { inbound_only, effective_at }`. `body.not_before` (optional ISO 8601 time, with `next_anchor` only, default: the time of the call) is the earliest time the change may apply: `effective_at` is the first billing anchor occurrence at or after it. A time in the past is a `BadRequestError` (400 `not_before_in_the_past`). Scheduling the change that is already pending resolves with the line unchanged, and a different pending change is a `ConflictError` (409 `variant_change_already_pending`). An immediate change does not withdraw a scheduled one.
53
+ - `client.lines.cancelVariantChange(id)` (`DELETE /v1/lines/{id}/variant`): withdraw the change scheduled for the billing anchor. `inbound_only` is not touched, and `pending_variant` becomes `null`. A line with no pending change is a `NotFoundError` (404 `no_pending_variant_change`), which includes a change that was already applied. A change applied during the call is a `ConflictError` (409 `variant_change_already_applied`). The call works on a line in any status.
54
+ - `Line.pending_variant`: `{ inbound_only, effective_at } | null` on every `Line`. `inbound_only` is what the line is now; `pending_variant` is what it becomes, and when. Test the object against `null`, not `pending_variant.inbound_only` for truthiness: `false` there is a scheduled move to two-way.
55
+ - Webhook events `line.variant_scheduled` and `line.variant_unscheduled` on the `LineEventType` alias. Both carry `data.line_id`, `data.inbound_only` (the value the line will take, or would have taken) and `data.effective_at`. They announce the pending change, not the change itself, which arrives as `line.variant_changed`. `line.variant_changed` carries the same three fields, plus `data.scheduled` (`false` for an immediate change, `true` for a change applied at the billing anchor) next to `data.line`, `data.from`, `data.to` and `data.changed_at`. A scheduled change that is discarded at the billing anchor sends no event: read the line.
56
+ - A test asserts that every `/v1` operation of the OpenAPI document has an SDK method, or is listed as deliberately not wrapped.
57
+ - 1.4.0: `verifyWebhook` verifies the Standard Webhooks headers (`webhook-id`, `webhook-timestamp`, `webhook-signature`) whenever `webhook-signature` is present, and falls back to the `X-iSnap-Signature` and `X-iSnap-Timestamp` headers otherwise. Release 2.0.0 removed that fallback: see Removed.
58
+ - 2.1.0: every webhook event carries your metadata. `WebhookPartnerMetadata` (`{ metadata, line_metadata }`, both `Record<string, unknown> | null`) is part of `data` on `WebhookEventBase` and on the event type of every family. `data.metadata` is your metadata on the resource the event is about: the line for `line.*`, the message for `message.*`, the message reacted to for `reaction.*`, the hosted macOS session for `macos_session.*`, the trial for `trial.*`, the pre-order for `pre_order.*`. It is always `null` for `typing_indicator.*`, `binding.*` and `webhook.*`. `data.line_metadata` is your metadata on the line the event is tied to (for `macos_session.*`, the line the session hosts), and the same object as `metadata` on `line.*`. Both keys are always present, `null` when there is no metadata, and are a snapshot taken when the event is created: a retry or a replay carries the same value.
59
+ - 2.1.0: `client.macosSessions.get(id)` (`GET /v1/macos-sessions/{id}`), `client.macosSessions.update(id, { metadata })` (`PATCH /v1/macos-sessions/{id}`) and `client.macosSessions.rent({ metadata })`. A rented session takes your metadata, returned on `MacosSession.metadata` and cleared when the session is released. `update` merges: a key you send overwrites, and a key sent as `null` is deleted. `rent(opts)`, without a body, is still accepted: the two call shapes are told apart by the `metadata` key.
60
+ - 2.1.0: `client.trial.get(trialId)` (`GET /v1/trial/{trial_id}`) and `client.trial.update(trialId, { metadata })` (`PATCH /v1/trial/{trial_id}`), plus `metadata` on `client.trial.init()` and on `TrialInitData`. `update` merges with the same rule.
61
+ - 2.1.0: `client.preOrders.create({ metadata })`. A pre-order takes your metadata, returned on `PreOrder.metadata` and carried by every `pre_order.*` event. It is not copied onto the line the pre-order produces.
62
+ - 2.1.0: metadata on every resource that takes it (lines, messages, BYOD pairing, pre-orders, hosted macOS sessions, trials) is limited to 20 keys and 8,192 bytes once serialized. A request over the limit is a `BadRequestError` (400), and a `PATCH` whose merged result is over the limit is a `400 metadata_too_large`.
63
+ - 2.2.0: `client.preOrders.update(id, { metadata })` (`PATCH /v1/pre-orders/{id}`) changes the metadata of a pre-order after its creation. `update` merges like `macosSessions.update` and `trial.update`: a key you send overwrites, a key sent as `null` is deleted, every other key is kept. It is accepted in every status, `fulfilled` and `cancelled` included, and resolves with the `PreOrder` that `get` returns. Every `pre_order.*` event sent afterward carries the new metadata as `data.metadata`, and an event already sent keeps its metadata on every retry and replay. The metadata is not copied onto the line the pre-order produces. A pre-order of another account is a `NotFoundError` (404). The body type is exported as `PatchPreOrderBody`. `MIN_API_VERSION` rises from `2.0.0` to `2.24.0`, the API version that added the operation.
37
64
 
38
65
  ### Removed
39
- - **`verifyWebhook` verifies the Standard Webhooks headers only** (`webhook-id` / `webhook-timestamp` / `webhook-signature`, WHA-3658) — breaking, MAJOR (`2.0.0`). The fallback to the `X-iSnap-Signature` / `X-iSnap-Timestamp` pair is removed, because iSnap no longer sends those headers: a request that carries only them is now rejected with `WebhookSignatureError` (`Missing webhook-id header`). The key derivation no longer strips a `whs_` prefix either; only `whsec_` secrets, the only kind iSnap mints, verify. Unchanged: the `[newSecret, oldSecret]` rotation array, the `tolerance` option and its 300 s default, case-insensitive header reads, and the return value. A caller that already receives iSnap deliveries needs no code change, since every delivery since `1.4.0` carries the standard headers.
66
+ - 2.0.0, breaking: `verifyWebhook` verifies the Standard Webhooks headers only (`webhook-id`, `webhook-timestamp`, `webhook-signature`). The fallback to the `X-iSnap-Signature` and `X-iSnap-Timestamp` headers is removed, because iSnap does not send those headers: a request that carries only them is rejected with `WebhookSignatureError` (`Missing webhook-id header`). The key derivation strips the `whsec_` prefix only. Unchanged: the array of secrets, the `tolerance` option and its 300-second default, case-insensitive header names, and the return value. Code that already receives iSnap deliveries needs no change, since every delivery since 1.4.0 carries the Standard Webhooks headers.
40
67
 
41
68
  ### Changed
42
- - **An owned test line is billed like a rental line** (WHA-3701, API `2.27.0`). `lines.convertToTest()` no longer stops billing: the test line stays on the wholesale partner's end-of-month invoice as the outbound product whatever its platform, on the same billing dates (`anniversary_at` and `billing_anchor_at` are kept), and `Line.monthly_price` reads that price (27500) instead of `0`. `lines.convertFromTest()` therefore leaves the bill unchanged. `lines.convertToTest()` now refuses an inbound line (`ConflictError`, 409 `test_line_not_inbound_only`: move it to outbound with `setVariant` first) and a line with a pending cancellation (409 `line_cancellation_pending`: `uncancel` first). `lines.terminate()` of a test line leaves the instant it ended as the line's `cancel_at`, and a line transferred to a wholesale partner carries the transfer instant as `activated_at`. No SDK code changes: the generated types and the JSDoc of `convertToTest`, `convertFromTest`, `cancel` and `transferOwnership` carry the new wording.
43
- - **`lines.assign()`, `lines.convertToTest()` and `lines.convertFromTest()` are wholesale-partner only** (WHA-3692, API `2.26.0`). A direct (non-wholesale) account is rejected with `PaymentRequiredError` (402 `checkout_required`) and nothing is reserved or converted. `assign()` refuses a direct account with or without `as_test_line`. `lines.transferOwnership()` of a line that is not billed per line (an owned test line, another pool line, a virtual shared line) to a non-wholesale recipient is a `ConflictError` (409 `line_recipient_not_wholesale`). `lines.terminate()` now ends an owned test line once no live trial rides it, which is otherwise a `ConflictError` (409 `test_line_in_use`). No SDK code changes: the existing error classes surface these refusals.
44
- - `src/generated/openapi.d.ts` is now generated from the **published** contract. `packages/backend/openapi.json` carries only the partner-facing `/v1/*` surface, so the internal operator routes (`/admin`, `/va`, `/farm-ops`, `/kam`, `/auth`, …) and the bridge-only `/v1/device/*` contract — plus every schema reachable only from them — are no longer emitted into the SDK types. Those routes are the dashboard, the ops back-office and the device bridge; none of them is part of the partner contract this SDK wraps, and no `ISnapClient` method referenced their types, so no documented method changes shape.
45
- - **`AppDownloadEntry.version` is now `string | null`** (API `1.15.0`, WHA-2538) — source-breaking for a consumer that renders `apps.manifest()`'s `version` without narrowing, which is the point. The field used to be a per-deployment configured string tied to no artifact: staging advertised `0.1.0-staging` for both platforms while the Mac ran `0.0.209` and the update channel published `0.0.x`, so the number could not be installed and the two platforms agreed only because both read one env value. It is now read from the release feed beside the artifact the download URL resolves to, and is `null` when that feed publishes nothing. Render the absence; do not substitute a number, and do not treat `null` as an error. It is also no longer the same string `byod.pair` returns as `bridge_version`.
69
+ - The generated types cover the public `/v1` operations only. Types of operations that are not part of the public API are no longer in the package. No `ISnapClient` method used them, so no documented method changes shape.
70
+ - `AppDownloadEntry.version` is `string | null`. Source-breaking for code that reads `version` from `apps.manifest()` without narrowing. It is `null` when no version is published for the platform: show that no version is published, do not substitute a number, and do not treat `null` as an error. It is not the `bridge_version` that `byod.pair` returns.
46
71
 
47
72
  ### Fixed
48
- - `User-Agent` misreported the SDK version. `SDK_VERSION` was left at `1.0.0` through `package.json`'s bumps to `1.1.0` and `1.2.0`, and it is the sole input to the header, so every request from the published package mis-identified its own version to server, proxy and CDN logs. `SDK_VERSION` now tracks `package.json` (`1.2.0`), and `src/version.test.ts` reads the published version off disk and fails the build the next time they disagree.
49
- - **`ReactionEvent.data` is now the flat contract §4.3.2 payload** (`parent_message_id`, `reaction_id`, `reaction_type`, `reaction_emoji`, `direction`, a direction-appropriate handle, and one of `received_at` / `added_at` / `removed_at`). The previous `{ reaction: Reaction }` nesting never matched any delivery, so the documented happy path (`event.data.reaction.id`) always threw `TypeError` — with TypeScript's blessing. `reaction_type` now also admits `custom` and `reaction_emoji` is nullable, neither of which the borrowed REST `Reaction` schema could express. The new `ReactionEventData` is a union discriminated on `direction`, so reading `from_handle` on an outbound payload (or `actor_handle` on an inbound one) is a compile error — **source-breaking for consumers that read those keys without narrowing**, though no such consumer could have been working at runtime. No wire, schema, or `api_version` change: the producers were already correct.
50
- - `packages/sdk/examples/` is now linted and typechecked. `lint` covers `examples/`, and they are in `tsconfig.json` itself — so the single `tsc --noEmit` pass sees them and, more importantly, so does the editor: a mistake in an example is red as you type rather than minutes later in CI, which is how these defects reached a published tarball in the first place. `tsconfig.build.json` carries its own `include` + `rootDir` so emit stays bounded to `src/` no matter how the editor program grows, and `dist/` is byte-identical to before. That gap had let four defects ship in reference code: `handle-webhook.ts` imported the non-existent `isTypingEvent` (it is `isTypingIndicatorEvent`) so the example died at import, dereferenced `event.data.reaction.id`, and dropped every `pre_order.*` delivery into its unhandled `else` (no `isPreOrderEvent` branch); `upload-attachment.ts` sent `attachment_ids` instead of the contract's `attachments`.
51
- - Regenerated `src/generated/openapi.d.ts` against API `1.3.0`. `lookup.check()` now types the `202` pending trio (`pending`, `probe_id`, `retry_after`), so the re-poll branch is reachable without a cast.
52
- - `verify:generated` script + `src/generated.test.ts` assert the committed types are byte-identical to `openapi-typescript` output, so the published tarball can no longer ship a stale contract.
73
+ - `User-Agent` misreported the SDK version: `SDK_VERSION` had stayed at `1.0.0` while the package version moved. `SDK_VERSION` now equals the package version, and a test fails when the two disagree.
74
+ - `ReactionEvent.data` is the flat payload the API sends: `parent_message_id`, `reaction_id`, `reaction_type`, `reaction_emoji`, `direction`, a handle, and one of `received_at`, `added_at` or `removed_at`. The previous `{ reaction: Reaction }` nesting never matched a delivery. `reaction_type` also admits `custom`, and `reaction_emoji` can be `null`. `ReactionEventData` is a union on `direction`: reading `from_handle` on an outbound payload, or `actor_handle` on an inbound one, is a compile error. Source-breaking for code that read those keys without narrowing.
75
+ - The example scripts are linted and type-checked. Four defects are fixed: `handle-webhook.ts` imported `isTypingEvent`, which does not exist (the guard is `isTypingIndicatorEvent`), read `event.data.reaction.id`, and had no branch for `pre_order.*` events; `upload-attachment.ts` sent `attachment_ids` where the API field is `attachments`.
76
+ - Types regenerated from API `1.3.0`: `lookup.check()` types the pending result (`pending`, `probe_id`, `retry_after`).
77
+ - A check asserts that the bundled types are the ones generated from the OpenAPI document they are built with.