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