coss 0.4.0 → 0.5.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
@@ -1,2358 +1,4 @@
1
- //#region src/api-version.ts
2
- /**
3
- * API versions this SDK knows, oldest first: a hand-written mirror of `API_VERSIONS` in the API
4
- * (`apps/api/test/sdk-contract.test.ts` keeps them equal).
5
- */
6
- const API_VERSIONS = ["2026-10-10"];
7
- /** The version this SDK's types describe, sent with every request unless `apiVersion` overrides it. */
8
- const API_VERSION = "2026-10-10";
9
- //#endregion
10
- //#region src/version.ts
11
- /** SDK version, sent in the User-Agent. A test keeps it equal to package.json's `version`. */
12
- const VERSION = "0.4.0";
13
- //#endregion
14
- //#region src/core/errors.ts
15
- const API_ERROR_TYPES = /* @__PURE__ */ new Set([
16
- "invalid_request_error",
17
- "authentication_error",
18
- "permission_error",
19
- "not_found_error",
20
- "idempotency_error",
21
- "rate_limit_error",
22
- "billing_error",
23
- "api_error"
24
- ]);
25
- function isRecord(value) {
26
- return typeof value === "object" && value !== null && !Array.isArray(value);
27
- }
28
- function parseIssues(value) {
29
- if (!Array.isArray(value)) return void 0;
30
- const issues = [];
31
- for (const item of value) if (isRecord(item) && typeof item.path === "string" && typeof item.message === "string") issues.push({
32
- path: item.path,
33
- message: item.message
34
- });
35
- return issues;
36
- }
37
- /**
38
- * Maps a non-2xx response to a `CossError`. Bodies that are not the API's error envelope (a proxy's
39
- * HTML 502, an empty 503) become `api_error` / `unexpected_response`.
40
- */
41
- function errorFromResponse(status, statusText, body, headerRequestId) {
42
- let parsed;
43
- try {
44
- parsed = JSON.parse(body);
45
- } catch {
46
- parsed = void 0;
47
- }
48
- const envelope = isRecord(parsed) ? parsed.error : void 0;
49
- if (!isRecord(envelope) || typeof envelope.message !== "string") return {
50
- type: "api_error",
51
- code: "unexpected_response",
52
- message: `The coss.com API returned an unexpected HTTP ${status}${statusText ? ` (${statusText})` : ""} response.`,
53
- status,
54
- request_id: headerRequestId
55
- };
56
- const error = {
57
- type: typeof envelope.type === "string" && API_ERROR_TYPES.has(envelope.type) ? envelope.type : "api_error",
58
- code: typeof envelope.code === "string" ? envelope.code : "unknown_error",
59
- message: envelope.message,
60
- status,
61
- request_id: typeof envelope.request_id === "string" ? envelope.request_id : headerRequestId
62
- };
63
- if (typeof envelope.param === "string") error.param = envelope.param;
64
- const issues = parseIssues(envelope.issues);
65
- if (issues) error.issues = issues;
66
- return error;
67
- }
68
- /** Builds an error for a failure that happened on the client (no HTTP response to read). */
69
- function clientError(type, code, message) {
70
- return {
71
- type,
72
- code,
73
- message,
74
- status: null,
75
- request_id: null
76
- };
77
- }
78
- //#endregion
79
- //#region src/core/http.ts
80
- const INITIAL_RETRY_DELAY_MS = 500;
81
- const MAX_RETRY_DELAY_MS = 8e3;
82
- const MAX_RETRY_AFTER_MS = 6e4;
83
- /** Exponential backoff (500ms, 1s, 2s … capped at 8s) minus up to 25% random jitter. */
84
- function backoffDelay(retry, random = Math.random) {
85
- return Math.min(INITIAL_RETRY_DELAY_MS * 2 ** retry, MAX_RETRY_DELAY_MS) * (1 - random() * .25);
86
- }
87
- /** `Retry-After` as milliseconds. Accepts delay-seconds or an HTTP date; `null` if absent/invalid. */
88
- function parseRetryAfter(value, now = Date.now()) {
89
- const trimmed = value?.trim();
90
- if (!trimmed) return null;
91
- const seconds = Number(trimmed);
92
- if (Number.isFinite(seconds)) return seconds >= 0 ? seconds * 1e3 : null;
93
- const date = Date.parse(trimmed);
94
- return Number.isNaN(date) ? null : Math.max(0, date - now);
95
- }
96
- /** 409 (idempotent request still in progress), 429 and 5xx are transient. */
97
- function isRetryableStatus(status) {
98
- return status === 409 || status === 429 || status >= 500;
99
- }
100
- function sleep(ms, signal) {
101
- return new Promise((resolve) => {
102
- if (signal?.aborted) {
103
- resolve();
104
- return;
105
- }
106
- const done = () => {
107
- clearTimeout(timer);
108
- signal?.removeEventListener("abort", done);
109
- resolve();
110
- };
111
- const timer = setTimeout(done, ms);
112
- signal?.addEventListener("abort", done, { once: true });
113
- });
114
- }
115
- /** Error message plus the underlying cause (undici's "fetch failed" hides ECONNREFUSED there). */
116
- function describe(error) {
117
- if (!(error instanceof Error)) return String(error);
118
- const cause = error.cause instanceof Error ? error.cause.message : void 0;
119
- return cause && cause !== error.message ? `${error.message} (${cause})` : error.message;
120
- }
121
- function abortedError() {
122
- return clientError("connection_error", "aborted", "The request was aborted.");
123
- }
124
- /**
125
- * The request pipeline shared by all resources: auth + JSON, a per-attempt timeout, retries with
126
- * backoff, and mapping every failure to a `CossError`. It never throws for API or network errors.
127
- */
128
- var HttpClient = class {
129
- #apiKey;
130
- #baseUrl;
131
- #fetch;
132
- #timeout;
133
- #maxRetries;
134
- #apiVersion;
135
- #sleep;
136
- constructor(options) {
137
- this.#apiKey = options.apiKey;
138
- this.#baseUrl = options.baseUrl.replace(/\/+$/, "");
139
- this.#fetch = options.fetch;
140
- this.#timeout = options.timeout;
141
- this.#maxRetries = options.maxRetries;
142
- this.#apiVersion = options.apiVersion;
143
- this.#sleep = options.sleep ?? sleep;
144
- }
145
- async request(request) {
146
- let url = `${this.#baseUrl}${request.path}`;
147
- const query = new URLSearchParams();
148
- for (const [name, value] of Object.entries(request.query ?? {})) if (value !== void 0) query.set(name, String(value));
149
- const search = query.toString();
150
- if (search) url += `?${search}`;
151
- const headers = {
152
- Accept: request.responseType === "text" || request.responseType === "bytes" ? "*/*" : "application/json",
153
- Authorization: `Bearer ${this.#apiKey}`,
154
- "User-Agent": `coss-typescript/${VERSION}`,
155
- "Coss-Version": this.#apiVersion
156
- };
157
- let body;
158
- if (request.body !== void 0) {
159
- headers["Content-Type"] = "application/json";
160
- body = JSON.stringify(request.body);
161
- }
162
- if (request.method === "POST") headers["Idempotency-Key"] = request.idempotencyKey ?? crypto.randomUUID();
163
- try {
164
- new Headers(headers);
165
- } catch (cause) {
166
- return {
167
- data: null,
168
- error: clientError("invalid_request_error", "invalid_header", `Invalid request header: ${describe(cause)}`)
169
- };
170
- }
171
- const init = {
172
- method: request.method,
173
- headers,
174
- body
175
- };
176
- for (let retry = 0;; retry++) {
177
- if (request.signal?.aborted) return {
178
- data: null,
179
- error: abortedError()
180
- };
181
- const attempt = await this.#attempt(url, init, request.signal, request.responseType);
182
- if (request.retry === false || !attempt.retry || retry >= this.#maxRetries) return attempt.result;
183
- const delay = attempt.retryAfterMs ?? backoffDelay(retry);
184
- if (delay > MAX_RETRY_AFTER_MS) return attempt.result;
185
- await this.#sleep(delay, request.signal);
186
- }
187
- }
188
- async #attempt(url, init, callerSignal, responseType) {
189
- const timeoutSignal = AbortSignal.timeout(this.#timeout);
190
- const signal = callerSignal ? AbortSignal.any([callerSignal, timeoutSignal]) : timeoutSignal;
191
- let response;
192
- let text;
193
- let bytes = null;
194
- try {
195
- response = await this.#fetch(url, {
196
- ...init,
197
- signal
198
- });
199
- if (responseType === "bytes") {
200
- bytes = new Uint8Array(await response.arrayBuffer());
201
- text = response.ok ? "" : new TextDecoder().decode(bytes);
202
- } else text = await response.text();
203
- } catch (cause) {
204
- if (callerSignal?.aborted) return {
205
- result: failed(abortedError()),
206
- retry: false,
207
- retryAfterMs: null
208
- };
209
- const timeoutMessage = `Request timed out after ${this.#timeout}ms.`;
210
- return {
211
- result: failed(timeoutSignal.aborted ? clientError("timeout_error", "request_timeout", timeoutMessage) : clientError("connection_error", "network_error", `Could not reach the coss.com API at ${this.#baseUrl}: ${describe(cause)}`)),
212
- retry: true,
213
- retryAfterMs: null
214
- };
215
- }
216
- const requestId = response.headers.get("x-request-id");
217
- if (!response.ok) return {
218
- result: failed(errorFromResponse(response.status, response.statusText, text, requestId)),
219
- retry: isRetryableStatus(response.status),
220
- retryAfterMs: parseRetryAfter(response.headers.get("retry-after"))
221
- };
222
- if (responseType === "text") return {
223
- result: {
224
- data: text,
225
- error: null
226
- },
227
- retry: false,
228
- retryAfterMs: null
229
- };
230
- if (responseType === "bytes") return {
231
- result: {
232
- data: bytes,
233
- error: null
234
- },
235
- retry: false,
236
- retryAfterMs: null
237
- };
238
- try {
239
- return {
240
- result: {
241
- data: JSON.parse(text),
242
- error: null
243
- },
244
- retry: false,
245
- retryAfterMs: null
246
- };
247
- } catch {
248
- return {
249
- result: failed({
250
- type: "api_error",
251
- code: "invalid_response",
252
- message: `The coss.com API returned an HTTP ${response.status} response that is not valid JSON.`,
253
- status: response.status,
254
- request_id: requestId
255
- }),
256
- retry: false,
257
- retryAfterMs: null
258
- };
259
- }
260
- }
261
- };
262
- function failed(error) {
263
- return {
264
- data: null,
265
- error
266
- };
267
- }
268
- //#endregion
269
- //#region src/resources/api-key.ts
270
- /** `coss.apiKey`: the API key the client was created with. */
271
- var ApiKeyResource = class {
272
- #http;
273
- /** @internal Use `new Coss().apiKey`. */
274
- constructor(http) {
275
- this.#http = http;
276
- }
277
- /** Revokes the client's own API key, at once: every later request with it fails. */
278
- revoke(options) {
279
- return this.#http.request({
280
- method: "DELETE",
281
- path: "/v1/api_key",
282
- signal: options?.signal
283
- });
284
- }
285
- };
286
- //#endregion
287
- //#region src/resources/list-query.ts
288
- /** One query parameter: lists are comma-joined (an empty one is left out), dates ISO 8601. */
289
- function joined(value) {
290
- if (value === void 0) return void 0;
291
- if (value instanceof Date) return value.toISOString();
292
- if (Array.isArray(value)) return value.length === 0 ? void 0 : value.join(",");
293
- return String(value);
294
- }
295
- /** The query string of a list method whose filters accept arrays and dates. */
296
- function listQuery(params) {
297
- const query = {};
298
- for (const [name, value] of Object.entries(params)) query[name] = joined(value);
299
- return query;
300
- }
301
- //#endregion
302
- //#region src/resources/audit-events.ts
303
- /**
304
- * `coss.auditEvents`: the organization's audit log, newest first: changes made by members, API
305
- * keys and coss.com support. Organization-wide, whichever environment the key belongs to.
306
- */
307
- var AuditEventsResource = class {
308
- #http;
309
- /** @internal Use `new Coss().auditEvents`. */
310
- constructor(http) {
311
- this.#http = http;
312
- }
313
- /** Lists audit events, newest first. Pass the last `id` as `after` while `has_more` is true. */
314
- list(params = {}, options) {
315
- return this.#http.request({
316
- method: "GET",
317
- path: "/v1/audit_events",
318
- query: listQuery(params),
319
- signal: options?.signal
320
- });
321
- }
322
- /** Retrieves one audit event. */
323
- get(id, options) {
324
- return this.#http.request({
325
- method: "GET",
326
- path: `/v1/audit_events/${encodeURIComponent(id)}`,
327
- signal: options?.signal
328
- });
329
- }
330
- };
331
- //#endregion
332
- //#region src/resources/billing.ts
333
- /** `coss.billing.invoices`: the organization's invoices, newest first. */
334
- var BillingInvoicesResource = class {
335
- #http;
336
- /** @internal Use `new Coss().billing.invoices`. */
337
- constructor(http) {
338
- this.#http = http;
339
- }
340
- /** Lists invoices (without lines). Pass the last `id` as `after` while `has_more` is true. */
341
- list(params = {}, options) {
342
- return this.#http.request({
343
- method: "GET",
344
- path: "/v1/billing/invoices",
345
- query: listQuery(params),
346
- signal: options?.signal
347
- });
348
- }
349
- /** Retrieves one invoice with its lines. */
350
- get(id, options) {
351
- return this.#http.request({
352
- method: "GET",
353
- path: `/v1/billing/invoices/${encodeURIComponent(id)}`,
354
- signal: options?.signal
355
- });
356
- }
357
- };
358
- /** `coss.billing.credits`: the organization's credits and what's left of them. */
359
- var BillingCreditsResource = class {
360
- #http;
361
- /** @internal Use `new Coss().billing.credits`. */
362
- constructor(http) {
363
- this.#http = http;
364
- }
365
- /** Lists credits, newest first (usable ones by default). */
366
- list(params = {}, options) {
367
- return this.#http.request({
368
- method: "GET",
369
- path: "/v1/billing/credits",
370
- query: listQuery(params),
371
- signal: options?.signal
372
- });
373
- }
374
- };
375
- /**
376
- * `coss.billing`: the organization's plan, usage, invoices and credits (read only; plan changes
377
- * are made in the dashboard). Organization-wide, whichever environment the key belongs to.
378
- */
379
- var BillingResource = class {
380
- #http;
381
- invoices;
382
- credits;
383
- /** @internal Use `new Coss().billing`. */
384
- constructor(http) {
385
- this.#http = http;
386
- this.invoices = new BillingInvoicesResource(http);
387
- this.credits = new BillingCreditsResource(http);
388
- }
389
- /** The plan, the current month's usage and estimate, standing and what the plan includes. */
390
- get(options) {
391
- return this.#http.request({
392
- method: "GET",
393
- path: "/v1/billing",
394
- signal: options?.signal
395
- });
396
- }
397
- /** Billable usage per meter and bucket (the current month, by day, by default), oldest first. */
398
- usage(params = {}, options) {
399
- return this.#http.request({
400
- method: "GET",
401
- path: "/v1/billing/usage",
402
- query: listQuery(params),
403
- signal: options?.signal
404
- });
405
- }
406
- };
407
- //#endregion
408
- //#region src/resources/dmarc.ts
409
- const dmarcPath = (domainId) => `/v1/domains/${encodeURIComponent(domainId)}/dmarc`;
410
- /** `coss.domains.dmarc.reports`: the aggregate reports received about a domain. */
411
- var DmarcReportsResource = class {
412
- #http;
413
- /** @internal Use `new Coss().domains.dmarc.reports`. */
414
- constructor(http) {
415
- this.#http = http;
416
- }
417
- /** Lists the domain's reports, newest first, without their rows. */
418
- list(domainId, params = {}, options) {
419
- return this.#http.request({
420
- method: "GET",
421
- path: `${dmarcPath(domainId)}/reports`,
422
- query: listQuery(params),
423
- signal: options?.signal
424
- });
425
- }
426
- /** Retrieves one report with its rows. */
427
- get(domainId, reportId, options) {
428
- return this.#http.request({
429
- method: "GET",
430
- path: `${dmarcPath(domainId)}/reports/${encodeURIComponent(reportId)}`,
431
- signal: options?.signal
432
- });
433
- }
434
- };
435
- /**
436
- * `coss.domains.dmarc`: a domain's DMARC record, the guided path from `p=none` to `p=reject`, and
437
- * the aggregate reports mailbox providers send to its `report_address`.
438
- */
439
- var DmarcResource = class {
440
- #http;
441
- /** The domain's aggregate reports. */
442
- reports;
443
- /** @internal Use `new Coss().domains.dmarc`. */
444
- constructor(http) {
445
- this.#http = http;
446
- this.reports = new DmarcReportsResource(http);
447
- }
448
- /**
449
- * The domain's DMARC status: its published record, the record to publish next and whether
450
- * the last 14 days of reports say that is safe (`ready`), and a summary of those reports.
451
- */
452
- get(domainId, options) {
453
- return this.#http.request({
454
- method: "GET",
455
- path: dmarcPath(domainId),
456
- signal: options?.signal
457
- });
458
- }
459
- };
460
- //#endregion
461
- //#region src/resources/receiving-domains.ts
462
- const receivingPath = (domainId) => `/v1/domains/${encodeURIComponent(domainId)}/receiving`;
463
- /**
464
- * `coss.domains.receiving`: a domain's receiving hostname (the domain itself or a subdomain, e.g.
465
- * `inbound.acme.com`). Email sent to any address at it is received by the API key's environment.
466
- */
467
- var ReceivingDomainsResource = class {
468
- #http;
469
- /** @internal Use `new Coss().domains.receiving`. */
470
- constructor(http) {
471
- this.#http = http;
472
- }
473
- /**
474
- * Starts receiving at a hostname of the domain, for the API key's environment, and returns the
475
- * domain with the MX record to publish in `data.receiving.record`.
476
- */
477
- create(domainId, params, options) {
478
- return this.#http.request({
479
- method: "POST",
480
- path: receivingPath(domainId),
481
- body: params,
482
- idempotencyKey: options?.idempotencyKey,
483
- signal: options?.signal
484
- });
485
- }
486
- /** Stops receiving at the domain's hostname. Emails already received are kept. */
487
- delete(domainId, options) {
488
- return this.#http.request({
489
- method: "DELETE",
490
- path: receivingPath(domainId),
491
- signal: options?.signal
492
- });
493
- }
494
- };
495
- //#endregion
496
- //#region src/resources/tracking-domains.ts
497
- const trackingPath = (domainId) => `/v1/domains/${encodeURIComponent(domainId)}/tracking`;
498
- /**
499
- * `coss.domains.tracking`: a domain's custom tracking domain (e.g. `links.acme.com`). Open pixels
500
- * and click redirects of emails sent from the domain use it while it is `active`.
501
- */
502
- var TrackingDomainsResource = class {
503
- #http;
504
- /** @internal Use `new Coss().domains.tracking`. */
505
- constructor(http) {
506
- this.#http = http;
507
- }
508
- /**
509
- * Sets up a subdomain of the domain as its tracking domain and returns the domain, with the
510
- * CNAME to publish in `data.tracking.record`. Setup gives up after 72 hours.
511
- */
512
- create(domainId, params, options) {
513
- return this.#http.request({
514
- method: "POST",
515
- path: trackingPath(domainId),
516
- body: params,
517
- idempotencyKey: options?.idempotencyKey,
518
- signal: options?.signal
519
- });
520
- }
521
- /**
522
- * Removes the domain's tracking domain. Later emails use the default tracking host; links in
523
- * emails already sent through it stop working.
524
- */
525
- delete(domainId, options) {
526
- return this.#http.request({
527
- method: "DELETE",
528
- path: trackingPath(domainId),
529
- signal: options?.signal
530
- });
531
- }
532
- };
533
- //#endregion
534
- //#region src/resources/domains.ts
535
- /**
536
- * `coss.domains`: the domains live (`coss_live_…`) keys may send from. Domains belong to the
537
- * organization, so every API key of the organization sees the same ones.
538
- */
539
- var DomainsResource = class {
540
- #http;
541
- /** Each domain's custom tracking domain: add and remove it. */
542
- tracking;
543
- /** Each domain's receiving hostname: start and stop receiving email at it. */
544
- receiving;
545
- /** Each domain's DMARC status, guidance and aggregate reports. */
546
- dmarc;
547
- /** @internal Use `new Coss().domains`. */
548
- constructor(http) {
549
- this.#http = http;
550
- this.tracking = new TrackingDomainsResource(http);
551
- this.receiving = new ReceivingDomainsResource(http);
552
- this.dmarc = new DmarcResource(http);
553
- }
554
- /**
555
- * Adds a domain and returns the DNS records to publish (`data.records`). The records are
556
- * checked in the background; verification gives up after 72 hours.
557
- */
558
- create(params, options) {
559
- return this.#http.request({
560
- method: "POST",
561
- path: "/v1/domains",
562
- body: params,
563
- idempotencyKey: options?.idempotencyKey,
564
- signal: options?.signal
565
- });
566
- }
567
- /** Lists the organization's domains, ordered by name. */
568
- list(options) {
569
- return this.#http.request({
570
- method: "GET",
571
- path: "/v1/domains",
572
- signal: options?.signal
573
- });
574
- }
575
- /** Retrieves a domain with the result of the last DNS check. */
576
- get(id, options) {
577
- return this.#http.request({
578
- method: "GET",
579
- path: `/v1/domains/${encodeURIComponent(id)}`,
580
- signal: options?.signal
581
- });
582
- }
583
- /**
584
- * Checks the domain's records now instead of waiting for the next background check. A `failed`
585
- * domain starts verification over with fresh DKIM records, which have to be published again.
586
- * Its tracking domain, if any, is checked too.
587
- */
588
- verify(id, options) {
589
- return this.#http.request({
590
- method: "POST",
591
- path: `/v1/domains/${encodeURIComponent(id)}/verify`,
592
- idempotencyKey: options?.idempotencyKey,
593
- signal: options?.signal
594
- });
595
- }
596
- /** Removes the domain. Emails already sent are unaffected; live keys can no longer use it. */
597
- delete(id, options) {
598
- return this.#http.request({
599
- method: "DELETE",
600
- path: `/v1/domains/${encodeURIComponent(id)}`,
601
- signal: options?.signal
602
- });
603
- }
604
- };
605
- //#endregion
606
- //#region src/react.ts
607
- /**
608
- * React Email: a send's `react` is rendered into `html` (and `text`, unless given) by
609
- * `@react-email/render`, an optional peer dependency imported only when a send has `react`, so the
610
- * SDK itself keeps zero dependencies.
611
- */
612
- let renderer;
613
- /** Imports `@react-email/render` once; `null` when it isn't installed. */
614
- function loadReactEmailRenderer() {
615
- renderer ??= (async () => {
616
- try {
617
- return await import("@react-email/render");
618
- } catch {
619
- return null;
620
- }
621
- })();
622
- return renderer;
623
- }
624
- /**
625
- * Turns `react` into `html` and `text`; params without it pass through. Rendering mistakes come back
626
- * as `invalid_request_error`s naming `param`, like the API's validation errors, never thrown.
627
- */
628
- async function renderReactEmail(params, param, load = loadReactEmailRenderer) {
629
- const { react, ...body } = params;
630
- if (react === void 0) return {
631
- body,
632
- error: null
633
- };
634
- if (body.template_id !== void 0) return failure("validation_error", "Pass either `react` or `template_id`, not both.", param);
635
- if (body.html !== void 0) return failure("validation_error", "Pass either `react` or `html`, not both.", param);
636
- const renderer = await load();
637
- if (!renderer) return failure("react_renderer_missing", "Sending `react` needs the `@react-email/render` package: install it next to `coss`.", param);
638
- try {
639
- const html = await renderer.render(react);
640
- if (body.text !== void 0) return {
641
- body: {
642
- ...body,
643
- html
644
- },
645
- error: null
646
- };
647
- const text = renderer.toPlainText ? renderer.toPlainText(html) : await renderer.render(react, { plainText: true });
648
- return {
649
- body: {
650
- ...body,
651
- html,
652
- text
653
- },
654
- error: null
655
- };
656
- } catch (cause) {
657
- return failure("react_render_failed", `Rendering \`react\` failed: ${cause instanceof Error ? cause.message : String(cause)}`, param);
658
- }
659
- }
660
- function failure(code, message, param) {
661
- return {
662
- body: null,
663
- error: {
664
- ...clientError("invalid_request_error", code, message),
665
- param
666
- }
667
- };
668
- }
669
- //#endregion
670
- //#region src/resources/dedicated-ips.ts
671
- /**
672
- * `coss.email.dedicatedIps`: the organization's own sending IPs (the Dedicated IPs add-on),
673
- * managed and warmed up automatically.
674
- */
675
- var DedicatedIpsResource = class {
676
- #http;
677
- /** @internal Use `new Coss().email.dedicatedIps`. */
678
- constructor(http) {
679
- this.#http = http;
680
- }
681
- /** The pool's status and IPs (`not_enabled` without the add-on). */
682
- get(options) {
683
- return this.#http.request({
684
- method: "GET",
685
- path: "/v1/dedicated_ips",
686
- signal: options?.signal
687
- });
688
- }
689
- };
690
- //#endregion
691
- //#region src/resources/email-templates.ts
692
- const templatePath = (template) => `/v1/email_templates/${encodeURIComponent(template)}`;
693
- /** `coss.email.templates.versions`: a template's published versions. */
694
- var EmailTemplateVersionsResource = class {
695
- #http;
696
- /** @internal Use `new Coss().email.templates.versions`. */
697
- constructor(http) {
698
- this.#http = http;
699
- }
700
- /** Published versions, newest first. */
701
- list(template, params = {}, options) {
702
- return this.#http.request({
703
- method: "GET",
704
- path: `${templatePath(template)}/versions`,
705
- query: listQuery(params),
706
- signal: options?.signal
707
- });
708
- }
709
- get(template, version, options) {
710
- return this.#http.request({
711
- method: "GET",
712
- path: `${templatePath(template)}/versions/${version}`,
713
- signal: options?.signal
714
- });
715
- }
716
- /**
717
- * Replaces the draft with this version's content; publish the draft to send it again. Never
718
- * automatically retried: every restore is a new draft revision, so a repeat could overwrite an
719
- * edit saved in between.
720
- */
721
- restore(template, version, options) {
722
- return this.#http.request({
723
- method: "POST",
724
- path: `${templatePath(template)}/versions/${version}/restore`,
725
- retry: false,
726
- signal: options?.signal
727
- });
728
- }
729
- };
730
- /**
731
- * `coss.email.templates`: the environment's email templates. Templates are addressed by id or
732
- * alias. Edit the draft, publish it, then send with `coss.email.send({ template_id, variables })`.
733
- */
734
- var EmailTemplatesResource = class {
735
- #http;
736
- /** Published versions. */
737
- versions;
738
- /** @internal Use `new Coss().email.templates`. */
739
- constructor(http) {
740
- this.#http = http;
741
- this.versions = new EmailTemplateVersionsResource(http);
742
- }
743
- /**
744
- * Creates a template and its draft. Never automatically retried: the API doesn't deduplicate it
745
- * (a template with an `alias` can't be created twice, though).
746
- */
747
- create(params, options) {
748
- return this.#http.request({
749
- method: "POST",
750
- path: "/v1/email_templates",
751
- retry: false,
752
- body: params,
753
- idempotencyKey: options?.idempotencyKey,
754
- signal: options?.signal
755
- });
756
- }
757
- /** The environment's templates, newest first. */
758
- list(params = {}, options) {
759
- return this.#http.request({
760
- method: "GET",
761
- path: "/v1/email_templates",
762
- query: listQuery(params),
763
- signal: options?.signal
764
- });
765
- }
766
- get(template, options) {
767
- return this.#http.request({
768
- method: "GET",
769
- path: templatePath(template),
770
- signal: options?.signal
771
- });
772
- }
773
- /** Changes its name, alias or description. */
774
- update(template, params, options) {
775
- return this.#http.request({
776
- method: "PATCH",
777
- path: templatePath(template),
778
- body: params,
779
- signal: options?.signal
780
- });
781
- }
782
- /** Deletes it with every version. Emails already sent keep their content. */
783
- delete(template, options) {
784
- return this.#http.request({
785
- method: "DELETE",
786
- path: templatePath(template),
787
- signal: options?.signal
788
- });
789
- }
790
- /** The draft, with `problems` that keep it from being published. */
791
- getDraft(template, options) {
792
- return this.#http.request({
793
- method: "GET",
794
- path: `${templatePath(template)}/draft`,
795
- signal: options?.signal
796
- });
797
- }
798
- /**
799
- * Replaces the whole draft. Sends keep using the published version until you publish. Never
800
- * automatically retried: every save is a new revision, so a repeat whose first attempt was saved
801
- * would fail with `template_revision_mismatch` (or, without `revision`, overwrite an edit saved
802
- * in between). Read the draft again before retrying.
803
- */
804
- updateDraft(template, params, options) {
805
- return this.#http.request({
806
- method: "PUT",
807
- path: `${templatePath(template)}/draft`,
808
- retry: false,
809
- body: params,
810
- signal: options?.signal
811
- });
812
- }
813
- /**
814
- * Publishes the draft as the next version, which sends use from then on. Automatically retried
815
- * only with a `revision`: a draft without changes since the last publish returns that version,
816
- * and one saved again since is refused. Without it, a retry could publish someone else's newer
817
- * edits as yet another version.
818
- */
819
- publish(template, params = {}, options) {
820
- return this.#http.request({
821
- method: "POST",
822
- path: `${templatePath(template)}/publish`,
823
- retry: params.revision !== void 0,
824
- body: params,
825
- signal: options?.signal
826
- });
827
- }
828
- };
829
- //#endregion
830
- //#region src/resources/received-emails.ts
831
- const emailPath = (id) => `/v1/received_emails/${encodeURIComponent(id)}`;
832
- /**
833
- * `coss.email.received`: emails received by the API key's environment, at its inbound address
834
- * (`address()`) or at a receiving domain (`coss.domains.receiving`). An `email.received` webhook
835
- * announces each one.
836
- */
837
- var ReceivedEmailsResource = class {
838
- #http;
839
- /** @internal Use `new Coss().email.received`. */
840
- constructor(http) {
841
- this.#http = http;
842
- }
843
- /** Lists received emails, newest first, without bodies. Pass the last `id` as `after` while `has_more` is true. */
844
- list(params = {}, options) {
845
- return this.#http.request({
846
- method: "GET",
847
- path: "/v1/received_emails",
848
- query: listQuery(params),
849
- signal: options?.signal
850
- });
851
- }
852
- /** Retrieves a received email with its headers and bodies. */
853
- get(id, options) {
854
- return this.#http.request({
855
- method: "GET",
856
- path: emailPath(id),
857
- signal: options?.signal
858
- });
859
- }
860
- /** The whole message as received (`message/rfc822` bytes). */
861
- getRaw(id, options) {
862
- return this.#http.request({
863
- method: "GET",
864
- path: `${emailPath(id)}/raw`,
865
- responseType: "bytes",
866
- signal: options?.signal
867
- });
868
- }
869
- /** An attachment's bytes (untrusted: its declared type is the attachment's `content_type`). */
870
- getAttachment(id, attachmentId, options) {
871
- return this.#http.request({
872
- method: "GET",
873
- path: `${emailPath(id)}/attachments/${encodeURIComponent(attachmentId)}`,
874
- responseType: "bytes",
875
- signal: options?.signal
876
- });
877
- }
878
- /**
879
- * The environment's inbound domain: email to any address at it (`support@<domain>`) is
880
- * received, with no DNS setup.
881
- */
882
- address(options) {
883
- return this.#http.request({
884
- method: "GET",
885
- path: "/v1/received_emails/address",
886
- signal: options?.signal
887
- });
888
- }
889
- /** Deletes a received email with its raw message and attachments right away. */
890
- delete(id, options) {
891
- return this.#http.request({
892
- method: "DELETE",
893
- path: emailPath(id),
894
- signal: options?.signal
895
- });
896
- }
897
- };
898
- //#endregion
899
- //#region src/resources/suppressions.ts
900
- /** The API's per-request maximum for imports. */
901
- const IMPORT_BATCH_SIZE = 1e3;
902
- /**
903
- * `coss.email.suppressions`: the suppression list of the API key's environment. Sends skip
904
- * suppressed recipients; permanent bounces and complaints are added automatically.
905
- */
906
- var SuppressionResource = class {
907
- #http;
908
- /** @internal Use `new Coss().email.suppressions`. */
909
- constructor(http) {
910
- this.#http = http;
911
- }
912
- /**
913
- * Suppresses an address for every email (`scope: "*"`, the default) or for one category, e.g.
914
- * when a recipient unsubscribes. Returns the existing entry if there already is one.
915
- */
916
- add(params, options) {
917
- return this.#http.request({
918
- method: "POST",
919
- path: "/v1/suppressions",
920
- body: params,
921
- idempotencyKey: options?.idempotencyKey,
922
- signal: options?.signal
923
- });
924
- }
925
- /**
926
- * Adds many entries at once (reason `import`), 1,000 per request. Invalid entries are skipped
927
- * and reported in `invalid`; entries already on the list count as `existing`. If a request
928
- * fails, the earlier batches stay imported: importing everything again is safe.
929
- */
930
- async import(params, options) {
931
- const total = {
932
- object: "suppression_import",
933
- created: 0,
934
- existing: 0,
935
- invalid: []
936
- };
937
- for (let start = 0; start === 0 || start < params.suppressions.length;) {
938
- const batch = params.suppressions.slice(start, start + IMPORT_BATCH_SIZE);
939
- const result = await this.#http.request({
940
- method: "POST",
941
- path: "/v1/suppressions/import",
942
- body: { suppressions: batch },
943
- signal: options?.signal
944
- });
945
- if (result.error) return result;
946
- total.created += result.data.created;
947
- total.existing += result.data.existing;
948
- for (const entry of result.data.invalid) total.invalid.push({
949
- ...entry,
950
- index: entry.index + start
951
- });
952
- start += IMPORT_BATCH_SIZE;
953
- }
954
- return {
955
- data: total,
956
- error: null
957
- };
958
- }
959
- /**
960
- * The whole list as CSV (`address,scope,reason,created_at,email_id,id`, oldest first), which
961
- * `import` (or the dashboard) accepts again.
962
- */
963
- export(params = {}, options) {
964
- return this.#http.request({
965
- method: "GET",
966
- path: "/v1/suppressions/export",
967
- query: { ...params },
968
- responseType: "text",
969
- signal: options?.signal
970
- });
971
- }
972
- /** Lists entries, newest first. Pass the last `id` as `after` while `has_more` is true. */
973
- list(params = {}, options) {
974
- return this.#http.request({
975
- method: "GET",
976
- path: "/v1/suppressions",
977
- query: { ...params },
978
- signal: options?.signal
979
- });
980
- }
981
- /** Whether a send to `address` (with `category`, if given) would skip it. */
982
- check(params, options) {
983
- return this.#http.request({
984
- method: "GET",
985
- path: "/v1/suppressions/check",
986
- query: { ...params },
987
- signal: options?.signal
988
- });
989
- }
990
- /** Retrieves one entry. */
991
- get(id, options) {
992
- return this.#http.request({
993
- method: "GET",
994
- path: `/v1/suppressions/${encodeURIComponent(id)}`,
995
- signal: options?.signal
996
- });
997
- }
998
- /** Removes an entry, so later sends reach the address again (e.g. when a recipient resubscribes). */
999
- remove(id, options) {
1000
- return this.#http.request({
1001
- method: "DELETE",
1002
- path: `/v1/suppressions/${encodeURIComponent(id)}`,
1003
- signal: options?.signal
1004
- });
1005
- }
1006
- };
1007
- //#endregion
1008
- //#region src/resources/tracking.ts
1009
- const categoryPath = (category) => `/v1/tracking_settings/categories/${encodeURIComponent(category)}`;
1010
- /**
1011
- * `coss.email.tracking`: which emails of the API key's environment have their opens and clicks
1012
- * tracked and get one-click unsubscribe headers. Emails keep the settings that applied when they
1013
- * were sent; a send's own `tracking` option wins over them.
1014
- */
1015
- var TrackingResource = class {
1016
- #http;
1017
- /** @internal Use `new Coss().email.tracking`. */
1018
- constructor(http) {
1019
- this.#http = http;
1020
- }
1021
- /** The environment default and the category rules. */
1022
- get(options) {
1023
- return this.#http.request({
1024
- method: "GET",
1025
- path: "/v1/tracking_settings",
1026
- signal: options?.signal
1027
- });
1028
- }
1029
- /**
1030
- * Sets the environment default, which applies to emails without a rule for their category.
1031
- * Fields left out keep their value; a new default starts with both off.
1032
- */
1033
- updateDefault(params, options) {
1034
- return this.#http.request({
1035
- method: "PATCH",
1036
- path: "/v1/tracking_settings/default",
1037
- body: params,
1038
- signal: options?.signal
1039
- });
1040
- }
1041
- /** Removes the environment default: emails without a category rule are then not tracked. */
1042
- removeDefault(options) {
1043
- return this.#http.request({
1044
- method: "DELETE",
1045
- path: "/v1/tracking_settings/default",
1046
- signal: options?.signal
1047
- });
1048
- }
1049
- /**
1050
- * Sets the rule for emails sent with `category`, which wins over the default. Fields left out
1051
- * keep their value; a new rule starts with both off.
1052
- */
1053
- updateCategory(category, params, options) {
1054
- return this.#http.request({
1055
- method: "PATCH",
1056
- path: categoryPath(category),
1057
- body: params,
1058
- signal: options?.signal
1059
- });
1060
- }
1061
- /** Removes a category's rule: its emails follow the environment default again. */
1062
- removeCategory(category, options) {
1063
- return this.#http.request({
1064
- method: "DELETE",
1065
- path: categoryPath(category),
1066
- signal: options?.signal
1067
- });
1068
- }
1069
- };
1070
- //#endregion
1071
- //#region src/resources/email.ts
1072
- /** `coss.email`: transactional email. */
1073
- var EmailResource = class {
1074
- #http;
1075
- /** The environment's suppression list. */
1076
- suppressions;
1077
- /** The environment's open and click tracking settings. */
1078
- tracking;
1079
- /** Emails the environment received. */
1080
- received;
1081
- /** The environment's email templates. */
1082
- templates;
1083
- /** The organization's dedicated IPs. */
1084
- dedicatedIps;
1085
- /** @internal Use `new Coss().email`. */
1086
- constructor(http) {
1087
- this.#http = http;
1088
- this.suppressions = new SuppressionResource(http);
1089
- this.tracking = new TrackingResource(http);
1090
- this.received = new ReceivedEmailsResource(http);
1091
- this.templates = new EmailTemplatesResource(http);
1092
- this.dedicatedIps = new DedicatedIpsResource(http);
1093
- }
1094
- /**
1095
- * Sends an email, with its own subject and body or from a published template (`template_id`
1096
- * and `variables`). It is returned `queued` and handed to the delivery provider moments later:
1097
- * `get` it or listen for the `email.sent` / `email.failed` webhooks for the outcome. Safe to
1098
- * retry: the request always carries an `Idempotency-Key` (yours, or a generated one reused
1099
- * across automatic retries), so the API never sends it twice. A `react` component is rendered
1100
- * once, before the first attempt.
1101
- */
1102
- async send(params, options) {
1103
- const { body, error } = await renderReactEmail(params, "react");
1104
- if (error) return {
1105
- data: null,
1106
- error
1107
- };
1108
- return this.#http.request({
1109
- method: "POST",
1110
- path: "/v1/emails",
1111
- body,
1112
- idempotencyKey: options?.idempotencyKey,
1113
- signal: options?.signal
1114
- });
1115
- }
1116
- /**
1117
- * Sends up to 100 emails in one request, each as `send` would. The batch is all or nothing: if
1118
- * any email is invalid (the error's `issues` name it, e.g. `emails.3.to`), none is sent. Its
1119
- * recipients count against the send quota together. Safe to retry: one `Idempotency-Key` covers
1120
- * the whole batch. Larger lists need several calls, each with its own key.
1121
- */
1122
- async sendBatch(emails, options) {
1123
- const rendered = await Promise.all(emails.map((email, index) => renderReactEmail(email, `emails.${index}.react`)));
1124
- const bodies = [];
1125
- for (const { body, error } of rendered) {
1126
- if (error) return {
1127
- data: null,
1128
- error
1129
- };
1130
- bodies.push(body);
1131
- }
1132
- return this.#http.request({
1133
- method: "POST",
1134
- path: "/v1/emails/batch",
1135
- body: { emails: bodies },
1136
- idempotencyKey: options?.idempotencyKey,
1137
- signal: options?.signal
1138
- });
1139
- }
1140
- /** Retrieves a batch sent by `sendBatch`, with its emails' current statuses in request order. */
1141
- getBatch(id, options) {
1142
- return this.#http.request({
1143
- method: "GET",
1144
- path: `/v1/emails/batch/${encodeURIComponent(id)}`,
1145
- signal: options?.signal
1146
- });
1147
- }
1148
- /** Retrieves an email sent from the same environment as the API key. */
1149
- get(id, options) {
1150
- return this.#http.request({
1151
- method: "GET",
1152
- path: `/v1/emails/${encodeURIComponent(id)}`,
1153
- signal: options?.signal
1154
- });
1155
- }
1156
- /**
1157
- * Lists emails sent from the same environment as the API key, newest first and without their
1158
- * content (`get` one for `html`, `text`, `headers` and `attachments`). Pass the last `id` as
1159
- * `after` while `has_more` is true.
1160
- */
1161
- list(params = {}, options) {
1162
- return this.#http.request({
1163
- method: "GET",
1164
- path: "/v1/emails",
1165
- query: listQuery(params),
1166
- signal: options?.signal
1167
- });
1168
- }
1169
- /**
1170
- * Cancels a scheduled email. Canceling an already canceled email returns it; any other email
1171
- * fails with `email_not_cancelable`.
1172
- */
1173
- cancel(id, options) {
1174
- return this.#http.request({
1175
- method: "POST",
1176
- path: `/v1/emails/${encodeURIComponent(id)}/cancel`,
1177
- signal: options?.signal
1178
- });
1179
- }
1180
- /**
1181
- * Moves a scheduled email to a new time and records an `email.rescheduled` event. The time it
1182
- * already has returns it unchanged; an email that is no longer scheduled fails with
1183
- * `email_not_reschedulable`.
1184
- */
1185
- reschedule(id, params, options) {
1186
- return this.#http.request({
1187
- method: "POST",
1188
- path: `/v1/emails/${encodeURIComponent(id)}/reschedule`,
1189
- body: params,
1190
- signal: options?.signal
1191
- });
1192
- }
1193
- /** Lists an email's delivery events, oldest first. */
1194
- listEvents(id, options) {
1195
- return this.#http.request({
1196
- method: "GET",
1197
- path: `/v1/emails/${encodeURIComponent(id)}/events`,
1198
- signal: options?.signal
1199
- });
1200
- }
1201
- /** Lists the links tracked for clicks in an email, in document order, with click counts. */
1202
- listLinks(id, options) {
1203
- return this.#http.request({
1204
- method: "GET",
1205
- path: `/v1/emails/${encodeURIComponent(id)}/links`,
1206
- signal: options?.signal
1207
- });
1208
- }
1209
- };
1210
- //#endregion
1211
- //#region src/resources/environment.ts
1212
- /** `coss.environment`: which environment, project and organization the API key belongs to. */
1213
- var EnvironmentResource = class {
1214
- #http;
1215
- /** @internal Use `new Coss().environment`. */
1216
- constructor(http) {
1217
- this.#http = http;
1218
- }
1219
- /** The API key's environment, its project and organization, and the key itself. */
1220
- get(options) {
1221
- return this.#http.request({
1222
- method: "GET",
1223
- path: "/v1/environment",
1224
- signal: options?.signal
1225
- });
1226
- }
1227
- };
1228
- //#endregion
1229
- //#region src/resources/hooks.ts
1230
- const segment = encodeURIComponent;
1231
- const applicationPath = (application) => `/v1/hooks/applications/${segment(application)}`;
1232
- const endpointPath = (application, id) => `${applicationPath(application)}/endpoints/${segment(id)}`;
1233
- /** `coss.hooks.applications`: your customers, each with their own endpoints and portal. */
1234
- var HookApplicationsResource = class {
1235
- #http;
1236
- /** @internal Use `new Coss().hooks.applications`. */
1237
- constructor(http) {
1238
- this.#http = http;
1239
- }
1240
- /** Creates an application. Never automatically retried (the API does not deduplicate it). */
1241
- create(params, options) {
1242
- return this.#http.request({
1243
- method: "POST",
1244
- path: "/v1/hooks/applications",
1245
- retry: false,
1246
- body: params,
1247
- idempotencyKey: options?.idempotencyKey,
1248
- signal: options?.signal
1249
- });
1250
- }
1251
- /** Lists the environment's applications, newest first. */
1252
- list(params = {}, options) {
1253
- return this.#http.request({
1254
- method: "GET",
1255
- path: "/v1/hooks/applications",
1256
- query: listQuery(params),
1257
- signal: options?.signal
1258
- });
1259
- }
1260
- /** Retrieves an application by its id or uid. */
1261
- get(application, options) {
1262
- return this.#http.request({
1263
- method: "GET",
1264
- path: applicationPath(application),
1265
- signal: options?.signal
1266
- });
1267
- }
1268
- update(application, params, options) {
1269
- return this.#http.request({
1270
- method: "PATCH",
1271
- path: applicationPath(application),
1272
- body: params,
1273
- signal: options?.signal
1274
- });
1275
- }
1276
- /** Deletes the application with its endpoints and portal sessions. */
1277
- delete(application, options) {
1278
- return this.#http.request({
1279
- method: "DELETE",
1280
- path: applicationPath(application),
1281
- signal: options?.signal
1282
- });
1283
- }
1284
- };
1285
- /** `coss.hooks.eventTypes`: the catalog of messages you send, which your users subscribe from. */
1286
- var HookEventTypesResource = class {
1287
- #http;
1288
- /** @internal Use `new Coss().hooks.eventTypes`. */
1289
- constructor(http) {
1290
- this.#http = http;
1291
- }
1292
- /** Creates an event type. Never automatically retried (a retry would find it existing). */
1293
- create(params, options) {
1294
- return this.#http.request({
1295
- method: "POST",
1296
- path: "/v1/hooks/event_types",
1297
- retry: false,
1298
- body: params,
1299
- idempotencyKey: options?.idempotencyKey,
1300
- signal: options?.signal
1301
- });
1302
- }
1303
- /** Lists event types by name (archived ones only with `include_archived`). */
1304
- list(params = {}, options) {
1305
- return this.#http.request({
1306
- method: "GET",
1307
- path: "/v1/hooks/event_types",
1308
- query: listQuery(params),
1309
- signal: options?.signal
1310
- });
1311
- }
1312
- get(name, options) {
1313
- return this.#http.request({
1314
- method: "GET",
1315
- path: `/v1/hooks/event_types/${segment(name)}`,
1316
- signal: options?.signal
1317
- });
1318
- }
1319
- /** Changes its description, schema or examples, or archives or restores it. */
1320
- update(name, params, options) {
1321
- return this.#http.request({
1322
- method: "PATCH",
1323
- path: `/v1/hooks/event_types/${segment(name)}`,
1324
- body: params,
1325
- signal: options?.signal
1326
- });
1327
- }
1328
- /** Archives it: hidden from the portal and new subscriptions. */
1329
- archive(name, options) {
1330
- return this.#http.request({
1331
- method: "DELETE",
1332
- path: `/v1/hooks/event_types/${segment(name)}`,
1333
- signal: options?.signal
1334
- });
1335
- }
1336
- };
1337
- /** `coss.hooks.endpoints`: an application's endpoints (usually added by its users in the portal). */
1338
- var HookEndpointsResource = class {
1339
- #http;
1340
- /** @internal Use `new Coss().hooks.endpoints`. */
1341
- constructor(http) {
1342
- this.#http = http;
1343
- }
1344
- /** Creates an endpoint; the result carries its secret. Never automatically retried. */
1345
- create(application, params, options) {
1346
- return this.#http.request({
1347
- method: "POST",
1348
- path: `${applicationPath(application)}/endpoints`,
1349
- retry: false,
1350
- body: params,
1351
- idempotencyKey: options?.idempotencyKey,
1352
- signal: options?.signal
1353
- });
1354
- }
1355
- list(application, options) {
1356
- return this.#http.request({
1357
- method: "GET",
1358
- path: `${applicationPath(application)}/endpoints`,
1359
- signal: options?.signal
1360
- });
1361
- }
1362
- get(application, id, options) {
1363
- return this.#http.request({
1364
- method: "GET",
1365
- path: endpointPath(application, id),
1366
- signal: options?.signal
1367
- });
1368
- }
1369
- update(application, id, params, options) {
1370
- return this.#http.request({
1371
- method: "PATCH",
1372
- path: endpointPath(application, id),
1373
- body: params,
1374
- signal: options?.signal
1375
- });
1376
- }
1377
- delete(application, id, options) {
1378
- return this.#http.request({
1379
- method: "DELETE",
1380
- path: endpointPath(application, id),
1381
- signal: options?.signal
1382
- });
1383
- }
1384
- /** The endpoint's current signing secret. */
1385
- getSecret(application, id, options) {
1386
- return this.#http.request({
1387
- method: "GET",
1388
- path: `${endpointPath(application, id)}/secret`,
1389
- signal: options?.signal
1390
- });
1391
- }
1392
- /** Replaces the signing secret. Never automatically retried (a second roll would stop the first). */
1393
- rollSecret(application, id, params = {}, options) {
1394
- return this.#http.request({
1395
- method: "POST",
1396
- path: `${endpointPath(application, id)}/roll_secret`,
1397
- retry: false,
1398
- body: params,
1399
- idempotencyKey: options?.idempotencyKey,
1400
- signal: options?.signal
1401
- });
1402
- }
1403
- /** Requeues the endpoint's failed deliveries of messages sent since `since` (in the background). */
1404
- recover(application, id, params, options) {
1405
- const since = params.since instanceof Date ? params.since.toISOString() : params.since;
1406
- return this.#http.request({
1407
- method: "POST",
1408
- path: `${endpointPath(application, id)}/recover`,
1409
- body: { since },
1410
- idempotencyKey: options?.idempotencyKey,
1411
- signal: options?.signal
1412
- });
1413
- }
1414
- getRecovery(application, id, recoveryId, options) {
1415
- return this.#http.request({
1416
- method: "GET",
1417
- path: `${endpointPath(application, id)}/recoveries/${segment(recoveryId)}`,
1418
- signal: options?.signal
1419
- });
1420
- }
1421
- /** Sends a message to this endpoint only. Never automatically retried. */
1422
- sendTest(application, id, params, options) {
1423
- return this.#http.request({
1424
- method: "POST",
1425
- path: `${endpointPath(application, id)}/test`,
1426
- retry: false,
1427
- body: params,
1428
- idempotencyKey: options?.idempotencyKey,
1429
- signal: options?.signal
1430
- });
1431
- }
1432
- /** The endpoint's deliveries, newest first. */
1433
- listDeliveries(application, id, params = {}, options) {
1434
- return this.#http.request({
1435
- method: "GET",
1436
- path: `${endpointPath(application, id)}/deliveries`,
1437
- query: listQuery(params),
1438
- signal: options?.signal
1439
- });
1440
- }
1441
- };
1442
- /** `coss.hooks.messages`: send a message once; coss.com delivers it to every subscribed endpoint. */
1443
- var HookMessagesResource = class {
1444
- #http;
1445
- /** @internal Use `new Coss().hooks.messages`. */
1446
- constructor(http) {
1447
- this.#http = http;
1448
- }
1449
- /**
1450
- * Sends a message to an application. Safe to retry: every attempt carries the same
1451
- * `Idempotency-Key`, so a retried send is delivered once.
1452
- */
1453
- send(params, options) {
1454
- const { application, ...body } = params;
1455
- return this.#http.request({
1456
- method: "POST",
1457
- path: `${applicationPath(application)}/messages`,
1458
- body,
1459
- idempotencyKey: options?.idempotencyKey,
1460
- signal: options?.signal
1461
- });
1462
- }
1463
- /** The application's messages, newest first. */
1464
- list(application, params = {}, options) {
1465
- return this.#http.request({
1466
- method: "GET",
1467
- path: `${applicationPath(application)}/messages`,
1468
- query: listQuery(params),
1469
- signal: options?.signal
1470
- });
1471
- }
1472
- get(application, id, options) {
1473
- return this.#http.request({
1474
- method: "GET",
1475
- path: `${applicationPath(application)}/messages/${segment(id)}`,
1476
- signal: options?.signal
1477
- });
1478
- }
1479
- /** One delivery per endpoint the message went to. */
1480
- listDeliveries(application, id, options) {
1481
- return this.#http.request({
1482
- method: "GET",
1483
- path: `${applicationPath(application)}/messages/${segment(id)}/deliveries`,
1484
- signal: options?.signal
1485
- });
1486
- }
1487
- };
1488
- /** `coss.hooks.deliveries`: one message's delivery to one endpoint. */
1489
- var HookDeliveriesResource = class {
1490
- #http;
1491
- /** @internal Use `new Coss().hooks.deliveries`. */
1492
- constructor(http) {
1493
- this.#http = http;
1494
- }
1495
- get(application, id, options) {
1496
- return this.#http.request({
1497
- method: "GET",
1498
- path: `${applicationPath(application)}/deliveries/${segment(id)}`,
1499
- signal: options?.signal
1500
- });
1501
- }
1502
- /** Every HTTP request of the delivery, oldest first. */
1503
- listAttempts(application, id, options) {
1504
- return this.#http.request({
1505
- method: "GET",
1506
- path: `${applicationPath(application)}/deliveries/${segment(id)}/attempts`,
1507
- signal: options?.signal
1508
- });
1509
- }
1510
- /** Queues a finished delivery for one more attempt. Never automatically retried. */
1511
- retry(application, id, options) {
1512
- return this.#http.request({
1513
- method: "POST",
1514
- path: `${applicationPath(application)}/deliveries/${segment(id)}/retry`,
1515
- retry: false,
1516
- idempotencyKey: options?.idempotencyKey,
1517
- signal: options?.signal
1518
- });
1519
- }
1520
- };
1521
- /** `coss.hooks.portal`: a ready-made page for an application's user to manage their endpoints. */
1522
- var HookPortalResource = class {
1523
- #http;
1524
- /** @internal Use `new Coss().hooks.portal`. */
1525
- constructor(http) {
1526
- this.#http = http;
1527
- }
1528
- /**
1529
- * Signs the application's user in to the portal: open or embed the returned `url`. Call it from
1530
- * your backend each time the user opens the portal.
1531
- */
1532
- createSession(params, options) {
1533
- const { application, ...body } = params;
1534
- return this.#http.request({
1535
- method: "POST",
1536
- path: `${applicationPath(application)}/portal_sessions`,
1537
- body,
1538
- idempotencyKey: options?.idempotencyKey,
1539
- signal: options?.signal
1540
- });
1541
- }
1542
- };
1543
- /**
1544
- * `coss.hooks`: webhooks as a service. Send a message to one of your applications once
1545
- * (`coss.hooks.messages.send`); coss.com delivers it to every endpoint its users registered, signed
1546
- * (Standard Webhooks), with retries, and gives them a portal to manage it all.
1547
- */
1548
- var HooksResource = class {
1549
- applications;
1550
- eventTypes;
1551
- endpoints;
1552
- messages;
1553
- deliveries;
1554
- portal;
1555
- /** @internal Use `new Coss().hooks`. */
1556
- constructor(http) {
1557
- this.applications = new HookApplicationsResource(http);
1558
- this.eventTypes = new HookEventTypesResource(http);
1559
- this.endpoints = new HookEndpointsResource(http);
1560
- this.messages = new HookMessagesResource(http);
1561
- this.deliveries = new HookDeliveriesResource(http);
1562
- this.portal = new HookPortalResource(http);
1563
- }
1564
- };
1565
- //#endregion
1566
- //#region src/resources/log-drains.ts
1567
- const drainPath = (id) => `/v1/log_drains/${encodeURIComponent(id)}`;
1568
- /** `coss.logDrains.batches`: a drain's delivery log, each batch with every HTTP attempt. */
1569
- var LogDrainBatchesResource = class {
1570
- #http;
1571
- /** @internal Use `new Coss().logDrains.batches`. */
1572
- constructor(http) {
1573
- this.#http = http;
1574
- }
1575
- /** Lists the drain's batches, newest first. Pass the last `id` as `after` while `has_more` is true. */
1576
- list(drainId, params = {}, options) {
1577
- return this.#http.request({
1578
- method: "GET",
1579
- path: `${drainPath(drainId)}/batches`,
1580
- query: { ...params },
1581
- signal: options?.signal
1582
- });
1583
- }
1584
- /** Retrieves one batch of the drain. */
1585
- get(drainId, id, options) {
1586
- return this.#http.request({
1587
- method: "GET",
1588
- path: `${drainPath(drainId)}/batches/${encodeURIComponent(id)}`,
1589
- signal: options?.signal
1590
- });
1591
- }
1592
- };
1593
- /**
1594
- * `coss.logDrains`: HTTPS endpoints the environment's log is streamed to (API requests, email
1595
- * events, webhook attempts and audit events), in signed NDJSON batches. Drains belong to the API
1596
- * key's own environment, so a `coss_test_…` key only ever manages sandbox drains.
1597
- */
1598
- var LogDrainsResource = class {
1599
- #http;
1600
- /** Each drain's delivery log. */
1601
- batches;
1602
- /** @internal Use `new Coss().logDrains`. */
1603
- constructor(http) {
1604
- this.#http = http;
1605
- this.batches = new LogDrainBatchesResource(http);
1606
- }
1607
- /**
1608
- * Creates a drain. The result carries its `secret` (returned only here) — store it and pass it
1609
- * to `verifyLogDrainBatch` for every request. Creation is never automatically retried: the API
1610
- * does not deduplicate it. After a lost response, list drains and remove the one with the
1611
- * unknown secret before creating a replacement.
1612
- */
1613
- create(params, options) {
1614
- return this.#http.request({
1615
- method: "POST",
1616
- path: "/v1/log_drains",
1617
- retry: false,
1618
- body: params,
1619
- idempotencyKey: options?.idempotencyKey,
1620
- signal: options?.signal
1621
- });
1622
- }
1623
- /** Lists the environment's drains, oldest first. Secrets are never included. */
1624
- list(options) {
1625
- return this.#http.request({
1626
- method: "GET",
1627
- path: "/v1/log_drains",
1628
- signal: options?.signal
1629
- });
1630
- }
1631
- /** Retrieves a drain of the API key's environment. */
1632
- get(id, options) {
1633
- return this.#http.request({
1634
- method: "GET",
1635
- path: drainPath(id),
1636
- signal: options?.signal
1637
- });
1638
- }
1639
- /**
1640
- * Changes the URL, description, sources or `enabled` flag. The signing secret stays the same.
1641
- * Disabling drops the lines still waiting for the drain; enabling it again (also after coss.com
1642
- * disabled it for failing) sends lines logged from then on.
1643
- */
1644
- update(id, params, options) {
1645
- return this.#http.request({
1646
- method: "PATCH",
1647
- path: drainPath(id),
1648
- body: params,
1649
- signal: options?.signal
1650
- });
1651
- }
1652
- /** Deletes the drain and its batch log. To pause it instead, update `enabled` to false. */
1653
- delete(id, options) {
1654
- return this.#http.request({
1655
- method: "DELETE",
1656
- path: drainPath(id),
1657
- signal: options?.signal
1658
- });
1659
- }
1660
- };
1661
- //#endregion
1662
- //#region src/resources/logs.ts
1663
- /**
1664
- * `coss.logs`: the API key's environment log, newest first: API requests made with its keys,
1665
- * email events and webhook delivery attempts.
1666
- */
1667
- var LogsResource = class {
1668
- #http;
1669
- /** @internal Use `new Coss().logs`. */
1670
- constructor(http) {
1671
- this.#http = http;
1672
- }
1673
- /**
1674
- * Lists log lines, newest first (the last hour unless `from`/`to` say otherwise). Pass the last
1675
- * `id` as `after` while `has_more` is true.
1676
- */
1677
- list(params = {}, options) {
1678
- return this.#http.request({
1679
- method: "GET",
1680
- path: "/v1/logs",
1681
- query: listQuery(params),
1682
- signal: options?.signal
1683
- });
1684
- }
1685
- /** Retrieves one log line. */
1686
- get(id, options) {
1687
- return this.#http.request({
1688
- method: "GET",
1689
- path: `/v1/logs/${encodeURIComponent(id)}`,
1690
- signal: options?.signal
1691
- });
1692
- }
1693
- };
1694
- //#endregion
1695
- //#region src/resources/reputation.ts
1696
- /**
1697
- * `coss.reputation`: the organization's standing with the coss.com reputation guard, which suspends
1698
- * live sending automatically when bounce or complaint rates cross its thresholds.
1699
- */
1700
- var ReputationResource = class {
1701
- #http;
1702
- /** @internal Use `new Coss().reputation`. */
1703
- constructor(http) {
1704
- this.#http = http;
1705
- }
1706
- /** The current status and the latest rates measured over live environments. */
1707
- get(options) {
1708
- return this.#http.request({
1709
- method: "GET",
1710
- path: "/v1/reputation",
1711
- signal: options?.signal
1712
- });
1713
- }
1714
- };
1715
- //#endregion
1716
- //#region src/resources/risk.ts
1717
- const LIST_ENTRY_TYPES = [
1718
- "email",
1719
- "domain",
1720
- "ip",
1721
- "asn",
1722
- "country",
1723
- "user"
1724
- ];
1725
- /** `coss.risk.assessments`: reading past assessments (`assess` lives on `coss.risk`). */
1726
- var RiskAssessmentsResource = class {
1727
- #http;
1728
- /** @internal Use `new Coss().risk.assessments`. */
1729
- constructor(http) {
1730
- this.#http = http;
1731
- }
1732
- /** Retrieves one assessment. */
1733
- get(id, options) {
1734
- return this.#http.request({
1735
- method: "GET",
1736
- path: `/v1/risk/assessments/${encodeURIComponent(id)}`,
1737
- signal: options?.signal
1738
- });
1739
- }
1740
- /**
1741
- * Lists assessments, newest first (`review_status: "open"` is the review queue). Pass the last
1742
- * `id` as `after` while `has_more` is true.
1743
- */
1744
- list(params = {}, options) {
1745
- return this.#http.request({
1746
- method: "GET",
1747
- path: "/v1/risk/assessments",
1748
- query: { ...params },
1749
- signal: options?.signal
1750
- });
1751
- }
1752
- };
1753
- /** `coss.risk.lists`: the environment's allow and block lists. */
1754
- var RiskListsResource = class {
1755
- #http;
1756
- /** @internal Use `new Coss().risk.lists`. */
1757
- constructor(http) {
1758
- this.#http = http;
1759
- }
1760
- /**
1761
- * Adds an entry: `coss.risk.lists.add("block", { domain: "evil.example" })`. An allow-list match
1762
- * makes decisions `allow`, a block-list match `block`. Returns the existing entry if there is one.
1763
- */
1764
- add(list, entry, options) {
1765
- const type = LIST_ENTRY_TYPES.find((name) => name in entry);
1766
- const body = {
1767
- list,
1768
- type,
1769
- value: String(entry[type] ?? ""),
1770
- ...entry.note === void 0 ? {} : { note: entry.note },
1771
- ...entry.expires_at === void 0 ? {} : { expires_at: entry.expires_at instanceof Date ? entry.expires_at.toISOString() : entry.expires_at }
1772
- };
1773
- return this.#http.request({
1774
- method: "POST",
1775
- path: "/v1/risk/list_entries",
1776
- body,
1777
- idempotencyKey: options?.idempotencyKey,
1778
- signal: options?.signal
1779
- });
1780
- }
1781
- /** Lists entries, newest first. Pass the last `id` as `after` while `has_more` is true. */
1782
- list(params = {}, options) {
1783
- return this.#http.request({
1784
- method: "GET",
1785
- path: "/v1/risk/list_entries",
1786
- query: { ...params },
1787
- signal: options?.signal
1788
- });
1789
- }
1790
- /** Retrieves one entry. */
1791
- get(id, options) {
1792
- return this.#http.request({
1793
- method: "GET",
1794
- path: `/v1/risk/list_entries/${encodeURIComponent(id)}`,
1795
- signal: options?.signal
1796
- });
1797
- }
1798
- /** Removes an entry. */
1799
- remove(id, options) {
1800
- return this.#http.request({
1801
- method: "DELETE",
1802
- path: `/v1/risk/list_entries/${encodeURIComponent(id)}`,
1803
- signal: options?.signal
1804
- });
1805
- }
1806
- };
1807
- /** `coss.risk.settings`: the environment's thresholds, disabled reasons and captcha provider. */
1808
- var RiskSettingsResource = class {
1809
- #http;
1810
- /** @internal Use `new Coss().risk.settings`. */
1811
- constructor(http) {
1812
- this.#http = http;
1813
- }
1814
- get(options) {
1815
- return this.#http.request({
1816
- method: "GET",
1817
- path: "/v1/risk/settings",
1818
- signal: options?.signal
1819
- });
1820
- }
1821
- /** Changes the fields given. The captcha secret is write-only. */
1822
- update(params, options) {
1823
- return this.#http.request({
1824
- method: "PATCH",
1825
- path: "/v1/risk/settings",
1826
- body: params,
1827
- signal: options?.signal
1828
- });
1829
- }
1830
- };
1831
- /**
1832
- * `coss.risk.rules`: the environment's rules. After the lists, the first enabled rule whose
1833
- * conditions match an event decides it.
1834
- */
1835
- var RiskRulesResource = class {
1836
- #http;
1837
- /** @internal Use `new Coss().risk.rules`. */
1838
- constructor(http) {
1839
- this.#http = http;
1840
- }
1841
- /** Creates a rule. Not retried automatically: a retry could create it twice. */
1842
- create(params, options) {
1843
- return this.#http.request({
1844
- method: "POST",
1845
- path: "/v1/risk/rules",
1846
- body: params,
1847
- retry: false,
1848
- signal: options?.signal
1849
- });
1850
- }
1851
- /** Every rule, in evaluation order. */
1852
- list(options) {
1853
- return this.#http.request({
1854
- method: "GET",
1855
- path: "/v1/risk/rules",
1856
- signal: options?.signal
1857
- });
1858
- }
1859
- get(id, options) {
1860
- return this.#http.request({
1861
- method: "GET",
1862
- path: `/v1/risk/rules/${encodeURIComponent(id)}`,
1863
- signal: options?.signal
1864
- });
1865
- }
1866
- /** Changes the fields given; `conditions` replaces the whole list. */
1867
- update(id, params, options) {
1868
- return this.#http.request({
1869
- method: "PATCH",
1870
- path: `/v1/risk/rules/${encodeURIComponent(id)}`,
1871
- body: params,
1872
- signal: options?.signal
1873
- });
1874
- }
1875
- delete(id, options) {
1876
- return this.#http.request({
1877
- method: "DELETE",
1878
- path: `/v1/risk/rules/${encodeURIComponent(id)}`,
1879
- signal: options?.signal
1880
- });
1881
- }
1882
- };
1883
- /**
1884
- * `coss.risk.limitBuckets`: your rate limit buckets, which `coss.risk.limit()` charges per key.
1885
- */
1886
- var RiskLimitBucketsResource = class {
1887
- #http;
1888
- /** @internal Use `new Coss().risk.limitBuckets`. */
1889
- constructor(http) {
1890
- this.#http = http;
1891
- }
1892
- /** Creates a bucket. Not retried automatically: a retry would find its name taken. */
1893
- create(params, options) {
1894
- return this.#http.request({
1895
- method: "POST",
1896
- path: "/v1/risk/limit_buckets",
1897
- body: params,
1898
- retry: false,
1899
- signal: options?.signal
1900
- });
1901
- }
1902
- /** Every bucket, by name. */
1903
- list(options) {
1904
- return this.#http.request({
1905
- method: "GET",
1906
- path: "/v1/risk/limit_buckets",
1907
- signal: options?.signal
1908
- });
1909
- }
1910
- get(id, options) {
1911
- return this.#http.request({
1912
- method: "GET",
1913
- path: `/v1/risk/limit_buckets/${encodeURIComponent(id)}`,
1914
- signal: options?.signal
1915
- });
1916
- }
1917
- /** Changes the fields given; the next check uses them. */
1918
- update(id, params, options) {
1919
- return this.#http.request({
1920
- method: "PATCH",
1921
- path: `/v1/risk/limit_buckets/${encodeURIComponent(id)}`,
1922
- body: params,
1923
- signal: options?.signal
1924
- });
1925
- }
1926
- delete(id, options) {
1927
- return this.#http.request({
1928
- method: "DELETE",
1929
- path: `/v1/risk/limit_buckets/${encodeURIComponent(id)}`,
1930
- signal: options?.signal
1931
- });
1932
- }
1933
- };
1934
- /** `coss.risk.users`: what coss.com remembers about your users. */
1935
- var RiskUsersResource = class {
1936
- #http;
1937
- /** @internal Use `new Coss().risk.users`. */
1938
- constructor(http) {
1939
- this.#http = http;
1940
- }
1941
- /**
1942
- * Call when you delete a user: coss.com deletes what identifies them (their mailbox, fraud reports,
1943
- * and the user id, email, IP and user agent on their assessments). Safe to repeat.
1944
- */
1945
- forget(userId, options) {
1946
- return this.#http.request({
1947
- method: "DELETE",
1948
- path: `/v1/risk/users/${encodeURIComponent(userId)}`,
1949
- signal: options?.signal
1950
- });
1951
- }
1952
- };
1953
- /**
1954
- * `coss.risk`: assess sign-ups, logins and other events. Call it from your server and treat an
1955
- * error as `allow` (fail open), so an outage never locks your users out.
1956
- *
1957
- * ```ts
1958
- * const { data } = await coss.risk.assess({ event: "signup", user: { email }, ip, user_agent });
1959
- * if (data?.decision === "block") return refuse();
1960
- * ```
1961
- */
1962
- var RiskResource = class {
1963
- /** Past assessments (`get`, `list`). */
1964
- assessments;
1965
- /** Allow and block lists (`add`, `list`, `get`, `remove`). */
1966
- lists;
1967
- /** Forgetting deleted users. */
1968
- users;
1969
- /** Thresholds, disabled reasons and the captcha provider (`get`, `update`). */
1970
- settings;
1971
- /** Rules (`create`, `list`, `get`, `update`, `delete`). */
1972
- rules;
1973
- /** Your rate limit buckets (`create`, `list`, `get`, `update`, `delete`). */
1974
- limitBuckets;
1975
- #http;
1976
- /** @internal Use `new Coss().risk`. */
1977
- constructor(http) {
1978
- this.#http = http;
1979
- this.assessments = new RiskAssessmentsResource(http);
1980
- this.lists = new RiskListsResource(http);
1981
- this.users = new RiskUsersResource(http);
1982
- this.settings = new RiskSettingsResource(http);
1983
- this.rules = new RiskRulesResource(http);
1984
- this.limitBuckets = new RiskLimitBucketsResource(http);
1985
- }
1986
- /**
1987
- * Assesses an event and returns the decision with its score and reasons. Retries reuse one
1988
- * `Idempotency-Key`, so an event is never counted twice.
1989
- */
1990
- assess(params, options) {
1991
- return this.#http.request({
1992
- method: "POST",
1993
- path: "/v1/risk/assessments",
1994
- body: params,
1995
- idempotencyKey: options?.idempotencyKey,
1996
- signal: options?.signal
1997
- });
1998
- }
1999
- /**
2000
- * Reports what an assessed user turned out to be: `fraud` and `abuse` teach later assessments to
2001
- * flag the same mailbox, user, card, device, IP and subnet; `legitimate` takes that back.
2002
- * Resolves a review, and counts in `calibration()`.
2003
- */
2004
- feedback(id, params, options) {
2005
- return this.#http.request({
2006
- method: "POST",
2007
- path: `/v1/risk/assessments/${encodeURIComponent(id)}/feedback`,
2008
- body: params,
2009
- idempotencyKey: options?.idempotencyKey,
2010
- signal: options?.signal
2011
- });
2012
- }
2013
- /**
2014
- * How often each reason and rule was right over the last 90 days, by your feedback, and the
2015
- * reason weights that supports. Apply them with `settings.update({ reason_weights })`.
2016
- */
2017
- calibration(options) {
2018
- return this.#http.request({
2019
- method: "GET",
2020
- path: "/v1/risk/calibration",
2021
- signal: options?.signal
2022
- });
2023
- }
2024
- /**
2025
- * Checks an email address on its own: syntax, disposable domains, deliverability, role
2026
- * accounts, free providers, the canonical mailbox, typos and domain age. Nothing is stored.
2027
- */
2028
- checkEmail(email, options) {
2029
- return this.#http.request({
2030
- method: "POST",
2031
- path: "/v1/risk/email/check",
2032
- body: { email },
2033
- signal: options?.signal
2034
- });
2035
- }
2036
- /**
2037
- * Checks an IP address on its own: Tor, cloud, hosting and VPN networks, ASN and country, and
2038
- * VPN, proxy and relay exits when coss.com's privacy data is available.
2039
- */
2040
- checkIp(ip, options) {
2041
- return this.#http.request({
2042
- method: "POST",
2043
- path: "/v1/risk/ip/check",
2044
- body: { ip },
2045
- signal: options?.signal
2046
- });
2047
- }
2048
- /**
2049
- * Scores text for spam, phishing, malware and fraud. Scores only, never a verdict: you choose
2050
- * the thresholds. The text is neither stored nor logged.
2051
- */
2052
- classify(params, options) {
2053
- return this.#http.request({
2054
- method: "POST",
2055
- path: "/v1/risk/content/classify",
2056
- body: params,
2057
- signal: options?.signal
2058
- });
2059
- }
2060
- /**
2061
- * Takes `cost` tokens (default 1) from `key`'s share of one of your buckets
2062
- * (`coss.risk.limitBuckets`). Retries reuse one `Idempotency-Key`, so they are charged once.
2063
- *
2064
- * ```ts
2065
- * const { data } = await coss.risk.limit({ bucket: "password_reset", key: email });
2066
- * if (data && !data.allowed) return tooManyRequests(data.retry_after_ms);
2067
- * ```
2068
- */
2069
- limit(params, options) {
2070
- return this.#http.request({
2071
- method: "POST",
2072
- path: "/v1/risk/limits",
2073
- body: params,
2074
- idempotencyKey: options?.idempotencyKey,
2075
- signal: options?.signal
2076
- });
2077
- }
2078
- };
2079
- //#endregion
2080
- //#region src/resources/webhook-deliveries.ts
2081
- const deliveriesPath = (endpointId) => `/v1/webhook_endpoints/${encodeURIComponent(endpointId)}/deliveries`;
2082
- /**
2083
- * `coss.webhookEndpoints.deliveries`: an endpoint's delivery log. Each delivery carries every
2084
- * HTTP attempt and the payload as sent.
2085
- */
2086
- var WebhookDeliveriesResource = class {
2087
- #http;
2088
- /** @internal Use `new Coss().webhookEndpoints.deliveries`. */
2089
- constructor(http) {
2090
- this.#http = http;
2091
- }
2092
- /** Lists the endpoint's deliveries, newest first. Pass the last `id` as `after` while `has_more` is true. */
2093
- list(endpointId, params = {}, options) {
2094
- return this.#http.request({
2095
- method: "GET",
2096
- path: deliveriesPath(endpointId),
2097
- query: { ...params },
2098
- signal: options?.signal
2099
- });
2100
- }
2101
- /** Retrieves one delivery of the endpoint. */
2102
- get(endpointId, id, options) {
2103
- return this.#http.request({
2104
- method: "GET",
2105
- path: `${deliveriesPath(endpointId)}/${encodeURIComponent(id)}`,
2106
- signal: options?.signal
2107
- });
2108
- }
2109
- /**
2110
- * Queues a finished delivery for one more attempt, made within seconds. A delivery that is
2111
- * still `pending` is returned unchanged (it is already scheduled for `next_attempt_at`).
2112
- * Never automatically retried: the API does not deduplicate replay requests, even with an
2113
- * idempotency key.
2114
- */
2115
- retry(endpointId, id, options) {
2116
- return this.#http.request({
2117
- method: "POST",
2118
- path: `${deliveriesPath(endpointId)}/${encodeURIComponent(id)}/retry`,
2119
- retry: false,
2120
- idempotencyKey: options?.idempotencyKey,
2121
- signal: options?.signal
2122
- });
2123
- }
2124
- };
2125
- //#endregion
2126
- //#region src/resources/webhook-endpoints.ts
2127
- /**
2128
- * `coss.webhookEndpoints`: the URLs that receive signed event notifications. Endpoints belong to
2129
- * the API key's own environment, so a `coss_test_…` key only ever manages sandbox endpoints.
2130
- */
2131
- var WebhookEndpointsResource = class {
2132
- #http;
2133
- /** Each endpoint's delivery log: list, retrieve and retry deliveries. */
2134
- deliveries;
2135
- /** @internal Use `new Coss().webhookEndpoints`. */
2136
- constructor(http) {
2137
- this.#http = http;
2138
- this.deliveries = new WebhookDeliveriesResource(http);
2139
- }
2140
- /**
2141
- * Creates an endpoint. The result carries its `secret` (returned again only by `rollSecret`) —
2142
- * store it and pass it to `verifyWebhook` for every delivery. Creation is never automatically retried:
2143
- * the API does not deduplicate it, even with an idempotency key. After a lost response,
2144
- * list endpoints and remove the endpoint with the unknown secret before creating a replacement.
2145
- */
2146
- create(params, options) {
2147
- return this.#http.request({
2148
- method: "POST",
2149
- path: "/v1/webhook_endpoints",
2150
- retry: false,
2151
- body: params,
2152
- idempotencyKey: options?.idempotencyKey,
2153
- signal: options?.signal
2154
- });
2155
- }
2156
- /** Lists the environment's endpoints, oldest first. Secrets are never included. */
2157
- list(options) {
2158
- return this.#http.request({
2159
- method: "GET",
2160
- path: "/v1/webhook_endpoints",
2161
- signal: options?.signal
2162
- });
2163
- }
2164
- /** Retrieves an endpoint of the API key's environment. */
2165
- get(id, options) {
2166
- return this.#http.request({
2167
- method: "GET",
2168
- path: `/v1/webhook_endpoints/${encodeURIComponent(id)}`,
2169
- signal: options?.signal
2170
- });
2171
- }
2172
- /**
2173
- * Changes the URL, description, subscribed event types or `enabled` flag. The signing secret
2174
- * stays the same (see `rollSecret`), so receivers keep verifying deliveries.
2175
- */
2176
- update(id, params, options) {
2177
- return this.#http.request({
2178
- method: "PATCH",
2179
- path: `/v1/webhook_endpoints/${encodeURIComponent(id)}`,
2180
- body: params,
2181
- signal: options?.signal
2182
- });
2183
- }
2184
- /**
2185
- * Replaces the endpoint's signing secret; the result carries the new `secret`. Until
2186
- * `previous_secret_expires_at` (a day by default), deliveries are signed with both secrets, so
2187
- * `verifyWebhook` accepts them with either: deploy the new one, then let the old one expire.
2188
- * Never automatically retried (a second roll would stop the original secret at once): after a
2189
- * lost response, roll again and deploy that secret.
2190
- */
2191
- rollSecret(id, params = {}, options) {
2192
- return this.#http.request({
2193
- method: "POST",
2194
- path: `/v1/webhook_endpoints/${encodeURIComponent(id)}/roll_secret`,
2195
- retry: false,
2196
- body: params,
2197
- idempotencyKey: options?.idempotencyKey,
2198
- signal: options?.signal
2199
- });
2200
- }
2201
- /**
2202
- * Queues the endpoint's deliveries that failed since `since` for one more attempt each (at most
2203
- * 1,000 per call; while `has_more` is true, call again with the same `since`), e.g. after fixing a
2204
- * receiver that was down. The endpoint must be enabled.
2205
- */
2206
- recover(id, params, options) {
2207
- const since = params.since instanceof Date ? params.since.toISOString() : params.since;
2208
- return this.#http.request({
2209
- method: "POST",
2210
- path: `/v1/webhook_endpoints/${encodeURIComponent(id)}/recover`,
2211
- body: { since },
2212
- idempotencyKey: options?.idempotencyKey,
2213
- signal: options?.signal
2214
- });
2215
- }
2216
- /** Deletes the endpoint and its delivery log. To pause it instead, update `enabled` to false. */
2217
- delete(id, options) {
2218
- return this.#http.request({
2219
- method: "DELETE",
2220
- path: `/v1/webhook_endpoints/${encodeURIComponent(id)}`,
2221
- signal: options?.signal
2222
- });
2223
- }
2224
- };
2225
- //#endregion
2226
- //#region src/resources/webhook-listeners.ts
2227
- /**
2228
- * `coss.webhookListeners`: what `coss listen` uses to forward an environment's events to a local
2229
- * server. A listener receives events created after it opens, while it is polled; it is closed by
2230
- * `delete` or after 10 minutes without a poll.
2231
- */
2232
- var WebhookListenersResource = class {
2233
- #http;
2234
- /** @internal Use `new Coss().webhookListeners`. */
2235
- constructor(http) {
2236
- this.#http = http;
2237
- }
2238
- /** Opens a listener. Never retried automatically: a lost answer leaves one to expire. */
2239
- create(params = {}, options) {
2240
- return this.#http.request({
2241
- method: "POST",
2242
- path: "/v1/webhook_listeners",
2243
- retry: false,
2244
- body: params,
2245
- signal: options?.signal
2246
- });
2247
- }
2248
- /**
2249
- * Acknowledges earlier deliveries and waits (up to `wait_ms`) for more. Never retried
2250
- * automatically: call it in a loop, and keep unacknowledged acks for the next call after an error.
2251
- */
2252
- poll(id, params = {}, options) {
2253
- return this.#http.request({
2254
- method: "POST",
2255
- path: `/v1/webhook_listeners/${encodeURIComponent(id)}/poll`,
2256
- retry: false,
2257
- body: params,
2258
- signal: options?.signal
2259
- });
2260
- }
2261
- /** Closes a listener: it receives nothing more. */
2262
- delete(id, options) {
2263
- return this.#http.request({
2264
- method: "DELETE",
2265
- path: `/v1/webhook_listeners/${encodeURIComponent(id)}`,
2266
- signal: options?.signal
2267
- });
2268
- }
2269
- };
2270
- //#endregion
2271
- //#region src/client.ts
2272
- const DEFAULT_BASE_URL = "https://api.coss.com";
2273
- const DEFAULT_TIMEOUT_MS = 3e4;
2274
- const DEFAULT_MAX_RETRIES = 2;
2275
- const MAX_TIMEOUT_MS = 2147483647;
2276
- /** Reads an env variable where one exists (Node, Bun, Deno's `process`), never throwing. */
2277
- function readEnv(name) {
2278
- try {
2279
- return (globalThis.process?.env)?.[name]?.trim() || void 0;
2280
- } catch {
2281
- return;
2282
- }
2283
- }
2284
- function retries(value) {
2285
- return value !== void 0 && Number.isFinite(value) && value >= 0 ? Math.floor(value) : DEFAULT_MAX_RETRIES;
2286
- }
2287
- function timeoutMs(value) {
2288
- return value !== void 0 && Number.isFinite(value) && value > 0 ? Math.min(Math.ceil(value), MAX_TIMEOUT_MS) : DEFAULT_TIMEOUT_MS;
2289
- }
2290
- /**
2291
- * The coss.com client. One API key covers every product.
2292
- *
2293
- * ```ts
2294
- * const coss = new Coss({ apiKey: "coss_test_…" });
2295
- * const { data, error } = await coss.email.send({ from, to, subject, html });
2296
- * ```
2297
- */
2298
- var Coss = class {
2299
- email;
2300
- /** The API key's environment, project and organization (`coss.environment.get()`). */
2301
- environment;
2302
- /** The client's own API key (`coss.apiKey.revoke()`). */
2303
- apiKey;
2304
- /** Sending domains of the organization (`coss.domains.create`, `.verify`, …). */
2305
- domains;
2306
- /** Webhook endpoints of the API key's environment. */
2307
- webhookEndpoints;
2308
- /** Temporary listeners `coss listen` pulls the environment's events from. */
2309
- webhookListeners;
2310
- /** The organization's sending reputation (`coss.reputation.get()`). */
2311
- reputation;
2312
- /** The environment's log: API requests, email events, webhook attempts (`coss.logs.list()`). */
2313
- logs;
2314
- /** HTTPS endpoints the environment's log is streamed to (`coss.logDrains.create()`). */
2315
- logDrains;
2316
- /** The organization's audit log: changes by members, API keys and coss.com support (`coss.auditEvents.list()`). */
2317
- auditEvents;
2318
- /** Hooks, webhooks as a service: `coss.hooks.messages.send()` delivers to your users' endpoints. */
2319
- hooks;
2320
- /** Risk assessments of sign-ups, logins and other events (`coss.risk.assess()`). */
2321
- risk;
2322
- /** The organization's plan, usage, invoices and credits (`coss.billing.get()`). */
2323
- billing;
2324
- /**
2325
- * Throws only for programmer errors: no API key, or running in a browser without
2326
- * `dangerouslyAllowBrowser`. Request failures are returned as `{ data: null, error }`.
2327
- */
2328
- constructor(options = {}) {
2329
- if (typeof globalThis.document !== "undefined" && !options.dangerouslyAllowBrowser) throw new Error("Refusing to create a coss.com client in a browser-like environment: coss.com API keys are secret, and any key sent to the browser can be read by anyone using the page. Call coss.com from your server instead, or pass `dangerouslyAllowBrowser: true` if you understand the risk.");
2330
- const apiKey = options.apiKey?.trim() || readEnv("COSS_API_KEY");
2331
- if (!apiKey) throw new Error("Missing coss.com API key. Pass `apiKey` to `new Coss({ apiKey })` or set the COSS_API_KEY environment variable.");
2332
- const http = new HttpClient({
2333
- apiKey,
2334
- baseUrl: options.baseUrl?.trim() || readEnv("COSS_BASE_URL") || DEFAULT_BASE_URL,
2335
- fetch: options.fetch ?? ((input, init) => globalThis.fetch(input, init)),
2336
- timeout: timeoutMs(options.timeout),
2337
- maxRetries: retries(options.maxRetries),
2338
- apiVersion: options.apiVersion?.trim() || "2026-10-10"
2339
- });
2340
- this.email = new EmailResource(http);
2341
- this.environment = new EnvironmentResource(http);
2342
- this.apiKey = new ApiKeyResource(http);
2343
- this.domains = new DomainsResource(http);
2344
- this.webhookEndpoints = new WebhookEndpointsResource(http);
2345
- this.webhookListeners = new WebhookListenersResource(http);
2346
- this.reputation = new ReputationResource(http);
2347
- this.logs = new LogsResource(http);
2348
- this.logDrains = new LogDrainsResource(http);
2349
- this.auditEvents = new AuditEventsResource(http);
2350
- this.hooks = new HooksResource(http);
2351
- this.risk = new RiskResource(http);
2352
- this.billing = new BillingResource(http);
2353
- }
2354
- };
2355
- //#endregion
1
+ import { a as API_VERSIONS, i as API_VERSION, r as VERSION, t as Coss } from "./client-CCVBtkpV.js";
2356
2
  //#region src/webhooks.ts
2357
3
  /** A webhook request failed verification: reject it (e.g. respond 400). */
2358
4
  var WebhookVerificationError = class extends Error {