@billionsend/node 0.1.1 → 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
@@ -81,7 +81,7 @@ function errorClass(status) {
81
81
  case 409:
82
82
  return ConflictError;
83
83
  default:
84
- return status >= 500 ? APIError : BillionSendError;
84
+ return BillionSendError;
85
85
  }
86
86
  }
87
87
  function errorFromResponse(status, statusText, text, headers = {}) {
@@ -141,8 +141,9 @@ function newIdempotencyKey() {
141
141
  const bytes = new Uint8Array(16);
142
142
  if (typeof webCrypto?.getRandomValues === "function") webCrypto.getRandomValues(bytes);
143
143
  else for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256);
144
- bytes[6] = (bytes[6] ?? 0) & 15 | 64;
145
- 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);
146
147
  const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
147
148
  return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
148
149
  }
@@ -165,7 +166,7 @@ function sleep(ms, signal) {
165
166
  }
166
167
 
167
168
  // src/version.ts
168
- var VERSION = "0.1.1";
169
+ var VERSION = "0.2.0";
169
170
 
170
171
  // src/core.ts
171
172
  var DEFAULT_BASE_URL = "https://api.billionsend.com";
@@ -176,6 +177,10 @@ function readEnv(name) {
176
177
  const value = env?.[name];
177
178
  return value === void 0 || value === "" ? void 0 : value;
178
179
  }
180
+ function cleanKey(key) {
181
+ const trimmed = key?.trim();
182
+ return trimmed === void 0 || trimmed === "" ? void 0 : trimmed;
183
+ }
179
184
  function failure(error, headers = null) {
180
185
  return { data: null, error, headers };
181
186
  }
@@ -201,17 +206,33 @@ function lowerCaseKeys(headers) {
201
206
  }
202
207
  return out;
203
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
+ }
204
218
  function fillPath(template, params) {
205
219
  let missing;
220
+ let dotted;
206
221
  const filled = template.replace(/\{([^}]+)\}/g, (_, name) => {
207
222
  const value = params?.[name];
208
223
  if (value === void 0 || value === null || String(value) === "") {
209
224
  missing ??= name;
210
225
  return "";
211
226
  }
212
- return encodeURIComponent(String(value));
227
+ const text = String(value);
228
+ if (text === "." || text === "..") dotted ??= name;
229
+ return encodeURIComponent(text);
213
230
  });
214
- 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;
215
236
  }
