@billionsend/node 0.1.0 → 0.2.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/dist/index.cjs CHANGED
@@ -33,6 +33,11 @@ var RateLimitError = class extends BillionSendError {
33
33
  }
34
34
  };
35
35
  var APIError = class extends BillionSendError {
36
+ retryAfter;
37
+ constructor(init) {
38
+ super(init);
39
+ this.retryAfter = init.retryAfter ?? null;
40
+ }
36
41
  };
37
42
  var APIConnectionError = class extends BillionSendError {
38
43
  constructor(message = "Connection error") {
@@ -76,7 +81,7 @@ function errorClass(status) {
76
81
  case 409:
77
82
  return ConflictError;
78
83
  default:
79
- return status >= 500 ? APIError : BillionSendError;
84
+ return BillionSendError;
80
85
  }
81
86
  }
82
87
  function errorFromResponse(status, statusText, text, headers = {}) {
@@ -99,6 +104,7 @@ function errorFromResponse(status, statusText, text, headers = {}) {
99
104
  const init = { message, name, statusCode: status, requestId: headers["x-request-id"] ?? null };
100
105
  if (status === 429)
101
106
  return new RateLimitError({ ...init, retryAfter: parseRetryAfter(headers["retry-after"]) });
107
+ if (status >= 500) return new APIError({ ...init, retryAfter: parseRetryAfter(headers["retry-after"]) });
102
108
  return new (errorClass(status))(init);
103
109
  }
104
110
 
@@ -135,8 +141,9 @@ function newIdempotencyKey() {
135
141
  const bytes = new Uint8Array(16);
136
142
  if (typeof webCrypto?.getRandomValues === "function") webCrypto.getRandomValues(bytes);
137
143
  else for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256);
138
- bytes[6] = (bytes[6] ?? 0) & 15 | 64;
139
- bytes[8] = (bytes[8] ?? 0) & 63 | 128;
144
+ const view = new DataView(bytes.buffer);
145
+ view.setUint8(6, view.getUint8(6) & 15 | 64);
146
+ view.setUint8(8, view.getUint8(8) & 63 | 128);
140
147
  const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
141
148
  return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
142
149
  }
@@ -159,7 +166,7 @@ function sleep(ms, signal) {
159
166
  }
160
167
 
161
168
  // src/version.ts
162
- var VERSION = "0.1.0";
169
+ var VERSION = "0.2.0";
163
170
 
164
171
  // src/core.ts
165
172
  var DEFAULT_BASE_URL = "https://api.billionsend.com";
@@ -170,6 +177,10 @@ function readEnv(name) {
170
177
  const value = env?.[name];
171
178
  return value === void 0 || value === "" ? void 0 : value;
172
179
  }
180
+ function cleanKey(key) {
181
+ const trimmed = key?.trim();
182
+ return trimmed === void 0 || trimmed === "" ? void 0 : trimmed;
183
+ }
173
184
  function failure(error, headers = null) {
174
185
  return { data: null, error, headers };
175
186
  }
@@ -195,17 +206,33 @@ function lowerCaseKeys(headers) {
195
206
  }
196
207
  return out;
197
208
  }
209
+ var HEADER_NAME = /^[!#$%&'*+.^_`|~0-9a-z-]+$/;
210
+ var HEADER_VALUE = /^[\t\x20-\x7e]*$/;
211
+ function invalidHeader(headers) {
212
+ for (const [name, value] of Object.entries(headers)) {
213
+ if (!HEADER_NAME.test(name)) return JSON.stringify(name.replace(/[^\x20-\x7e]/g, "?"));
214
+ if (!HEADER_VALUE.test(value)) return name;
215
+ }
216
+ return void 0;
217
+ }
198
218
  function fillPath(template, params) {
199
219
  let missing;
220
+ let dotted;
200
221
  const filled = template.replace(/\{([^}]+)\}/g, (_, name) => {
201
222
  const value = params?.[name];
202
223
  if (value === void 0 || value === null || String(value) === "") {
203
224
  missing ??= name;
204
225
  return "";
205
226
  }
206
- return encodeURIComponent(String(value));
227
+ const text = String(value);
228
+ if (text === "." || text === "..") dotted ??= name;
229
+ return encodeURIComponent(text);
207
230
  });
208
- return missing === void 0 ? filled : applicationError(`Missing path parameter "${missing}"`);
231
+ if (missing !== void 0) return applicationError(`Missing path parameter "${missing}"`);
232
+ if (dotted !== void 0) {
233
+ return applicationError(`Invalid path parameter "${dotted}": "." and ".." are not ids`);
234
+ }
235
+ return filled;
209
236
  }
