@signalhousellc/sdk 1.5.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +5 -56
  2. package/index.d.ts +1 -0
  3. package/index.js +2 -0
  4. package/package.json +32 -34
  5. package/voice-browser.d.ts +1 -0
  6. package/voice-browser.js +2 -0
  7. package/warn.js +7 -0
  8. package/webhooks.d.ts +1 -0
  9. package/webhooks.js +2 -0
  10. package/scripts/install-skills.mjs +0 -329
  11. package/skills/VENDORED.json +0 -22
  12. package/skills/signalhouse-10dlc/SKILL.md +0 -172
  13. package/skills/signalhouse-10dlc/examples/brightsmile-onboarding.md +0 -62
  14. package/skills/signalhouse-10dlc/references/tcr-rejection-causes.md +0 -104
  15. package/skills/signalhouse-advisor/SKILL.md +0 -84
  16. package/skills/signalhouse-numbers/SKILL.md +0 -82
  17. package/skills/signalhouse-setup/SKILL.md +0 -121
  18. package/skills/signalhouse-sms/SKILL.md +0 -81
  19. package/skills/signalhouse-webhooks/SKILL.md +0 -148
  20. package/src/SignalHouseSDK.js +0 -201
  21. package/src/domains/Agents.js +0 -987
  22. package/src/domains/Auth.js +0 -225
  23. package/src/domains/Billing.js +0 -264
  24. package/src/domains/Brands.js +0 -508
  25. package/src/domains/Campaigns.js +0 -691
  26. package/src/domains/Dnc.js +0 -168
  27. package/src/domains/Groups.js +0 -187
  28. package/src/domains/Landings.js +0 -237
  29. package/src/domains/Messages.js +0 -609
  30. package/src/domains/Notifications.js +0 -62
  31. package/src/domains/Numbers.js +0 -572
  32. package/src/domains/Onboarding.js +0 -128
  33. package/src/domains/Registrations.js +0 -246
  34. package/src/domains/Shortlinks.js +0 -80
  35. package/src/domains/Subgroups.js +0 -136
  36. package/src/domains/Subscriptions.js +0 -146
  37. package/src/domains/Templates.js +0 -403
  38. package/src/domains/Tickets.js +0 -100
  39. package/src/domains/Users.js +0 -228
  40. package/src/domains/Voice.js +0 -41
  41. package/src/domains/Webhooks.js +0 -125
  42. package/src/domains/voice/Analytics.js +0 -82
  43. package/src/domains/voice/CallLogs.js +0 -111
  44. package/src/domains/voice/Calls.js +0 -118
  45. package/src/domains/voice/GlobalVoiceSettings.js +0 -54
  46. package/src/domains/voice/NumberRoutes.js +0 -82
  47. package/src/domains/voice/ProgrammableVoiceProfiles.js +0 -191
  48. package/src/domains/voice/SipProfiles.js +0 -203
  49. package/src/domains/voice/SipTrunks.js +0 -203
  50. package/src/domains/voice/Tokens.js +0 -96
  51. package/src/domains/voice/browser/Call.js +0 -366
  52. package/src/domains/voice/browser/Device.js +0 -484
  53. package/src/domains/voice/browser/index.js +0 -17
  54. package/src/webhooks/verifySignature.js +0 -66