216
237
  function queryString(query) {
217
238
  if (!query) return "";
@@ -219,7 +240,7 @@ function queryString(query) {
219
240
  for (const [key, value] of Object.entries(query)) {
220
241
  if (value === void 0 || value === null) continue;
221
242
  if (Array.isArray(value)) {
222
- params.append(key, value.map(String).join(","));
243
+ if (value.length > 0) params.append(key, value.map(String).join(","));
223
244
  } else {
224
245
  params.append(key, String(value));
225
246
  }
@@ -235,7 +256,7 @@ var Core = class {
235
256
  #fetch;
236
257
  #headers;
237
258
  constructor(options) {
238
- this.#apiKey = options.apiKey ?? readEnv("BILLIONSEND_API_KEY");
259
+ this.#apiKey = cleanKey(options.apiKey) ?? cleanKey(readEnv("BILLIONSEND_API_KEY"));
239
260
  this.baseUrl = (options.baseUrl ?? readEnv("BILLIONSEND_BASE_URL") ?? DEFAULT_BASE_URL).replace(
240
261
  /\/+$/,
241
262
  ""
@@ -253,10 +274,6 @@ var Core = class {
253
274
  this.#fetch = fetchImpl;
254
275
  this.#headers = lowerCaseKeys(options.headers);
255
276
  }
256
- /** Whether an API key is configured. */
257
- get hasApiKey() {
258
- return this.#apiKey !== void 0;
259
- }
260
277
  /** Calls one operation and parses its JSON answer. */
261
278
  request(method, path, init = {}) {
262
279
  return this.#execute(method, path, init, false);
@@ -288,7 +305,10 @@ var Core = class {
288
305
  ...lowerCaseKeys(init.headers)
289
306
  };
290
307
  let body;
291
- 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) {
292
312
  body = JSON.stringify(init.body);
293
313
  headers["content-type"] = "application/json";
294
314
  }
@@ -298,14 +318,24 @@ var Core = class {
298
318
  }
299
319
  if (auth) headers.authorization = `Bearer ${this.#apiKey}`;
300
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
+ }
301
330
  const keyed = headers["idempotency-key"] !== void 0;
302
- const retryable2 = IDEMPOTENT_METHODS.has(method) || keyed;
331
+ const safeToRepeat = IDEMPOTENT_METHODS.has(method) || keyed;
303
332
  const maxRetries = options.maxRetries ?? this.maxRetries;
304
333
  const timeoutMs = options.timeoutMs ?? this.timeoutMs;
305
334
  for (let attempt = 0; ; attempt++) {
306
335
  const outcome = await this.#attempt(method, url, headers, body, timeoutMs, options.signal, stream);
307
336
  const error = outcome.result.error;
308
- 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)) {
309
339
  return outcome.result;
310
340
  }
311
341
  const delay = retryDelayMs(attempt, outcome.retryAfter);
@@ -314,6 +344,7 @@ var Core = class {
314
344
  }
315
345
  }
316
346
  async #attempt(method, url, headers, body, timeoutMs, signal, stream) {
347
+ if (signal?.aborted) return { result: failure(applicationError("Request was aborted")) };
317
348
  const controller = new AbortController();
318
349
  let timedOut = false;
319
350
  const timer = setTimeout(() => {
@@ -321,8 +352,7 @@ var Core = class {
321
352
  controller.abort();
322
353
  }, timeoutMs);
323
354
  const onAbort = () => controller.abort();
324
- if (signal?.aborted) controller.abort();
325
- else signal?.addEventListener("abort", onAbort, { once: true });
355
+ signal?.addEventListener("abort", onAbort, { once: true });
326
356
  const release = () => {
327
357
  clearTimeout(timer);
328
358
  signal?.removeEventListener("abort", onAbort);
@@ -362,6 +392,8 @@ var Core = class {
362
392
  const text = await response.text();
363
393
  release();
364
394
  if (response.ok) {
395
+ if (text.trim() === "")
396
+ return { result: { data: null, error: null, headers: responseHeaders } };
365
397
  try {
366
398
  return { result: { data: JSON.parse(text), error: null, headers: responseHeaders } };
367
399
  } catch {
@@ -429,7 +461,22 @@ function idempotent(options) {
429
461
  }
430
462
 
431
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
+ };
432
478
  var Domains = class extends Resource {
479
+ claims = new DomainClaims(this.core);
433
480
  /** `POST /domains` */
434
481
  create(payload, options) {
435
482
  return this.core.request("post", "/domains", { body: payload, options });
@@ -472,12 +519,56 @@ var ApiKeys = class extends Resource {
472
519
  listAll(params, options) {
473
520
  return paginate((cursor) => this.list({ ...params, ...cursor }, options), params);
474
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
+ }
475
526
  /** `DELETE /api-keys/{id}` */
476
527
  delete(id, options) {
477
528
  return this.core.request("delete", "/api-keys/{id}", { path: { id }, options });
478
529
  }
479
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
+ };
480
570
  var Webhooks = class extends Resource {
571
+ events = new WebhookEvents(this.core);
481
572
  /** `POST /webhooks` */
482
573
  create(payload, options) {
483
574
  return this.core.request("post", "/webhooks", { body: payload, options });
@@ -502,9 +593,41 @@ var Webhooks = class extends Resource {
502
593
  delete(id, options) {
503
594
  return this.core.request("delete", "/webhooks/{id}", { path: { id }, options });
504
595
  }
505
- /** `POST /webhooks/{id}/rotate`: rotates the signing secret. */
506
- rotate(id, payload, options) {
507
- 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 });
508
631
  }
509
632
  };
510
633
  var Usage = class extends Resource {
@@ -534,6 +657,113 @@ var Agent = class extends Resource {
534
657
  }
535
658
  };
536
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
+
537
767
  // src/resources/broadcasts.ts
538
768
  var Broadcasts = class extends Resource {
539
769
  /** `POST /broadcasts` */
@@ -560,6 +790,30 @@ var Broadcasts = class extends Resource {
560
790
  delete(id, options) {
561
791
  return this.core.request("delete", "/broadcasts/{id}", { path: { id }, options });
562
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
+ }
563
817
  /** `POST /broadcasts/{id}/send` */
564
818
  send(id, payload, options) {
565
819
  return this.core.request("post", "/broadcasts/{id}/send", { path: { id }, body: payload, options });
@@ -610,10 +864,7 @@ var Templates = class extends Resource {
610
864
 
611
865
  // src/resources/contacts.ts
612
866
  var ContactBatch = class extends Resource {
613
- /**
614
- * `POST /contacts/batch`: up to 1000 contacts, each shaped like {@link Contacts.create}'s payload.
615
- * The API document leaves the items untyped; the endpoint validates each one as a contact.
616
- */
867
+ /** `POST /contacts/batch`: up to 1000 contacts, each shaped like {@link Contacts.create}'s payload. */
617
868
  create(payload, params, options) {
618
869
  return this.core.request("post", "/contacts/batch", {
619
870
  body: payload,
@@ -645,7 +896,50 @@ var ContactTopics = class extends Resource {
645
896
  });
646
897
  }
647
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
+ };
648
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
+ }
649
943
  /** `POST /contacts/{id}/segments/{segmentId}` */
650
944
  add(contactId, segmentId, options) {
651
945
  return this.core.request("post", "/contacts/{id}/segments/{segmentId}", {
@@ -663,6 +957,7 @@ var ContactSegments = class extends Resource {
663
957
  };
664
958
  var Contacts = class extends Resource {
665
959
  batch = new ContactBatch(this.core);
960
+ imports = new ContactImports(this.core);
666
961
  topics = new ContactTopics(this.core);
667
962
  segments = new ContactSegments(this.core);
668
963
  /** `POST /contacts` */
@@ -884,16 +1179,47 @@ var ReceivedEmails = class extends Resource {
884
1179
  });
885
1180
  }
886
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
+ };
887
1203
  var Emails = class extends Resource {
888
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
+ }
889
1218
  /** `POST /emails` */
890
1219
  send(payload, options) {
891
1220
  return this.core.request("post", "/emails", { body: payload, ...idempotent(options) });
892
1221
  }
893
- /**
894
- * `POST /emails/batch`: up to 100 emails, each shaped like {@link Emails.send}'s payload.
895
- * The API document leaves the items untyped; the endpoint validates each one as a send.
896
- */
1222
+ /** `POST /emails/batch`: up to 100 emails, each shaped like {@link Emails.send}'s payload. */
897
1223
  batch(payload, options) {
898
1224
  return this.core.request("post", "/emails/batch", {
899
1225
  body: payload,
@@ -929,25 +1255,29 @@ var Emails = class extends Resource {
929
1255
  insights(id, options) {
930
1256
  return this.core.request("get", "/emails/{id}/insights", { path: { id }, options });
931
1257
  }
932
- /** `GET /emails/metrics` */
933
- metrics(params, options) {
934
- 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 });
935
1265
  }
936
1266
  };
937
1267
 
938
1268
  // src/sse.ts
939
1269
  var STREAM_GAP_EVENT = "stream.gap";
1270
+ var DEFAULT_IDLE_TIMEOUT_MS = 45e3;
940
1271
  var LINE_BREAK = /\r\n|\r|\n/;
941
- async function* parseEventStream(body, hooks = { onRetry() {
942
- } }, initialId = null) {
1272
+ async function* parseEventStream(body, hooks, initialId = null) {
943
1273
  const reader = body.getReader();
944
1274
  const decoder = new TextDecoder("utf-8");
945
1275
  let buffer = "";
946
- let first = true;
947
1276
  let lastId = initialId;
948
1277
  let eventName = "";
949
1278
  let dataLines = [];
950
1279
  let hasData = false;
1280
+ let idPending = false;
951
1281
  function* takeLines(final) {
952
1282
  while (true) {
953
1283
  const match = LINE_BREAK.exec(buffer);
@@ -962,8 +1292,11 @@ async function* parseEventStream(body, hooks = { onRetry() {
962
1292
  if (line === "") {
963
1293
  if (!hasData) {
964
1294
  eventName = "";
1295
+ if (idPending && lastId !== null) hooks.onId?.(lastId);
1296
+ idPending = false;
965
1297
  return void 0;
966
1298
  }
1299
+ idPending = false;
967
1300
  const raw = dataLines.join("\n");
968
1301
  let data = raw;
969
1302
  try {
@@ -991,7 +1324,10 @@ async function* parseEventStream(body, hooks = { onRetry() {
991
1324
  hasData = true;
992
1325
  break;
993
1326
  case "id":
994
- if (!value.includes("\0")) lastId = value;
1327
+ if (!value.includes("\0")) {
1328
+ lastId = value;
1329
+ idPending = true;
1330
+ }
995
1331
  break;
996
1332
  case "retry":
997
1333
  if (/^\d+$/.test(value)) hooks.onRetry(Number(value));
@@ -1010,11 +1346,8 @@ async function* parseEventStream(body, hooks = { onRetry() {
1010
1346
  }
1011
1347
  return;
1012
1348
  }
1349
+ hooks.onActivity?.();
1013
1350
  buffer += decoder.decode(value, { stream: true });
1014
- if (first && buffer.length > 0) {
1015
- if (buffer.charCodeAt(0) === 65279) buffer = buffer.slice(1);
1016
- first = false;
1017
- }
1018
1351
  for (const line of takeLines(false)) {
1019
1352
  const event = processLine(line);
1020
1353
  if (event) yield event;
@@ -1079,10 +1412,23 @@ var EventStream = class {
1079
1412
  while (!this.#closed) {
1080
1413
  const connection = this.#connection;
1081
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();
1082
1422
  try {
1083
1423
  const events = parseEventStream(
1084
1424
  connection.response.body,
1085
- { 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
+ },
1086
1432
  this.#lastEventId
1087
1433
  );
1088
1434
  for await (const event of events) {
@@ -1101,6 +1447,8 @@ var EventStream = class {
1101
1447
  if (this.#endsOn.has(event.event)) return;
1102
1448
  }
1103
1449
  } catch {
1450
+ } finally {
1451
+ clearTimeout(idle);
1104
1452
  }
1105
1453
  connection.close();
1106
1454
  this.#connection = null;
@@ -1148,6 +1496,14 @@ var InboxAgentSettings = class extends Resource {
1148
1496
  get(inboxId, options) {
1149
1497
  return this.core.request("get", "/inboxes/{inbox_id}/agent", { path: { inbox_id: inboxId }, options });
1150
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
+ }
1151
1507
  };
1152
1508
  var InboxSafety = class extends Resource {
1153
1509
  /** `GET /inboxes/{inbox_id}/safety` */
@@ -1543,10 +1899,6 @@ var Unsubscribes = class extends Resource {
1543
1899
  listAll(params, options) {
1544
1900
  return paginate((cursor) => this.list({ ...params, ...cursor }, options), params);
1545
1901
  }
1546
- /** `DELETE /unsubscribes/{id}` */
1547
- delete(id, options) {
1548
- return this.core.request("delete", "/unsubscribes/{id}", { path: { id }, options });
1549
- }
1550
1902
  };
1551
1903
  var Verifications = class extends Resource {
1552
1904
  /** `GET /verifications/availability` */
@@ -1595,6 +1947,10 @@ var BillionSend = class {
1595
1947
  deliverability;
1596
1948
  inboxes;
1597
1949
  agent;
1950
+ automations;
1951
+ events;
1952
+ logs;
1953
+ oauthGrants;
1598
1954
  #core;
1599
1955
  /**
1600
1956
  * @param apiKeyOrOptions An API key (`bs_...`), or options. Without a key the
@@ -1622,6 +1978,10 @@ var BillionSend = class {
1622
1978
  this.deliverability = new Deliverability(core);
1623
1979
  this.inboxes = new Inboxes(core);
1624
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);
1625
1985
  }
1626
1986
  /** The API base URL this client calls. */
1627
1987
  get baseUrl() {
@@ -1658,7 +2018,8 @@ function encodeBase64(bytes) {
1658
2018
  return btoa(binary);
1659
2019
  }
1660
2020
  function secretKey(secret) {
1661
- 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;
1662
2023
  const key = encoded === null ? null : decodeBase64(encoded);
1663
2024
  if (encoded === null || key === null || key.length < SECRET_MIN_BYTES || key.length > SECRET_MAX_BYTES || encodeBase64(key) !== encoded) {
1664
2025
  throw new WebhookVerificationError("The webhook secret is not a whsec_ secret");
@@ -1677,14 +2038,12 @@ function bytesOf(payload) {
1677
2038
  }
1678
2039
  function equal(a, b) {
1679
2040
  if (a.length !== b.length) return false;
1680
- let diff = 0;
1681
- for (let i = 0; i < a.length; i++) diff |= (a[i] ?? 0) ^ (b[i] ?? 0);
1682
- return diff === 0;
2041
+ return a.reduce((diff, byte, i) => diff | byte ^ b[i], 0) === 0;
1683
2042
  }
1684
2043
  async function verifyWebhook(payload, headers, secret, options = {}) {
1685
- const id = header(headers, "webhook-id");
1686
- const timestamp = header(headers, "webhook-timestamp");
1687
- 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();
1688
2047
  if (!id || !timestamp || !signature) {
1689
2048
  throw new WebhookVerificationError(
1690
2049
  "Missing the webhook-id, webhook-timestamp or webhook-signature header"
@@ -1706,7 +2065,7 @@ async function verifyWebhook(payload, headers, secret, options = {}) {
1706
2065
  signed.set(prefix);
1707
2066
  signed.set(body, prefix.length);
1708
2067
  const expected = new Uint8Array(await subtle.sign("HMAC", key, signed));
1709
- const matched = signature.split(" ").some((candidate) => {
2068
+ const matched = signature.split(/\s+/).some((candidate) => {
1710
2069
  const comma = candidate.indexOf(",");
1711
2070
  if (comma === -1 || candidate.slice(0, comma) !== "v1") return false;
1712
2071
  const given = decodeBase64(candidate.slice(comma + 1));