@devitek/mailsink-cli 0.0.0-stage → 0.3.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/bin.mjs ADDED
@@ -0,0 +1,2924 @@
1
+ #!/usr/bin/env node
2
+ import { parseArgs } from "node:util";
3
+ import { z } from "zod";
4
+ // ../contracts/src/address.ts
5
+ const EmailCheck = z.email();
6
+ const ANGLE_RE = /^(.*?)\s*<([^<>]+)>$/;
7
+ function unquote(name) {
8
+ const trimmed = name.trim();
9
+ if (trimmed.length >= 2 && trimmed.startsWith("\"") && trimmed.endsWith("\"")) return trimmed.slice(1, -1).replace(/\\(.)/g, "$1").trim();
10
+ return trimmed;
11
+ }
12
+ /**
13
+ * Parses "jane@x.io", "Jane <jane@x.io>" or "\"Doe, Jane\" <jane@x.io>".
14
+ * Returns null when the e-mail part is invalid. The e-mail is lower-cased.
15
+ */
16
+ function parseAddress(input) {
17
+ const raw = input.trim();
18
+ const match = ANGLE_RE.exec(raw);
19
+ const email = (match ? match[2] ?? "" : raw).trim();
20
+ if (!EmailCheck.safeParse(email).success) return null;
21
+ const name = match ? unquote(match[1] ?? "") : "";
22
+ return name ? {
23
+ email: email.toLowerCase(),
24
+ name
25
+ } : { email: email.toLowerCase() };
26
+ }
27
+ const AddressObject = z.object({
28
+ email: z.string(),
29
+ name: z.string().optional()
30
+ });
31
+ function fromObject(value) {
32
+ const parsed = parseAddress(value.email);
33
+ if (!parsed || parsed.name) return null;
34
+ const name = value.name?.trim();
35
+ return name ? {
36
+ ...parsed,
37
+ name
38
+ } : parsed;
39
+ }
40
+ /** "Jane <jane@x.io>" | "jane@x.io" | { email, name? } -> { email, name? } */
41
+ const Address = z.union([z.string(), AddressObject]).transform((value, ctx) => {
42
+ const parsed = typeof value === "string" ? parseAddress(value) : fromObject(value);
43
+ if (!parsed) {
44
+ ctx.issues.push({
45
+ code: "custom",
46
+ input: value,
47
+ message: "Invalid address, expected \"jane@x.io\" or \"Jane <jane@x.io>\"",
48
+ params: { code: "invalid_address" }
49
+ });
50
+ return z.NEVER;
51
+ }
52
+ return parsed;
53
+ });
54
+ /** One address or an array of addresses, always output as an array. */
55
+ const AddressList = z.union([Address, z.array(Address)]).transform((v) => Array.isArray(v) ? v : [v]);
56
+ /** Address as returned by the API (keys always present). */
57
+ const AddressOut = z.object({
58
+ email: z.string(),
59
+ name: z.string().nullable()
60
+ });
61
+ // ../contracts/src/common.ts
62
+ /**
63
+ * Refinement options carrying an English message (D19) and a stable machine-readable code
64
+ * in `params.code`, so the UI can map it to a translated label.
65
+ */
66
+ function issue(code, message, path) {
67
+ return {
68
+ message,
69
+ path,
70
+ params: { code }
71
+ };
72
+ }
73
+ /** Lower-cased e-mail address. */
74
+ const Email = z.email().transform((e) => e.toLowerCase());
75
+ const Slug = z.string().regex(/^[a-z0-9][a-z0-9-]{1,62}$/, "Invalid slug");
76
+ const UNIT_SECONDS = {
77
+ s: 1,
78
+ m: 60,
79
+ h: 3600,
80
+ d: 86400
81
+ };
82
+ const DURATION_RE = /^(\d+)(s|m|h|d)$/;
83
+ /** "90s" | "30m" | "1h" | "7d" -> seconds, or null when the string is not a duration. */
84
+ function parseDuration(input) {
85
+ const match = DURATION_RE.exec(input);
86
+ if (!match) return null;
87
+ const [, amount, unit] = match;
88
+ return Number(amount) * UNIT_SECONDS[unit];
89
+ }
90
+ /** Positive integer seconds, or a string such as "1h" or "7d". Output: seconds. */
91
+ const Duration = z.union([z.number(), z.string()]).transform((value, ctx) => {
92
+ const seconds = typeof value === "number" ? value : parseDuration(value);
93
+ if (seconds === null || !Number.isSafeInteger(seconds) || seconds <= 0) {
94
+ ctx.issues.push({
95
+ code: "custom",
96
+ input: value,
97
+ message: "Expected positive integer seconds or a duration such as \"30m\", \"1h\" or \"7d\"",
98
+ params: { code: "invalid_duration" }
99
+ });
100
+ return z.NEVER;
101
+ }
102
+ return seconds;
103
+ });
104
+ /** Boolean from a query string ("true", "1", "yes"…) or from a router that already parsed it. */
105
+ const QueryBool = z.union([z.boolean(), z.stringbool()]);
106
+ const IsoDateTime = z.iso.datetime({ offset: true });
107
+ const Tag = z.object({
108
+ name: z.string().regex(/^[\w-]{1,256}$/, "Tag names use letters, digits, \"_\" and \"-\""),
109
+ value: z.string().max(256)
110
+ });
111
+ /** Cursor pagination envelope shared by every list endpoint. */
112
+ function Page(item) {
113
+ return z.object({
114
+ data: z.array(item),
115
+ nextCursor: z.string().nullable()
116
+ });
117
+ }
118
+ const PageLimit = z.coerce.number().int().min(1).max(200).default(50);
119
+ // ../contracts/src/ids.ts
120
+ function prefixedId(prefix) {
121
+ return z.string().regex(new RegExp(`^${prefix}_[A-Za-z0-9-]{1,64}$`), `Expected an id starting with "${prefix}_"`);
122
+ }
123
+ const WorkspaceId = prefixedId("ws");
124
+ const ConnectionId = prefixedId("con");
125
+ const OverrideId = prefixedId("ovr");
126
+ const MessageId = prefixedId("msg");
127
+ const AttachmentId = prefixedId("att");
128
+ const EventId = prefixedId("evt");
129
+ const WebhookEndpointId = prefixedId("whe");
130
+ const WebhookDeliveryId = prefixedId("whd");
131
+ /** Workspace reference accepted by `:id` and `X-Mailsink-Workspace`: id or slug. */
132
+ const WorkspaceRef = z.union([WorkspaceId, Slug]);
133
+ const ConnectionKey = z.string().regex(/^msk_[A-Za-z0-9_-]{16,128}$/, "Invalid msk_ key");
134
+ const WorkspaceKey = z.string().regex(/^mskw_[A-Za-z0-9_-]{16,128}$/, "Invalid mskw_ key");
135
+ // ../contracts/src/status.ts
136
+ const DeliveryStatus = z.enum([
137
+ "queued",
138
+ "sent",
139
+ "delivered",
140
+ "deferred",
141
+ "soft_bounce",
142
+ "hard_bounce",
143
+ "complained",
144
+ "failed",
145
+ "invalid",
146
+ "suppressed"
147
+ ]);
148
+ /** Final statuses the simulation can draw (queued, sent and suppressed are not drawn). */
149
+ const SimulatedStatus = DeliveryStatus.exclude([
150
+ "queued",
151
+ "sent",
152
+ "suppressed"
153
+ ]);
154
+ /** Canonical webhook events (D22), see 03-contracts « Webhooks » for the per-format mapping. */
155
+ const CanonicalEvent = z.enum([
156
+ "email.sent",
157
+ "email.delivered",
158
+ "email.deferred",
159
+ "email.soft_bounced",
160
+ "email.hard_bounced",
161
+ "email.complained",
162
+ "email.opened",
163
+ "email.clicked",
164
+ "email.suppressed",
165
+ "email.failed",
166
+ "email.invalid"
167
+ ]);
168
+ const ConnectionKind = z.enum([
169
+ "resend",
170
+ "brevo",
171
+ "smtp"
172
+ ]);
173
+ const MessageSource = z.enum([
174
+ "native",
175
+ "resend",
176
+ "brevo",
177
+ "smtp"
178
+ ]);
179
+ const EventType = z.enum([
180
+ "accepted",
181
+ "sent",
182
+ "delivered",
183
+ "deferred",
184
+ "soft_bounce",
185
+ "hard_bounce",
186
+ "complained",
187
+ "failed",
188
+ "invalid",
189
+ "suppressed",
190
+ "opened",
191
+ "clicked"
192
+ ]);
193
+ const EventOrigin = z.enum([
194
+ "simulation",
195
+ "api",
196
+ "ui",
197
+ "mcp"
198
+ ]);
199
+ const RecipientKind = z.enum([
200
+ "to",
201
+ "cc",
202
+ "bcc"
203
+ ]);
204
+ // ../contracts/src/settings.ts
205
+ const DEFAULT_RETENTION_SECONDS = 604800;
206
+ const MAX_DELAY_MS = 6e5;
207
+ const Percent = z.number().min(0).max(100);
208
+ /** Retention: a Duration between 1 minute and 365 days. */
209
+ const Retention = Duration.pipe(z.number().min(60, "Retention must be at least 60s").max(31536e3, "Retention max is 365d"));
210
+ /** Percentages per simulated status; the remainder goes to `delivered`. */
211
+ const StatusRates = z.partialRecord(SimulatedStatus, Percent).refine((r) => Object.values(r).reduce((sum, v) => sum + (v ?? 0), 0) <= 100, issue("rates_sum_exceeds_100", "Status rates must not add up to more than 100"));
212
+ const RecipientRule = z.object({
213
+ match: z.string().min(1),
214
+ status: SimulatedStatus.optional(),
215
+ delayMs: z.number().int().min(0).max(MAX_DELAY_MS).optional(),
216
+ smtpCode: z.number().int().min(400).max(599).optional()
217
+ }).refine((r) => r.status !== void 0 || r.delayMs !== void 0, issue("rule_needs_effect", "A rule needs a status or a delayMs"));
218
+ const Latency = z.object({
219
+ minMs: z.number().int().min(0).max(MAX_DELAY_MS),
220
+ maxMs: z.number().int().min(0).max(MAX_DELAY_MS)
221
+ }).refine((l) => l.minMs <= l.maxMs, issue("latency_min_gt_max", "minMs must be lower than or equal to maxMs", ["maxMs"]));
222
+ /** Fails the request itself (HTTP or SMTP), before ingestion. */
223
+ const Chaos = z.object({
224
+ errorRate: Percent,
225
+ httpCodes: z.array(z.union([
226
+ z.literal(429),
227
+ z.literal(500),
228
+ z.literal(502),
229
+ z.literal(503)
230
+ ])).min(1).default([500]),
231
+ smtpCodes: z.array(z.union([
232
+ z.literal(421),
233
+ z.literal(451),
234
+ z.literal(452),
235
+ z.literal(550)
236
+ ])).min(1).default([451])
237
+ });
238
+ const RateLimitSettings = z.object({
239
+ limit: z.number().int().positive(),
240
+ windowSeconds: z.number().int().positive().default(1),
241
+ burst: z.number().int().positive().optional()
242
+ });
243
+ const RecipientRules = z.array(RecipientRule).max(50);
244
+ /** Partial simulation settings (connection level, override): absent keys inherit. */
245
+ const SimulationSettingsPatch = z.object({
246
+ rates: StatusRates.optional(),
247
+ rules: RecipientRules.optional(),
248
+ latency: Latency.optional(),
249
+ openRate: Percent.optional(),
250
+ clickRate: Percent.optional()
251
+ });
252
+ /** Complete simulation settings (workspace level, resolved values). */
253
+ const SimulationSettings = z.object({
254
+ rates: StatusRates.default({ delivered: 100 }),
255
+ rules: RecipientRules.default([]),
256
+ latency: Latency.default({
257
+ minMs: 0,
258
+ maxMs: 0
259
+ }),
260
+ openRate: Percent.default(0),
261
+ clickRate: Percent.default(0)
262
+ });
263
+ // ../contracts/src/templates.ts
264
+ const TemplateId = prefixedId("tpl");
265
+ /** Brevo template id: positive 32-bit integer (Postgres `integer`). */
266
+ const TemplateExternalId = z.coerce.number().int().positive().max(0x7fffffff);
267
+ const MAX_BODY_CHARS = 1e6;
268
+ const TemplateFields = {
269
+ name: z.string().trim().min(1).max(200),
270
+ subject: z.string().max(998),
271
+ html: z.string().max(MAX_BODY_CHARS).nullable().optional(),
272
+ text: z.string().max(MAX_BODY_CHARS).nullable().optional(),
273
+ /** Default sender of the emails sent with this template, unless the request sets one. */
274
+ sender: Address.nullable().optional()
275
+ };
276
+ const hasBody = (t) => Boolean(t.html || t.text);
277
+ /** `POST /admin/workspaces/:id/templates` and the `templates` seed of a new workspace. */
278
+ const TemplateInput = z.object({
279
+ /** Brevo `templateId`; the next free id of the workspace when absent. */
280
+ externalId: TemplateExternalId.optional(),
281
+ ...TemplateFields
282
+ }).refine(hasBody, issue("html_or_text_required", "html or text is required", ["html"]));
283
+ z.object({
284
+ name: TemplateFields.name.optional(),
285
+ subject: TemplateFields.subject.optional(),
286
+ html: TemplateFields.html,
287
+ text: TemplateFields.text,
288
+ sender: TemplateFields.sender
289
+ }).refine((p) => Object.values(p).some((v) => v !== void 0), {
290
+ message: "At least one field is required",
291
+ params: { code: "empty_patch" }
292
+ });
293
+ const TemplateView = z.object({
294
+ id: TemplateId,
295
+ externalId: z.number().int(),
296
+ name: z.string(),
297
+ subject: z.string(),
298
+ html: z.string().nullable(),
299
+ text: z.string().nullable(),
300
+ sender: AddressOut.nullable(),
301
+ createdAt: IsoDateTime,
302
+ updatedAt: IsoDateTime
303
+ });
304
+ z.object({
305
+ id: WorkspaceRef,
306
+ templateId: TemplateExternalId
307
+ });
308
+ z.object({
309
+ cursor: TemplateExternalId.optional(),
310
+ limit: PageLimit
311
+ });
312
+ const ListTemplatesResponse = Page(TemplateView);
313
+ const TemplateSeed = z.array(TemplateInput).max(500);
314
+ // ../contracts/src/admin.ts
315
+ const Name$1 = z.string().trim().min(1).max(80);
316
+ /** Per-connection overrides of workspace defaults; absent = inherit. */
317
+ const ConnectionSettingsInput = {
318
+ name: Name$1,
319
+ retention: Retention.optional(),
320
+ rateLimit: RateLimitSettings.nullable().optional(),
321
+ simulation: SimulationSettingsPatch.optional()
322
+ };
323
+ const ConnectionInput = z.discriminatedUnion("kind", [
324
+ z.object({
325
+ kind: z.literal("resend"),
326
+ ...ConnectionSettingsInput
327
+ }),
328
+ z.object({
329
+ kind: z.literal("brevo"),
330
+ ...ConnectionSettingsInput
331
+ }),
332
+ z.object({
333
+ kind: z.literal("smtp"),
334
+ ...ConnectionSettingsInput,
335
+ smtpUsername: z.string().regex(/^[a-zA-Z0-9._-]{3,64}$/).optional()
336
+ })
337
+ ]);
338
+ const IDLE_TTL_BOUNDS = {
339
+ min: 60,
340
+ max: 2592e3
341
+ };
342
+ z.object({
343
+ name: Name$1,
344
+ slug: Slug.optional(),
345
+ description: z.string().max(500).optional(),
346
+ ephemeral: z.boolean().default(false),
347
+ idleTtlSeconds: z.number().int().min(IDLE_TTL_BOUNDS.min).max(IDLE_TTL_BOUNDS.max).optional(),
348
+ retention: Retention.default(DEFAULT_RETENTION_SECONDS),
349
+ maxMessages: z.number().int().positive().optional(),
350
+ rateLimit: RateLimitSettings.nullable().optional(),
351
+ simulation: SimulationSettings.optional(),
352
+ metadata: z.record(z.string(), z.string().max(256)).optional(),
353
+ connections: z.array(ConnectionInput).max(20).default([]),
354
+ templates: TemplateSeed.optional()
355
+ }).refine((w) => w.ephemeral || w.idleTtlSeconds === void 0, issue("idle_ttl_requires_ephemeral", "idleTtlSeconds requires ephemeral: true", ["idleTtlSeconds"]));
356
+ const ConnectionView = z.object({
357
+ id: ConnectionId,
358
+ name: z.string(),
359
+ kind: ConnectionKind,
360
+ smtpUsername: z.string().nullable(),
361
+ keyPreview: z.string().nullable(),
362
+ retentionSeconds: z.number().int().nullable(),
363
+ rateLimit: RateLimitSettings.nullable(),
364
+ simulation: SimulationSettingsPatch.nullable(),
365
+ disabledAt: IsoDateTime.nullable(),
366
+ createdAt: IsoDateTime
367
+ });
368
+ const WorkspaceView = z.object({
369
+ id: WorkspaceId,
370
+ slug: Slug,
371
+ name: z.string(),
372
+ description: z.string().nullable(),
373
+ ephemeral: z.boolean(),
374
+ idleTtlSeconds: z.number().int().nullable(),
375
+ expiresAt: IsoDateTime.nullable(),
376
+ lastActivityAt: IsoDateTime,
377
+ retentionSeconds: z.number().int(),
378
+ maxMessages: z.number().int().nullable(),
379
+ rateLimit: RateLimitSettings.nullable(),
380
+ simulation: SimulationSettings,
381
+ metadata: z.record(z.string(), z.string()).nullable(),
382
+ urls: z.object({
383
+ ui: z.string(),
384
+ capture: z.string(),
385
+ mcp: z.string()
386
+ }),
387
+ createdAt: IsoDateTime
388
+ });
389
+ const WorkspaceDetail = WorkspaceView.extend({ connections: z.array(ConnectionView) });
390
+ /** Secrets, returned once at creation. */
391
+ const ConnectionCredentials = z.discriminatedUnion("kind", [
392
+ z.object({
393
+ kind: z.literal("resend"),
394
+ apiKey: ConnectionKey,
395
+ baseUrl: z.string()
396
+ }),
397
+ z.object({
398
+ kind: z.literal("brevo"),
399
+ apiKey: ConnectionKey,
400
+ baseUrl: z.string()
401
+ }),
402
+ z.object({
403
+ kind: z.literal("smtp"),
404
+ smtpHost: z.string(),
405
+ smtpPort: z.number().int().min(1).max(65535),
406
+ smtpUser: z.string(),
407
+ smtpPass: z.string()
408
+ })
409
+ ]);
410
+ /** 201, secrets shown once. */
411
+ const CreateWorkspaceResponse = z.object({
412
+ workspace: WorkspaceView,
413
+ workspaceKey: WorkspaceKey,
414
+ connections: z.array(ConnectionView.extend({
415
+ credentials: ConnectionCredentials,
416
+ envSnippet: z.string()
417
+ }))
418
+ });
419
+ z.object({
420
+ includeEphemeral: QueryBool.default(false),
421
+ /** Keyset cursor: the `nextCursor` of the previous page, the id of its last workspace. */
422
+ cursor: WorkspaceId.optional(),
423
+ limit: PageLimit
424
+ });
425
+ const ListWorkspacesResponse = Page(WorkspaceView);
426
+ const BREVO_MAX_TOTAL_RECIPIENTS = 2e3;
427
+ const BrevoAddress = z.object({
428
+ email: Email,
429
+ name: z.string().max(70).optional()
430
+ });
431
+ const Recipients = z.array(BrevoAddress).max(99);
432
+ const Params = z.record(z.string(), z.unknown());
433
+ const BrevoAttachment = z.object({
434
+ content: z.base64().optional(),
435
+ url: z.url().optional(),
436
+ name: z.string().min(1).max(255).optional()
437
+ }).refine((a) => a.content !== void 0 || a.url !== void 0, {
438
+ message: "An attachment needs content or url",
439
+ params: { code: "attachment_content_required" }
440
+ }).refine((a) => a.content === void 0 || a.name !== void 0, {
441
+ message: "name is required with content",
442
+ params: { code: "attachment_name_required" },
443
+ path: ["name"]
444
+ });
445
+ const BrevoMessageVersion = z.object({
446
+ to: Recipients.min(1),
447
+ cc: Recipients.optional(),
448
+ bcc: Recipients.optional(),
449
+ replyTo: BrevoAddress.optional(),
450
+ subject: z.string().max(998).optional(),
451
+ htmlContent: z.string().optional(),
452
+ textContent: z.string().optional(),
453
+ params: Params.optional()
454
+ });
455
+ const recipientCount = (r) => (r.to?.length ?? 0) + (r.cc?.length ?? 0) + (r.bcc?.length ?? 0);
456
+ z.object({
457
+ sender: BrevoAddress.optional(),
458
+ to: Recipients.optional(),
459
+ cc: Recipients.optional(),
460
+ bcc: Recipients.optional(),
461
+ replyTo: BrevoAddress.optional(),
462
+ subject: z.string().max(998).optional(),
463
+ htmlContent: z.string().optional(),
464
+ textContent: z.string().optional(),
465
+ templateId: TemplateExternalId.optional(),
466
+ params: Params.optional(),
467
+ headers: z.record(z.string(), z.union([
468
+ z.string(),
469
+ z.number(),
470
+ z.boolean()
471
+ ])).transform((h) => Object.fromEntries(Object.entries(h).map(([k, v]) => [k, String(v)]))).optional(),
472
+ attachment: z.array(BrevoAttachment).max(100).optional(),
473
+ tags: z.array(z.string().min(1).max(256)).max(50).optional(),
474
+ scheduledAt: IsoDateTime.optional(),
475
+ batchId: z.uuid().optional(),
476
+ messageVersions: z.array(BrevoMessageVersion).min(1).max(1e3).optional()
477
+ }).refine((b) => b.messageVersions !== void 0 || (b.to?.length ?? 0) > 0, issue("to_required", "to is required when messageVersions is absent", ["to"])).refine((b) => b.templateId !== void 0 || Boolean(b.htmlContent || b.textContent), issue("content_required", "htmlContent, textContent or templateId is required", ["htmlContent"])).refine((b) => b.templateId !== void 0 || b.sender !== void 0, issue("sender_required", "sender is required when templateId is absent", ["sender"])).refine((b) => b.templateId !== void 0 || b.subject !== void 0 || (b.messageVersions?.every((v) => v.subject !== void 0) ?? false), issue("subject_required", "subject is required when templateId is absent", ["subject"])).refine((b) => (b.messageVersions ? b.messageVersions.reduce((sum, v) => sum + recipientCount(v), 0) : recipientCount(b)) <= BREVO_MAX_TOTAL_RECIPIENTS, issue("too_many_recipients", `At most ${BREVO_MAX_TOTAL_RECIPIENTS} recipients`, ["to"]));
478
+ z.union([z.object({ messageId: z.string() }), z.object({ messageIds: z.array(z.string()) })]);
479
+ /** Brevo error codes Mailsink answers with (developers.brevo.com, « Error codes »). */
480
+ const BrevoErrorCode = z.enum([
481
+ "invalid_parameter",
482
+ "missing_parameter",
483
+ "out_of_range",
484
+ "unauthorized",
485
+ "permission_denied",
486
+ "document_not_found",
487
+ "duplicate_parameter",
488
+ "too_many_requests",
489
+ "chaos_injected",
490
+ "internal_error"
491
+ ]);
492
+ z.object({
493
+ code: BrevoErrorCode,
494
+ message: z.string()
495
+ });
496
+ // ../contracts/src/brevo-read.ts
497
+ /** A YYYY-MM-DD calendar day that exists (2026-02-30 does not). */
498
+ const BrevoDay = z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "Use the YYYY-MM-DD format").refine((d) => (/* @__PURE__ */ new Date(`${d}T00:00:00Z`)).toISOString().startsWith(d), "Invalid date");
499
+ /** Last day of the one month window starting at `start` (2026-01-31 -> 2026-02-28). */
500
+ function brevoMonthEnd(start) {
501
+ const [y, m, d] = start.split("-").map(Number);
502
+ const lastOfNext = new Date(Date.UTC(y, m + 1, 0)).getUTCDate();
503
+ return new Date(Date.UTC(y, m, Math.min(d, lastOfNext))).toISOString().slice(0, 10);
504
+ }
505
+ const Sort = z.enum(["asc", "desc"]).default("desc");
506
+ const Offset = z.coerce.number().int().min(0).default(0);
507
+ const bothDatesOrNone = (q) => q.startDate === void 0 === (q.endDate === void 0);
508
+ const datesInOrder = (q) => !q.startDate || !q.endDate || q.startDate <= q.endDate;
509
+ const dateIssue = issue("date_range_required", "startDate and endDate go together", ["startDate"]);
510
+ const orderIssue = issue("date_range_order", "endDate must not be before startDate", ["endDate"]);
511
+ z.object({
512
+ email: Email.optional(),
513
+ templateId: TemplateExternalId.optional(),
514
+ messageId: z.string().trim().min(1).optional(),
515
+ startDate: BrevoDay.optional(),
516
+ endDate: BrevoDay.optional(),
517
+ sort: Sort,
518
+ limit: z.coerce.number().int().min(0).max(500).default(500),
519
+ offset: Offset
520
+ }).refine((q) => q.email !== void 0 || q.templateId !== void 0 || q.messageId !== void 0, issue("filter_required", "email, templateId or messageId is required", ["email"])).refine(bothDatesOrNone, dateIssue).refine(datesInOrder, orderIssue).refine((q) => !q.startDate || !q.endDate || q.endDate <= brevoMonthEnd(q.startDate), issue("date_range_too_long", "The date range is at most one month", ["endDate"]));
521
+ const BrevoTransactionalEmail = z.object({
522
+ email: z.string(),
523
+ subject: z.string(),
524
+ templateId: z.number().int().optional(),
525
+ messageId: z.string(),
526
+ uuid: z.string(),
527
+ date: z.string(),
528
+ from: z.string().optional(),
529
+ tags: z.array(z.string()).optional()
530
+ });
531
+ z.object({
532
+ count: z.number().int(),
533
+ transactionalEmails: z.array(BrevoTransactionalEmail)
534
+ });
535
+ /** `senders`: comma separated, also repeated (`senders=a&senders=b`, the SDK sends both). */
536
+ const Senders = z.union([z.string(), z.array(z.string())]).transform((v) => [...new Set([v].flat().flatMap((s) => s.split(",")).map((s) => s.trim().toLowerCase()).filter(Boolean))]);
537
+ /** Coarse check without the workspace timezone: past today at UTC+14, the furthest zone
538
+ * (core checks the day of the workspace timezone, D284). */
539
+ const notInFuture = (d) => !d || d <= new Date(Date.now() + 504e5).toISOString().slice(0, 10);
540
+ z.object({
541
+ startDate: BrevoDay.optional(),
542
+ endDate: BrevoDay.optional(),
543
+ limit: z.coerce.number().int().min(0).max(100).default(50),
544
+ offset: Offset,
545
+ senders: Senders.optional(),
546
+ sort: Sort
547
+ }).refine(bothDatesOrNone, dateIssue).refine(datesInOrder, orderIssue).refine((q) => notInFuture(q.startDate) && notInFuture(q.endDate), issue("date_in_future", "Dates cannot be in the future", ["endDate"]));
548
+ /** Reason codes of Brevo; Mailsink lists `hardBounce`, `contactFlaggedAsSpam`, `adminBlocked`. */
549
+ const BrevoBlockReasonCode = z.enum([
550
+ "unsubscribedViaMA",
551
+ "unsubscribedViaEmail",
552
+ "adminBlocked",
553
+ "unsubscribedViaApi",
554
+ "hardBounce",
555
+ "contactFlaggedAsSpam"
556
+ ]);
557
+ const BrevoBlockedContact = z.object({
558
+ email: z.string(),
559
+ senderEmail: z.string().nullable(),
560
+ reason: z.object({
561
+ code: BrevoBlockReasonCode,
562
+ message: z.string()
563
+ }),
564
+ blockedAt: z.string()
565
+ });
566
+ z.object({
567
+ contacts: z.array(BrevoBlockedContact),
568
+ count: z.number().int()
569
+ });
570
+ z.object({ email: Email });
571
+ // ../contracts/src/webhook.ts
572
+ const PayloadFormat = z.enum([
573
+ "unified",
574
+ "resend",
575
+ "brevo"
576
+ ]);
577
+ const BrevoAuth = z.discriminatedUnion("type", [
578
+ z.object({ type: z.literal("none") }),
579
+ z.object({
580
+ type: z.literal("bearer"),
581
+ token: z.string().min(1).max(500)
582
+ }),
583
+ z.object({
584
+ type: z.literal("basic"),
585
+ username: z.string().min(1).max(200).regex(/^[^:]*$/, "The username cannot contain \":\""),
586
+ password: z.string().max(500)
587
+ })
588
+ ]);
589
+ const CustomHeader = z.object({
590
+ key: z.string().regex(/^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,100}$/, "Invalid header name"),
591
+ value: z.string().max(1e3)
592
+ });
593
+ const WebhookUrl = z.url({ protocol: /^https?$/ }).max(2e3);
594
+ const EventNames = z.array(z.string().min(1).max(100)).min(1).max(50);
595
+ z.object({
596
+ connectionId: ConnectionId.nullable(),
597
+ url: WebhookUrl,
598
+ payloadFormat: PayloadFormat.optional(),
599
+ events: EventNames,
600
+ description: z.string().max(200).optional(),
601
+ brevoAuth: BrevoAuth.optional(),
602
+ customHeaders: z.array(CustomHeader).max(10).optional(),
603
+ enabled: z.boolean().optional()
604
+ });
605
+ z.object({
606
+ connectionId: ConnectionId.nullable().optional(),
607
+ url: WebhookUrl.optional(),
608
+ payloadFormat: PayloadFormat.optional(),
609
+ events: EventNames.optional(),
610
+ description: z.string().max(200).nullable().optional(),
611
+ brevoAuth: BrevoAuth.optional(),
612
+ customHeaders: z.array(CustomHeader).max(10).optional(),
613
+ enabled: z.boolean().optional(),
614
+ rotateSecret: z.literal(true).optional()
615
+ });
616
+ const WebhookEndpointView = z.object({
617
+ id: WebhookEndpointId,
618
+ numericId: z.number().int(),
619
+ connectionId: ConnectionId.nullable(),
620
+ url: z.string(),
621
+ payloadFormat: PayloadFormat,
622
+ events: z.array(z.string()),
623
+ canonicalEvents: z.array(CanonicalEvent),
624
+ unsupportedEvents: z.array(CanonicalEvent),
625
+ description: z.string().nullable(),
626
+ brevoAuth: z.object({
627
+ type: z.enum([
628
+ "none",
629
+ "bearer",
630
+ "basic"
631
+ ]),
632
+ username: z.string().optional()
633
+ }),
634
+ customHeaders: z.array(CustomHeader),
635
+ secretPreview: z.string().nullable(),
636
+ enabled: z.boolean(),
637
+ createdAt: IsoDateTime,
638
+ updatedAt: IsoDateTime
639
+ });
640
+ /** Creation and rotation answer the clear secret once (unified and resend formats). */
641
+ const WebhookEndpointWithSecret = WebhookEndpointView.extend({ secret: z.string().nullable() });
642
+ z.object({ connectionId: ConnectionId.optional() });
643
+ const ListWebhookEndpointsResponse = z.object({ data: z.array(WebhookEndpointView) });
644
+ z.object({
645
+ payloadFormat: PayloadFormat,
646
+ event: z.string().min(1).max(100),
647
+ connectionId: ConnectionId.optional()
648
+ });
649
+ const WebhookPreviewResponse = z.object({
650
+ body: z.string(),
651
+ headers: z.record(z.string(), z.string())
652
+ });
653
+ z.object({ event: z.string().min(1).max(100).optional() });
654
+ // ../contracts/src/webhook-delivery.ts
655
+ const WebhookDeliveryStatus = z.enum([
656
+ "pending",
657
+ "retrying",
658
+ "succeeded",
659
+ "failed"
660
+ ]);
661
+ const ReplayMode = z.enum(["exact", "resign"]);
662
+ const WebhookDeliveryView = z.object({
663
+ id: WebhookDeliveryId,
664
+ endpointId: WebhookEndpointId,
665
+ messageId: MessageId.nullable(),
666
+ eventId: EventId.nullable(),
667
+ payloadFormat: PayloadFormat,
668
+ canonicalEvent: CanonicalEvent,
669
+ dialectEvent: z.string(),
670
+ recipient: z.string().nullable(),
671
+ status: WebhookDeliveryStatus,
672
+ attemptCount: z.number().int(),
673
+ nextAttemptAt: IsoDateTime.nullable(),
674
+ lastStatusCode: z.number().int().nullable(),
675
+ replayOf: WebhookDeliveryId.nullable(),
676
+ replayMode: ReplayMode.nullable(),
677
+ /** Current URL of the endpoint; null when the endpoint is unknown to the producer. */
678
+ endpointUrl: z.string().nullable(),
679
+ /** Duration of the last attempt; null before the first attempt. */
680
+ durationMs: z.number().int().nullable(),
681
+ createdAt: IsoDateTime
682
+ });
683
+ const WebhookAttemptView = z.object({
684
+ id: z.string(),
685
+ attemptNo: z.number().int(),
686
+ requestHeaders: z.record(z.string(), z.string()),
687
+ signedAt: z.number().int().nullable(),
688
+ responseStatus: z.number().int().nullable(),
689
+ responseBody: z.string().nullable(),
690
+ durationMs: z.number().int(),
691
+ error: z.string().nullable(),
692
+ createdAt: IsoDateTime
693
+ });
694
+ const WebhookDeliveryDetail = WebhookDeliveryView.extend({
695
+ body: z.string(),
696
+ contentType: z.string(),
697
+ attempts: z.array(WebhookAttemptView)
698
+ });
699
+ z.object({
700
+ endpointId: WebhookEndpointId.optional(),
701
+ payloadFormat: PayloadFormat.optional(),
702
+ messageId: MessageId.optional(),
703
+ status: WebhookDeliveryStatus.optional(),
704
+ limit: PageLimit,
705
+ cursor: WebhookDeliveryId.optional(),
706
+ /** Page number (pages of `limit`); when given, `cursor` is ignored (UI pager, #112). */
707
+ page: z.coerce.number().int().min(1).max(1e5).optional()
708
+ });
709
+ /** One page, its keyset cursor and the number of deliveries matching the filters. */
710
+ const ListWebhookDeliveriesResponse = Page(WebhookDeliveryView).extend({ total: z.number().int().min(0) });
711
+ z.object({
712
+ mode: ReplayMode.default("exact"),
713
+ attemptId: z.string().optional()
714
+ });
715
+ // ../contracts/src/capture.ts
716
+ const WAIT_TIMEOUT_MAX_MS = 3e4;
717
+ z.object({
718
+ to: z.string().optional(),
719
+ from: z.string().optional(),
720
+ subject: z.string().optional(),
721
+ tag: z.string().optional(),
722
+ status: z.preprocess((v) => typeof v === "string" ? v.split(",") : v, z.array(DeliveryStatus)).optional(),
723
+ connectionId: ConnectionId.optional(),
724
+ since: IsoDateTime.optional(),
725
+ until: IsoDateTime.optional(),
726
+ q: z.string().optional(),
727
+ limit: PageLimit,
728
+ cursor: z.string().optional(),
729
+ wait: QueryBool.default(false),
730
+ timeout: z.coerce.number().int().min(0).max(WAIT_TIMEOUT_MAX_MS).default(5e3)
731
+ }).refine((q) => !q.since || !q.until || Date.parse(q.since) <= Date.parse(q.until), issue("since_after_until", "since must be before until", ["until"]));
732
+ const MessageSummary = z.object({
733
+ id: MessageId,
734
+ connectionId: ConnectionId.nullable(),
735
+ source: MessageSource,
736
+ from: AddressOut,
737
+ to: z.array(AddressOut),
738
+ subject: z.string(),
739
+ status: DeliveryStatus,
740
+ tags: z.array(Tag),
741
+ hasAttachments: z.boolean(),
742
+ createdAt: IsoDateTime
743
+ });
744
+ const ListMessagesResponse = Page(MessageSummary);
745
+ const MessageEventView = z.object({
746
+ id: EventId,
747
+ type: EventType,
748
+ origin: EventOrigin,
749
+ recipient: z.string().nullable(),
750
+ data: z.object({
751
+ url: z.string().optional(),
752
+ userAgent: z.string().optional(),
753
+ reason: z.string().optional(),
754
+ smtpCode: z.number().int().optional()
755
+ }),
756
+ occurredAt: IsoDateTime
757
+ });
758
+ const AttachmentView = z.object({
759
+ id: AttachmentId,
760
+ filename: z.string().nullable(),
761
+ contentType: z.string(),
762
+ contentId: z.string().nullable(),
763
+ sizeBytes: z.number().int(),
764
+ inline: z.boolean(),
765
+ downloadUrl: z.string()
766
+ });
767
+ const RecipientView = z.object({
768
+ email: z.string(),
769
+ name: z.string().nullable(),
770
+ kind: RecipientKind,
771
+ status: DeliveryStatus,
772
+ reason: z.string().nullable()
773
+ });
774
+ const MessageDetail = MessageSummary.extend({
775
+ cc: z.array(AddressOut),
776
+ bcc: z.array(AddressOut),
777
+ replyTo: z.array(AddressOut),
778
+ html: z.string().nullable(),
779
+ text: z.string().nullable(),
780
+ headers: z.record(z.string(), z.string()),
781
+ metadata: z.record(z.string(), z.unknown()),
782
+ links: z.array(z.object({
783
+ url: z.string(),
784
+ text: z.string().optional()
785
+ })),
786
+ attachments: z.array(AttachmentView),
787
+ recipients: z.array(RecipientView),
788
+ events: z.array(MessageEventView),
789
+ rawUrl: z.string(),
790
+ simulation: z.record(z.string(), z.unknown()).nullable(),
791
+ webhookDeliveries: z.array(WebhookDeliveryView)
792
+ });
793
+ z.discriminatedUnion("type", [
794
+ z.object({
795
+ type: z.literal("opened"),
796
+ recipient: z.email().optional(),
797
+ userAgent: z.string().optional()
798
+ }),
799
+ z.object({
800
+ type: z.literal("clicked"),
801
+ url: z.url(),
802
+ recipient: z.email().optional(),
803
+ userAgent: z.string().optional()
804
+ }),
805
+ z.object({
806
+ type: z.literal("status"),
807
+ status: SimulatedStatus,
808
+ recipient: z.email().optional(),
809
+ reason: z.string().max(500).optional()
810
+ })
811
+ ]);
812
+ /** 202: the events written (one per recipient) and the webhook deliveries they created. */
813
+ const TriggerEventResponse = z.object({
814
+ events: z.array(MessageEventView),
815
+ webhookDeliveries: z.array(z.object({
816
+ id: z.string(),
817
+ endpointId: z.string()
818
+ }))
819
+ });
820
+ z.object({
821
+ connectionId: ConnectionId.optional(),
822
+ before: IsoDateTime.optional(),
823
+ includeLogs: QueryBool.default(true)
824
+ });
825
+ const PurgeResponse = z.object({ count: z.number().int().min(0) });
826
+ // ../contracts/src/demo.ts
827
+ const DemoLocale = z.enum(["en", "fr"]);
828
+ z.object({ locale: DemoLocale.default("en") });
829
+ const SeedDemoResponse = z.object({
830
+ count: z.number().int().min(0),
831
+ /** Ids of the stored messages, oldest first. */
832
+ messageIds: z.array(MessageId)
833
+ });
834
+ // ../contracts/src/errors.ts
835
+ /** Error codes of the native, capture and admin APIs. Messages stay English (D19). */
836
+ const ErrorCode = z.enum([
837
+ "unauthorized",
838
+ "forbidden",
839
+ "validation_error",
840
+ "not_found",
841
+ "conflict",
842
+ "idempotency_mismatch",
843
+ "rate_limited",
844
+ "payload_too_large",
845
+ "chaos_injected",
846
+ "wait_timeout",
847
+ "internal_error"
848
+ ]);
849
+ const ApiError = z.object({
850
+ code: ErrorCode,
851
+ message: z.string(),
852
+ details: z.unknown().optional()
853
+ });
854
+ z.object({
855
+ error: ApiError,
856
+ requestId: z.string()
857
+ });
858
+ // ../contracts/src/logs.ts
859
+ const ApiLogId = prefixedId("req");
860
+ const SmtpSessionId = prefixedId("smtp");
861
+ /** Mirrors the `api_dialect` pg enum: the HTTP surface a call hit. */
862
+ const ApiDialect = z.enum([
863
+ "native",
864
+ "resend",
865
+ "brevo",
866
+ "admin",
867
+ "capture",
868
+ "mcp"
869
+ ]);
870
+ /** Mirrors the `smtp_outcome` pg enum. */
871
+ const SmtpOutcome = z.enum([
872
+ "accepted",
873
+ "rejected",
874
+ "auth_failed",
875
+ "error"
876
+ ]);
877
+ const csv = (item) => z.preprocess((v) => typeof v === "string" ? v.split(",") : v, z.array(item));
878
+ /** Page-number pagination of the log tables (server side, with the total for the pager). */
879
+ function NumberedPage(item) {
880
+ return z.object({
881
+ data: z.array(item),
882
+ total: z.number().int().min(0),
883
+ page: z.number().int().min(1),
884
+ pageSize: z.number().int().min(1)
885
+ });
886
+ }
887
+ const paging = {
888
+ page: z.coerce.number().int().min(1).default(1),
889
+ pageSize: z.coerce.number().int().min(1).max(200).default(50)
890
+ };
891
+ const sinceBeforeUntil = (q) => !q.since || !q.until || Date.parse(q.since) <= Date.parse(q.until);
892
+ const sinceIssue = issue("since_after_until", "since must be before until", ["until"]);
893
+ /** One status code (`404`) or a class (`4xx`). */
894
+ const StatusFilter = z.string().regex(/^[1-5](\d\d|xx)$/, "Expected a status such as 404 or 4xx");
895
+ const ApiLogSort = z.enum([
896
+ "createdAt",
897
+ "-createdAt",
898
+ "durationMs",
899
+ "-durationMs",
900
+ "statusCode",
901
+ "-statusCode"
902
+ ]);
903
+ z.object({
904
+ connectionId: ConnectionId.optional(),
905
+ dialect: csv(ApiDialect).optional(),
906
+ status: csv(StatusFilter).optional(),
907
+ errorCode: z.string().optional(),
908
+ method: z.string().transform((m) => m.toUpperCase()).optional(),
909
+ path: z.string().optional(),
910
+ messageId: MessageId.optional(),
911
+ since: IsoDateTime.optional(),
912
+ until: IsoDateTime.optional(),
913
+ sort: ApiLogSort.default("-createdAt"),
914
+ ...paging
915
+ }).refine(sinceBeforeUntil, sinceIssue);
916
+ const ApiLogSummary = z.object({
917
+ id: ApiLogId,
918
+ connectionId: ConnectionId.nullable(),
919
+ dialect: ApiDialect,
920
+ method: z.string(),
921
+ path: z.string(),
922
+ statusCode: z.number().int(),
923
+ durationMs: z.number().int().min(0),
924
+ errorCode: z.string().nullable(),
925
+ messageIds: z.array(MessageId),
926
+ createdAt: IsoDateTime
927
+ });
928
+ const ApiLogDetail = ApiLogSummary.extend({
929
+ requestHeaders: z.record(z.string(), z.string()),
930
+ requestBody: z.unknown().nullable(),
931
+ /** Headers of the answer (rate limit, request id…); empty for calls logged before #112. */
932
+ responseHeaders: z.record(z.string(), z.string()),
933
+ responseBody: z.unknown().nullable(),
934
+ ip: z.string().nullable()
935
+ });
936
+ const ListApiLogsResponse = NumberedPage(ApiLogSummary);
937
+ const SmtpSessionSort = z.enum(["startedAt", "-startedAt"]);
938
+ z.object({
939
+ connectionId: ConnectionId.optional(),
940
+ outcome: csv(SmtpOutcome).optional(),
941
+ q: z.string().optional(),
942
+ messageId: MessageId.optional(),
943
+ since: IsoDateTime.optional(),
944
+ until: IsoDateTime.optional(),
945
+ sort: SmtpSessionSort.default("-startedAt"),
946
+ ...paging
947
+ }).refine(sinceBeforeUntil, sinceIssue);
948
+ const TranscriptLine = z.object({
949
+ at: z.number(),
950
+ dir: z.enum(["C", "S"]),
951
+ line: z.string()
952
+ });
953
+ const SmtpSessionSummary = z.object({
954
+ id: SmtpSessionId,
955
+ connectionId: ConnectionId.nullable(),
956
+ remoteAddress: z.string(),
957
+ clientHostname: z.string().nullable(),
958
+ authUser: z.string().nullable(),
959
+ secure: z.boolean(),
960
+ outcome: SmtpOutcome,
961
+ error: z.string().nullable(),
962
+ messageIds: z.array(MessageId),
963
+ startedAt: IsoDateTime,
964
+ endedAt: IsoDateTime.nullable()
965
+ });
966
+ const SmtpSessionDetail = SmtpSessionSummary.extend({ transcript: z.array(TranscriptLine) });
967
+ const ListSmtpSessionsResponse = NumberedPage(SmtpSessionSummary);
968
+ z.object({ id: ApiLogId });
969
+ z.object({ id: SmtpSessionId });
970
+ const AttachmentInput = z.object({
971
+ filename: z.string().min(1).max(255),
972
+ content: z.base64(),
973
+ contentType: z.string().optional(),
974
+ contentId: z.string().optional()
975
+ });
976
+ z.object({
977
+ from: Address,
978
+ to: AddressList,
979
+ cc: AddressList.optional(),
980
+ bcc: AddressList.optional(),
981
+ replyTo: AddressList.optional(),
982
+ subject: z.string().max(998),
983
+ html: z.string().optional(),
984
+ text: z.string().optional(),
985
+ headers: z.record(z.string(), z.string()).optional(),
986
+ tags: z.array(Tag).max(50).optional(),
987
+ attachments: z.array(AttachmentInput).max(100).optional(),
988
+ metadata: z.record(z.string(), z.unknown()).optional()
989
+ }).refine((e) => e.to.length > 0, issue("to_required", "At least one \"to\" recipient", ["to"])).refine((e) => Boolean(e.html || e.text), issue("html_or_text_required", "Either html or text is required", ["html"])).refine((e) => e.to.length + (e.cc?.length ?? 0) + (e.bcc?.length ?? 0) <= 50, issue("too_many_recipients", `At most 50 recipients (to + cc + bcc)`, ["to"]));
990
+ z.object({
991
+ id: MessageId,
992
+ status: DeliveryStatus
993
+ });
994
+ z.array(z.unknown()).min(1).max(100);
995
+ const BatchItemResult = z.discriminatedUnion("ok", [z.object({
996
+ ok: z.literal(true),
997
+ index: z.number().int(),
998
+ id: MessageId
999
+ }), z.object({
1000
+ ok: z.literal(false),
1001
+ index: z.number().int(),
1002
+ error: ApiError
1003
+ })]);
1004
+ z.object({ data: z.array(BatchItemResult) });
1005
+ // ../contracts/src/override.ts
1006
+ const OverrideConfig = z.object({
1007
+ rates: StatusRates.optional(),
1008
+ rules: z.array(RecipientRule).max(50).optional(),
1009
+ latency: Latency.optional(),
1010
+ chaos: Chaos.optional(),
1011
+ rateLimit: RateLimitSettings.optional()
1012
+ }).refine((c) => Object.values(c).some((v) => v !== void 0), issue("override_empty", "An override needs at least one setting"));
1013
+ z.object({
1014
+ connectionId: ConnectionId.optional(),
1015
+ config: OverrideConfig,
1016
+ ttl: Duration.optional()
1017
+ });
1018
+ z.object({ connectionId: ConnectionId.optional() });
1019
+ const OverrideView = z.object({
1020
+ id: OverrideId,
1021
+ connectionId: ConnectionId.nullable(),
1022
+ config: OverrideConfig,
1023
+ activatedVia: EventOrigin,
1024
+ expiresAt: IsoDateTime.nullable(),
1025
+ createdAt: IsoDateTime
1026
+ });
1027
+ const OverrideState = z.object({
1028
+ workspace: OverrideView.nullable(),
1029
+ connections: z.array(OverrideView),
1030
+ effective: z.record(ConnectionId, SimulationSettings)
1031
+ });
1032
+ // ../contracts/src/resend.ts
1033
+ const RESEND_ADDRESS_HINT = "The email address needs to follow the `email@example.com` or `Name <email@example.com>` format.";
1034
+ /** "jane@x.io" or "Jane <jane@x.io>" (strings only, as Resend) to { email, name? }. */
1035
+ const ResendAddress = z.string().transform((value, ctx) => {
1036
+ const parsed = parseAddress(value);
1037
+ if (!parsed) {
1038
+ ctx.issues.push({
1039
+ code: "custom",
1040
+ input: value,
1041
+ message: RESEND_ADDRESS_HINT,
1042
+ params: { code: "invalid_address" }
1043
+ });
1044
+ return z.NEVER;
1045
+ }
1046
+ return parsed;
1047
+ });
1048
+ /** One address or an array of addresses, always output as an array. */
1049
+ const ResendAddressList = z.union([ResendAddress, z.array(ResendAddress)]).transform((v) => Array.isArray(v) ? v : [v]);
1050
+ const TAG_PART = z.string().min(1).max(256).regex(/^[A-Za-z0-9_-]+$/, "Tags can only contain ASCII letters, numbers, underscores or dashes (at most 256 characters).");
1051
+ const ResendTag = z.object({
1052
+ name: TAG_PART,
1053
+ value: TAG_PART
1054
+ });
1055
+ const ResendAttachment = z.object({
1056
+ content: z.base64().optional(),
1057
+ path: z.string().optional(),
1058
+ filename: z.string().optional(),
1059
+ content_type: z.string().optional(),
1060
+ content_id: z.string().optional()
1061
+ }).refine((a) => a.content !== void 0 || a.path !== void 0, issue("attachment_content_required", "Attachment must have either a `content` or `path`.")).refine((a) => a.content !== void 0, issue("attachment_path_unsupported", "Mailsink does not fetch attachment `path` URLs: send the file as `content`."));
1062
+ z.object({
1063
+ from: ResendAddress,
1064
+ to: ResendAddressList,
1065
+ subject: z.string(),
1066
+ cc: ResendAddressList.optional(),
1067
+ bcc: ResendAddressList.optional(),
1068
+ reply_to: ResendAddressList.optional(),
1069
+ replyTo: ResendAddressList.optional(),
1070
+ html: z.string().optional(),
1071
+ text: z.string().optional(),
1072
+ headers: z.record(z.string(), z.string()).optional(),
1073
+ attachments: z.array(ResendAttachment).optional(),
1074
+ tags: z.array(ResendTag).optional(),
1075
+ scheduled_at: z.string().optional(),
1076
+ topic_id: z.string().nullable().optional(),
1077
+ template: z.unknown().optional()
1078
+ }).refine((e) => e.template === void 0, issue("template_unsupported", "Resend hosted templates are not supported by Mailsink: send `html` or `text`.", ["template"])).refine((e) => e.to.length > 0, issue("to_required", "Missing `to` field.", ["to"])).refine((e) => e.to.length <= 50, issue("too_many_recipients", `The \`to\` field can have at most 50 addresses.`, ["to"])).refine((e) => e.html !== void 0 || e.text !== void 0, issue("html_or_text_required", "Missing `html` or `text` field.", ["html"]));
1079
+ z.enum(["strict", "permissive"]);
1080
+ z.object({ id: z.uuid() });
1081
+ z.object({
1082
+ data: z.array(z.object({ id: z.uuid() })),
1083
+ /** Permissive mode only: the refused items, the others are in `data`. */
1084
+ errors: z.array(z.object({
1085
+ index: z.number().int(),
1086
+ message: z.string()
1087
+ })).optional()
1088
+ });
1089
+ const ResendLastEvent = z.enum([
1090
+ "bounced",
1091
+ "canceled",
1092
+ "clicked",
1093
+ "complained",
1094
+ "delivered",
1095
+ "delivery_delayed",
1096
+ "failed",
1097
+ "opened",
1098
+ "queued",
1099
+ "scheduled",
1100
+ "sent",
1101
+ "suppressed"
1102
+ ]);
1103
+ z.object({
1104
+ object: z.literal("email"),
1105
+ id: z.uuid(),
1106
+ message_id: z.string(),
1107
+ to: z.array(z.string()),
1108
+ from: z.string(),
1109
+ created_at: z.string(),
1110
+ subject: z.string(),
1111
+ html: z.string().nullable(),
1112
+ text: z.string().nullable(),
1113
+ bcc: z.array(z.string()),
1114
+ cc: z.array(z.string()),
1115
+ reply_to: z.array(z.string()),
1116
+ last_event: ResendLastEvent,
1117
+ scheduled_at: z.string().nullable(),
1118
+ tags: z.array(z.object({
1119
+ name: z.string(),
1120
+ value: z.string()
1121
+ }))
1122
+ });
1123
+ /** Names Mailsink answers with (a subset of the SDK's `RESEND_ERROR_CODE_KEY`). */
1124
+ const ResendErrorName = z.enum([
1125
+ "missing_api_key",
1126
+ "validation_error",
1127
+ "missing_required_field",
1128
+ "invalid_attachment",
1129
+ "invalid_parameter",
1130
+ "invalid_idempotency_key",
1131
+ "invalid_idempotent_request",
1132
+ "concurrent_idempotent_requests",
1133
+ "restricted_api_key",
1134
+ "not_found",
1135
+ "rate_limit_exceeded",
1136
+ "application_error",
1137
+ "service_unavailable"
1138
+ ]);
1139
+ z.object({
1140
+ statusCode: z.number().int(),
1141
+ name: ResendErrorName,
1142
+ message: z.string()
1143
+ });
1144
+ z.object({ ephemeral: z.boolean().default(false) });
1145
+ /**
1146
+ * Free text of a URL: `?q=2026` arrives as a number from the router's JSON parsing. A blank
1147
+ * or malformed value is dropped rather than failing the page.
1148
+ */
1149
+ const urlText = z.preprocess((v) => typeof v === "number" ? String(v) : v, z.string().trim().min(1).max(500).optional()).catch(void 0);
1150
+ /** Tabs of the message viewer (#40). */
1151
+ const InboxTab = z.enum([
1152
+ "preview",
1153
+ "text",
1154
+ "links",
1155
+ "headers",
1156
+ "history"
1157
+ ]);
1158
+ z.object({
1159
+ q: urlText,
1160
+ status: DeliveryStatus.optional().catch(void 0),
1161
+ connectionId: ConnectionId.optional().catch(void 0),
1162
+ tag: urlText,
1163
+ m: MessageId.optional().catch(void 0),
1164
+ tab: InboxTab.optional().catch(void 0)
1165
+ });
1166
+ /** Tabs of the logs explorer (#41). */
1167
+ const LogsTab = z.enum([
1168
+ "api",
1169
+ "smtp",
1170
+ "webhooks"
1171
+ ]);
1172
+ /** Sort of the log tables: the API sort keys; `createdAt` is `startedAt` for SMTP. */
1173
+ const LogsSort = ApiLogSort;
1174
+ /** A facet with several values: an array (router JSON) or comma-separated text. */
1175
+ const facet = (item) => z.preprocess((v) => typeof v === "string" ? v.split(",") : v, z.array(item).min(1).max(20).optional()).catch(void 0);
1176
+ const pageNumber = z.coerce.number().int().min(1).max(1e5).optional().catch(void 0);
1177
+ z.object({
1178
+ tab: LogsTab.optional().catch(void 0),
1179
+ q: urlText,
1180
+ connectionId: ConnectionId.optional().catch(void 0),
1181
+ dialect: facet(ApiDialect),
1182
+ code: facet(StatusFilter),
1183
+ outcome: facet(SmtpOutcome),
1184
+ delivery: WebhookDeliveryStatus.optional().catch(void 0),
1185
+ format: PayloadFormat.optional().catch(void 0),
1186
+ endpointId: WebhookEndpointId.optional().catch(void 0),
1187
+ messageId: MessageId.optional().catch(void 0),
1188
+ since: IsoDateTime.optional().catch(void 0),
1189
+ until: IsoDateTime.optional().catch(void 0),
1190
+ method: z.string().regex(/^[A-Za-z]{3,7}$/).transform((m) => m.toUpperCase()).optional().catch(void 0),
1191
+ errorCode: z.string().regex(/^[a-z0-9_]{1,64}$/).optional().catch(void 0),
1192
+ sort: LogsSort.optional().catch(void 0),
1193
+ page: pageNumber,
1194
+ pageSize: z.coerce.number().int().min(10).max(200).optional().catch(void 0),
1195
+ cursor: WebhookDeliveryId.optional().catch(void 0),
1196
+ inspect: z.string().min(1).max(80).optional().catch(void 0)
1197
+ });
1198
+ z.object({ connection: z.string().max(64).optional() });
1199
+ /** Sections of the workspace settings page (#43, prototype « Paramètres »). */
1200
+ const SettingsSection = z.enum([
1201
+ "connections",
1202
+ "webhooks",
1203
+ "retention",
1204
+ "simulation",
1205
+ "templates",
1206
+ "mcp"
1207
+ ]);
1208
+ z.object({ section: SettingsSection.optional().catch(void 0) });
1209
+ z.object({ email: urlText });
1210
+ // ../contracts/src/server-clock.ts
1211
+ const HEADER_PRECISION_MS = 1e3;
1212
+ function createServerClock(clientNow = Date.now) {
1213
+ let lower = Number.NEGATIVE_INFINITY;
1214
+ let upper = Number.POSITIVE_INFINITY;
1215
+ const offset = () => Math.min(Math.max(0, lower), upper);
1216
+ return {
1217
+ now: () => new Date(clientNow() + offset()),
1218
+ offset,
1219
+ observe(dateHeader, sentAt, receivedAt) {
1220
+ const serverAt = dateHeader ? Date.parse(dateHeader) : NaN;
1221
+ if (Number.isNaN(serverAt)) return;
1222
+ const low = serverAt - receivedAt;
1223
+ const high = serverAt + HEADER_PRECISION_MS - sentAt;
1224
+ if (Math.max(low, lower) <= Math.min(high, upper)) {
1225
+ lower = Math.max(low, lower);
1226
+ upper = Math.min(high, upper);
1227
+ } else {
1228
+ lower = low;
1229
+ upper = high;
1230
+ }
1231
+ }
1232
+ };
1233
+ }
1234
+ // ../contracts/src/stream.ts
1235
+ const StreamEvent = z.discriminatedUnion("type", [
1236
+ z.object({
1237
+ type: z.literal("message.created"),
1238
+ message: MessageSummary
1239
+ }),
1240
+ z.object({
1241
+ type: z.literal("message.status"),
1242
+ messageId: MessageId,
1243
+ status: DeliveryStatus,
1244
+ recipient: z.string().nullable()
1245
+ }),
1246
+ z.object({
1247
+ type: z.literal("message.event"),
1248
+ messageId: MessageId,
1249
+ event: MessageEventView
1250
+ }),
1251
+ z.object({
1252
+ type: z.literal("webhook.delivery"),
1253
+ delivery: WebhookDeliveryView
1254
+ }),
1255
+ z.object({
1256
+ type: z.literal("log.api"),
1257
+ log: ApiLogSummary
1258
+ }),
1259
+ z.object({
1260
+ type: z.literal("log.smtp"),
1261
+ session: SmtpSessionSummary
1262
+ }),
1263
+ z.object({
1264
+ type: z.literal("override.changed"),
1265
+ state: OverrideState
1266
+ }),
1267
+ z.object({
1268
+ type: z.literal("messages.purged"),
1269
+ count: z.number().int().min(0)
1270
+ }),
1271
+ z.object({
1272
+ type: z.literal("workspace.deleted"),
1273
+ workspaceId: WorkspaceId
1274
+ })
1275
+ ]);
1276
+ const StreamEventType = z.enum([
1277
+ "message.created",
1278
+ "message.status",
1279
+ "message.event",
1280
+ "webhook.delivery",
1281
+ "log.api",
1282
+ "log.smtp",
1283
+ "override.changed",
1284
+ "messages.purged",
1285
+ "workspace.deleted"
1286
+ ]);
1287
+ z.object({
1288
+ connectionId: ConnectionId.optional(),
1289
+ types: z.preprocess((v) => typeof v === "string" ? v.split(",") : v, z.array(StreamEventType)).optional()
1290
+ });
1291
+ // ../contracts/src/suppression.ts
1292
+ const SuppressionId = prefixedId("sup");
1293
+ /** Mirrors the pg enum `suppression_reason`. */
1294
+ const SuppressionReason = z.enum([
1295
+ "hard_bounce",
1296
+ "complained",
1297
+ "manual"
1298
+ ]);
1299
+ z.object({
1300
+ email: z.string().optional(),
1301
+ limit: PageLimit,
1302
+ cursor: SuppressionId.optional()
1303
+ });
1304
+ z.object({ email: Email.optional() });
1305
+ /** One page plus the number of addresses matching the filter (every page). */
1306
+ const ListSuppressionsResponse = Page(z.object({
1307
+ id: SuppressionId,
1308
+ email: z.string(),
1309
+ reason: SuppressionReason,
1310
+ messageId: MessageId.nullable(),
1311
+ /** Connection of the message that put the address on the list; null without one. */
1312
+ connectionId: ConnectionId.nullable(),
1313
+ createdAt: IsoDateTime
1314
+ })).extend({ total: z.number().int().min(0) });
1315
+ const DeleteSuppressionsResponse = z.object({ count: z.number().int().min(0) });
1316
+ z.object({
1317
+ id: z.string(),
1318
+ event: CanonicalEvent,
1319
+ occurredAt: z.iso.datetime(),
1320
+ workspaceId: z.string(),
1321
+ connectionId: z.string().nullable(),
1322
+ connectionKind: z.enum([
1323
+ "resend",
1324
+ "brevo",
1325
+ "smtp"
1326
+ ]).nullable(),
1327
+ messageId: z.string(),
1328
+ providerMessageId: z.string(),
1329
+ recipient: z.string().nullable(),
1330
+ from: z.string(),
1331
+ to: z.array(z.string()),
1332
+ subject: z.string(),
1333
+ tags: z.array(Tag),
1334
+ metadata: z.record(z.string(), z.unknown()),
1335
+ detail: z.object({
1336
+ reason: z.string().optional(),
1337
+ smtpCode: z.number().optional(),
1338
+ url: z.string().optional(),
1339
+ userAgent: z.string().optional()
1340
+ })
1341
+ });
1342
+ z.object({
1343
+ type: z.enum([
1344
+ "email.sent",
1345
+ "email.delivered",
1346
+ "email.delivery_delayed",
1347
+ "email.complained",
1348
+ "email.bounced",
1349
+ "email.opened",
1350
+ "email.clicked",
1351
+ "email.failed"
1352
+ ]),
1353
+ created_at: z.iso.datetime(),
1354
+ data: z.object({
1355
+ email_id: z.string(),
1356
+ from: z.string(),
1357
+ to: z.array(z.string()),
1358
+ subject: z.string(),
1359
+ created_at: z.iso.datetime(),
1360
+ tags: z.record(z.string(), z.string()).optional(),
1361
+ bounce: z.object({
1362
+ message: z.string(),
1363
+ type: z.literal("Permanent"),
1364
+ subType: z.string()
1365
+ }).optional(),
1366
+ click: z.object({
1367
+ link: z.string(),
1368
+ ipAddress: z.string(),
1369
+ userAgent: z.string(),
1370
+ timestamp: z.iso.datetime()
1371
+ }).optional(),
1372
+ failed: z.object({ reason: z.string() }).optional()
1373
+ })
1374
+ });
1375
+ z.object({
1376
+ event: z.enum([
1377
+ "request",
1378
+ "delivered",
1379
+ "soft_bounce",
1380
+ "hard_bounce",
1381
+ "spam",
1382
+ "opened",
1383
+ "click",
1384
+ "deferred",
1385
+ "blocked",
1386
+ "invalid_email",
1387
+ "error"
1388
+ ]),
1389
+ email: z.string(),
1390
+ id: z.number().int(),
1391
+ date: z.string(),
1392
+ ts: z.number().int(),
1393
+ ts_event: z.number().int(),
1394
+ ts_epoch: z.number().int(),
1395
+ "message-id": z.string(),
1396
+ subject: z.string(),
1397
+ tag: z.string().optional(),
1398
+ tags: z.array(z.string()).optional(),
1399
+ template_id: z.number().int().optional(),
1400
+ "X-Mailin-custom": z.string().optional(),
1401
+ link: z.string().optional(),
1402
+ reason: z.string().optional(),
1403
+ source: z.enum(["API", "SMTP"]).optional()
1404
+ });
1405
+ // ../contracts/src/workspace-manage.ts
1406
+ const Name = z.string().trim().min(1).max(80);
1407
+ z.object({
1408
+ name: Name.optional(),
1409
+ description: z.string().max(500).nullable().optional(),
1410
+ retention: Retention.optional(),
1411
+ rateLimit: RateLimitSettings.nullable().optional(),
1412
+ maxMessages: z.number().int().positive().max(1e7).nullable().optional(),
1413
+ simulation: SimulationSettings.optional()
1414
+ }).refine((patch) => Object.values(patch).some((value) => value !== void 0), issue("empty_patch", "Nothing to update"));
1415
+ z.object({
1416
+ name: Name.optional(),
1417
+ enabled: z.boolean().optional()
1418
+ }).refine((patch) => patch.name !== void 0 || patch.enabled !== void 0, issue("empty_patch", "Nothing to update"));
1419
+ /** A connection with its secrets: answered once, at creation or rotation. */
1420
+ const CreatedConnection = ConnectionView.extend({
1421
+ credentials: ConnectionCredentials,
1422
+ envSnippet: z.string()
1423
+ });
1424
+ /** `POST /admin/workspaces/:id/key/rotate`: the new `mskw_` key, answered once. */
1425
+ const RotatedWorkspaceKey = z.object({
1426
+ workspaceKey: WorkspaceKey,
1427
+ keyPreview: z.string()
1428
+ });
1429
+ // ../sdk/src/errors.ts
1430
+ /** Every failure of the SDK. `code` is stable; `message` is English and may change. */
1431
+ var MailsinkError = class extends Error {
1432
+ name = "MailsinkError";
1433
+ code;
1434
+ status;
1435
+ requestId;
1436
+ details;
1437
+ constructor(init) {
1438
+ super(init.message, init.cause === void 0 ? void 0 : { cause: init.cause });
1439
+ this.code = init.code;
1440
+ this.status = init.status ?? null;
1441
+ this.requestId = init.requestId ?? null;
1442
+ this.details = init.details;
1443
+ }
1444
+ };
1445
+ /** Narrows an unknown error, optionally to one code: `isMailsinkError(e, 'wait_timeout')`. */
1446
+ function isMailsinkError(error, code) {
1447
+ return error instanceof MailsinkError && (code === void 0 || error.code === code);
1448
+ }
1449
+ const CODE_BY_STATUS = {
1450
+ 401: "unauthorized",
1451
+ 403: "forbidden",
1452
+ 404: "not_found",
1453
+ 408: "wait_timeout",
1454
+ 409: "conflict",
1455
+ 413: "payload_too_large",
1456
+ 422: "validation_error",
1457
+ 429: "rate_limited"
1458
+ };
1459
+ const codeForStatus = (status) => CODE_BY_STATUS[status] ?? "internal_error";
1460
+ /**
1461
+ * Long polls `GET /capture/messages?wait=true` until one message matches, then answers the
1462
+ * earliest one of the page (the first that arrived) as a full detail.
1463
+ */
1464
+ async function waitForMessage(t, reader, filters, options) {
1465
+ const since = options.since ?? filters.since ?? t.clock.now();
1466
+ const timeout = options.timeout ?? 1e4;
1467
+ const deadline = Date.now() + timeout;
1468
+ let last;
1469
+ do {
1470
+ const chunk = Math.max(0, Math.min(deadline - Date.now(), WAIT_TIMEOUT_MAX_MS));
1471
+ try {
1472
+ const first = (await t.json({
1473
+ method: "GET",
1474
+ path: "/capture/messages",
1475
+ auth: "workspace",
1476
+ query: {
1477
+ ...filters,
1478
+ since,
1479
+ wait: true,
1480
+ timeout: chunk
1481
+ },
1482
+ signal: options.signal
1483
+ })).data.at(-1);
1484
+ if (first) return reader.get(first.id);
1485
+ } catch (error) {
1486
+ if (!isMailsinkError(error, "wait_timeout")) throw error;
1487
+ last = error;
1488
+ }
1489
+ } while (Date.now() < deadline);
1490
+ throw new MailsinkError({
1491
+ code: "wait_timeout",
1492
+ message: `No message matched ${describe(filters)} within ${timeout} ms`,
1493
+ status: last?.status ?? 408,
1494
+ requestId: last?.requestId,
1495
+ details: {
1496
+ filters,
1497
+ since: since instanceof Date ? since.toISOString() : since,
1498
+ timeout
1499
+ }
1500
+ });
1501
+ }
1502
+ function describe(filters) {
1503
+ const entries = Object.entries(filters).filter(([, v]) => v !== void 0);
1504
+ return entries.length ? JSON.stringify(Object.fromEntries(entries)) : "any message";
1505
+ }
1506
+ // ../sdk/src/query.ts
1507
+ /**
1508
+ * Query string of a call: `undefined` and `null` are left out, arrays are comma-separated
1509
+ * (every list filter of the API accepts it), dates are ISO 8601.
1510
+ */
1511
+ function toSearchParams(query) {
1512
+ const params = new URLSearchParams();
1513
+ for (const [name, value] of Object.entries(query)) {
1514
+ if (value === void 0 || value === null) continue;
1515
+ if (Array.isArray(value)) {
1516
+ if (value.length > 0) params.set(name, value.join(","));
1517
+ } else if (value instanceof Date) params.set(name, value.toISOString());
1518
+ else params.set(name, String(value));
1519
+ }
1520
+ return params;
1521
+ }
1522
+ // ../sdk/src/http.ts
1523
+ const REQUEST_ID_HEADER = "x-request-id";
1524
+ const WORKSPACE_HEADER = "x-mailsink-workspace";
1525
+ /** Path segment, encoded: `path\`/capture/messages/${id}\``. */
1526
+ const seg = (value) => encodeURIComponent(value);
1527
+ function createTransport(options, clock = createServerClock()) {
1528
+ const base = new URL(String(options.url));
1529
+ if (!base.pathname.endsWith("/")) base.pathname += "/";
1530
+ const doFetch = options.fetch ?? ((input, init) => globalThis.fetch(input, init));
1531
+ const transport = {
1532
+ options,
1533
+ clock,
1534
+ url(path, query) {
1535
+ const url = new URL(path.replace(/^\//, ""), base);
1536
+ if (query) url.search = toSearchParams(query).toString();
1537
+ return url;
1538
+ },
1539
+ headers(auth, extra) {
1540
+ const headers = new Headers(options.headers);
1541
+ for (const [name, value] of new Headers(extra)) headers.set(name, value);
1542
+ headers.set("authorization", `Bearer ${credential(options, auth)}`);
1543
+ if (options.workspace && auth === "workspace") headers.set(WORKSPACE_HEADER, options.workspace);
1544
+ return headers;
1545
+ },
1546
+ async send(call) {
1547
+ const headers = transport.headers(call.auth, call.headers);
1548
+ let body;
1549
+ if (call.body !== void 0) {
1550
+ headers.set("content-type", "application/json");
1551
+ body = JSON.stringify(call.body);
1552
+ }
1553
+ let response;
1554
+ const sentAt = Date.now();
1555
+ try {
1556
+ response = await doFetch(transport.url(call.path, call.query), {
1557
+ method: call.method,
1558
+ headers,
1559
+ body,
1560
+ signal: call.signal
1561
+ });
1562
+ } catch (cause) {
1563
+ if (call.signal?.aborted) throw call.signal.reason ?? cause;
1564
+ throw new MailsinkError({
1565
+ code: "network_error",
1566
+ message: `${call.method} ${call.path} failed: ${cause?.message ?? cause}`,
1567
+ cause
1568
+ });
1569
+ }
1570
+ clock.observe(response.headers.get("date"), sentAt, Date.now());
1571
+ if (!response.ok) throw await errorFrom(response);
1572
+ return response;
1573
+ },
1574
+ async json(call) {
1575
+ const response = await transport.send(call);
1576
+ const requestId = response.headers.get(REQUEST_ID_HEADER);
1577
+ if (response.status === 204) return void 0;
1578
+ let value;
1579
+ try {
1580
+ value = await response.json();
1581
+ } catch (cause) {
1582
+ throw new MailsinkError({
1583
+ code: "invalid_response",
1584
+ message: `${call.method} ${call.path}: the answer is not JSON`,
1585
+ status: response.status,
1586
+ requestId,
1587
+ cause
1588
+ });
1589
+ }
1590
+ if (!options.validate || !call.schema) return value;
1591
+ const parsed = call.schema.safeParse(value);
1592
+ if (parsed.success) return parsed.data;
1593
+ throw new MailsinkError({
1594
+ code: "invalid_response",
1595
+ message: `${call.method} ${call.path}: the answer does not match its contract`,
1596
+ status: response.status,
1597
+ requestId,
1598
+ details: parsed.error.issues
1599
+ });
1600
+ }
1601
+ };
1602
+ return transport;
1603
+ }
1604
+ function credential(options, auth) {
1605
+ if (auth === "admin") {
1606
+ if (options.adminKey) return options.adminKey;
1607
+ throw new MailsinkError({
1608
+ code: "unauthorized",
1609
+ message: "adminKey is required for admin calls"
1610
+ });
1611
+ }
1612
+ if (options.key) return options.key;
1613
+ if (options.adminKey && options.workspace) return options.adminKey;
1614
+ throw new MailsinkError({
1615
+ code: "unauthorized",
1616
+ message: "key (or adminKey with workspace) is required for workspace calls"
1617
+ });
1618
+ }
1619
+ /** Reads an error answer: the contract body `{ error, requestId }` when it is one. */
1620
+ async function errorFrom(response) {
1621
+ let requestId = response.headers.get(REQUEST_ID_HEADER);
1622
+ const text = await response.text().catch(() => "");
1623
+ let body;
1624
+ try {
1625
+ body = JSON.parse(text);
1626
+ } catch {
1627
+ body = {};
1628
+ }
1629
+ const error = body?.error;
1630
+ if (typeof body?.requestId === "string") requestId ??= body.requestId;
1631
+ if (error && typeof error.code === "string" && typeof error.message === "string") return new MailsinkError({
1632
+ code: error.code,
1633
+ message: error.message,
1634
+ status: response.status,
1635
+ requestId,
1636
+ details: error.details
1637
+ });
1638
+ return new MailsinkError({
1639
+ code: codeForStatus(response.status),
1640
+ message: `HTTP ${response.status}${text ? `: ${text.slice(0, 200)}` : ""}`,
1641
+ status: response.status,
1642
+ requestId
1643
+ });
1644
+ }
1645
+ // ../sdk/src/admin/connections.ts
1646
+ /** `/admin/workspaces/:ref/connections` (Admin key). `ref` is a workspace id or slug. */
1647
+ function connectionsApi(t) {
1648
+ const path = (ref, id, suffix = "") => `/admin/workspaces/${seg(ref)}/connections${id ? `/${seg(id)}` : ""}${suffix}`;
1649
+ return {
1650
+ /** Adds a connection; its credentials are answered once. */
1651
+ create: (ref, input) => t.json({
1652
+ method: "POST",
1653
+ path: path(ref),
1654
+ auth: "admin",
1655
+ body: input,
1656
+ schema: CreatedConnection
1657
+ }),
1658
+ /** Renames, disables (`enabled: false`) or enables a connection. */
1659
+ update: (ref, connectionId, patch) => t.json({
1660
+ method: "PATCH",
1661
+ path: path(ref, connectionId),
1662
+ auth: "admin",
1663
+ body: patch,
1664
+ schema: ConnectionView
1665
+ }),
1666
+ /** Hard delete; messages and logs keep a null connection. */
1667
+ delete: (ref, connectionId) => t.json({
1668
+ method: "DELETE",
1669
+ path: path(ref, connectionId),
1670
+ auth: "admin"
1671
+ }),
1672
+ /** New `msk_` key or SMTP password, the previous one revoked at once. */
1673
+ rotate: (ref, connectionId) => t.json({
1674
+ method: "POST",
1675
+ path: path(ref, connectionId, "/rotate"),
1676
+ auth: "admin",
1677
+ schema: CreatedConnection
1678
+ })
1679
+ };
1680
+ }
1681
+ // ../sdk/src/admin/templates.ts
1682
+ /** Brevo templates of a workspace (Admin key); `templateId` is the numeric Brevo id. */
1683
+ function templatesApi(t) {
1684
+ const path = (ref, templateId) => `/admin/workspaces/${seg(ref)}/templates${templateId === void 0 ? "" : `/${templateId}`}`;
1685
+ return {
1686
+ list: (ref, params = {}) => t.json({
1687
+ method: "GET",
1688
+ path: path(ref),
1689
+ auth: "admin",
1690
+ query: params,
1691
+ schema: ListTemplatesResponse
1692
+ }),
1693
+ create: (ref, input) => t.json({
1694
+ method: "POST",
1695
+ path: path(ref),
1696
+ auth: "admin",
1697
+ body: input,
1698
+ schema: TemplateView
1699
+ }),
1700
+ get: (ref, templateId) => t.json({
1701
+ method: "GET",
1702
+ path: path(ref, templateId),
1703
+ auth: "admin",
1704
+ schema: TemplateView
1705
+ }),
1706
+ update: (ref, templateId, patch) => t.json({
1707
+ method: "PATCH",
1708
+ path: path(ref, templateId),
1709
+ auth: "admin",
1710
+ body: patch,
1711
+ schema: TemplateView
1712
+ }),
1713
+ delete: (ref, templateId) => t.json({
1714
+ method: "DELETE",
1715
+ path: path(ref, templateId),
1716
+ auth: "admin"
1717
+ })
1718
+ };
1719
+ }
1720
+ // ../sdk/src/admin/workspaces.ts
1721
+ /** `/admin/workspaces` (Admin key). `ref` is a workspace id or slug. */
1722
+ function workspacesApi(t) {
1723
+ const path = (ref, suffix = "") => `/admin/workspaces/${seg(ref)}${suffix}`;
1724
+ return {
1725
+ /** Creates a workspace, persistent or ephemeral, with its connections; secrets once. */
1726
+ create: (input) => t.json({
1727
+ method: "POST",
1728
+ path: "/admin/workspaces",
1729
+ auth: "admin",
1730
+ body: input,
1731
+ schema: CreateWorkspaceResponse
1732
+ }),
1733
+ /** One page, persistent workspaces only unless `includeEphemeral`. */
1734
+ list: (params = {}) => t.json({
1735
+ method: "GET",
1736
+ path: "/admin/workspaces",
1737
+ auth: "admin",
1738
+ query: params,
1739
+ schema: ListWorkspacesResponse
1740
+ }),
1741
+ get: (ref) => t.json({
1742
+ method: "GET",
1743
+ path: path(ref),
1744
+ auth: "admin",
1745
+ schema: WorkspaceDetail
1746
+ }),
1747
+ update: (ref, patch) => t.json({
1748
+ method: "PATCH",
1749
+ path: path(ref),
1750
+ auth: "admin",
1751
+ body: patch,
1752
+ schema: WorkspaceView
1753
+ }),
1754
+ /** Immediate hard delete: messages, logs and keys go with it. */
1755
+ delete: (ref) => t.json({
1756
+ method: "DELETE",
1757
+ path: path(ref),
1758
+ auth: "admin"
1759
+ }),
1760
+ /** New `mskw_` key, every previous one revoked at once (D207). */
1761
+ rotateKey: (ref) => t.json({
1762
+ method: "POST",
1763
+ path: path(ref, "/key/rotate"),
1764
+ auth: "admin",
1765
+ schema: RotatedWorkspaceKey
1766
+ })
1767
+ };
1768
+ }
1769
+ // ../sdk/src/capture/logs.ts
1770
+ /** API request log of a scope: `/capture/logs/api` (workspace) or `/admin/logs/api`. */
1771
+ function apiLogsApi(t, scope) {
1772
+ const base = scope === "admin" ? "/admin/logs/api" : "/capture/logs/api";
1773
+ return {
1774
+ list: (params = {}) => t.json({
1775
+ method: "GET",
1776
+ path: base,
1777
+ auth: scope,
1778
+ query: params,
1779
+ schema: ListApiLogsResponse
1780
+ }),
1781
+ get: (id) => t.json({
1782
+ method: "GET",
1783
+ path: `${base}/${seg(id)}`,
1784
+ auth: scope,
1785
+ schema: ApiLogDetail
1786
+ })
1787
+ };
1788
+ }
1789
+ /** `/capture/logs/*`: API calls and SMTP sessions (with transcript) of the workspace. */
1790
+ function logsApi(t) {
1791
+ return {
1792
+ api: apiLogsApi(t, "workspace"),
1793
+ smtp: {
1794
+ list: (params = {}) => t.json({
1795
+ method: "GET",
1796
+ path: "/capture/logs/smtp",
1797
+ auth: "workspace",
1798
+ query: params,
1799
+ schema: ListSmtpSessionsResponse
1800
+ }),
1801
+ get: (id) => t.json({
1802
+ method: "GET",
1803
+ path: `/capture/logs/smtp/${seg(id)}`,
1804
+ auth: "workspace",
1805
+ schema: SmtpSessionDetail
1806
+ })
1807
+ }
1808
+ };
1809
+ }
1810
+ // ../sdk/src/capture/messages.ts
1811
+ /** `/capture/messages`: the captured messages of the workspace. */
1812
+ function messagesApi(t) {
1813
+ const path = (id, suffix = "") => `/capture/messages/${seg(id)}${suffix}`;
1814
+ const api = {
1815
+ /** One page, newest first. Filters: substrings, `tag`, `status`, `since`, `q`... */
1816
+ list: (params = {}, init = {}) => t.json({
1817
+ method: "GET",
1818
+ path: "/capture/messages",
1819
+ auth: "workspace",
1820
+ query: params,
1821
+ schema: ListMessagesResponse,
1822
+ signal: init.signal
1823
+ }),
1824
+ /** Full detail: bodies, headers, links, attachments, recipients, events, deliveries. */
1825
+ get: (id) => t.json({
1826
+ method: "GET",
1827
+ path: path(id),
1828
+ auth: "workspace",
1829
+ schema: MessageDetail
1830
+ }),
1831
+ /**
1832
+ * Resolves the first message matching `filters` created at or after `since` (default:
1833
+ * the time of this call, so start it before the action or pass `since`), as a full
1834
+ * detail. Throws `MailsinkError` `wait_timeout` when none comes within `timeout`.
1835
+ */
1836
+ waitFor: (filters = {}, options = {}) => waitForMessage(t, api, filters, options),
1837
+ /** The raw source (`message/rfc822`) as text. */
1838
+ raw: async (id) => (await t.send({
1839
+ method: "GET",
1840
+ path: path(id, "/raw"),
1841
+ auth: "workspace"
1842
+ })).text(),
1843
+ /** One attachment, as stored. */
1844
+ attachment: async (id, attachmentId) => {
1845
+ const response = await t.send({
1846
+ method: "GET",
1847
+ path: path(id, `/attachments/${seg(attachmentId)}`),
1848
+ auth: "workspace"
1849
+ });
1850
+ return {
1851
+ filename: filenameOf(response.headers.get("content-disposition")),
1852
+ contentType: response.headers.get("content-type") ?? "application/octet-stream",
1853
+ data: new Uint8Array(await response.arrayBuffer())
1854
+ };
1855
+ },
1856
+ /** Deletes messages (and their logs unless `includeLogs: false`); `{ count }`. */
1857
+ purge: (params = {}) => t.json({
1858
+ method: "DELETE",
1859
+ path: "/capture/messages",
1860
+ auth: "workspace",
1861
+ query: params,
1862
+ schema: PurgeResponse
1863
+ }),
1864
+ /** Forces `opened`, `clicked` or a simulated status (bounce, complaint...). */
1865
+ triggerEvent: (id, input) => t.json({
1866
+ method: "POST",
1867
+ path: path(id, "/events"),
1868
+ auth: "workspace",
1869
+ body: input,
1870
+ schema: TriggerEventResponse
1871
+ }),
1872
+ /** Stores the demo data set (eight messages) through the ingestion pipeline. */
1873
+ seedDemo: (input = {}) => t.json({
1874
+ method: "POST",
1875
+ path: "/capture/demo",
1876
+ auth: "workspace",
1877
+ body: input,
1878
+ schema: SeedDemoResponse
1879
+ })
1880
+ };
1881
+ return api;
1882
+ }
1883
+ /** File name of a `Content-Disposition` header, the RFC 5987 `filename*` first. */
1884
+ function filenameOf(disposition) {
1885
+ if (!disposition) return null;
1886
+ const extended = /filename\*\s*=\s*([\w-]+)''([^;]+)/i.exec(disposition);
1887
+ if (extended?.[2]) try {
1888
+ return decodeURIComponent(extended[2].trim());
1889
+ } catch {}
1890
+ const plain = /filename\s*=\s*(?:"((?:[^"\\]|\\.)*)"|([^;\s]+))/i.exec(disposition);
1891
+ return plain ? (plain[1] ?? plain[2] ?? "").replace(/\\(.)/g, "$1") : null;
1892
+ }
1893
+ // ../sdk/src/capture/overrides.ts
1894
+ /** `/capture/override`: temporary simulation settings (rates, rules, latency, chaos...). */
1895
+ function overridesApi(t) {
1896
+ const api = {
1897
+ /** Active overrides and the effective settings per connection. */
1898
+ get: () => t.json({
1899
+ method: "GET",
1900
+ path: "/capture/override",
1901
+ auth: "workspace",
1902
+ schema: OverrideState
1903
+ }),
1904
+ /** Replaces the active override of the scope. */
1905
+ activate: (config, options = {}) => t.json({
1906
+ method: "POST",
1907
+ path: "/capture/override",
1908
+ auth: "workspace",
1909
+ body: {
1910
+ config,
1911
+ connectionId: options.connectionId,
1912
+ ttl: options.ttl
1913
+ },
1914
+ schema: OverrideState
1915
+ }),
1916
+ /** Back to the settings for the scope (idempotent). */
1917
+ reset: (options = {}) => t.json({
1918
+ method: "POST",
1919
+ path: "/capture/override/reset",
1920
+ auth: "workspace",
1921
+ body: { connectionId: options.connectionId },
1922
+ schema: OverrideState
1923
+ }),
1924
+ /**
1925
+ * Runs `fn` under an override and always resets the scope afterwards, `fn` failing
1926
+ * included. Resolves what `fn` resolves.
1927
+ */
1928
+ with: async (config, fn, options = {}) => {
1929
+ await api.activate(config, options);
1930
+ try {
1931
+ return await fn();
1932
+ } finally {
1933
+ await api.reset({ connectionId: options.connectionId });
1934
+ }
1935
+ }
1936
+ };
1937
+ return api;
1938
+ }
1939
+ // ../sdk/src/capture/suppressions.ts
1940
+ /** `/capture/suppressions`: addresses listed after a hard bounce or a complaint. */
1941
+ function suppressionsApi(t) {
1942
+ const remove = (email) => t.json({
1943
+ method: "DELETE",
1944
+ path: "/capture/suppressions",
1945
+ auth: "workspace",
1946
+ query: { email },
1947
+ schema: DeleteSuppressionsResponse
1948
+ });
1949
+ return {
1950
+ /** Newest first; `email` is a case-insensitive substring. */
1951
+ list: (params = {}) => t.json({
1952
+ method: "GET",
1953
+ path: "/capture/suppressions",
1954
+ auth: "workspace",
1955
+ query: params,
1956
+ schema: ListSuppressionsResponse
1957
+ }),
1958
+ /** Removes one address (exact match); `{ count }`. */
1959
+ delete: (email) => remove(email),
1960
+ /** Empties the whole list of the workspace; `{ count }`. */
1961
+ clear: () => remove()
1962
+ };
1963
+ }
1964
+ // ../sdk/src/capture/webhooks.ts
1965
+ /** `/capture/webhooks`: endpoints, the delivery log and replays. */
1966
+ function webhooksApi(t) {
1967
+ const path = (id, suffix = "") => `/capture/webhooks/${seg(id)}${suffix}`;
1968
+ const deliveryPath = (id, suffix = "") => `/capture/webhooks/deliveries/${seg(id)}${suffix}`;
1969
+ return {
1970
+ /** Endpoints of a connection scope and of the workspace scope, oldest first. */
1971
+ list: (params = {}) => t.json({
1972
+ method: "GET",
1973
+ path: "/capture/webhooks",
1974
+ auth: "workspace",
1975
+ query: params,
1976
+ schema: ListWebhookEndpointsResponse
1977
+ }),
1978
+ /** Creates an endpoint; its signing secret is answered once. */
1979
+ create: (input) => t.json({
1980
+ method: "POST",
1981
+ path: "/capture/webhooks",
1982
+ auth: "workspace",
1983
+ body: input,
1984
+ schema: WebhookEndpointWithSecret
1985
+ }),
1986
+ get: (id) => t.json({
1987
+ method: "GET",
1988
+ path: path(id),
1989
+ auth: "workspace",
1990
+ schema: WebhookEndpointView
1991
+ }),
1992
+ /** `secret` is set when one was issued (`rotateSecret: true`, format change). */
1993
+ update: (id, patch) => t.json({
1994
+ method: "PATCH",
1995
+ path: path(id),
1996
+ auth: "workspace",
1997
+ body: patch,
1998
+ schema: WebhookEndpointWithSecret
1999
+ }),
2000
+ /** Deletes the endpoint and its deliveries. */
2001
+ delete: (id) => t.json({
2002
+ method: "DELETE",
2003
+ path: path(id),
2004
+ auth: "workspace"
2005
+ }),
2006
+ /** Body and headers the real formatter would send, secrets masked. */
2007
+ preview: (input) => t.json({
2008
+ method: "POST",
2009
+ path: "/capture/webhooks/preview",
2010
+ auth: "workspace",
2011
+ body: input,
2012
+ schema: WebhookPreviewResponse
2013
+ }),
2014
+ /** Sends one signed sample event (default `email.delivered`) to the endpoint now. */
2015
+ test: (id, input = {}) => t.json({
2016
+ method: "POST",
2017
+ path: path(id, "/test"),
2018
+ auth: "workspace",
2019
+ body: input,
2020
+ schema: WebhookDeliveryDetail
2021
+ }),
2022
+ deliveries: {
2023
+ /** Newest first, filtered by endpoint, format, message or status. */
2024
+ list: (params = {}) => t.json({
2025
+ method: "GET",
2026
+ path: "/capture/webhooks/deliveries",
2027
+ auth: "workspace",
2028
+ query: params,
2029
+ schema: ListWebhookDeliveriesResponse
2030
+ }),
2031
+ /** A delivery with every attempt and its exact headers. */
2032
+ get: (id) => t.json({
2033
+ method: "GET",
2034
+ path: deliveryPath(id),
2035
+ auth: "workspace",
2036
+ schema: WebhookDeliveryDetail
2037
+ }),
2038
+ /** Queues a replay (`exact` headers or `resign`), answered pending. */
2039
+ replay: (id, input = {}) => t.json({
2040
+ method: "POST",
2041
+ path: deliveryPath(id, "/replay"),
2042
+ auth: "workspace",
2043
+ body: input,
2044
+ schema: WebhookDeliveryView
2045
+ })
2046
+ }
2047
+ };
2048
+ }
2049
+ // ../sdk/src/stream/sse.ts
2050
+ /**
2051
+ * Incremental `text/event-stream` parser: push decoded text with `feed`, get the frames
2052
+ * completed by it. Comments (`: ping`) are skipped, `retry:` is reported through `onRetry`.
2053
+ */
2054
+ var SseParser = class {
2055
+ onRetry;
2056
+ lastEventId = "";
2057
+ buffer = "";
2058
+ data = [];
2059
+ hasId = false;
2060
+ constructor(onRetry = () => {}) {
2061
+ this.onRetry = onRetry;
2062
+ }
2063
+ feed(text) {
2064
+ this.buffer += text;
2065
+ const frames = [];
2066
+ for (;;) {
2067
+ const match = /\r\n|\r|\n/.exec(this.buffer);
2068
+ if (!match || match[0] === "\r" && match.index === this.buffer.length - 1) break;
2069
+ const line = this.buffer.slice(0, match.index);
2070
+ this.buffer = this.buffer.slice(match.index + match[0].length);
2071
+ const frame = this.line(line);
2072
+ if (frame) frames.push(frame);
2073
+ }
2074
+ return frames;
2075
+ }
2076
+ line(line) {
2077
+ if (line === "") return this.dispatch();
2078
+ if (line.startsWith(":")) return void 0;
2079
+ const colon = line.indexOf(":");
2080
+ const field = colon === -1 ? line : line.slice(0, colon);
2081
+ let value = colon === -1 ? "" : line.slice(colon + 1);
2082
+ if (value.startsWith(" ")) value = value.slice(1);
2083
+ if (field === "data") this.data.push(value);
2084
+ else if (field === "id" && !value.includes("\0")) {
2085
+ this.lastEventId = value;
2086
+ this.hasId = true;
2087
+ } else if (field === "retry" && /^\d+$/.test(value)) this.onRetry(Number(value));
2088
+ }
2089
+ dispatch() {
2090
+ const data = this.data;
2091
+ const hasId = this.hasId;
2092
+ this.data = [];
2093
+ this.hasId = false;
2094
+ if (data.length === 0) return void 0;
2095
+ return {
2096
+ data: data.join("\n"),
2097
+ lastEventId: this.lastEventId,
2098
+ hasId
2099
+ };
2100
+ }
2101
+ };
2102
+ // ../sdk/src/stream/subscribe.ts
2103
+ const DEFAULT_RETRY_MS = 3e3;
2104
+ const FATAL_STATUS = /* @__PURE__ */ new Set([
2105
+ 400,
2106
+ 401,
2107
+ 403,
2108
+ 404,
2109
+ 422
2110
+ ]);
2111
+ /**
2112
+ * Subscribes to `GET /capture/stream` (SSE over `fetch`, so Node and browsers alike) and
2113
+ * reconnects with `Last-Event-ID` when the connection drops: frames with an id missed
2114
+ * meanwhile are replayed by the server. Stops on `close()`, on the abort signal, or after a
2115
+ * `workspace.deleted` frame.
2116
+ */
2117
+ function subscribe(t, handler, options = {}) {
2118
+ const controller = new AbortController();
2119
+ const stop = () => controller.abort();
2120
+ options.signal?.addEventListener("abort", stop, { once: true });
2121
+ if (options.signal?.aborted) stop();
2122
+ let lastEventId = options.lastEventId;
2123
+ let serverRetry;
2124
+ let opened = false;
2125
+ let markReady = () => {};
2126
+ let failReady = () => {};
2127
+ const ready = new Promise((resolve, reject) => {
2128
+ markReady = resolve;
2129
+ failReady = reject;
2130
+ });
2131
+ ready.catch(() => {});
2132
+ const report = (error) => options.onError?.(error);
2133
+ async function connect() {
2134
+ const response = await t.send({
2135
+ method: "GET",
2136
+ path: "/capture/stream",
2137
+ auth: "workspace",
2138
+ query: {
2139
+ types: options.types,
2140
+ connectionId: options.connectionId
2141
+ },
2142
+ headers: {
2143
+ accept: "text/event-stream",
2144
+ ...lastEventId && { "last-event-id": lastEventId }
2145
+ },
2146
+ signal: controller.signal
2147
+ });
2148
+ opened = true;
2149
+ markReady();
2150
+ options.onOpen?.();
2151
+ if (!response.body) return "reconnect";
2152
+ const parser = new SseParser((ms) => {
2153
+ serverRetry = ms;
2154
+ });
2155
+ const reader = response.body.getReader();
2156
+ const decoder = new TextDecoder();
2157
+ for (;;) {
2158
+ const { done, value } = await reader.read();
2159
+ if (done) return "reconnect";
2160
+ for (const frame of parser.feed(decoder.decode(value, { stream: true }))) {
2161
+ if (frame.hasId) lastEventId = frame.lastEventId;
2162
+ const event = readEvent(frame.data, t.options.validate === true);
2163
+ if (!event) {
2164
+ report(new MailsinkError({
2165
+ code: "invalid_response",
2166
+ message: "Unreadable stream frame",
2167
+ details: frame.data
2168
+ }));
2169
+ continue;
2170
+ }
2171
+ try {
2172
+ await handler(event, { id: frame.hasId ? frame.lastEventId : null });
2173
+ } catch (error) {
2174
+ report(error);
2175
+ }
2176
+ if (event.type === "workspace.deleted") {
2177
+ await reader.cancel().catch(() => {});
2178
+ return "stop";
2179
+ }
2180
+ }
2181
+ }
2182
+ }
2183
+ async function run() {
2184
+ while (!controller.signal.aborted) {
2185
+ try {
2186
+ if (await connect() === "stop") return;
2187
+ } catch (error) {
2188
+ if (controller.signal.aborted) return;
2189
+ const fatal = error instanceof MailsinkError && FATAL_STATUS.has(error.status ?? 0);
2190
+ report(error);
2191
+ if (fatal) {
2192
+ if (!opened) failReady(error);
2193
+ throw error;
2194
+ }
2195
+ }
2196
+ if (controller.signal.aborted) return;
2197
+ await sleep(options.retryMs ?? serverRetry ?? DEFAULT_RETRY_MS, controller.signal);
2198
+ }
2199
+ }
2200
+ const done = run().finally(() => {
2201
+ options.signal?.removeEventListener("abort", stop);
2202
+ controller.abort();
2203
+ markReady();
2204
+ });
2205
+ done.catch(() => {});
2206
+ return {
2207
+ ready,
2208
+ done,
2209
+ get lastEventId() {
2210
+ return lastEventId;
2211
+ },
2212
+ close: stop
2213
+ };
2214
+ }
2215
+ function readEvent(data, validate) {
2216
+ try {
2217
+ const value = JSON.parse(data);
2218
+ if (!validate) return value;
2219
+ const parsed = StreamEvent.safeParse(value);
2220
+ return parsed.success ? parsed.data : void 0;
2221
+ } catch {
2222
+ return;
2223
+ }
2224
+ }
2225
+ function sleep(ms, signal) {
2226
+ return new Promise((resolve) => {
2227
+ const timer = setTimeout(done, ms);
2228
+ signal.addEventListener("abort", done, { once: true });
2229
+ function done() {
2230
+ clearTimeout(timer);
2231
+ signal.removeEventListener("abort", done);
2232
+ resolve();
2233
+ }
2234
+ });
2235
+ }
2236
+ // ../sdk/src/client.ts
2237
+ /**
2238
+ * A Mailsink client. Admin calls need `adminKey`; workspace calls (messages, overrides,
2239
+ * suppressions, webhooks, logs, stream) need a workspace or connection `key`, or the
2240
+ * `adminKey` with `workspace`.
2241
+ *
2242
+ * ```ts
2243
+ * const mailsink = createMailsink({ url: 'http://localhost:3000', key: process.env.MAILSINK_KEY })
2244
+ * const email = await mailsink.messages.waitFor({ to: 'jane@example.com' })
2245
+ * ```
2246
+ */
2247
+ function createMailsink(options) {
2248
+ return build(options, createServerClock());
2249
+ }
2250
+ function build(options, clock) {
2251
+ const t = createTransport(options, clock);
2252
+ return {
2253
+ options: t.options,
2254
+ admin: {
2255
+ workspaces: workspacesApi(t),
2256
+ connections: connectionsApi(t),
2257
+ templates: templatesApi(t),
2258
+ /** API calls without a workspace (`/admin/logs/api`). */
2259
+ logs: apiLogsApi(t, "admin")
2260
+ },
2261
+ messages: messagesApi(t),
2262
+ overrides: overridesApi(t),
2263
+ suppressions: suppressionsApi(t),
2264
+ webhooks: webhooksApi(t),
2265
+ logs: logsApi(t),
2266
+ stream: {
2267
+ /** Live `StreamEvent`s of the workspace, reconnecting with `Last-Event-ID`. */
2268
+ subscribe: (handler, subscribeOptions) => subscribe(t, handler, subscribeOptions) },
2269
+ /**
2270
+ * A client with some options changed, e.g. scoped to the workspace just created:
2271
+ * `mailsink.with({ key: created.workspaceKey })`.
2272
+ */
2273
+ with: (patch) => {
2274
+ const next = {
2275
+ ...options,
2276
+ ...patch
2277
+ };
2278
+ return build(next, String(next.url) === String(options.url) ? clock : createServerClock());
2279
+ },
2280
+ now: () => clock.now()
2281
+ };
2282
+ }
2283
+ // ../sdk/src/helpers/links.ts
2284
+ const HREF = /\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/gi;
2285
+ const BARE_URL = /\bhttps?:\/\/[^\s<>"'`)\]]+/gi;
2286
+ const ENTITIES = {
2287
+ amp: "&",
2288
+ lt: "<",
2289
+ gt: ">",
2290
+ quot: "\"",
2291
+ apos: "'"
2292
+ };
2293
+ /** Decodes the HTML entities found in attribute values (`&amp;`, `&#38;`, `&#x26;`). */
2294
+ function decodeEntities(value) {
2295
+ return value.replace(/&(#x[\da-f]+|#\d+|[a-z]+);/gi, (whole, name) => {
2296
+ if (name[0] !== "#") return ENTITIES[name.toLowerCase()] ?? whole;
2297
+ const code = name[1] === "x" || name[1] === "X" ? parseInt(name.slice(2), 16) : Number(name.slice(1));
2298
+ return Number.isFinite(code) ? String.fromCodePoint(code) : whole;
2299
+ });
2300
+ }
2301
+ /**
2302
+ * Every http(s) link of a message, in order of appearance and without duplicates: the
2303
+ * links the server extracted, then the `href`s of the HTML body, then the URLs of the
2304
+ * text body.
2305
+ */
2306
+ function extractLinks(message) {
2307
+ const found = [];
2308
+ for (const link of message.links ?? []) found.push(link.url);
2309
+ for (const match of (message.html ?? "").matchAll(HREF)) found.push(decodeEntities((match[1] ?? match[2] ?? match[3] ?? "").trim()));
2310
+ for (const match of (message.text ?? "").matchAll(BARE_URL)) found.push(match[0].replace(/[.,;:!?]+$/, ""));
2311
+ return [...new Set(found.filter((url) => /^https?:\/\//i.test(url)))];
2312
+ }
2313
+ /**
2314
+ * The first link matching: a substring of the URL, a RegExp tested on it, or a predicate
2315
+ * on the parsed URL. `null` when none does.
2316
+ */
2317
+ function findLink(message, matcher) {
2318
+ for (const url of extractLinks(message)) {
2319
+ if (typeof matcher === "string" && url.includes(matcher)) return url;
2320
+ if (matcher instanceof RegExp && new RegExp(matcher.source, matcher.flags.replace("g", "")).test(url)) return url;
2321
+ if (typeof matcher === "function") {
2322
+ const parsed = URL.canParse(url) ? new URL(url) : null;
2323
+ if (parsed && matcher(parsed)) return url;
2324
+ }
2325
+ }
2326
+ return null;
2327
+ }
2328
+ // src/errors.ts
2329
+ /** Exit codes of every command (docs/guides/cli.md). */
2330
+ const EXIT = {
2331
+ ok: 0,
2332
+ /** The call failed: API error, network, authentication. */
2333
+ failure: 1,
2334
+ /** Bad command line: unknown command or option, invalid value, missing credential. */
2335
+ usage: 2,
2336
+ /** `mailsink wait`: no message matched before the timeout. */
2337
+ waitTimeout: 3
2338
+ };
2339
+ /** A command line mistake, reported with exit code 2. */
2340
+ var UsageError = class extends Error {
2341
+ name = "UsageError";
2342
+ };
2343
+ /** `parseArgs` rejects unknown options and bad values with `ERR_PARSE_ARGS_*` codes. */
2344
+ function isParseArgsError(error) {
2345
+ const code = error?.code;
2346
+ return typeof code === "string" && code.startsWith("ERR_PARSE_ARGS_");
2347
+ }
2348
+ /** Exit code and one-line English message of a failure. Never prints a key. */
2349
+ function describeFailure(error) {
2350
+ if (error instanceof UsageError || isParseArgsError(error)) return {
2351
+ code: EXIT.usage,
2352
+ message: error.message
2353
+ };
2354
+ if (isMailsinkError(error)) {
2355
+ const request = error.requestId ? ` (request ${error.requestId})` : "";
2356
+ return {
2357
+ code: error.code === "wait_timeout" ? EXIT.waitTimeout : EXIT.failure,
2358
+ message: `${error.code}: ${error.message}${request}`
2359
+ };
2360
+ }
2361
+ return {
2362
+ code: EXIT.failure,
2363
+ message: error instanceof Error ? error.message : String(error)
2364
+ };
2365
+ }
2366
+ // src/config.ts
2367
+ const DEFAULT_MAILSINK_URL = "http://localhost:3000";
2368
+ /** `parseArgs` options shared by every piloting command. */
2369
+ const CLIENT_OPTIONS = {
2370
+ url: { type: "string" },
2371
+ "admin-key": { type: "string" },
2372
+ key: { type: "string" },
2373
+ workspace: { type: "string" },
2374
+ json: {
2375
+ type: "boolean",
2376
+ default: false
2377
+ }
2378
+ };
2379
+ function resolveSettings(flags, env) {
2380
+ const url = flags.url ?? env.MAILSINK_URL ?? "http://localhost:3000";
2381
+ if (!URL.canParse(url) || !/^https?:$/.test(new URL(url).protocol)) throw new UsageError("Invalid MAILSINK_URL: expected an http(s) URL");
2382
+ return {
2383
+ url,
2384
+ adminKey: flags["admin-key"] ?? env.MAILSINK_ADMIN_KEY,
2385
+ key: flags.key ?? env.MAILSINK_KEY,
2386
+ workspace: flags.workspace ?? env.MAILSINK_WORKSPACE
2387
+ };
2388
+ }
2389
+ /** Client for the Admin API (`workspace` commands): needs the Admin key. */
2390
+ function adminClient(settings) {
2391
+ if (!settings.adminKey) throw new UsageError("MAILSINK_ADMIN_KEY (or --admin-key) is required");
2392
+ return createMailsink({
2393
+ url: settings.url,
2394
+ adminKey: settings.adminKey
2395
+ });
2396
+ }
2397
+ /**
2398
+ * Client for the Capture API of one workspace: a workspace or connection key, or the
2399
+ * Admin key with the workspace id or slug.
2400
+ */
2401
+ function workspaceClient(settings) {
2402
+ if (settings.key) return createMailsink({
2403
+ url: settings.url,
2404
+ key: settings.key,
2405
+ workspace: settings.workspace
2406
+ });
2407
+ if (settings.adminKey && settings.workspace) return createMailsink({
2408
+ url: settings.url,
2409
+ adminKey: settings.adminKey,
2410
+ workspace: settings.workspace
2411
+ });
2412
+ throw new UsageError("MAILSINK_KEY (or --key) is required, or MAILSINK_ADMIN_KEY with MAILSINK_WORKSPACE");
2413
+ }
2414
+ // src/output.ts
2415
+ /** `--json`: one pretty-printed JSON document on stdout. */
2416
+ function printJson(io, value) {
2417
+ io.out(JSON.stringify(value, null, 2));
2418
+ }
2419
+ /** Left-aligned columns, two spaces apart; `null` and `undefined` print as `-`. */
2420
+ function table(headers, rows) {
2421
+ const cells = [headers, ...rows.map((row) => row.map((c) => c == null ? "-" : String(c)))];
2422
+ const widths = headers.map((_, i) => Math.max(...cells.map((row) => row[i]?.length ?? 0)));
2423
+ return cells.map((row) => row.map((cell, i) => i === row.length - 1 ? cell : cell.padEnd(widths[i] ?? 0)).join(" ")).join("\n");
2424
+ }
2425
+ /** `.env` lines (`NAME=value`), skipping absent values; values are printed as is. */
2426
+ function envLines(entries) {
2427
+ return entries.filter(([, value]) => value !== void 0 && value !== null).map(([name, value]) => `${name}=${value}`).join("\n");
2428
+ }
2429
+ // src/parse.ts
2430
+ const MS_PER_UNIT = {
2431
+ ms: 1,
2432
+ s: 1e3,
2433
+ m: 6e4,
2434
+ h: 36e5,
2435
+ d: 864e5
2436
+ };
2437
+ const DURATION = /^(\d+(?:\.\d+)?)(ms|s|m|h|d)?$/;
2438
+ /** `"500ms"`, `"5s"`, `"2m"`, `"1h"`, `"1d"`; a bare number is seconds. */
2439
+ function parseDurationMs(value, option) {
2440
+ const match = DURATION.exec(value.trim());
2441
+ if (!match) throw new UsageError(`--${option}: expected a duration such as 500ms, 5s, 2m or 1h`);
2442
+ const unit = match[2] ?? "s";
2443
+ return Math.round(Number(match[1]) * MS_PER_UNIT[unit]);
2444
+ }
2445
+ /** A duration in whole seconds (the server TTLs), at least one second. */
2446
+ function parseDurationSeconds(value, option) {
2447
+ const ms = parseDurationMs(value, option);
2448
+ if (ms < 1e3 || ms % 1e3 !== 0) throw new UsageError(`--${option}: expected whole seconds, such as 90s, 30m or 1h`);
2449
+ return ms / 1e3;
2450
+ }
2451
+ /** `"20"` or `"20%"`, from 0 to 100. */
2452
+ function parsePercent(value, option) {
2453
+ const n = Number(value.trim().replace(/%$/, ""));
2454
+ if (value.trim() === "" || !Number.isFinite(n) || n < 0 || n > 100) throw new UsageError(`--${option}: expected a percentage from 0 to 100`);
2455
+ return n;
2456
+ }
2457
+ /** `"100-500"` (ms) or `"200"` for a fixed latency. */
2458
+ function parseLatency(value) {
2459
+ const match = /^(\d+)(?:-(\d+))?$/.exec(value.trim());
2460
+ const minMs = Number(match?.[1]);
2461
+ const maxMs = Number(match?.[2] ?? match?.[1]);
2462
+ if (!match || minMs > maxMs) throw new UsageError("--latency: expected <min>-<max> in ms, such as 100-500");
2463
+ return {
2464
+ minMs,
2465
+ maxMs
2466
+ };
2467
+ }
2468
+ const CONNECTION_KINDS = [
2469
+ "resend",
2470
+ "brevo",
2471
+ "smtp"
2472
+ ];
2473
+ /** `"resend:app"` -> `{ kind: 'resend', name: 'app' }`; the name defaults to the kind. */
2474
+ function parseConnection(value) {
2475
+ const [kind = "", ...rest] = value.split(":");
2476
+ const name = rest.join(":").trim() || kind;
2477
+ if (!CONNECTION_KINDS.includes(kind)) throw new UsageError(`--connection: expected <kind>[:<name>] with kind ${CONNECTION_KINDS.join(", ")}`);
2478
+ return {
2479
+ kind,
2480
+ name
2481
+ };
2482
+ }
2483
+ /**
2484
+ * `--since`: an ISO date, `now`, or a duration ago (`5m` = five minutes ago). Absent:
2485
+ * the epoch, so a message stored before the command started counts.
2486
+ */
2487
+ function parseSince(value, now = /* @__PURE__ */ new Date()) {
2488
+ if (value === void 0) return /* @__PURE__ */ new Date(0);
2489
+ if (value === "now") return now;
2490
+ if (DURATION.test(value)) return new Date(now.getTime() - parseDurationMs(value, "since"));
2491
+ const date = new Date(value);
2492
+ if (Number.isNaN(date.getTime())) throw new UsageError("--since: expected an ISO date, \"now\" or a duration such as 5m");
2493
+ return date;
2494
+ }
2495
+ /** `"*+bounce@*=hard_bounce"` -> a recipient rule. */
2496
+ function parseRule(value) {
2497
+ const at = value.lastIndexOf("=");
2498
+ const match = value.slice(0, at).trim();
2499
+ const status = value.slice(at + 1).trim();
2500
+ if (at <= 0 || !match || !status) throw new UsageError("--rule: expected <glob>=<status>, such as \"*+bounce@*=hard_bounce\"");
2501
+ return {
2502
+ match,
2503
+ status
2504
+ };
2505
+ }
2506
+ // src/commands/override.ts
2507
+ /** Status rate flags: `--hard-bounce 20` = 20 % of the messages end hard bounced. */
2508
+ const RATE_FLAGS = {
2509
+ delivered: "delivered",
2510
+ deferred: "deferred",
2511
+ "soft-bounce": "soft_bounce",
2512
+ "hard-bounce": "hard_bounce",
2513
+ complained: "complained",
2514
+ failed: "failed",
2515
+ invalid: "invalid"
2516
+ };
2517
+ const rateOptions = Object.fromEntries(Object.keys(RATE_FLAGS).map((flag) => [flag, { type: "string" }]));
2518
+ async function overrideCommand(argv, env, io) {
2519
+ const [action, ...rest] = argv;
2520
+ if (action === "set") return set(rest, env, io);
2521
+ if (action === "reset") return reset(rest, env, io);
2522
+ throw new UsageError(action === void 0 ? "mailsink override: expected set or reset" : `Unknown override action "${action}": expected set or reset`);
2523
+ }
2524
+ async function set(args, env, io) {
2525
+ const { values } = parseArgs({
2526
+ args,
2527
+ options: {
2528
+ ...CLIENT_OPTIONS,
2529
+ ...rateOptions,
2530
+ latency: { type: "string" },
2531
+ "error-rate": { type: "string" },
2532
+ rule: {
2533
+ type: "string",
2534
+ multiple: true,
2535
+ default: []
2536
+ },
2537
+ config: { type: "string" },
2538
+ ttl: { type: "string" },
2539
+ connection: { type: "string" }
2540
+ },
2541
+ strict: true
2542
+ });
2543
+ const config = buildConfig(values);
2544
+ if (Object.keys(config).length === 0) throw new UsageError("mailsink override set: give at least one setting (see --help)");
2545
+ const state = await workspaceClient(resolveSettings(values, env)).overrides.activate(config, {
2546
+ connectionId: values.connection,
2547
+ ttl: values.ttl === void 0 ? void 0 : parseDurationSeconds(values.ttl, "ttl")
2548
+ });
2549
+ if (values.json) return printJson(io, state);
2550
+ io.out(describeActive(state, values.connection));
2551
+ }
2552
+ /** The override body: `--config` JSON first, then the flags on top of it. */
2553
+ function buildConfig(values) {
2554
+ let config = {};
2555
+ if (values.config !== void 0) {
2556
+ try {
2557
+ config = JSON.parse(values.config);
2558
+ } catch {
2559
+ throw new UsageError("--config: expected a JSON object");
2560
+ }
2561
+ if (!config || typeof config !== "object" || Array.isArray(config)) throw new UsageError("--config: expected a JSON object");
2562
+ }
2563
+ const rates = { ...config.rates };
2564
+ for (const flag of Object.keys(RATE_FLAGS)) {
2565
+ const value = values[flag];
2566
+ if (value !== void 0) rates[RATE_FLAGS[flag]] = parsePercent(value, flag);
2567
+ }
2568
+ if (Object.keys(rates).length > 0) config.rates = rates;
2569
+ if (values.latency !== void 0) config.latency = parseLatency(values.latency);
2570
+ if (values["error-rate"] !== void 0) config.chaos = {
2571
+ ...config.chaos,
2572
+ errorRate: parsePercent(values["error-rate"], "error-rate")
2573
+ };
2574
+ if (values.rule.length > 0) config.rules = [...config.rules ?? [], ...values.rule.map(parseRule)];
2575
+ return config;
2576
+ }
2577
+ async function reset(args, env, io) {
2578
+ const { values } = parseArgs({
2579
+ args,
2580
+ options: {
2581
+ ...CLIENT_OPTIONS,
2582
+ connection: { type: "string" }
2583
+ },
2584
+ strict: true
2585
+ });
2586
+ const state = await workspaceClient(resolveSettings(values, env)).overrides.reset({ connectionId: values.connection });
2587
+ if (values.json) return printJson(io, state);
2588
+ io.out(`Override reset on ${values.connection ? `connection ${values.connection}` : "the workspace"}.`);
2589
+ }
2590
+ function describeActive(state, connectionId) {
2591
+ const active = connectionId ? state.connections.find((o) => o.connectionId === connectionId) : state.workspace;
2592
+ return `Override active on ${connectionId ? `connection ${connectionId}` : "the workspace"}${active?.expiresAt ? `, until ${active.expiresAt}` : ""}: ${JSON.stringify(active?.config ?? {})}`;
2593
+ }
2594
+ // src/commands/purge.ts
2595
+ async function purgeCommand(args, env, io) {
2596
+ const { values } = parseArgs({
2597
+ args,
2598
+ options: {
2599
+ ...CLIENT_OPTIONS,
2600
+ connection: { type: "string" },
2601
+ before: { type: "string" },
2602
+ "keep-logs": {
2603
+ type: "boolean",
2604
+ default: false
2605
+ }
2606
+ },
2607
+ strict: true
2608
+ });
2609
+ let before;
2610
+ if (values.before !== void 0) {
2611
+ const date = new Date(values.before);
2612
+ if (Number.isNaN(date.getTime())) throw new UsageError("--before: expected an ISO date");
2613
+ before = date.toISOString();
2614
+ }
2615
+ const result = await workspaceClient(resolveSettings(values, env)).messages.purge({
2616
+ connectionId: values.connection,
2617
+ before,
2618
+ includeLogs: !values["keep-logs"]
2619
+ });
2620
+ if (values.json) return printJson(io, result);
2621
+ io.out(`Purged ${result.count} message${result.count === 1 ? "" : "s"}.`);
2622
+ }
2623
+ async function waitCommand(args, env, io) {
2624
+ const { values, positionals } = parseArgs({
2625
+ args,
2626
+ options: {
2627
+ ...CLIENT_OPTIONS,
2628
+ to: { type: "string" },
2629
+ from: { type: "string" },
2630
+ subject: { type: "string" },
2631
+ tag: { type: "string" },
2632
+ q: { type: "string" },
2633
+ connection: { type: "string" },
2634
+ since: { type: "string" },
2635
+ timeout: {
2636
+ type: "string",
2637
+ default: "10s"
2638
+ },
2639
+ link: { type: "string" }
2640
+ },
2641
+ allowPositionals: true,
2642
+ strict: true
2643
+ });
2644
+ if (positionals.length > 0) throw new UsageError(`mailsink wait: unexpected argument "${positionals[0]}"`);
2645
+ const timeout = parseDurationMs(values.timeout, "timeout");
2646
+ const since = parseSince(values.since);
2647
+ const message = await workspaceClient(resolveSettings(values, env)).messages.waitFor({
2648
+ to: values.to,
2649
+ from: values.from,
2650
+ subject: values.subject,
2651
+ tag: values.tag,
2652
+ q: values.q,
2653
+ connectionId: values.connection
2654
+ }, {
2655
+ timeout,
2656
+ since
2657
+ });
2658
+ const extractedLinks = extractLinks(message);
2659
+ const link = values.link === void 0 ? void 0 : findLink(message, values.link);
2660
+ if (values.link !== void 0 && !link) throw new Error(`No link of message ${message.id} contains "${values.link}"`);
2661
+ if (values.json) return printJson(io, {
2662
+ ...message,
2663
+ extractedLinks,
2664
+ link
2665
+ });
2666
+ io.out(link ?? summary(message, extractedLinks));
2667
+ }
2668
+ function summary(message, links) {
2669
+ const address = (a) => a.name ? `${a.name} <${a.email}>` : a.email;
2670
+ return [
2671
+ `ID ${message.id}`,
2672
+ `Date ${message.createdAt}`,
2673
+ `From ${address(message.from)}`,
2674
+ `To ${message.to.map(address).join(", ")}`,
2675
+ `Subject ${message.subject}`,
2676
+ `Status ${message.status}`,
2677
+ ...links.length ? ["Links", ...links.map((url) => ` ${url}`)] : []
2678
+ ].join("\n");
2679
+ }
2680
+ // src/commands/workspace.ts
2681
+ const DEFAULT_WORKSPACE_NAME = "mailsink-cli";
2682
+ async function workspaceCommand(argv, env, io) {
2683
+ const [action, ...rest] = argv;
2684
+ switch (action) {
2685
+ case "create": return create(rest, env, io);
2686
+ case "list": return list(rest, env, io);
2687
+ case "delete": return remove(rest, env, io);
2688
+ default: throw new UsageError(action === void 0 ? "mailsink workspace: expected create, list or delete" : `Unknown workspace action "${action}": expected create, list or delete`);
2689
+ }
2690
+ }
2691
+ async function create(args, env, io) {
2692
+ const { values } = parseArgs({
2693
+ args,
2694
+ options: {
2695
+ ...CLIENT_OPTIONS,
2696
+ name: {
2697
+ type: "string",
2698
+ default: DEFAULT_WORKSPACE_NAME
2699
+ },
2700
+ slug: { type: "string" },
2701
+ ephemeral: {
2702
+ type: "boolean",
2703
+ default: false
2704
+ },
2705
+ ttl: { type: "string" },
2706
+ retention: { type: "string" },
2707
+ connection: {
2708
+ type: "string",
2709
+ multiple: true,
2710
+ default: []
2711
+ }
2712
+ },
2713
+ strict: true
2714
+ });
2715
+ if (values.ttl !== void 0 && !values.ephemeral) throw new UsageError("--ttl requires --ephemeral");
2716
+ const settings = resolveSettings(values, env);
2717
+ const created = await adminClient(settings).admin.workspaces.create({
2718
+ name: values.name,
2719
+ slug: values.slug,
2720
+ ephemeral: values.ephemeral,
2721
+ idleTtlSeconds: values.ttl === void 0 ? void 0 : parseDurationSeconds(values.ttl, "ttl"),
2722
+ retention: values.retention === void 0 ? void 0 : parseDurationSeconds(values.retention, "retention"),
2723
+ connections: values.connection.map(parseConnection)
2724
+ });
2725
+ if (values.json) return printJson(io, created);
2726
+ io.out(credentialsEnv(settings.url, created));
2727
+ }
2728
+ /**
2729
+ * The credentials as `.env` lines, ready for `>> "$GITHUB_ENV"` or `export $(…)`: the
2730
+ * workspace, its `mskw_` key as MAILSINK_KEY, then each connection's snippet.
2731
+ */
2732
+ function credentialsEnv(url, created) {
2733
+ return [envLines([
2734
+ ["MAILSINK_URL", url],
2735
+ ["MAILSINK_WORKSPACE_ID", created.workspace.id],
2736
+ ["MAILSINK_WORKSPACE_SLUG", created.workspace.slug],
2737
+ ["MAILSINK_KEY", created.workspaceKey]
2738
+ ]), ...created.connections.map((c) => c.envSnippet.trimEnd())].join("\n");
2739
+ }
2740
+ async function list(args, env, io) {
2741
+ const { values } = parseArgs({
2742
+ args,
2743
+ options: {
2744
+ ...CLIENT_OPTIONS,
2745
+ ephemeral: {
2746
+ type: "boolean",
2747
+ default: false
2748
+ }
2749
+ },
2750
+ strict: true
2751
+ });
2752
+ const client = adminClient(resolveSettings(values, env));
2753
+ const workspaces = [];
2754
+ let cursor;
2755
+ do {
2756
+ const page = await client.admin.workspaces.list({
2757
+ includeEphemeral: values.ephemeral,
2758
+ cursor,
2759
+ limit: 200
2760
+ });
2761
+ workspaces.push(...page.data);
2762
+ cursor = page.nextCursor ?? void 0;
2763
+ } while (cursor);
2764
+ if (values.json) return printJson(io, workspaces);
2765
+ if (workspaces.length === 0) return io.out("No workspace.");
2766
+ io.out(table([
2767
+ "ID",
2768
+ "SLUG",
2769
+ "EPHEMERAL",
2770
+ "EXPIRES",
2771
+ "NAME"
2772
+ ], workspaces.map((w) => [
2773
+ w.id,
2774
+ w.slug,
2775
+ w.ephemeral ? "yes" : "no",
2776
+ w.expiresAt,
2777
+ w.name
2778
+ ])));
2779
+ }
2780
+ async function remove(args, env, io) {
2781
+ const { values, positionals } = parseArgs({
2782
+ args,
2783
+ options: CLIENT_OPTIONS,
2784
+ allowPositionals: true,
2785
+ strict: true
2786
+ });
2787
+ if (positionals.length === 0) throw new UsageError("mailsink workspace delete: expected at least one <id|slug>");
2788
+ const client = adminClient(resolveSettings(values, env));
2789
+ for (const ref of positionals) await client.admin.workspaces.delete(ref);
2790
+ if (values.json) return printJson(io, { deleted: positionals });
2791
+ for (const ref of positionals) io.out(`Deleted workspace ${ref}.`);
2792
+ }
2793
+ // src/usage.ts
2794
+ const USAGE = `Usage: mailsink <command> [options]
2795
+
2796
+ Piloting (HTTP API, for CI and shell scripts):
2797
+ mailsink workspace create [--ephemeral] [--ttl 1h] [--name <name>] [--slug <slug>]
2798
+ [--retention 7d] [--connection <kind>[:<name>]]...
2799
+ Create a workspace, print its credentials as .env lines
2800
+ mailsink workspace list [--ephemeral]
2801
+ List the workspaces (--ephemeral: include ephemeral ones)
2802
+ mailsink workspace delete <id|slug>...
2803
+ Delete workspaces with their messages and logs
2804
+ mailsink wait [--to <s>] [--from <s>] [--subject <s>] [--tag <name[:value]>] [--q <text>]
2805
+ [--connection <id>] [--since <iso|now|5m>] [--timeout 10s] [--link <s>]
2806
+ Wait for a matching message (exit code 3 on timeout)
2807
+ mailsink override set [--hard-bounce 20] [--soft-bounce 5] [--deferred 5] [--complained 1]
2808
+ [--failed 1] [--invalid 1] [--delivered 50] [--latency 100-500]
2809
+ [--error-rate 10] [--rule '<glob>=<status>']... [--config <json>]
2810
+ [--ttl 10m]
2811
+ [--connection <id>]
2812
+ Activate a simulation override (rates in %, latency in ms)
2813
+ mailsink override reset [--connection <id>]
2814
+ Back to the configured simulation settings
2815
+ mailsink purge [--connection <id>] [--before <iso>] [--keep-logs]
2816
+ Delete the captured messages
2817
+
2818
+ Server side:
2819
+ mailsink migrate [--database-url <url>] Apply pending database migrations
2820
+ mailsink mcp [--url <url>] [--key <key>] [--workspace <id|slug>]
2821
+ MCP server on stdio, proxied to <url>/mcp
2822
+ mailsink help Show this help
2823
+
2824
+ Options of the piloting commands, each with its environment variable:
2825
+ --url <url> MAILSINK_URL base URL (default ${DEFAULT_MAILSINK_URL})
2826
+ --admin-key <key> MAILSINK_ADMIN_KEY Admin key (workspace commands)
2827
+ --key <key> MAILSINK_KEY workspace key (mskw_...) or connection key (msk_...)
2828
+ --workspace <ref> MAILSINK_WORKSPACE workspace id or slug, with the Admin key only
2829
+ --json print the API answer as JSON
2830
+
2831
+ DATABASE_URL (migrate): postgres://..., pglite://<dir> or pglite://memory (default
2832
+ pglite://./data). Prefer the environment to flags for keys: flags show in process lists.
2833
+ Exit codes: 0 success, 1 failure, 2 invalid command line, 3 wait timeout.`;
2834
+ // src/index.ts
2835
+ /** The database drivers `migrate` needs, optional peers of @devitek/mailsink-cli. */
2836
+ const DB_PEERS = [
2837
+ "drizzle-orm",
2838
+ "pg",
2839
+ "@electric-sql/pglite"
2840
+ ];
2841
+ /**
2842
+ * `migrate` and `mcp` load lazily: the piloting commands never import the database
2843
+ * drivers, which `npx @devitek/mailsink-cli` does not install (D251).
2844
+ */
2845
+ async function loadMigrate() {
2846
+ try {
2847
+ return await import("./migrate-yxDoMMKo.mjs");
2848
+ } catch (error) {
2849
+ const code = error.code;
2850
+ const missing = DB_PEERS.find((name) => String(error).includes(`'${name}`));
2851
+ if (code !== "ERR_MODULE_NOT_FOUND" || !missing) throw error;
2852
+ throw new Error(`mailsink migrate needs ${DB_PEERS.join(", ")} (missing: ${missing}). Run it from the Docker image, or install them next to @devitek/mailsink-cli.`);
2853
+ }
2854
+ }
2855
+ /** Runs the CLI and returns the process exit code. Never prints a key on stderr. */
2856
+ async function run(argv, env, io) {
2857
+ const [command, ...rest] = argv;
2858
+ try {
2859
+ switch (command) {
2860
+ case void 0:
2861
+ case "help":
2862
+ case "--help":
2863
+ case "-h":
2864
+ io.out(USAGE);
2865
+ return EXIT.ok;
2866
+ case "workspace":
2867
+ await workspaceCommand(rest, env, io);
2868
+ return EXIT.ok;
2869
+ case "wait":
2870
+ await waitCommand(rest, env, io);
2871
+ return EXIT.ok;
2872
+ case "override":
2873
+ await overrideCommand(rest, env, io);
2874
+ return EXIT.ok;
2875
+ case "purge":
2876
+ await purgeCommand(rest, env, io);
2877
+ return EXIT.ok;
2878
+ case "migrate": {
2879
+ const { values } = parseArgs({
2880
+ args: rest,
2881
+ options: { "database-url": { type: "string" } },
2882
+ strict: true
2883
+ });
2884
+ const { migrateCommand } = await loadMigrate();
2885
+ await migrateCommand({ databaseUrl: values["database-url"] ?? env.DATABASE_URL }, io);
2886
+ return EXIT.ok;
2887
+ }
2888
+ case "mcp": {
2889
+ const { values } = parseArgs({
2890
+ args: rest,
2891
+ options: {
2892
+ url: { type: "string" },
2893
+ key: { type: "string" },
2894
+ workspace: { type: "string" }
2895
+ },
2896
+ strict: true
2897
+ });
2898
+ const key = values.key ?? env.MAILSINK_KEY;
2899
+ if (!key) throw new Error("MAILSINK_KEY (or --key) is required");
2900
+ const { mcpCommand } = await import("./mcp-CN6V5uOE.mjs");
2901
+ await mcpCommand({
2902
+ url: values.url ?? env.MAILSINK_URL ?? "http://localhost:3000",
2903
+ key,
2904
+ workspace: values.workspace ?? env.MAILSINK_WORKSPACE
2905
+ }, io);
2906
+ return EXIT.ok;
2907
+ }
2908
+ default:
2909
+ io.err(`Unknown command "${command}".\n\n${USAGE}`);
2910
+ return EXIT.usage;
2911
+ }
2912
+ } catch (error) {
2913
+ const failure = describeFailure(error);
2914
+ io.err(failure.message);
2915
+ return failure.code;
2916
+ }
2917
+ }
2918
+ // src/bin.ts
2919
+ const code = await run(process.argv.slice(2), process.env, {
2920
+ out: (line) => process.stdout.write(`${line}\n`),
2921
+ err: (line) => process.stderr.write(`${line}\n`)
2922
+ });
2923
+ process.exitCode = code;
2924
+ export {};