@@ -1,81 +0,0 @@
1
- ---
2
- name: signalhouse-sms
3
- description: >-
4
- Sending SMS and MMS on Signal House: what a successful-looking response does not prove, the
5
- parameter name that differs between the SDK and the raw API, how segments drive cost, and the
6
- carrier and opt-out gates that stop a send.
7
- TRIGGER when the user is sending or scripting SMS, MMS or group MMS; when a message came back
8
- successful but never arrived; when a send fails or is rejected; when they ask about delivery
9
- status, delivery receipts, message cost, segments, emoji, or STOP and opt-outs.
10
- SKIP for 10DLC brand and campaign registration, for buying numbers, and for webhook endpoint
11
- setup, which have their own skills. This one assumes a number that is already able to send.
12
- ---
13
-
14
- # Sending on Signal House
15
-
16
- ## What cannot happen
17
-
18
- **`success: true` does not prove the message went out.** When the Moderation API blocks content, the
19
- send does **not** raise an API error. The recipients are written to the message log as **accepted but
20
- `FAILED`** and returned like a normal send, so the caller sees a normal success envelope. Any code
21
- that treats a 2xx as "delivered" reports a blocked campaign as a working one. Confirm outcomes from
22
- message status or a delivery webhook, never from the send response alone.
23
-
24
- **A number cannot send just because the account owns it.** It must be in `READY` status on an
25
- `ACTIVE` campaign, under a brand that is `VERIFIED` or `VETTED_VERIFIED`. A brand-new number is not a
26
- sendable number. See `signalhouse-10dlc`.
27
-
28
- **The recipient field is named differently in the SDK and the API.** The raw API takes
29
- `recipientPhoneNumber` (**singular**, still an array). The JS SDK takes `recipientPhoneNumbers`
30
- (**plural**) and maps it internally. A direct HTTP caller who copies the SDK's plural name gets a
31
- validation failure, and it reads as a mysterious 400 rather than a typo.
32
-
33
- **Opt-out suppression is environment-gated, so a STOP is not automatically a block.**
34
- `DNC_ENFORCEMENT_MODE` has three settings, `off`, `log` and `enforce`, and the default is **`log`**.
35
- In `log` mode the platform queries suppressions and records what it *would* have blocked, then lets
36
- every recipient through. So:
37
-
38
- - Never tell a customer that STOP replies are being enforced without checking the environment.
39
- - Never tell them suppression does not exist either. The list is real and is being recorded.
40
- - STOP and HELP confirmations deliberately bypass suppression. They are addressed to someone who is
41
- on the list by design, so seeing one go out is not evidence that suppression is broken.
42
-
43
- **Sending is billed per segment, not per message.** A single non-GSM character, such as an emoji or a
44
- curly quote pasted from a document, flips the whole body to a different encoding and
45
- multiplies the segment count, and the cost, silently. Message body length is a billing decision.
46
-
47
- **Carrier throughput is capped above the API.** There is a T-Mobile daily segment cap tracked per
48
- brand EIN and an AT&T per-minute segment limit. Hitting either fails messages with a recorded reason
49
- rather than raising an exception at the call site. A burst where most messages went out and some did not
50
- is what this looks like in practice.
51
-
52
- ## Order of operations
53
-
54
- 1. **Confirm the sender can send.** Check the number's status is `READY` rather than assuming.
55
- 2. **Know the segment count and current fee** before a bulk send. Fees are per group and read from
56
- `GET /billing/fees/:groupId`. Never quote a price from memory or from this file.
57
- 3. **Send.** `POST /message/sms` (JSON), `POST /message/mms` (multipart, max 5 attachments),
58
- `POST /message/groupMessage` (multipart, shared thread). The send is queued and returns **201**
59
- with an `insertedMessages` array holding one document per recipient.
60
- 4. **Read the outcome asynchronously.** `statusCallbackUrl` on the send, or `MESSAGE_DELIVERED` /
61
- `MESSAGE_FAILED` webhooks. Polling `GET /message` in a loop is the wrong shape and the rate-limit
62
- guidance says so explicitly.
63
-
64
- Message status runs `ENQUEUED → DEQUEUED → SENT → DELIVERED`, with `FAILED` reachable from the
65
- middle. `SENT` means handed to the carrier, not received by the handset. Only `DELIVERED` means
66
- delivered, and not every carrier returns one.
67
-
68
- ## Querying messages
69
-
70
- `GET /message` requires `groupId`, `startDate` and `endDate` **unless** you filter by `id`, which
71
- routes to a single-record lookup and skips the date-range requirement. Omitting them without an `id`
72
- is a 400, not an unbounded query. The API refuses rather than scanning.
73
-
74
- ## Where to look it up
75
-
76
- - **Every send parameter, message statuses and delivery receipts:** the Messages reference,
77
- https://app2.signalhouse.io/docs/messages.
78
- - **Current per-group fees:** `GET /billing/fees/:groupId`.
79
- - **Failure codes and what is retryable:** https://app2.signalhouse.io/docs/error-handling.
80
- - **Backoff and batching:** https://app2.signalhouse.io/docs/rate-limits.
81
- - **Why a number cannot send yet:** `signalhouse-10dlc`.
@@ -1,148 +0,0 @@
1
- ---
2
- name: signalhouse-webhooks
3
- description: >-
4
- Signal House webhooks: how delivery actually behaves, what a receiver can and cannot trust,
5
- and the retry window before an event is lost for good.
6
- TRIGGER when the user is setting up, debugging, or writing a receiver for Signal House
7
- webhooks; when webhook events appear to be missing, duplicated, or arriving late; when they
8
- ask how to verify a webhook is genuine; or when they are choosing an authType.
9
- SKIP for inbound message handling logic itself, for the SMS send path, and for questions about
10
- which events exist. That list is in the webhooks guide and changes independently of this.
11
- ---
12
-
13
- # Signal House webhooks
14
-
15
- ## What a receiver can verify
16
-
17
- **Deliveries to a webhook endpoint are signed.** Every endpoint created with `POST /webhook` gets a
18
- signing secret, returned in plaintext **exactly once**, as `signingSecret` in that create response.
19
- Every later read reports only `hasSigningSecret: true|false`. Store the secret at creation; nothing
20
- can hand it back. If it is lost or exposed, rotate it: `POST /webhook/:id/rotate-secret` returns a new
21
- secret once, and the old one keeps working for a grace window (`graceSeconds`, default 24h, max 7
22
- days, `0` for none) so the receiver can switch over without dropping deliveries.
23
-
24
- A signed delivery carries:
25
-
26
- | Header | Value |
27
- |---|---|
28
- | `X-SignalHouse-Signature` | hex HMAC-SHA256, keyed with the signing secret, over `${timestamp}.${rawBody}`. During a rotation grace window it stays on the **previous** secret and switches when the window ends |
29
- | `X-SignalHouse-Timestamp` | the `timestamp` in that string: Unix time in **milliseconds** |
30
- | `X-SignalHouse-Signature-V1` | `t=<ms>,v1=<hex>[,v1=<hex>]`: one signature per currently valid secret, newest first. During a rotation grace window it carries both the new and the previous secret's signature; accept a match on any |
31
- | `X-SignalHouse-Delivery-Id` | a UUID for this event to this endpoint, the same on every retry |
32
-
33
- A correct verifier:
34
-
35
- 1. **Uses the raw request body**, byte for byte, before any JSON parsing. Re-serializing a parsed
36
- body changes whitespace and key order and the signature stops matching.
37
- 2. **Recomputes the HMAC and compares in constant time.** The signature is bare hex, no prefix.
38
- 3. **Rejects a stale timestamp.** The timestamp is inside the signed string, so a captured request
39
- cannot be replayed with a fresh one. Pick a window (five minutes is common) and remember the
40
- header is milliseconds, not seconds.
41
- 4. **Rejects an unsigned request to an endpoint that has a secret.** Otherwise a forger simply
42
- leaves the headers off.
43
- 5. **Prefers `X-SignalHouse-Signature-V1`**, so a secret rotation never breaks verification.
44
-
45
- In Node, `verifyWebhookSignature` from `@signalhousellc/sdk/webhooks` does all of this and returns
46
- `{ valid, reason }` without throwing. Other languages implement the five steps directly; the
47
- Webhook Signing guide has a Python version.
48
-
49
- What is still **not** verifiable:
50
-
51
- - **Endpoints created before signing shipped (2026-09-03) are sent unsigned** until they get a
52
- secret. They report `hasSigningSecret: false`. Call `POST /webhook/:id/rotate-secret` once (or use
53
- *Create signing secret* in the portal's webhook edit view) to issue their first secret; deliveries
54
- are signed from then on.
55
- - **Per-number inbound URLs are never signed** (see below).
56
-
57
- For anything unsigned, the old rules still apply: do not treat the request as authenticated, and
58
- never take an irreversible or financial action on webhook content alone. Read the authoritative
59
- state back from the API first. Do not put secrets in a webhook URL as a substitute for
60
- verification; URLs end up in proxy logs and support screenshots.
61
-
62
- The `authType` setting (`NONE`, `BASIC`, `API_KEY`, `OAUTH2`, `HMAC`) chooses what *else* Signal
63
- House sends to the receiver. Signing does not depend on it: every endpoint with a secret is signed
64
- whatever `authType` says. `BASIC`/`API_KEY`/`OAUTH2` add credentials as a second layer; `HMAC` sends
65
- none and declares that the receiver authenticates by the signature alone.
66
-
67
- ## Retry behaviour, and when an event is gone
68
-
69
- Delivery is a **direct HTTP POST with a 3-second timeout**, made up to **3 times in total**. The
70
- waits between attempts back off exponentially with jitter: about 500 ms, then about 1 second
71
- (each up to 25% longer). It is not queued, so there is no queue-level redelivery behind it. Each
72
- attempt is signed afresh with a new timestamp and carries the **same** delivery id.
73
-
74
- What gets retried:
75
-
76
- - **Retried:** no response at all (network error, DNS failure, timeout), any **5xx**, and **429**.
77
- - **Not retried:** every other **4xx**. A receiver that answers 400, 401, 403 or 404 gets the
78
- event once. So return a 4xx only for a request you will never accept (a bad signature, say), and
79
- a 5xx or 429 for anything transient.
80
-
81
- Two numbers matter, and they are different things:
82
-
83
- - **A receiver has 3 seconds to respond.** Exceed it and the attempt is a failure, even if the
84
- work eventually succeeds on your side.
85
- - **The whole delivery window is about 11 seconds** worst case: three attempts that can each burn
86
- the full timeout, plus the two waits.
87
-
88
- - A receiver that is down, restarting, or rate-limited for longer than that **loses the push for
89
- that event**. There is no dead-letter queue and no replay endpoint.
90
- - A slow endpoint that exceeds 3 seconds and *then* completes its work has been recorded as a
91
- failure and will be sent the **same event again**. Dedupe on `X-SignalHouse-Delivery-Id`.
92
-
93
- So a correct receiver:
94
-
95
- 1. **Responds inside 3 seconds, and does the work afterwards.** Acknowledge, enqueue, process out
96
- of band. Any processing done before responding is spending a budget you do not control, and
97
- blowing it converts a successful handler into a duplicate delivery.
98
- 2. **Is idempotent on `X-SignalHouse-Delivery-Id`**, which every delivery carries, signed or not,
99
- including per-number inbound URLs.
100
- 3. **Reconciles against `GET /notification`.** This is the important one. Every event that would
101
- trigger a group webhook also writes a **notification record, created before endpoints are even
102
- looked up and independent of whether delivery succeeds**. It carries the same `{timestamp,
103
- event, identifier, metaData}` shape and is filterable by group, status and event type.
104
-
105
- That makes it the durable record and the webhook merely the push. A receiver that must not
106
- miss anything polls it to catch up after any outage, which is the only reliable recovery,
107
- given there is no replay endpoint.
108
-
109
- ## Setting one up
110
-
111
- Webhooks are created per group, and numbers can additionally carry their own inbound URL.
112
- `authType` picks how Signal House authenticates to the endpoint, and `credentials` is
113
- `{ key, secret }`, required whenever `authType` is not `NONE` or `HMAC` (and rejected with those two).
114
-
115
- | authType | What is sent |
116
- |---|---|
117
- | `NONE` | nothing. The endpoint is open to anyone who knows the URL |
118
- | `BASIC` | HTTP Basic; `key` is the username, `secret` is the password |
119
- | `API_KEY` | `key` holds the key; `secret` optional |
120
- | `OAUTH2` | `secret` is the access token sent as the Authorization value; `key` is required at create but unused in outgoing headers |
121
- | `HMAC` | no credentials and no Authorization header; the receiver verifies the signature headers. Rejected for an endpoint with no signing secret until it has one |
122
-
123
- Verify the signature on every endpoint that has one. `HMAC` (or `NONE`) is fine for a receiver
124
- that verifies signatures; `BASIC` or `API_KEY` on top is cheap defense in depth.
125
-
126
- **The table above does not cover per-number inbound URLs.** A number can carry
127
- `primaryInboundWebhookUrl` and `secondaryInboundWebhookUrl`, and inbound messages are posted to
128
- both. That path sends **no auth headers and no signature**, whatever is configured elsewhere: it has
129
- no endpoint record to hold a secret, so it is always unauthenticated. It does carry
130
- `X-SignalHouse-Delivery-Id`. Do not assume configuring a group webhook protects the per-number
131
- ones; it does not. Treat those URLs as fully public and put nothing behind them that matters
132
- without an independent check. If a number's inbound traffic needs verifying, route it through a
133
- signed group endpoint instead.
134
-
135
- ## Where to look it up
136
-
137
- - **The signing scheme, verification and rotation:** the Webhook Signing guide,
138
- https://app2.signalhouse.io/docs/webhook-signing.
139
- - **Event types and payload shape:** the Webhooks reference,
140
- https://app2.signalhouse.io/docs/webhooks. The event list changes independently of this skill;
141
- read it there rather than reciting it here.
142
- - **Whether an event actually happened:** `GET /notification`
143
- (https://app2.signalhouse.io/docs/notifications). The notification record is written
144
- independently of delivery, so it is the record and the webhook is the push.
145
- - **Whether a delivery failed:** Signal House logs every failed delivery with the group, the
146
- endpoint, the event and the HTTP status your endpoint returned (or none, for a timeout), so
147
- support can answer "did you get a 401 from us". There is still no API for a customer to list
148
- failed deliveries or replay one, so do not design a process that depends on it.
@@ -1,201 +0,0 @@
1
- import axios from "axios";
2
-
3
- // Bounds every request made by this SDK. Chosen well above typical p99 latency so it only trips on
4
- // a genuinely hung connection, not a slow-but-completing request.
5
- const REQUEST_TIMEOUT_MS = 30000;
6
-
7
- /**
8
- * @typedef {Object} RequestOptions
9
- * @property {string} [token] - An optional bearer token to include in the request for authentication
10
- * @property {object} [headers] - Additional headers to include in the request
11
- * @property {string} [idempotencyKey] - Sent as the Idempotency-Key header; a retry with the same key and request replays the first response instead of repeating it
12
- */
13
-
14
- /**
15
- * @typedef {Object} SignalHouseSDKConfig
16
- * @property {string} apiKey - The API key for authenticating requests to the SignalHouse API
17
- * @property {string} baseUrl - The base URL for the SignalHouse API (e.g., "https://api.signalhouse.com")
18
- * @property {boolean} [enableAdmin=false] - Enable admin-scoped behaviors on domains that support them
19
- */
20
-
21
- /**
22
- * The envelope every domain method resolves to. Non-2xx responses never reject; check `success` first.
23
- * @template T
24
- * @typedef {{ success: true, data: T, status: number } | { success: false, error: string|Object, status: number|null }} SdkResponse
25
- */
26
-
27
- // Main SDK Class (SignalHouseSDK.js)
28
- import { Auth } from "./domains/Auth.js";
29
- import { Billing } from "./domains/Billing.js";
30
- import { Brands } from "./domains/Brands.js";
31
- import { Campaigns } from "./domains/Campaigns.js";
32
- import { Groups } from "./domains/Groups.js";
33
- import { Landings } from "./domains/Landings.js";
34
- import { Messages } from "./domains/Messages.js";
35
- import { Templates } from "./domains/Templates.js";
36
- import { Numbers } from "./domains/Numbers.js";
37
- import { Registrations } from "./domains/Registrations.js";
38
- import { Onboarding } from "./domains/Onboarding.js";
39
- import { Dnc } from "./domains/Dnc.js";
40
- import { Shortlinks } from "./domains/Shortlinks.js";
41
- import { Subgroups } from "./domains/Subgroups.js";
42
- import { Subscriptions } from "./domains/Subscriptions.js";
43
- import { Tickets } from "./domains/Tickets.js";
44
- import { Users } from "./domains/Users.js";
45
- import { Notifications } from "./domains/Notifications.js";
46
- import { Webhooks } from "./domains/Webhooks.js";
47
- import { Voice } from "./domains/Voice.js";
48
- import { Agents } from "./domains/Agents.js";
49
-
50
- export class SignalHouseSDK {
51
- /**
52
- * Initialize the SignalHouseSDK with the required configuration
53
- * @param {SignalHouseSDKConfig} config - The configuration object for initializing the SDK
54
- * @throws {Error} Throws an error if the API key or base URL is missing from the configuration
55
- */
56
- constructor(config) {
57
- // Validate required config parameters
58
- if (!config?.apiKey) {
59
- throw new Error("API key is required to initialize SignalHouseSDK");
60
- }
61
- if (!config?.baseUrl) {
62
- throw new Error("Base URL is required to initialize SignalHouseSDK");
63
- }
64
-
65
- // Set instance properties
66
- this.baseUrl = config.baseUrl;
67
- this.apiKey = config.apiKey;
68
- this.enableAdmin = config.enableAdmin || false;
69
-
70
- // Shared internal request helper
71
- const client = this._createClient(false);
72
- const multipartClient = this._createClient(true);
73
-
74
- // API Domains
75
- this.auth = new Auth(client, this.enableAdmin);
76
- this.billing = new Billing(client, this.enableAdmin);
77
- this.brands = new Brands(client, multipartClient, this.enableAdmin);
78
- this.campaigns = new Campaigns(client, multipartClient, this.enableAdmin);
79
- this.groups = new Groups(client, this.enableAdmin);
80
- this.landings = new Landings(client, multipartClient, this.enableAdmin);
81
- this.messages = new Messages(client, multipartClient, this.enableAdmin);
82
- this.templates = new Templates(client, multipartClient, this.enableAdmin);
83
- this.numbers = new Numbers(client, multipartClient, this.enableAdmin);
84
- this.registrations = new Registrations(client, this.enableAdmin);
85
- this.onboarding = new Onboarding(client, this.enableAdmin);
86
- this.dnc = new Dnc(client, this.enableAdmin);
87
- this.shortlinks = new Shortlinks(client, this.enableAdmin);
88
- this.subgroups = new Subgroups(client, this.enableAdmin);
89
- this.subscriptions = new Subscriptions(client, this.enableAdmin);
90
- this.tickets = new Tickets(client, this.enableAdmin);
91
- this.users = new Users(client, this.enableAdmin);
92
- this.notifications = new Notifications(client, this.enableAdmin);
93
- this.webhooks = new Webhooks(client, this.enableAdmin);
94
- // Voice domain targets the voice-backend service under /voice. Available
95
- // like any other domain; gating (if any) will be decided later.
96
- this.voice = new Voice(client, this.enableAdmin);
97
- // AI Agents domain — customer-facing agent config under /agent.
98
- this.agents = new Agents(client, this.enableAdmin);
99
- }
100
-
101
- /**
102
- * Client for API requests
103
- * @private
104
- * @param {boolean} isMultipart - Whether to set the Content-Type header for multipart requests
105
- * @throws {Error} Throws an error if the API key or base URL is missing
106
- * @returns {Function} A function to make API requests
107
- */
108
- _createClient(isMultipart = false) {
109
- // Create an Axios instance with the base URL and default headers. `timeout` bounds every
110
- // request so a hung connection (server-side lock contention, a stalled upstream call) rejects
111
- // instead of leaving the caller's promise unsettled forever with no error and no feedback.
112
- const instance = axios.create({ baseURL: this.baseUrl, timeout: REQUEST_TIMEOUT_MS, headers: isMultipart ? {} : { "Content-Type": "application/json" } });
113
-
114
- // Add a request interceptor to include the API key in the Authorization header
115
- instance.interceptors.request.use((/** @type {import('axios').InternalAxiosRequestConfig & { token?: string, idempotencyKey?: string }} */ config) => {
116
- const token = config.token || this.apiKey;
117
- config.headers.Authorization = `Bearer ${token}`;
118
- if (config.idempotencyKey) config.headers["Idempotency-Key"] = config.idempotencyKey;
119
- delete config.token; // Remove token from config to avoid sending it as a header
120
- delete config.idempotencyKey;
121
- return config;
122
- });
123
-
124
- // Standardize responses. The fulfilled handler deliberately replaces the AxiosResponse with the
125
- // SdkResponse envelope, which axios's interceptor typing does not model; the cast keeps that intent visible.
126
- instance.interceptors.response.use(
127
- // Standard 2xx responses
128
- /** @type {(response: import('axios').AxiosResponse) => any} */
129
- ((response) => {
130
- return { success: true, data: response.data, status: response.status };
131
- }),
132
-
133
- // Non-2xx responses, plus timeouts and network failures (no `error.response` at all) - those
134
- // get a clear message here rather than surfacing axios's internal error.message verbatim.
135
- (error) => {
136
- if (!error.response) {
137
- const isTimeout = error.code === "ECONNABORTED" || /timeout/i.test(error.message || "");
138
- return {
139
- success: false,
140
- error: isTimeout ? "Request timed out. Please try again." : "Network error. Please check your connection and try again.",
141
- status: null,
142
- };
143
- }
144
- return {
145
- success: false,
146
- error: error.response?.data?.message || error.response?.data || error.message || 500,
147
- status: error.response?.status || error.response?.data || null,
148
- };
149
- },
150
- );
151
-
152
- const client = async (url, options = {}) => {
153
- // Extract the body from options and keep the rest as axios config
154
- const { body, ...axiosConfig } = options;
155
- return instance({ url, data: body, ...axiosConfig });
156
- };
157
-
158
- // Attach helpers to the client
159
- client._getQueryString = this._getQueryString.bind(this);
160
- client._require = this._require.bind(this);
161
-
162
- return client;
163
- }
164
-
165
- /**
166
- * Helper method to convert an object to a query string, excluding undefined values and the 'options' key
167
- * @private
168
- * @param {Object} obj - The object to convert to a query string
169
- * @returns {string} The query string
170
- */
171
- _getQueryString(obj) {
172
- const params = new URLSearchParams();
173
- Object.entries(obj).forEach(([key, value]) => {
174
- if (value !== undefined && key !== "options") {
175
- if (Array.isArray(value)) {
176
- value.forEach((v) => params.append(key, v));
177
- } else {
178
- params.append(key, value);
179
- }
180
- }
181
- });
182
- return params.toString() ? `?${params.toString()}` : "";
183
- }
184
-
185
- /**
186
- * Helper method to validate required fields necessary for a request parameter
187
- * @private
188
- * @param {Object} fields - An object where keys are field names and values are the corresponding values to check
189
- * @throws {Error} Throws an error if any required field is missing or empty
190
- */
191
- _require(fields) {
192
- for (const [name, value] of Object.entries(fields)) {
193
- if (value === undefined || value === null || value === "") {
194
- const error = /** @type {Error & { status?: number }} */ (new Error(`Missing required parameter: ${name}`));
195
- error.name = "SignalHouseValidationError";
196
- error.status = 400; // Match API validation code
197
- throw error;
198
- }
199
- }
200
- }
201
- }