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