smswire 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 SMSWire
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,116 @@
1
- # Temporary Holding Version
1
+ # SMSWire for Node.js
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Send SMS and one-time codes from your app through your own Android phones with [SMSWire](https://smswire.app).
4
+
5
+ ```sh
6
+ npm install smswire
7
+ ```
8
+
9
+ Node 20+ (also Bun, Deno and edge runtimes with `fetch` and Web Crypto). No dependencies.
10
+
11
+ ## Set up
12
+
13
+ Each project on the dashboard has an API key and a slug (the part after `/p/` in its endpoint). Keep them in the environment:
14
+
15
+ ```sh
16
+ SMSWIRE_KEY="smswire_live_…"
17
+ SMSWIRE_PROJECT="prj_…"
18
+ SMSWIRE_WEBHOOK_SECRET="whsec_…" # only if you receive webhooks
19
+ # SMSWIRE_URL="https://api.smswire.app" # your server, if you host SMSWire yourself
20
+ ```
21
+
22
+ ```ts
23
+ import { SMSWire } from 'smswire';
24
+
25
+ const sms = new SMSWire(); // or new SMSWire({ apiKey, project, baseUrl })
26
+ ```
27
+
28
+ ## Send
29
+
30
+ ```ts
31
+ const message = await sms.messages.send({
32
+ to: '+251911234567',
33
+ body: 'Your order {{order}} shipped',
34
+ variables: { order: 'A-1042' },
35
+ type: 'transactional', // otp | transactional | notification | marketing
36
+ tags: ['orders'],
37
+ metadata: { user_id: 42 }, // echoed back in webhooks
38
+ });
39
+ // → { id: 'msg_…', status: 'queued', segments: 1, … }
40
+
41
+ // Your own idempotency key makes your retries safe too (the SDK adds a random one otherwise).
42
+ await sms.messages.send({ to, body }, { idempotencyKey: `order-${order.id}` });
43
+
44
+ await sms.messages.get(message.id);
45
+ await sms.messages.cancel(message.id); // before it reaches a phone
46
+
47
+ const page = await sms.messages.list({ status: 'failed', limit: 50 });
48
+ for await (const m of sms.messages.listAll({ tag: 'orders' })) console.log(m.id, m.status);
49
+
50
+ const batch = await sms.messages.sendBulk({
51
+ name: 'Weekend sale',
52
+ body: 'Hi {{name}}, 20% off this weekend',
53
+ rate: 30, // per minute
54
+ messages: [{ to: '+251911234567', variables: { name: 'Abebe' } }, { to: '+251922345678', variables: { name: 'Sara' } }],
55
+ });
56
+ // → { batch_id, accepted, rejected: [{ index, to, reason }] }
57
+ ```
58
+
59
+ ## One-time codes
60
+
61
+ ```ts
62
+ const otp = await sms.otp.send({ to: '+251911234567', length: 6, ttl: 300 });
63
+ // later, with what the user typed:
64
+ const { valid, reason } = await sms.otp.verify({ id: otp.id, code: input });
65
+ // reason: invalid | expired | too_many_attempts | already_used
66
+ ```
67
+
68
+ ## Recurring sends
69
+
70
+ ```ts
71
+ const schedule = await sms.schedules.create({
72
+ name: 'Weekly report',
73
+ cron: '0 9 * * 1',
74
+ timezone: 'Africa/Addis_Ababa',
75
+ to: '+251911234567',
76
+ body: 'Your weekly report is ready',
77
+ });
78
+ await sms.schedules.update(schedule.id, { enabled: false });
79
+ await sms.schedules.list();
80
+ await sms.schedules.delete(schedule.id);
81
+ ```
82
+
83
+ ## Webhooks
84
+
85
+ Status updates (`message.status`) and replies (`message.received`) are POSTed to the project's webhook URL, signed with `X-SMSWire-Signature`. Verify the **raw** body:
86
+
87
+ ```ts
88
+ import express from 'express';
89
+ import { SMSWireSignatureError } from 'smswire';
90
+
91
+ app.post('/hooks/smswire', express.raw({ type: 'application/json' }), async (req, res) => {
92
+ let event;
93
+ try {
94
+ event = await sms.webhooks.verify(req.body, req.get('X-SMSWire-Signature'));
95
+ } catch (e) {
96
+ if (e instanceof SMSWireSignatureError) return res.sendStatus(400);
97
+ throw e;
98
+ }
99
+ if (event.event === 'message.status') await markOrder(event.metadata, event.status);
100
+ if (event.event === 'message.received') await handleReply(event.from, event.body);
101
+ res.sendStatus(200);
102
+ });
103
+ ```
104
+
105
+ Without a client: `verifyWebhook(rawBody, signature, secret)`. The same event can arrive twice; make the handler idempotent.
106
+
107
+ ## Errors and retries
108
+
109
+ Failed calls throw `SMSWireError` with `status` (null when no answer came), `code` (`invalid_request`, `invalid_api_key`, `rate_limited`, `daily_limit_reached`, `network_error`, `timeout`, …), `message` and `retryAfter`.
110
+
111
+ The SDK retries (default `maxRetries: 2`, waiting `Retry-After` or backing off):
112
+
113
+ - reads, updates, deletes and `messages.send` (it carries an idempotency key): on 429, 5xx and network errors;
114
+ - `sendBulk`, `otp.send`, `otp.verify`, `schedules.create`: on 429 only, since a 5xx or a dropped connection may already have done the work.
115
+
116
+ A `Retry-After` longer than `maxRetryWait` (60 s, e.g. a daily limit) throws at once.
package/dist/index.cjs ADDED
@@ -0,0 +1,309 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ SIGNATURE_HEADER: () => SIGNATURE_HEADER,
24
+ SMSWire: () => SMSWire,
25
+ SMSWireError: () => SMSWireError,
26
+ SMSWireSignatureError: () => SMSWireSignatureError,
27
+ VERSION: () => VERSION,
28
+ default: () => index_default,
29
+ verifyWebhook: () => verifyWebhook
30
+ });
31
+ module.exports = __toCommonJS(index_exports);
32
+
33
+ // src/errors.ts
34
+ var SMSWireError = class extends Error {
35
+ constructor(status, code, message, retryAfter2 = null, options) {
36
+ super(message, options);
37
+ this.status = status;
38
+ this.code = code;
39
+ this.retryAfter = retryAfter2;
40
+ }
41
+ status;
42
+ code;
43
+ retryAfter;
44
+ name = "SMSWireError";
45
+ };
46
+ var SMSWireSignatureError = class extends Error {
47
+ name = "SMSWireSignatureError";
48
+ };
49
+
50
+ // src/http.ts
51
+ var sleep = (seconds) => new Promise((r) => setTimeout(r, seconds * 1e3));
52
+ function retryAfter(header) {
53
+ if (!header) return null;
54
+ const n = Number(header);
55
+ if (Number.isFinite(n)) return Math.max(0, n);
56
+ const at = Date.parse(header);
57
+ return Number.isNaN(at) ? null : Math.max(0, (at - Date.now()) / 1e3);
58
+ }
59
+ var backoff = (attempt) => Math.min(8, 0.5 * 2 ** attempt) * (1 + Math.random() * 0.25);
60
+ async function errorFrom(res) {
61
+ const text = await res.text().catch(() => "");
62
+ let code = "http_error";
63
+ let message = `HTTP ${res.status}`;
64
+ try {
65
+ const body = JSON.parse(text);
66
+ if (typeof body.error === "string" && typeof body.message === "string") {
67
+ code = body.error;
68
+ message = body.message;
69
+ }
70
+ } catch {
71
+ }
72
+ return new SMSWireError(res.status, code, message, retryAfter(res.headers.get("retry-after")));
73
+ }
74
+ function retryDelay(err, req, attempt, opts) {
75
+ if (attempt >= opts.maxRetries) return null;
76
+ const retryable = err.status === 429 || req.idempotent && (err.status === null || err.status >= 500);
77
+ if (!retryable) return null;
78
+ if (err.retryAfter !== null) return err.retryAfter <= opts.maxRetryWait ? err.retryAfter : null;
79
+ return backoff(attempt);
80
+ }
81
+ async function send(opts, req) {
82
+ const url = new URL(opts.baseUrl.replace(/\/+$/, "") + req.path);
83
+ for (const [k, v] of Object.entries(req.query ?? {})) {
84
+ if (v !== void 0 && v !== null) url.searchParams.set(k, String(v));
85
+ }
86
+ const headers = {
87
+ Authorization: `Bearer ${opts.apiKey}`,
88
+ Accept: "application/json",
89
+ "User-Agent": opts.userAgent,
90
+ ...req.headers
91
+ };
92
+ if (req.body !== void 0) headers["Content-Type"] = "application/json";
93
+ const body = req.body === void 0 ? void 0 : JSON.stringify(req.body);
94
+ for (let attempt = 0; ; attempt++) {
95
+ let res;
96
+ let err;
97
+ try {
98
+ res = await opts.fetch(url, { method: req.method, headers, body, signal: AbortSignal.timeout(opts.timeout) });
99
+ } catch (e) {
100
+ const timedOut = e instanceof Error && e.name === "TimeoutError";
101
+ err = new SMSWireError(
102
+ null,
103
+ timedOut ? "timeout" : "network_error",
104
+ timedOut ? `No answer within ${opts.timeout} ms` : `Could not reach ${url.origin}: ${e.message}`,
105
+ null,
106
+ { cause: e }
107
+ );
108
+ }
109
+ if (res?.ok) {
110
+ const text = await res.text();
111
+ return text ? JSON.parse(text) : void 0;
112
+ }
113
+ if (res) err = await errorFrom(res);
114
+ const wait = retryDelay(err, req, attempt, opts);
115
+ if (wait === null) throw err;
116
+ await sleep(wait);
117
+ }
118
+ }
119
+
120
+ // src/resources/messages.ts
121
+ var Messages = class {
122
+ constructor(call, base) {
123
+ this.call = call;
124
+ this.base = base;
125
+ }
126
+ call;
127
+ base;
128
+ /** Queues one SMS for the project's phone. */
129
+ send(params, options = {}) {
130
+ return this.call({
131
+ method: "POST",
132
+ path: this.base,
133
+ body: params,
134
+ headers: { "Idempotency-Key": options.idempotencyKey ?? crypto.randomUUID() },
135
+ idempotent: true
136
+ });
137
+ }
138
+ /** Queues a batch. Invalid or opted-out items come back in `rejected`; the rest go out as one batch. */
139
+ sendBulk(params) {
140
+ return this.call({ method: "POST", path: `${this.base}/bulk`, body: params, idempotent: false });
141
+ }
142
+ get(id) {
143
+ return this.call({ method: "GET", path: `${this.base}/${encodeURIComponent(id)}`, idempotent: true });
144
+ }
145
+ /** Stops a message that hasn't reached a phone yet. */
146
+ cancel(id) {
147
+ return this.call({ method: "DELETE", path: `${this.base}/${encodeURIComponent(id)}`, idempotent: true });
148
+ }
149
+ /** One page, newest first. Pass `next_cursor` back as `cursor` for the next. */
150
+ list(params = {}) {
151
+ return this.call({ method: "GET", path: this.base, query: params, idempotent: true });
152
+ }
153
+ /** Every matching message, newest first, fetching pages as you go. */
154
+ async *listAll(params = {}) {
155
+ let cursor;
156
+ do {
157
+ const page = await this.list({ ...params, cursor: cursor ?? void 0 });
158
+ yield* page.data;
159
+ cursor = page.next_cursor;
160
+ } while (cursor);
161
+ }
162
+ };
163
+
164
+ // src/resources/otp.ts
165
+ var OneTimeCodes = class {
166
+ constructor(call, base) {
167
+ this.call = call;
168
+ this.base = base;
169
+ }
170
+ call;
171
+ base;
172
+ /** Texts a fresh code to `to`. Keep the returned `id` for verify(). */
173
+ send(params) {
174
+ return this.call({ method: "POST", path: this.base, body: params, idempotent: false });
175
+ }
176
+ /** Checks what the user typed. `valid` is false with a `reason` when it's wrong, expired or used. */
177
+ verify(params) {
178
+ return this.call({ method: "POST", path: `${this.base}/verify`, body: params, idempotent: false });
179
+ }
180
+ };
181
+
182
+ // src/resources/schedules.ts
183
+ var Schedules = class {
184
+ constructor(call, base) {
185
+ this.call = call;
186
+ this.base = base;
187
+ }
188
+ call;
189
+ base;
190
+ /** A message (or batch) sent again and again on a cron schedule. */
191
+ create(params) {
192
+ return this.call({ method: "POST", path: this.base, body: params, idempotent: false });
193
+ }
194
+ list() {
195
+ return this.call({ method: "GET", path: this.base, idempotent: true });
196
+ }
197
+ /** One schedule, with its recent runs. */
198
+ get(id) {
199
+ return this.call({ method: "GET", path: `${this.base}/${encodeURIComponent(id)}`, idempotent: true });
200
+ }
201
+ /** Absent fields stay as they are; recipients can't change. */
202
+ update(id, params) {
203
+ return this.call({ method: "PATCH", path: `${this.base}/${encodeURIComponent(id)}`, body: params, idempotent: true });
204
+ }
205
+ async delete(id) {
206
+ await this.call({ method: "DELETE", path: `${this.base}/${encodeURIComponent(id)}`, idempotent: true });
207
+ }
208
+ };
209
+
210
+ // src/webhooks.ts
211
+ var SIGNATURE_HEADER = "X-SMSWire-Signature";
212
+ var encoder = new TextEncoder();
213
+ function bytes(body) {
214
+ if (typeof body === "string") return encoder.encode(body);
215
+ return body instanceof Uint8Array ? body : new Uint8Array(body);
216
+ }
217
+ function parse(header) {
218
+ let t = null;
219
+ const signatures = [];
220
+ for (const part of header.split(",")) {
221
+ const i = part.indexOf("=");
222
+ if (i < 0) continue;
223
+ const key = part.slice(0, i).trim();
224
+ const value = part.slice(i + 1).trim();
225
+ if (key === "t" && /^\d+$/.test(value)) t = Number(value);
226
+ else if (key === "v1" && /^[0-9a-f]{64}$/i.test(value)) signatures.push(value.toLowerCase());
227
+ }
228
+ return t === null || !signatures.length ? null : { t, signatures };
229
+ }
230
+ async function hmacHex(secret, message) {
231
+ const key = await crypto.subtle.importKey("raw", encoder.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
232
+ const mac = new Uint8Array(await crypto.subtle.sign("HMAC", key, message));
233
+ return Array.from(mac, (b) => b.toString(16).padStart(2, "0")).join("");
234
+ }
235
+ function constantTimeEqual(a, b) {
236
+ if (a.length !== b.length) return false;
237
+ let diff = 0;
238
+ for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
239
+ return diff === 0;
240
+ }
241
+ async function verifyWebhook(rawBody, signature, secret, options = {}) {
242
+ if (!secret) throw new SMSWireSignatureError("No webhook signing secret given");
243
+ const parsed = parse(signature ?? "");
244
+ if (!parsed) throw new SMSWireSignatureError(`Missing or malformed ${SIGNATURE_HEADER} header`);
245
+ const now = options.now ?? Math.floor(Date.now() / 1e3);
246
+ if (Math.abs(now - parsed.t) > (options.tolerance ?? 300)) {
247
+ throw new SMSWireSignatureError("Signature timestamp is outside the tolerance");
248
+ }
249
+ const body = bytes(rawBody);
250
+ const prefix = encoder.encode(`${parsed.t}.`);
251
+ const signed = new Uint8Array(prefix.length + body.length);
252
+ signed.set(prefix);
253
+ signed.set(body, prefix.length);
254
+ const expected = await hmacHex(secret, signed);
255
+ if (!parsed.signatures.some((s) => constantTimeEqual(s, expected))) {
256
+ throw new SMSWireSignatureError("Signature does not match");
257
+ }
258
+ return JSON.parse(new TextDecoder().decode(body));
259
+ }
260
+
261
+ // src/client.ts
262
+ var VERSION = "0.1.0";
263
+ var env = (name) => typeof process === "undefined" ? void 0 : process.env?.[name] || void 0;
264
+ var SMSWire = class {
265
+ messages;
266
+ otp;
267
+ schedules;
268
+ webhooks;
269
+ constructor(options = {}) {
270
+ const apiKey = options.apiKey ?? env("SMSWIRE_KEY");
271
+ const project = options.project ?? env("SMSWIRE_PROJECT");
272
+ if (!apiKey) throw new Error("SMSWire: pass apiKey or set SMSWIRE_KEY");
273
+ if (!project) throw new Error("SMSWire: pass project or set SMSWIRE_PROJECT");
274
+ const http = {
275
+ apiKey,
276
+ baseUrl: options.baseUrl ?? env("SMSWIRE_URL") ?? "https://api.smswire.app",
277
+ maxRetries: options.maxRetries ?? 2,
278
+ maxRetryWait: options.maxRetryWait ?? 60,
279
+ timeout: options.timeout ?? 3e4,
280
+ fetch: options.fetch ?? globalThis.fetch.bind(globalThis),
281
+ userAgent: `smswire-node/${VERSION}`
282
+ };
283
+ const call = (req) => send(http, req);
284
+ const p = `/v1/p/${encodeURIComponent(project)}`;
285
+ this.messages = new Messages(call, `${p}/messages`);
286
+ this.otp = new OneTimeCodes(call, `${p}/otp`);
287
+ this.schedules = new Schedules(call, `${p}/schedules`);
288
+ const secret = options.webhookSecret ?? env("SMSWIRE_WEBHOOK_SECRET");
289
+ this.webhooks = {
290
+ verify: (rawBody, signature, opts) => {
291
+ if (!secret) throw new Error("SMSWire: pass webhookSecret or set SMSWIRE_WEBHOOK_SECRET");
292
+ return verifyWebhook(rawBody, signature, secret, opts);
293
+ }
294
+ };
295
+ }
296
+ };
297
+
298
+ // src/index.ts
299
+ var index_default = SMSWire;
300
+ // Annotate the CommonJS export names for ESM import in node:
301
+ 0 && (module.exports = {
302
+ SIGNATURE_HEADER,
303
+ SMSWire,
304
+ SMSWireError,
305
+ SMSWireSignatureError,
306
+ VERSION,
307
+ verifyWebhook
308
+ });
309
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/errors.ts","../src/http.ts","../src/resources/messages.ts","../src/resources/otp.ts","../src/resources/schedules.ts","../src/webhooks.ts","../src/client.ts"],"sourcesContent":["import { SMSWire } from './client';\n\nexport { SMSWire, VERSION, type ClientOptions } from './client';\nexport { SMSWireError, SMSWireSignatureError } from './errors';\nexport { verifyWebhook, SIGNATURE_HEADER, type VerifyOptions } from './webhooks';\nexport type { SendOptions } from './resources/messages';\nexport type * from './types';\nexport default SMSWire;\n","/** A request that failed: the API's answer (status, code, message) or a network problem (status null). */\nexport class SMSWireError extends Error {\n override readonly name: string = 'SMSWireError';\n\n constructor(\n /** HTTP status, or null when no answer arrived. */\n readonly status: number | null,\n /** Stable machine code, e.g. `invalid_request`, `rate_limited`, `network_error`, `timeout`. */\n readonly code: string,\n message: string,\n /** Seconds until trying again makes sense (from Retry-After), when the API said. */\n readonly retryAfter: number | null = null,\n options?: { cause?: unknown },\n ) {\n super(message, options);\n }\n}\n\n/** A webhook whose signature is missing, wrong or too old. Answer it with 400. */\nexport class SMSWireSignatureError extends Error {\n override readonly name = 'SMSWireSignatureError';\n}\n","import { SMSWireError } from './errors';\n\nexport interface HttpOptions {\n apiKey: string;\n baseUrl: string;\n maxRetries: number;\n maxRetryWait: number;\n timeout: number;\n fetch: typeof fetch;\n userAgent: string;\n}\n\nexport interface Request {\n method: 'GET' | 'POST' | 'PATCH' | 'DELETE';\n path: string;\n query?: Record<string, unknown>;\n body?: unknown;\n headers?: Record<string, string>;\n /** Safe to repeat after a 5xx or a dropped connection (GET, PATCH, DELETE, or a POST with an Idempotency-Key). */\n idempotent: boolean;\n}\n\nconst sleep = (seconds: number) => new Promise((r) => setTimeout(r, seconds * 1000));\n\n/** Seconds from a Retry-After header (seconds or an HTTP date). */\nfunction retryAfter(header: string | null): number | null {\n if (!header) return null;\n const n = Number(header);\n if (Number.isFinite(n)) return Math.max(0, n);\n const at = Date.parse(header);\n return Number.isNaN(at) ? null : Math.max(0, (at - Date.now()) / 1000);\n}\n\n/** Exponential backoff from 0.5 s, capped at 8 s, with up to 25% jitter. */\nconst backoff = (attempt: number) => Math.min(8, 0.5 * 2 ** attempt) * (1 + Math.random() * 0.25);\n\n/** The SDK's error for a non-2xx answer. */\nexport async function errorFrom(res: Response): Promise<SMSWireError> {\n const text = await res.text().catch(() => '');\n let code = 'http_error';\n let message = `HTTP ${res.status}`;\n try {\n const body = JSON.parse(text) as { error?: unknown; message?: unknown };\n if (typeof body.error === 'string' && typeof body.message === 'string') {\n code = body.error;\n message = body.message;\n }\n } catch {\n // Not JSON (a proxy's error page): keep the generic code.\n }\n return new SMSWireError(res.status, code, message, retryAfter(res.headers.get('retry-after')));\n}\n\n/** Whether to try [err] again on attempt [attempt] (0-based), and after how long. */\nexport function retryDelay(err: SMSWireError, req: Pick<Request, 'idempotent'>, attempt: number, opts: Pick<HttpOptions, 'maxRetries' | 'maxRetryWait'>): number | null {\n if (attempt >= opts.maxRetries) return null;\n const retryable = err.status === 429 || (req.idempotent && (err.status === null || err.status >= 500));\n if (!retryable) return null;\n if (err.retryAfter !== null) return err.retryAfter <= opts.maxRetryWait ? err.retryAfter : null;\n return backoff(attempt);\n}\n\nexport async function send<T>(opts: HttpOptions, req: Request): Promise<T> {\n const url = new URL(opts.baseUrl.replace(/\\/+$/, '') + req.path);\n for (const [k, v] of Object.entries(req.query ?? {})) {\n if (v !== undefined && v !== null) url.searchParams.set(k, String(v));\n }\n const headers: Record<string, string> = {\n Authorization: `Bearer ${opts.apiKey}`,\n Accept: 'application/json',\n 'User-Agent': opts.userAgent,\n ...req.headers,\n };\n if (req.body !== undefined) headers['Content-Type'] = 'application/json';\n const body = req.body === undefined ? undefined : JSON.stringify(req.body);\n\n for (let attempt = 0; ; attempt++) {\n let res: Response | undefined;\n let err: SMSWireError;\n try {\n res = await opts.fetch(url, { method: req.method, headers, body, signal: AbortSignal.timeout(opts.timeout) });\n } catch (e) {\n const timedOut = e instanceof Error && e.name === 'TimeoutError';\n err = new SMSWireError(\n null,\n timedOut ? 'timeout' : 'network_error',\n timedOut ? `No answer within ${opts.timeout} ms` : `Could not reach ${url.origin}: ${(e as Error).message}`,\n null,\n { cause: e },\n );\n }\n if (res?.ok) {\n const text = await res.text();\n return (text ? JSON.parse(text) : undefined) as T;\n }\n if (res) err = await errorFrom(res);\n const wait = retryDelay(err!, req, attempt, opts);\n if (wait === null) throw err!;\n await sleep(wait);\n }\n}\n","import type { Request } from '../http';\nimport type { BulkResult, ListMessagesParams, Message, MessagePage, SendBulkParams, SendMessageParams } from '../types';\n\nexport type Call = <T>(req: Request) => Promise<T>;\n\nexport interface SendOptions {\n /**\n * Repeating a send with the same key returns the first message instead of sending again.\n * Defaults to a fresh random key, so the SDK's own retries never send twice; pass your own\n * (an order id, say) to make your retries safe too.\n */\n idempotencyKey?: string;\n}\n\nexport class Messages {\n constructor(\n private readonly call: Call,\n private readonly base: string,\n ) {}\n\n /** Queues one SMS for the project's phone. */\n send(params: SendMessageParams, options: SendOptions = {}): Promise<Message> {\n return this.call({\n method: 'POST',\n path: this.base,\n body: params,\n headers: { 'Idempotency-Key': options.idempotencyKey ?? crypto.randomUUID() },\n idempotent: true,\n });\n }\n\n /** Queues a batch. Invalid or opted-out items come back in `rejected`; the rest go out as one batch. */\n sendBulk(params: SendBulkParams): Promise<BulkResult> {\n return this.call({ method: 'POST', path: `${this.base}/bulk`, body: params, idempotent: false });\n }\n\n get(id: string): Promise<Message> {\n return this.call({ method: 'GET', path: `${this.base}/${encodeURIComponent(id)}`, idempotent: true });\n }\n\n /** Stops a message that hasn't reached a phone yet. */\n cancel(id: string): Promise<Message> {\n return this.call({ method: 'DELETE', path: `${this.base}/${encodeURIComponent(id)}`, idempotent: true });\n }\n\n /** One page, newest first. Pass `next_cursor` back as `cursor` for the next. */\n list(params: ListMessagesParams = {}): Promise<MessagePage> {\n return this.call({ method: 'GET', path: this.base, query: params, idempotent: true });\n }\n\n /** Every matching message, newest first, fetching pages as you go. */\n async *listAll(params: Omit<ListMessagesParams, 'cursor'> = {}): AsyncGenerator<Message> {\n let cursor: string | null | undefined;\n do {\n const page = await this.list({ ...params, cursor: cursor ?? undefined });\n yield* page.data;\n cursor = page.next_cursor;\n } while (cursor);\n }\n}\n","import type { Otp, OtpVerification, SendOtpParams, VerifyOtpParams } from '../types';\nimport type { Call } from './messages';\n\nexport class OneTimeCodes {\n constructor(\n private readonly call: Call,\n private readonly base: string,\n ) {}\n\n /** Texts a fresh code to `to`. Keep the returned `id` for verify(). */\n send(params: SendOtpParams): Promise<Otp> {\n return this.call({ method: 'POST', path: this.base, body: params, idempotent: false });\n }\n\n /** Checks what the user typed. `valid` is false with a `reason` when it's wrong, expired or used. */\n verify(params: VerifyOtpParams): Promise<OtpVerification> {\n return this.call({ method: 'POST', path: `${this.base}/verify`, body: params, idempotent: false });\n }\n}\n","import type { CreateScheduleParams, Schedule, SchedulePage, UpdateScheduleParams } from '../types';\nimport type { Call } from './messages';\n\nexport class Schedules {\n constructor(\n private readonly call: Call,\n private readonly base: string,\n ) {}\n\n /** A message (or batch) sent again and again on a cron schedule. */\n create(params: CreateScheduleParams): Promise<Schedule> {\n return this.call({ method: 'POST', path: this.base, body: params, idempotent: false });\n }\n\n list(): Promise<SchedulePage> {\n return this.call({ method: 'GET', path: this.base, idempotent: true });\n }\n\n /** One schedule, with its recent runs. */\n get(id: string): Promise<Schedule> {\n return this.call({ method: 'GET', path: `${this.base}/${encodeURIComponent(id)}`, idempotent: true });\n }\n\n /** Absent fields stay as they are; recipients can't change. */\n update(id: string, params: UpdateScheduleParams): Promise<Schedule> {\n return this.call({ method: 'PATCH', path: `${this.base}/${encodeURIComponent(id)}`, body: params, idempotent: true });\n }\n\n async delete(id: string): Promise<void> {\n await this.call({ method: 'DELETE', path: `${this.base}/${encodeURIComponent(id)}`, idempotent: true });\n }\n}\n","import { SMSWireSignatureError } from './errors';\nimport type { WebhookEvent } from './types';\n\nexport interface VerifyOptions {\n /** Oldest (and furthest in the future) signature accepted, in seconds. Default 300. */\n tolerance?: number;\n /** The current time in unix seconds; for tests. */\n now?: number;\n}\n\n/** The header the signature arrives in. */\nexport const SIGNATURE_HEADER = 'X-SMSWire-Signature';\n\nconst encoder = new TextEncoder();\n\nfunction bytes(body: string | Uint8Array | ArrayBuffer): Uint8Array {\n if (typeof body === 'string') return encoder.encode(body);\n return body instanceof Uint8Array ? body : new Uint8Array(body);\n}\n\n/** `t=<unix>,v1=<hex>[,v1=<hex>…]`, in any order; null when it isn't one. */\nfunction parse(header: string): { t: number; signatures: string[] } | null {\n let t: number | null = null;\n const signatures: string[] = [];\n for (const part of header.split(',')) {\n const i = part.indexOf('=');\n if (i < 0) continue;\n const key = part.slice(0, i).trim();\n const value = part.slice(i + 1).trim();\n if (key === 't' && /^\\d+$/.test(value)) t = Number(value);\n else if (key === 'v1' && /^[0-9a-f]{64}$/i.test(value)) signatures.push(value.toLowerCase());\n }\n return t === null || !signatures.length ? null : { t, signatures };\n}\n\nasync function hmacHex(secret: string, message: Uint8Array<ArrayBuffer>): Promise<string> {\n const key = await crypto.subtle.importKey('raw', encoder.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);\n const mac = new Uint8Array(await crypto.subtle.sign('HMAC', key, message));\n return Array.from(mac, (b) => b.toString(16).padStart(2, '0')).join('');\n}\n\n/** Compares two equal-length strings without stopping at the first difference. */\nfunction constantTimeEqual(a: string, b: string): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);\n return diff === 0;\n}\n\n/**\n * Checks a webhook's X-SMSWire-Signature against the **raw** request body (not re-serialised JSON)\n * and returns the parsed event. Throws SMSWireSignatureError when the signature is missing,\n * wrong, or more than `tolerance` seconds off.\n */\nexport async function verifyWebhook(\n rawBody: string | Uint8Array | ArrayBuffer,\n signature: string | null | undefined,\n secret: string,\n options: VerifyOptions = {},\n): Promise<WebhookEvent> {\n if (!secret) throw new SMSWireSignatureError('No webhook signing secret given');\n const parsed = parse(signature ?? '');\n if (!parsed) throw new SMSWireSignatureError(`Missing or malformed ${SIGNATURE_HEADER} header`);\n const now = options.now ?? Math.floor(Date.now() / 1000);\n if (Math.abs(now - parsed.t) > (options.tolerance ?? 300)) {\n throw new SMSWireSignatureError('Signature timestamp is outside the tolerance');\n }\n const body = bytes(rawBody);\n const prefix = encoder.encode(`${parsed.t}.`);\n const signed = new Uint8Array(prefix.length + body.length);\n signed.set(prefix);\n signed.set(body, prefix.length);\n const expected = await hmacHex(secret, signed);\n if (!parsed.signatures.some((s) => constantTimeEqual(s, expected))) {\n throw new SMSWireSignatureError('Signature does not match');\n }\n return JSON.parse(new TextDecoder().decode(body)) as WebhookEvent;\n}\n","import { send, type HttpOptions, type Request } from './http';\nimport { Messages } from './resources/messages';\nimport { OneTimeCodes } from './resources/otp';\nimport { Schedules } from './resources/schedules';\nimport type { WebhookEvent } from './types';\nimport { verifyWebhook, type VerifyOptions } from './webhooks';\n\nexport const VERSION = '0.1.0';\n\nexport interface ClientOptions {\n /** The project's API key (`smswire_live_…`). Defaults to SMSWIRE_KEY. */\n apiKey?: string;\n /** The project's slug, the part after /p/ in its endpoint. Defaults to SMSWIRE_PROJECT. */\n project?: string;\n /** Defaults to SMSWIRE_URL, then https://api.smswire.app. */\n baseUrl?: string;\n /** Signing secret (`whsec_…`) for webhooks.verify(). Defaults to SMSWIRE_WEBHOOK_SECRET. */\n webhookSecret?: string;\n /** Retries after a 429, a 5xx or a network error (see the README for which calls). Default 2. */\n maxRetries?: number;\n /** Longest Retry-After worth waiting for, in seconds; longer ones throw at once. Default 60. */\n maxRetryWait?: number;\n /** Per-attempt timeout in milliseconds. Default 30 000. */\n timeout?: number;\n /** A fetch implementation, for runtimes or tests that need their own. */\n fetch?: typeof fetch;\n}\n\nconst env = (name: string): string | undefined =>\n typeof process === 'undefined' ? undefined : process.env?.[name] || undefined;\n\nexport class SMSWire {\n readonly messages: Messages;\n readonly otp: OneTimeCodes;\n readonly schedules: Schedules;\n readonly webhooks: { verify(rawBody: string | Uint8Array | ArrayBuffer, signature: string | null | undefined, options?: VerifyOptions): Promise<WebhookEvent> };\n\n constructor(options: ClientOptions = {}) {\n const apiKey = options.apiKey ?? env('SMSWIRE_KEY');\n const project = options.project ?? env('SMSWIRE_PROJECT');\n if (!apiKey) throw new Error('SMSWire: pass apiKey or set SMSWIRE_KEY');\n if (!project) throw new Error('SMSWire: pass project or set SMSWIRE_PROJECT');\n\n const http: HttpOptions = {\n apiKey,\n baseUrl: options.baseUrl ?? env('SMSWIRE_URL') ?? 'https://api.smswire.app',\n maxRetries: options.maxRetries ?? 2,\n maxRetryWait: options.maxRetryWait ?? 60,\n timeout: options.timeout ?? 30_000,\n fetch: options.fetch ?? globalThis.fetch.bind(globalThis),\n userAgent: `smswire-node/${VERSION}`,\n };\n const call = <T>(req: Request) => send<T>(http, req);\n const p = `/v1/p/${encodeURIComponent(project)}`;\n this.messages = new Messages(call, `${p}/messages`);\n this.otp = new OneTimeCodes(call, `${p}/otp`);\n this.schedules = new Schedules(call, `${p}/schedules`);\n\n const secret = options.webhookSecret ?? env('SMSWIRE_WEBHOOK_SECRET');\n this.webhooks = {\n verify: (rawBody, signature, opts) => {\n if (!secret) throw new Error('SMSWire: pass webhookSecret or set SMSWIRE_WEBHOOK_SECRET');\n return verifyWebhook(rawBody, signature, secret, opts);\n },\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCO,IAAM,eAAN,cAA2B,MAAM;AAAA,EAGtC,YAEW,QAEA,MACT,SAESA,cAA4B,MACrC,SACA;AACA,UAAM,SAAS,OAAO;AARb;AAEA;AAGA,sBAAAA;AAAA,EAIX;AAAA,EATW;AAAA,EAEA;AAAA,EAGA;AAAA,EATO,OAAe;AAcnC;AAGO,IAAM,wBAAN,cAAoC,MAAM;AAAA,EAC7B,OAAO;AAC3B;;;ACCA,IAAM,QAAQ,CAAC,YAAoB,IAAI,QAAQ,CAAC,MAAM,WAAW,GAAG,UAAU,GAAI,CAAC;AAGnF,SAAS,WAAW,QAAsC;AACxD,MAAI,CAAC,OAAQ,QAAO;AACpB,QAAM,IAAI,OAAO,MAAM;AACvB,MAAI,OAAO,SAAS,CAAC,EAAG,QAAO,KAAK,IAAI,GAAG,CAAC;AAC5C,QAAM,KAAK,KAAK,MAAM,MAAM;AAC5B,SAAO,OAAO,MAAM,EAAE,IAAI,OAAO,KAAK,IAAI,IAAI,KAAK,KAAK,IAAI,KAAK,GAAI;AACvE;AAGA,IAAM,UAAU,CAAC,YAAoB,KAAK,IAAI,GAAG,MAAM,KAAK,OAAO,KAAK,IAA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