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