210
237
  function queryString(query) {
211
238
  if (!query) return "";
@@ -213,7 +240,7 @@ function queryString(query) {
213
240
  for (const [key, value] of Object.entries(query)) {
214
241
  if (value === void 0 || value === null) continue;
215
242
  if (Array.isArray(value)) {
216
- params.append(key, value.map(String).join(","));
243
+ if (value.length > 0) params.append(key, value.map(String).join(","));
217
244
  } else {
218
245
  params.append(key, String(value));
219
246
  }
@@ -229,7 +256,7 @@ var Core = class {
229
256
  #fetch;
230
257
  #headers;
231
258
  constructor(options) {
232
- this.#apiKey = options.apiKey ?? readEnv("BILLIONSEND_API_KEY");
259
+ this.#apiKey = cleanKey(options.apiKey) ?? cleanKey(readEnv("BILLIONSEND_API_KEY"));
233
260
  this.baseUrl = (options.baseUrl ?? readEnv("BILLIONSEND_BASE_URL") ?? DEFAULT_BASE_URL).replace(
234
261
  /\/+$/,
235
262
  ""
@@ -247,10 +274,6 @@ var Core = class {
247
274
  this.#fetch = fetchImpl;
248
275
  this.#headers = lowerCaseKeys(options.headers);
249
276
  }
250
- /** Whether an API key is configured. */
251
- get hasApiKey() {
252
- return this.#apiKey !== void 0;
253
- }
254
277
  /** Calls one operation and parses its JSON answer. */
255
278
  request(method, path, init = {}) {
256
279
  return this.#execute(method, path, init, false);
@@ -282,7 +305,10 @@ var Core = class {
282
305
  ...lowerCaseKeys(init.headers)
283
306
  };
284
307
  let body;
285
- if (init.body !== void 0) {
308
+ if (init.form !== void 0) {
309
+ body = init.form;
310
+ delete headers["content-type"];
311
+ } else if (init.body !== void 0) {
286
312
  body = JSON.stringify(init.body);
287
313
  headers["content-type"] = "application/json";
288
314
  }
@@ -292,14 +318,24 @@ var Core = class {
292
318
  }
293
319
  if (auth) headers.authorization = `Bearer ${this.#apiKey}`;
294
320
  else delete headers.authorization;
321
+ const invalid = invalidHeader(headers);
322
+ if (invalid !== void 0) {
323
+ return failure(
324
+ new BillionSendError({
325
+ name: "invalid_header",
326
+ message: `The ${invalid} header has a value HTTP cannot carry (only printable ASCII and tabs); nothing was sent`
327
+ })
328
+ );
329
+ }
295
330
  const keyed = headers["idempotency-key"] !== void 0;
296
- const retryable2 = IDEMPOTENT_METHODS.has(method) || keyed;
331
+ const safeToRepeat = IDEMPOTENT_METHODS.has(method) || keyed;
297
332
  const maxRetries = options.maxRetries ?? this.maxRetries;
298
333
  const timeoutMs = options.timeoutMs ?? this.timeoutMs;
299
334
  for (let attempt = 0; ; attempt++) {
300
335
  const outcome = await this.#attempt(method, url, headers, body, timeoutMs, options.signal, stream);
301
336
  const error = outcome.result.error;
302
- if (error === null || !retryable2 || attempt >= maxRetries || !retryable(error, keyed)) {
337
+ const mayRepeat = safeToRepeat || error?.statusCode === 429;
338
+ if (error === null || !mayRepeat || attempt >= maxRetries || !retryable(error, keyed)) {
303
339
  return outcome.result;
304
340
  }
305
341
  const delay = retryDelayMs(attempt, outcome.retryAfter);
@@ -308,6 +344,7 @@ var Core = class {
308
344
  }
309
345
  }
310
346
  async #attempt(method, url, headers, body, timeoutMs, signal, stream) {
347
+ if (signal?.aborted) return { result: failure(applicationError("Request was aborted")) };
311
348
  const controller = new AbortController();
312
349
  let timedOut = false;
313
350
  const timer = setTimeout(() => {
@@ -315,8 +352,7 @@ var Core = class {
315
352
  controller.abort();
316
353
  }, timeoutMs);
317
354
  const onAbort = () => controller.abort();
318
- if (signal?.aborted) controller.abort();
319
- else signal?.addEventListener("abort", onAbort, { once: true });
355
+ signal?.addEventListener("abort", onAbort, { once: true });
320
356
  const release = () => {
321
357
  clearTimeout(timer);
322
358
  signal?.removeEventListener("abort", onAbort);
@@ -356,6 +392,8 @@ var Core = class {
356
392
  const text = await response.text();
357
393
  release();
358
394
  if (response.ok) {
395
+ if (text.trim() === "")
396
+ return { result: { data: null, error: null, headers: responseHeaders } };
359
397
  try {
360
398
  return { result: { data: JSON.parse(text), error: null, headers: responseHeaders } };
361
399
  } catch {
@@ -395,12 +433,19 @@ async function* paginate(fetchPage, start = {}) {
395
433
  while (true) {
396
434
  const page = await fetchPage(cursor);
397
435
  if (page.error !== null) throw page.error;
398
- const items = page.data.data;
436
+ const body = page.data;
437
+ const items = typeof body === "object" && body !== null ? body.data : void 0;
438
+ if (!Array.isArray(items)) throw applicationError("The list page has no data array");
399
439
  for (const item of items) yield item;
400
- if (!page.data.has_more || items.length === 0) return;
440
+ if (page.data.has_more !== true || items.length === 0) return;
401
441
  const edge = backward ? items[0] : items[items.length - 1];
402
- if (edge === void 0) return;
403
- cursor = backward ? { before: edge.id } : { after: edge.id };
442
+ const id = typeof edge === "object" && edge !== null ? edge.id : void 0;
443
+ if (typeof id !== "string" || id === "") {
444
+ throw applicationError(
445
+ `The ${backward ? "first" : "last"} item of the list page has no id to continue from`
446
+ );
447
+ }
448
+ cursor = backward ? { before: id } : { after: id };
404
449
  }
405
450
  }
406
451
 
@@ -416,7 +461,22 @@ function idempotent(options) {
416
461
  }
417
462
 
418
463
  // src/resources/account.ts
464
+ var DomainClaims = class extends Resource {
465
+ /** `POST /domains/claim`: starts a claim on a domain another team already holds. */
466
+ create(payload, options) {
467
+ return this.core.request("post", "/domains/claim", { body: payload, options });
468
+ }
469
+ /** `GET /domains/{id}/claim` */
470
+ get(id, options) {
471
+ return this.core.request("get", "/domains/{id}/claim", { path: { id }, options });
472
+ }
473
+ /** `POST /domains/{id}/claim/verify` */
474
+ verify(id, options) {
475
+ return this.core.request("post", "/domains/{id}/claim/verify", { path: { id }, options });
476
+ }
477
+ };
419
478
  var Domains = class extends Resource {
479
+ claims = new DomainClaims(this.core);
420
480
  /** `POST /domains` */
421
481
  create(payload, options) {
422
482
  return this.core.request("post", "/domains", { body: payload, options });
@@ -459,12 +519,56 @@ var ApiKeys = class extends Resource {
459
519
  listAll(params, options) {
460
520
  return paginate((cursor) => this.list({ ...params, ...cursor }, options), params);
461
521
  }
522
+ /** `PATCH /api-keys/{id}` */
523
+ update(id, payload, options) {
524
+ return this.core.request("patch", "/api-keys/{id}", { path: { id }, body: payload, options });
525
+ }
462
526
  /** `DELETE /api-keys/{id}` */
463
527
  delete(id, options) {
464
528
  return this.core.request("delete", "/api-keys/{id}", { path: { id }, options });
465
529
  }
466
530
  };
531
+ var WebhookEventAttempts = class extends Resource {
532
+ /** `GET /webhooks/{id}/events/{event_id}/attempts` */
533
+ list(id, eventId, params, options) {
534
+ return this.core.request("get", "/webhooks/{id}/events/{event_id}/attempts", {
535
+ path: { id, event_id: eventId },
536
+ query: params,
537
+ options
538
+ });
539
+ }
540
+ /** Every delivery attempt of one webhook event, fetched page by page. */
541
+ listAll(id, eventId, params, options) {
542
+ return paginate((cursor) => this.list(id, eventId, { ...params, ...cursor }, options), params);
543
+ }
544
+ };
545
+ var WebhookEvents = class extends Resource {
546
+ attempts = new WebhookEventAttempts(this.core);
547
+ /** `GET /webhooks/{id}/events` */
548
+ list(id, params, options) {
549
+ return this.core.request("get", "/webhooks/{id}/events", { path: { id }, query: params, options });
550
+ }
551
+ /** Every event of one webhook, fetched page by page. */
552
+ listAll(id, params, options) {
553
+ return paginate((cursor) => this.list(id, { ...params, ...cursor }, options), params);
554
+ }
555
+ /** `GET /webhooks/{id}/events/{event_id}` */
556
+ get(id, eventId, options) {
557
+ return this.core.request("get", "/webhooks/{id}/events/{event_id}", {
558
+ path: { id, event_id: eventId },
559
+ options
560
+ });
561
+ }
562
+ /** `POST /webhooks/{id}/events/{event_id}/replay` */
563
+ replay(id, eventId, options) {
564
+ return this.core.request("post", "/webhooks/{id}/events/{event_id}/replay", {
565
+ path: { id, event_id: eventId },
566
+ options
567
+ });
568
+ }
569
+ };
467
570
  var Webhooks = class extends Resource {
571
+ events = new WebhookEvents(this.core);
468
572
  /** `POST /webhooks` */
469
573
  create(payload, options) {
470
574
  return this.core.request("post", "/webhooks", { body: payload, options });
@@ -489,9 +593,41 @@ var Webhooks = class extends Resource {
489
593
  delete(id, options) {
490
594
  return this.core.request("delete", "/webhooks/{id}", { path: { id }, options });
491
595
  }
492
- /** `POST /webhooks/{id}/rotate`: rotates the signing secret. */
493
- rotate(id, payload, options) {
494
- return this.core.request("post", "/webhooks/{id}/rotate", { path: { id }, body: payload, options });
596
+ /** `POST /webhooks/{id}/signing-secret/rotate`: rotates the signing secret. */
597
+ rotateSigningSecret(id, payload, options) {
598
+ return this.core.request("post", "/webhooks/{id}/signing-secret/rotate", {
599
+ path: { id },
600
+ body: payload,
601
+ options
602
+ });
603
+ }
604
+ };
605
+ var Logs = class extends Resource {
606
+ /** `GET /logs` */
607
+ list(params, options) {
608
+ return this.core.request("get", "/logs", { query: params, options });
609
+ }
610
+ /** Every API request log entry, fetched page by page. */
611
+ listAll(params, options) {
612
+ return paginate((cursor) => this.list({ ...params, ...cursor }, options), params);
613
+ }
614
+ /** `GET /logs/{id}` */
615
+ get(id, options) {
616
+ return this.core.request("get", "/logs/{id}", { path: { id }, options });
617
+ }
618
+ };
619
+ var OauthGrants = class extends Resource {
620
+ /** `GET /oauth/grants` */
621
+ list(params, options) {
622
+ return this.core.request("get", "/oauth/grants", { query: params, options });
623
+ }
624
+ /** Every OAuth grant, fetched page by page. */
625
+ listAll(params, options) {
626
+ return paginate((cursor) => this.list({ ...params, ...cursor }, options), params);
627
+ }
628
+ /** `DELETE /oauth/grants/{id}` */
629
+ revoke(id, options) {
630
+ return this.core.request("delete", "/oauth/grants/{id}", { path: { id }, options });
495
631
  }
496
632
  };
497
633
  var Usage = class extends Resource {
@@ -521,6 +657,113 @@ var Agent = class extends Resource {
521
657
  }
522
658
  };
523
659
 
660
+ // src/resources/automations.ts
661
+ var AutomationRuns = class extends Resource {
662
+ /** `GET /automations/{id}/runs` */
663
+ list(id, params, options) {
664
+ return this.core.request("get", "/automations/{id}/runs", { path: { id }, query: params, options });
665
+ }
666
+ /** Every run of one automation, fetched page by page. */
667
+ listAll(id, params, options) {
668
+ return paginate((cursor) => this.list(id, { ...params, ...cursor }, options), params);
669
+ }
670
+ /** `GET /automations/{id}/runs/{run_id}` */
671
+ get(id, runId, options) {
672
+ return this.core.request("get", "/automations/{id}/runs/{run_id}", {
673
+ path: { id, run_id: runId },
674
+ options
675
+ });
676
+ }
677
+ /** `POST /automations/{id}/runs/{run_id}/cancel` */
678
+ cancel(id, runId, options) {
679
+ return this.core.request("post", "/automations/{id}/runs/{run_id}/cancel", {
680
+ path: { id, run_id: runId },
681
+ options
682
+ });
683
+ }
684
+ };
685
+ var Automations = class extends Resource {
686
+ runs = new AutomationRuns(this.core);
687
+ /** `POST /automations` */
688
+ create(payload, options) {
689
+ return this.core.request("post", "/automations", { body: payload, options });
690
+ }
691
+ /** `GET /automations` */
692
+ list(params, options) {
693
+ return this.core.request("get", "/automations", { query: params, options });
694
+ }
695
+ /** Every automation, fetched page by page. */
696
+ listAll(params, options) {
697
+ return paginate((cursor) => this.list({ ...params, ...cursor }, options), params);
698
+ }
699
+ /** `GET /automations/{id}` */
700
+ get(id, options) {
701
+ return this.core.request("get", "/automations/{id}", { path: { id }, options });
702
+ }
703
+ /** `PATCH /automations/{id}` */
704
+ update(id, payload, options) {
705
+ return this.core.request("patch", "/automations/{id}", { path: { id }, body: payload, options });
706
+ }
707
+ /** `DELETE /automations/{id}` */
708
+ remove(id, options) {
709
+ return this.core.request("delete", "/automations/{id}", { path: { id }, options });
710
+ }
711
+ /** `POST /automations/validate`: checks a definition without saving it. */
712
+ validate(payload, options) {
713
+ return this.core.request("post", "/automations/validate", { body: payload, options });
714
+ }
715
+ /** `POST /automations/{id}/duplicate` */
716
+ duplicate(id, options) {
717
+ return this.core.request("post", "/automations/{id}/duplicate", { path: { id }, options });
718
+ }
719
+ /** `POST /automations/{id}/simulate` */
720
+ simulate(id, payload, options) {
721
+ return this.core.request("post", "/automations/{id}/simulate", { path: { id }, body: payload, options });
722
+ }
723
+ /** `POST /automations/{id}/stop` */
724
+ stop(id, options) {
725
+ return this.core.request("post", "/automations/{id}/stop", { path: { id }, options });
726
+ }
727
+ /** `GET /automations/{id}/metrics` */
728
+ metrics(id, params, options) {
729
+ return this.core.request("get", "/automations/{id}/metrics", { path: { id }, query: params, options });
730
+ }
731
+ };
732
+ var Events = class extends Resource {
733
+ /** `POST /events`: defines a custom event. */
734
+ create(payload, options) {
735
+ return this.core.request("post", "/events", { body: payload, options });
736
+ }
737
+ /** `GET /events` */
738
+ list(params, options) {
739
+ return this.core.request("get", "/events", { query: params, options });
740
+ }
741
+ /** Every custom event, fetched page by page. */
742
+ listAll(params, options) {
743
+ return paginate((cursor) => this.list({ ...params, ...cursor }, options), params);
744
+ }
745
+ /** `GET /events/{id_or_name}` */
746
+ get(idOrName, options) {
747
+ return this.core.request("get", "/events/{id_or_name}", { path: { id_or_name: idOrName }, options });
748
+ }
749
+ /** `PATCH /events/{id_or_name}` */
750
+ update(idOrName, payload, options) {
751
+ return this.core.request("patch", "/events/{id_or_name}", {
752
+ path: { id_or_name: idOrName },
753
+ body: payload,
754
+ options
755
+ });
756
+ }
757
+ /** `DELETE /events/{id_or_name}` */
758
+ remove(idOrName, options) {
759
+ return this.core.request("delete", "/events/{id_or_name}", { path: { id_or_name: idOrName }, options });
760
+ }
761
+ /** `POST /events/send`: sends an event that starts the automations listening for it. */
762
+ send(payload, options) {
763
+ return this.core.request("post", "/events/send", { body: payload, ...idempotent(options) });
764
+ }
765
+ };
766
+
524
767
  // src/resources/broadcasts.ts
525
768
  var Broadcasts = class extends Resource {
526
769
  /** `POST /broadcasts` */
@@ -547,6 +790,30 @@ var Broadcasts = class extends Resource {
547
790
  delete(id, options) {
548
791
  return this.core.request("delete", "/broadcasts/{id}", { path: { id }, options });
549
792
  }
793
+ /** `GET /broadcasts/{id}/recipients`: the recipients with the given outcome (`type` is required). */
794
+ recipients(id, params, options) {
795
+ return this.core.request("get", "/broadcasts/{id}/recipients", {
796
+ path: { id },
797
+ query: params,
798
+ options
799
+ });
800
+ }
801
+ /** Every recipient of a broadcast, fetched page by page. */
802
+ recipientsAll(id, params, options) {
803
+ return paginate((cursor) => this.recipients(id, { ...params, ...cursor }, options), params);
804
+ }
805
+ /** `GET /broadcasts/{id}/clicked-links` */
806
+ clickedLinks(id, params, options) {
807
+ return this.core.request("get", "/broadcasts/{id}/clicked-links", {
808
+ path: { id },
809
+ query: params,
810
+ options
811
+ });
812
+ }
813
+ /** Every link clicked in a broadcast, fetched page by page. */
814
+ clickedLinksAll(id, params, options) {
815
+ return paginate((cursor) => this.clickedLinks(id, { ...params, ...cursor }, options), params);
816
+ }
550
817
  /** `POST /broadcasts/{id}/send` */
551
818
  send(id, payload, options) {
552
819
  return this.core.request("post", "/broadcasts/{id}/send", { path: { id }, body: payload, options });
@@ -597,10 +864,7 @@ var Templates = class extends Resource {
597
864
 
598
865
  // src/resources/contacts.ts
599
866
  var ContactBatch = class extends Resource {
600
- /**
601
- * `POST /contacts/batch`: up to 1000 contacts, each shaped like {@link Contacts.create}'s payload.
602
- * The API document leaves the items untyped; the endpoint validates each one as a contact.
603
- */
867
+ /** `POST /contacts/batch`: up to 1000 contacts, each shaped like {@link Contacts.create}'s payload. */
604
868
  create(payload, params, options) {
605
869
  return this.core.request("post", "/contacts/batch", {
606
870
  body: payload,
@@ -632,7 +896,50 @@ var ContactTopics = class extends Resource {
632
896
  });
633
897
  }
634
898
  };
899
+ var ContactImports = class extends Resource {
900
+ /** `POST /contacts/imports`: uploads a CSV and imports it in the background; poll {@link ContactImports.get}. */
901
+ create(params, options) {
902
+ const form = new FormData();
903
+ const { file, filename, column_map, on_conflict, segments, topics } = params;
904
+ const named = typeof file !== "string" && "name" in file && typeof file.name === "string" && file.name !== "";
905
+ form.append(
906
+ "file",
907
+ typeof file === "string" ? new Blob([file], { type: "text/csv" }) : file,
908
+ filename ?? (named ? file.name : "contacts.csv")
909
+ );
910
+ const json = (value) => typeof value === "string" ? value : JSON.stringify(value);
911
+ if (column_map !== void 0) form.append("column_map", json(column_map));
912
+ if (on_conflict !== void 0) form.append("on_conflict", on_conflict);
913
+ if (segments !== void 0) form.append("segments", json(segments));
914
+ if (topics !== void 0) form.append("topics", json(topics));
915
+ return this.core.request("post", "/contacts/imports", { form, options });
916
+ }
917
+ /** `GET /contacts/imports` */
918
+ list(params, options) {
919
+ return this.core.request("get", "/contacts/imports", { query: params, options });
920
+ }
921
+ /** Every contact import, fetched page by page. */
922
+ listAll(params, options) {
923
+ return paginate((cursor) => this.list({ ...params, ...cursor }, options), params);
924
+ }
925
+ /** `GET /contacts/imports/{id}` */
926
+ get(id, options) {
927
+ return this.core.request("get", "/contacts/imports/{id}", { path: { id }, options });
928
+ }
929
+ };
635
930
  var ContactSegments = class extends Resource {
931
+ /** `GET /contacts/{id}/segments` */
932
+ list(contactId, params, options) {
933
+ return this.core.request("get", "/contacts/{id}/segments", {
934
+ path: { id: contactId },
935
+ query: params,
936
+ options
937
+ });
938
+ }
939
+ /** Every segment a contact belongs to, fetched page by page. */
940
+ listAll(contactId, params, options) {
941
+ return paginate((cursor) => this.list(contactId, { ...params, ...cursor }, options), params);
942
+ }
636
943
  /** `POST /contacts/{id}/segments/{segmentId}` */
637
944
  add(contactId, segmentId, options) {
638
945
  return this.core.request("post", "/contacts/{id}/segments/{segmentId}", {
@@ -650,6 +957,7 @@ var ContactSegments = class extends Resource {
650
957
  };
651
958
  var Contacts = class extends Resource {
652
959
  batch = new ContactBatch(this.core);
960
+ imports = new ContactImports(this.core);
653
961
  topics = new ContactTopics(this.core);
654
962
  segments = new ContactSegments(this.core);
655
963
  /** `POST /contacts` */
@@ -871,16 +1179,47 @@ var ReceivedEmails = class extends Resource {
871
1179
  });
872
1180
  }
873
1181
  };
1182
+ var EmailAttachments = class extends Resource {
1183
+ /** `GET /emails/{email_id}/attachments` */
1184
+ list(emailId, params, options) {
1185
+ return this.core.request("get", "/emails/{email_id}/attachments", {
1186
+ path: { email_id: emailId },
1187
+ query: params,
1188
+ options
1189
+ });
1190
+ }
1191
+ /** Every attachment of a sent email, fetched page by page. */
1192
+ listAll(emailId, params, options) {
1193
+ return paginate((cursor) => this.list(emailId, { ...params, ...cursor }, options), params);
1194
+ }
1195
+ /** `GET /emails/{email_id}/attachments/{id}` */
1196
+ get(emailId, id, options) {
1197
+ return this.core.request("get", "/emails/{email_id}/attachments/{id}", {
1198
+ path: { email_id: emailId, id },
1199
+ options
1200
+ });
1201
+ }
1202
+ };
874
1203
  var Emails = class extends Resource {
875
1204
  receiving = new ReceivedEmails(this.core);
1205
+ attachments = new EmailAttachments(this.core);
1206
+ metrics;
1207
+ constructor(core) {
1208
+ super(core);
1209
+ this.metrics = Object.assign(
1210
+ (params, options) => core.request("get", "/emails/metrics", { query: params, options }),
1211
+ {
1212
+ links: (params, options) => core.request("get", "/emails/metrics/links", { query: params, options }),
1213
+ countries: (params, options) => core.request("get", "/emails/metrics/countries", { query: params, options }),
1214
+ clients: (params, options) => core.request("get", "/emails/metrics/clients", { query: params, options })
1215
+ }
1216
+ );
1217
+ }
876
1218
  /** `POST /emails` */
877
1219
  send(payload, options) {
878
1220
  return this.core.request("post", "/emails", { body: payload, ...idempotent(options) });
879
1221
  }
880
- /**
881
- * `POST /emails/batch`: up to 100 emails, each shaped like {@link Emails.send}'s payload.
882
- * The API document leaves the items untyped; the endpoint validates each one as a send.
883
- */
1222
+ /** `POST /emails/batch`: up to 100 emails, each shaped like {@link Emails.send}'s payload. */
884
1223
  batch(payload, options) {
885
1224
  return this.core.request("post", "/emails/batch", {
886
1225
  body: payload,
@@ -916,25 +1255,29 @@ var Emails = class extends Resource {
916
1255
  insights(id, options) {
917
1256
  return this.core.request("get", "/emails/{id}/insights", { path: { id }, options });
918
1257
  }
919
- /** `GET /emails/metrics` */
920
- metrics(params, options) {
921
- return this.core.request("get", "/emails/metrics", { query: params, options });
1258
+ /** `POST /emails/{id}/share` */
1259
+ share(id, payload, options) {
1260
+ return this.core.request("post", "/emails/{id}/share", { path: { id }, body: payload, options });
1261
+ }
1262
+ /** `DELETE /emails/{id}/share` */
1263
+ unshare(id, options) {
1264
+ return this.core.request("delete", "/emails/{id}/share", { path: { id }, options });
922
1265
  }
923
1266
  };
924
1267
 
925
1268
  // src/sse.ts
926
1269
  var STREAM_GAP_EVENT = "stream.gap";
1270
+ var DEFAULT_IDLE_TIMEOUT_MS = 45e3;
927
1271
  var LINE_BREAK = /\r\n|\r|\n/;
928
- async function* parseEventStream(body, hooks = { onRetry() {
929
- } }, initialId = null) {
1272
+ async function* parseEventStream(body, hooks, initialId = null) {
930
1273
  const reader = body.getReader();
931
1274
  const decoder = new TextDecoder("utf-8");
932
1275
  let buffer = "";
933
- let first = true;
934
1276
  let lastId = initialId;
935
1277
  let eventName = "";
936
1278
  let dataLines = [];
937
1279
  let hasData = false;
1280
+ let idPending = false;
938
1281
  function* takeLines(final) {
939
1282
  while (true) {
940
1283
  const match = LINE_BREAK.exec(buffer);
@@ -949,8 +1292,11 @@ async function* parseEventStream(body, hooks = { onRetry() {
949
1292
  if (line === "") {
950
1293
  if (!hasData) {
951
1294
  eventName = "";
1295
+ if (idPending && lastId !== null) hooks.onId?.(lastId);
1296
+ idPending = false;
952
1297
  return void 0;
953
1298
  }
1299
+ idPending = false;
954
1300
  const raw = dataLines.join("\n");
955
1301
  let data = raw;
956
1302
  try {
@@ -978,7 +1324,10 @@ async function* parseEventStream(body, hooks = { onRetry() {
978
1324
  hasData = true;
979
1325
  break;
980
1326
  case "id":
981
- if (!value.includes("\0")) lastId = value;
1327
+ if (!value.includes("\0")) {
1328
+ lastId = value;
1329
+ idPending = true;
1330
+ }
982
1331
  break;
983
1332
  case "retry":
984
1333
  if (/^\d+$/.test(value)) hooks.onRetry(Number(value));
@@ -997,11 +1346,8 @@ async function* parseEventStream(body, hooks = { onRetry() {
997
1346
  }
998
1347
  return;
999
1348
  }
1349
+ hooks.onActivity?.();
1000
1350
  buffer += decoder.decode(value, { stream: true });
1001
- if (first && buffer.length > 0) {
1002
- if (buffer.charCodeAt(0) === 65279) buffer = buffer.slice(1);
1003
- first = false;
1004
- }
1005
1351
  for (const line of takeLines(false)) {
1006
1352
  const event = processLine(line);
1007
1353
  if (event) yield event;
@@ -1060,19 +1406,32 @@ var EventStream = class {
1060
1406
  const reconnect = this.#options.reconnect !== false;
1061
1407
  const maxReconnects = this.#options.maxReconnects ?? 5;
1062
1408
  let failures = 0;
1409
+ let lastError = null;
1063
1410
  let gapAt;
1064
1411
  try {
1065
1412
  while (!this.#closed) {
1066
1413
  const connection = this.#connection;
1067
1414
  if (connection !== null && connection.response.body !== null) {
1415
+ const idleMs = this.#options.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS;
1416
+ let idle;
1417
+ const arm = () => {
1418
+ clearTimeout(idle);
1419
+ if (idleMs > 0) idle = setTimeout(() => connection.close(), idleMs);
1420
+ };
1421
+ arm();
1068
1422
  try {
1069
1423
  const events = parseEventStream(
1070
1424
  connection.response.body,
1071
- { onRetry: (ms) => this.#delayMs = ms },
1425
+ {
1426
+ onRetry: (ms) => this.#delayMs = ms,
1427
+ onActivity: arm,
1428
+ // An id-only block (the position a new stream opens at) counts: a connection that ends
1429
+ // before its first event must still resume from it.
1430
+ onId: (id) => this.#lastEventId = id
1431
+ },
1072
1432
  this.#lastEventId
1073
1433
  );
1074
1434
  for await (const event of events) {
1075
- failures = 0;
1076
1435
  if (event.event === STREAM_GAP_EVENT) {
1077
1436
  if (gapAt === this.#lastEventId) continue;
1078
1437
  gapAt = this.#lastEventId;
@@ -1088,18 +1447,23 @@ var EventStream = class {
1088
1447
  if (this.#endsOn.has(event.event)) return;
1089
1448
  }
1090
1449
  } catch {
1450
+ } finally {
1451
+ clearTimeout(idle);
1091
1452
  }
1092
1453
  connection.close();
1093
1454
  this.#connection = null;
1455
+ lastError = null;
1094
1456
  }
1095
1457
  if (this.#closed || !reconnect) return;
1096
1458
  failures++;
1097
1459
  if (failures > maxReconnects) {
1460
+ if (lastError !== null && lastError.statusCode !== null) throw lastError;
1098
1461
  throw new APIConnectionError(
1099
1462
  `The event stream disconnected; gave up after ${maxReconnects} reconnects`
1100
1463
  );
1101
1464
  }
1102
- if (!await sleep(this.#delayMs, this.#options.signal) || this.#closed) return;
1465
+ const hinted = retryAfterMs(lastError);
1466
+ if (!await sleep(hinted ?? this.#delayMs, this.#options.signal) || this.#closed) return;
1103
1467
  const next = await this.#connect(this.#lastEventId);
1104
1468
  if (this.#closed) {
1105
1469
  next.data?.close();
@@ -1107,15 +1471,24 @@ var EventStream = class {
1107
1471
  }
1108
1472
  if (next.error !== null) {
1109
1473
  if (!retryable(next.error, false)) throw next.error;
1474
+ const wait = retryAfterMs(next.error);
1475
+ if (wait !== null && wait > MAX_RETRY_AFTER_MS) throw next.error;
1476
+ lastError = next.error;
1110
1477
  continue;
1111
1478
  }
1112
1479
  this.#connection = next.data;
1480
+ failures = 0;
1481
+ lastError = null;
1113
1482
  }
1114
1483
  } finally {
1115
1484
  this.close();
1116
1485
  }
1117
1486
  }
1118
1487
  };
1488
+ function retryAfterMs(error) {
1489
+ const seconds = error instanceof RateLimitError || error instanceof APIError ? error.retryAfter : null;
1490
+ return seconds === null ? null : seconds * 1e3;
1491
+ }
1119
1492
 
1120
1493
  // src/resources/inboxes.ts
1121
1494
  var InboxAgentSettings = class extends Resource {
@@ -1123,6 +1496,14 @@ var InboxAgentSettings = class extends Resource {
1123
1496
  get(inboxId, options) {
1124
1497
  return this.core.request("get", "/inboxes/{inbox_id}/agent", { path: { inbox_id: inboxId }, options });
1125
1498
  }
1499
+ /** `PATCH /inboxes/{inbox_id}/agent` */
1500
+ update(inboxId, payload, options) {
1501
+ return this.core.request("patch", "/inboxes/{inbox_id}/agent", {
1502
+ path: { inbox_id: inboxId },
1503
+ body: payload,
1504
+ options
1505
+ });
1506
+ }
1126
1507
  };
1127
1508
  var InboxSafety = class extends Resource {
1128
1509
  /** `GET /inboxes/{inbox_id}/safety` */
@@ -1518,10 +1899,6 @@ var Unsubscribes = class extends Resource {
1518
1899
  listAll(params, options) {
1519
1900
  return paginate((cursor) => this.list({ ...params, ...cursor }, options), params);
1520
1901
  }
1521
- /** `DELETE /unsubscribes/{id}` */
1522
- delete(id, options) {
1523
- return this.core.request("delete", "/unsubscribes/{id}", { path: { id }, options });
1524
- }
1525
1902
  };
1526
1903
  var Verifications = class extends Resource {
1527
1904
  /** `GET /verifications/availability` */
@@ -1570,6 +1947,10 @@ var BillionSend = class {
1570
1947
  deliverability;
1571
1948
  inboxes;
1572
1949
  agent;
1950
+ automations;
1951
+ events;
1952
+ logs;
1953
+ oauthGrants;
1573
1954
  #core;
1574
1955
  /**
1575
1956
  * @param apiKeyOrOptions An API key (`bs_...`), or options. Without a key the
@@ -1597,6 +1978,10 @@ var BillionSend = class {
1597
1978
  this.deliverability = new Deliverability(core);
1598
1979
  this.inboxes = new Inboxes(core);
1599
1980
  this.agent = new Agent(core);
1981
+ this.automations = new Automations(core);
1982
+ this.events = new Events(core);
1983
+ this.logs = new Logs(core);
1984
+ this.oauthGrants = new OauthGrants(core);
1600
1985
  }
1601
1986
  /** The API base URL this client calls. */
1602
1987
  get baseUrl() {
@@ -1633,7 +2018,8 @@ function encodeBase64(bytes) {
1633
2018
  return btoa(binary);
1634
2019
  }
1635
2020
  function secretKey(secret) {
1636
- const encoded = secret.startsWith(SECRET_PREFIX) ? secret.slice(SECRET_PREFIX.length) : null;
2021
+ const text = secret.trim();
2022
+ const encoded = text.startsWith(SECRET_PREFIX) ? text.slice(SECRET_PREFIX.length) : null;
1637
2023
  const key = encoded === null ? null : decodeBase64(encoded);
1638
2024
  if (encoded === null || key === null || key.length < SECRET_MIN_BYTES || key.length > SECRET_MAX_BYTES || encodeBase64(key) !== encoded) {
1639
2025
  throw new WebhookVerificationError("The webhook secret is not a whsec_ secret");
@@ -1652,14 +2038,12 @@ function bytesOf(payload) {
1652
2038
  }
1653
2039
  function equal(a, b) {
1654
2040
  if (a.length !== b.length) return false;
1655
- let diff = 0;
1656
- for (let i = 0; i < a.length; i++) diff |= (a[i] ?? 0) ^ (b[i] ?? 0);
1657
- return diff === 0;
2041
+ return a.reduce((diff, byte, i) => diff | byte ^ b[i], 0) === 0;
1658
2042
  }
1659
2043
  async function verifyWebhook(payload, headers, secret, options = {}) {
1660
- const id = header(headers, "webhook-id");
1661
- const timestamp = header(headers, "webhook-timestamp");
1662
- const signature = header(headers, "webhook-signature");
2044
+ const id = header(headers, "webhook-id")?.trim();
2045
+ const timestamp = header(headers, "webhook-timestamp")?.trim();
2046
+ const signature = header(headers, "webhook-signature")?.trim();
1663
2047
  if (!id || !timestamp || !signature) {
1664
2048
  throw new WebhookVerificationError(
1665
2049
  "Missing the webhook-id, webhook-timestamp or webhook-signature header"
@@ -1681,7 +2065,7 @@ async function verifyWebhook(payload, headers, secret, options = {}) {
1681
2065
  signed.set(prefix);
1682
2066
  signed.set(body, prefix.length);
1683
2067
  const expected = new Uint8Array(await subtle.sign("HMAC", key, signed));
1684
- const matched = signature.split(" ").some((candidate) => {
2068
+ const matched = signature.split(/\s+/).some((candidate) => {
1685
2069
  const comma = candidate.indexOf(",");
1686
2070
  if (comma === -1 || candidate.slice(0, comma) !== "v1") return false;
1687
2071
  const given = decodeBase64(candidate.slice(comma + 1));