@devitek/mailsink-cli 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -46,7 +46,8 @@ Settings come from flags or from `MAILSINK_URL`, `MAILSINK_ADMIN_KEY`, `MAILSINK
46
46
  `MAILSINK_WORKSPACE`. Exit codes: `0` success, `1` failure, `2` invalid command line, `3`
47
47
  `wait` timed out.
48
48
 
49
- Full guide: [docs/guides/cli.md](https://github.com/Devitek/mailsink/blob/main/docs/guides/cli.md).
49
+ Full guide: [command line](https://mailsink.devitek.fr/guides/cli/) in the
50
+ [Mailsink documentation](https://mailsink.devitek.fr).
50
51
 
51
52
  ## License
52
53
 
package/dist/bin.mjs CHANGED
@@ -142,6 +142,7 @@ const DeliveryStatus = z.enum([
142
142
  "hard_bounce",
143
143
  "complained",
144
144
  "failed",
145
+ "invalid",
145
146
  "suppressed"
146
147
  ]);
147
148
  /** Final statuses the simulation can draw (queued, sent and suppressed are not drawn). */
@@ -161,7 +162,8 @@ const CanonicalEvent = z.enum([
161
162
  "email.opened",
162
163
  "email.clicked",
163
164
  "email.suppressed",
164
- "email.failed"
165
+ "email.failed",
166
+ "email.invalid"
165
167
  ]);
166
168
  const ConnectionKind = z.enum([
167
169
  "resend",
@@ -183,6 +185,7 @@ const EventType = z.enum([
183
185
  "hard_bounce",
184
186
  "complained",
185
187
  "failed",
188
+ "invalid",
186
189
  "suppressed",
187
190
  "opened",
188
191
  "clicked"
@@ -482,7 +485,6 @@ const BrevoErrorCode = z.enum([
482
485
  "permission_denied",
483
486
  "document_not_found",
484
487
  "duplicate_parameter",
485
- "duplicate_request",
486
488
  "too_many_requests",
487
489
  "chaos_injected",
488
490
  "internal_error"
@@ -491,6 +493,81 @@ z.object({
491
493
  code: BrevoErrorCode,
492
494
  message: z.string()
493
495
  });
496
+ // ../contracts/src/brevo-read.ts
497
+ /** A YYYY-MM-DD calendar day that exists (2026-02-30 does not). */
498
+ const BrevoDay = z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "Use the YYYY-MM-DD format").refine((d) => (/* @__PURE__ */ new Date(`${d}T00:00:00Z`)).toISOString().startsWith(d), "Invalid date");
499
+ /** Last day of the one month window starting at `start` (2026-01-31 -> 2026-02-28). */
500
+ function brevoMonthEnd(start) {
501
+ const [y, m, d] = start.split("-").map(Number);
502
+ const lastOfNext = new Date(Date.UTC(y, m + 1, 0)).getUTCDate();
503
+ return new Date(Date.UTC(y, m, Math.min(d, lastOfNext))).toISOString().slice(0, 10);
504
+ }
505
+ const Sort = z.enum(["asc", "desc"]).default("desc");
506
+ const Offset = z.coerce.number().int().min(0).default(0);
507
+ const bothDatesOrNone = (q) => q.startDate === void 0 === (q.endDate === void 0);
508
+ const datesInOrder = (q) => !q.startDate || !q.endDate || q.startDate <= q.endDate;
509
+ const dateIssue = issue("date_range_required", "startDate and endDate go together", ["startDate"]);
510
+ const orderIssue = issue("date_range_order", "endDate must not be before startDate", ["endDate"]);
511
+ z.object({
512
+ email: Email.optional(),
513
+ templateId: TemplateExternalId.optional(),
514
+ messageId: z.string().trim().min(1).optional(),
515
+ startDate: BrevoDay.optional(),
516
+ endDate: BrevoDay.optional(),
517
+ sort: Sort,
518
+ limit: z.coerce.number().int().min(0).max(500).default(500),
519
+ offset: Offset
520
+ }).refine((q) => q.email !== void 0 || q.templateId !== void 0 || q.messageId !== void 0, issue("filter_required", "email, templateId or messageId is required", ["email"])).refine(bothDatesOrNone, dateIssue).refine(datesInOrder, orderIssue).refine((q) => !q.startDate || !q.endDate || q.endDate <= brevoMonthEnd(q.startDate), issue("date_range_too_long", "The date range is at most one month", ["endDate"]));
521
+ const BrevoTransactionalEmail = z.object({
522
+ email: z.string(),
523
+ subject: z.string(),
524
+ templateId: z.number().int().optional(),
525
+ messageId: z.string(),
526
+ uuid: z.string(),
527
+ date: z.string(),
528
+ from: z.string().optional(),
529
+ tags: z.array(z.string()).optional()
530
+ });
531
+ z.object({
532
+ count: z.number().int(),
533
+ transactionalEmails: z.array(BrevoTransactionalEmail)
534
+ });
535
+ /** `senders`: comma separated, also repeated (`senders=a&senders=b`, the SDK sends both). */
536
+ const Senders = z.union([z.string(), z.array(z.string())]).transform((v) => [...new Set([v].flat().flatMap((s) => s.split(",")).map((s) => s.trim().toLowerCase()).filter(Boolean))]);
537
+ /** Coarse check without the workspace timezone: past today at UTC+14, the furthest zone
538
+ * (core checks the day of the workspace timezone, D284). */
539
+ const notInFuture = (d) => !d || d <= new Date(Date.now() + 504e5).toISOString().slice(0, 10);
540
+ z.object({
541
+ startDate: BrevoDay.optional(),
542
+ endDate: BrevoDay.optional(),
543
+ limit: z.coerce.number().int().min(0).max(100).default(50),
544
+ offset: Offset,
545
+ senders: Senders.optional(),
546
+ sort: Sort
547
+ }).refine(bothDatesOrNone, dateIssue).refine(datesInOrder, orderIssue).refine((q) => notInFuture(q.startDate) && notInFuture(q.endDate), issue("date_in_future", "Dates cannot be in the future", ["endDate"]));
548
+ /** Reason codes of Brevo; Mailsink lists `hardBounce`, `contactFlaggedAsSpam`, `adminBlocked`. */
549
+ const BrevoBlockReasonCode = z.enum([
550
+ "unsubscribedViaMA",
551
+ "unsubscribedViaEmail",
552
+ "adminBlocked",
553
+ "unsubscribedViaApi",
554
+ "hardBounce",
555
+ "contactFlaggedAsSpam"
556
+ ]);
557
+ const BrevoBlockedContact = z.object({
558
+ email: z.string(),
559
+ senderEmail: z.string().nullable(),
560
+ reason: z.object({
561
+ code: BrevoBlockReasonCode,
562
+ message: z.string()
563
+ }),
564
+ blockedAt: z.string()
565
+ });
566
+ z.object({
567
+ contacts: z.array(BrevoBlockedContact),
568
+ count: z.number().int()
569
+ });
570
+ z.object({ email: Email });
494
571
  // ../contracts/src/webhook.ts
495
572
  const PayloadFormat = z.enum([
496
573
  "unified",
@@ -727,14 +804,7 @@ z.discriminatedUnion("type", [
727
804
  }),
728
805
  z.object({
729
806
  type: z.literal("status"),
730
- status: z.enum([
731
- "delivered",
732
- "deferred",
733
- "soft_bounce",
734
- "hard_bounce",
735
- "complained",
736
- "failed"
737
- ]),
807
+ status: SimulatedStatus,
738
808
  recipient: z.email().optional(),
739
809
  reason: z.string().max(500).optional()
740
810
  })
@@ -1137,6 +1207,30 @@ const SettingsSection = z.enum([
1137
1207
  ]);
1138
1208
  z.object({ section: SettingsSection.optional().catch(void 0) });
1139
1209
  z.object({ email: urlText });
1210
+ // ../contracts/src/server-clock.ts
1211
+ const HEADER_PRECISION_MS = 1e3;
1212
+ function createServerClock(clientNow = Date.now) {
1213
+ let lower = Number.NEGATIVE_INFINITY;
1214
+ let upper = Number.POSITIVE_INFINITY;
1215
+ const offset = () => Math.min(Math.max(0, lower), upper);
1216
+ return {
1217
+ now: () => new Date(clientNow() + offset()),
1218
+ offset,
1219
+ observe(dateHeader, sentAt, receivedAt) {
1220
+ const serverAt = dateHeader ? Date.parse(dateHeader) : NaN;
1221
+ if (Number.isNaN(serverAt)) return;
1222
+ const low = serverAt - receivedAt;
1223
+ const high = serverAt + HEADER_PRECISION_MS - sentAt;
1224
+ if (Math.max(low, lower) <= Math.min(high, upper)) {
1225
+ lower = Math.max(low, lower);
1226
+ upper = Math.min(high, upper);
1227
+ } else {
1228
+ lower = low;
1229
+ upper = high;
1230
+ }
1231
+ }
1232
+ };
1233
+ }
1140
1234
  // ../contracts/src/stream.ts
1141
1235
  const StreamEvent = z.discriminatedUnion("type", [
1142
1236
  z.object({
@@ -1288,7 +1382,9 @@ z.object({
1288
1382
  "opened",
1289
1383
  "click",
1290
1384
  "deferred",
1291
- "blocked"
1385
+ "blocked",
1386
+ "invalid_email",
1387
+ "error"
1292
1388
  ]),
1293
1389
  email: z.string(),
1294
1390
  id: z.number().int(),
@@ -1366,7 +1462,7 @@ const codeForStatus = (status) => CODE_BY_STATUS[status] ?? "internal_error";
1366
1462
  * earliest one of the page (the first that arrived) as a full detail.
1367
1463
  */
1368
1464
  async function waitForMessage(t, reader, filters, options) {
1369
- const since = options.since ?? filters.since ?? /* @__PURE__ */ new Date();
1465
+ const since = options.since ?? filters.since ?? t.clock.now();
1370
1466
  const timeout = options.timeout ?? 1e4;
1371
1467
  const deadline = Date.now() + timeout;
1372
1468
  let last;
@@ -1428,12 +1524,13 @@ const REQUEST_ID_HEADER = "x-request-id";
1428
1524
  const WORKSPACE_HEADER = "x-mailsink-workspace";
1429
1525
  /** Path segment, encoded: `path\`/capture/messages/${id}\``. */
1430
1526
  const seg = (value) => encodeURIComponent(value);
1431
- function createTransport(options) {
1527
+ function createTransport(options, clock = createServerClock()) {
1432
1528
  const base = new URL(String(options.url));
1433
1529
  if (!base.pathname.endsWith("/")) base.pathname += "/";
1434
1530
  const doFetch = options.fetch ?? ((input, init) => globalThis.fetch(input, init));
1435
1531
  const transport = {
1436
1532
  options,
1533
+ clock,
1437
1534
  url(path, query) {
1438
1535
  const url = new URL(path.replace(/^\//, ""), base);
1439
1536
  if (query) url.search = toSearchParams(query).toString();
@@ -1454,6 +1551,7 @@ function createTransport(options) {
1454
1551
  body = JSON.stringify(call.body);
1455
1552
  }
1456
1553
  let response;
1554
+ const sentAt = Date.now();
1457
1555
  try {
1458
1556
  response = await doFetch(transport.url(call.path, call.query), {
1459
1557
  method: call.method,
@@ -1469,6 +1567,7 @@ function createTransport(options) {
1469
1567
  cause
1470
1568
  });
1471
1569
  }
1570
+ clock.observe(response.headers.get("date"), sentAt, Date.now());
1472
1571
  if (!response.ok) throw await errorFrom(response);
1473
1572
  return response;
1474
1573
  },
@@ -2146,7 +2245,10 @@ function sleep(ms, signal) {
2146
2245
  * ```
2147
2246
  */
2148
2247
  function createMailsink(options) {
2149
- const t = createTransport(options);
2248
+ return build(options, createServerClock());
2249
+ }
2250
+ function build(options, clock) {
2251
+ const t = createTransport(options, clock);
2150
2252
  return {
2151
2253
  options: t.options,
2152
2254
  admin: {
@@ -2168,10 +2270,14 @@ subscribe: (handler, subscribeOptions) => subscribe(t, handler, subscribeOptions
2168
2270
  * A client with some options changed, e.g. scoped to the workspace just created:
2169
2271
  * `mailsink.with({ key: created.workspaceKey })`.
2170
2272
  */
2171
- with: (patch) => createMailsink({
2172
- ...options,
2173
- ...patch
2174
- })
2273
+ with: (patch) => {
2274
+ const next = {
2275
+ ...options,
2276
+ ...patch
2277
+ };
2278
+ return build(next, String(next.url) === String(options.url) ? clock : createServerClock());
2279
+ },
2280
+ now: () => clock.now()
2175
2281
  };
2176
2282
  }
2177
2283
  // ../sdk/src/helpers/links.ts
@@ -2405,7 +2511,8 @@ const RATE_FLAGS = {
2405
2511
  "soft-bounce": "soft_bounce",
2406
2512
  "hard-bounce": "hard_bounce",
2407
2513
  complained: "complained",
2408
- failed: "failed"
2514
+ failed: "failed",
2515
+ invalid: "invalid"
2409
2516
  };
2410
2517
  const rateOptions = Object.fromEntries(Object.keys(RATE_FLAGS).map((flag) => [flag, { type: "string" }]));
2411
2518
  async function overrideCommand(argv, env, io) {
@@ -2698,8 +2805,9 @@ Piloting (HTTP API, for CI and shell scripts):
2698
2805
  [--connection <id>] [--since <iso|now|5m>] [--timeout 10s] [--link <s>]
2699
2806
  Wait for a matching message (exit code 3 on timeout)
2700
2807
  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]
2808
+ [--failed 1] [--invalid 1] [--delivered 50] [--latency 100-500]
2809
+ [--error-rate 10] [--rule '<glob>=<status>']... [--config <json>]
2810
+ [--ttl 10m]
2703
2811
  [--connection <id>]
2704
2812
  Activate a simulation override (rates in %, latency in ms)
2705
2813
  mailsink override reset [--connection <id>]
@@ -2736,7 +2844,7 @@ const DB_PEERS = [
2736
2844
  */
2737
2845
  async function loadMigrate() {
2738
2846
  try {
2739
- return await import("./migrate-MfcW916y.mjs");
2847
+ return await import("./migrate-yxDoMMKo.mjs");
2740
2848
  } catch (error) {
2741
2849
  const code = error.code;
2742
2850
  const missing = DB_PEERS.find((name) => String(error).includes(`'${name}`));
@@ -103,6 +103,7 @@ const deliveryStatus = pgEnum("delivery_status", [
103
103
  "hard_bounce",
104
104
  "complained",
105
105
  "failed",
106
+ "invalid",
106
107
  "suppressed"
107
108
  ]);
108
109
  const eventType = pgEnum("event_type", [
@@ -114,6 +115,7 @@ const eventType = pgEnum("event_type", [
114
115
  "hard_bounce",
115
116
  "complained",
116
117
  "failed",
118
+ "invalid",
117
119
  "suppressed",
118
120
  "opened",
119
121
  "clicked"
@@ -150,7 +152,8 @@ const webhookEvent = pgEnum("webhook_event", [
150
152
  "email.opened",
151
153
  "email.clicked",
152
154
  "email.suppressed",
153
- "email.failed"
155
+ "email.failed",
156
+ "email.invalid"
154
157
  ]);
155
158
  const brevoAuthType = pgEnum("brevo_auth_type", [
156
159
  "none",
@@ -0,0 +1,47 @@
1
+ ALTER TYPE "public"."delivery_status" ADD VALUE 'invalid' BEFORE 'suppressed';--> statement-breakpoint
2
+ ALTER TYPE "public"."event_type" ADD VALUE 'invalid' BEFORE 'suppressed';--> statement-breakpoint
3
+ -- Hand-written (#153): webhook_event is recreated instead of `ADD VALUE`, because a value
4
+ -- added to an existing enum cannot be used in the migration transaction, and the backfill
5
+ -- below writes 'email.invalid'.
6
+ ALTER TYPE "public"."webhook_event" RENAME TO "webhook_event_0003";--> statement-breakpoint
7
+ CREATE TYPE "public"."webhook_event" AS ENUM('email.sent', 'email.delivered', 'email.deferred', 'email.soft_bounced', 'email.hard_bounced', 'email.complained', 'email.opened', 'email.clicked', 'email.suppressed', 'email.failed', 'email.invalid');--> statement-breakpoint
8
+ ALTER TABLE "webhook_endpoints" ALTER COLUMN "events" SET DATA TYPE "public"."webhook_event"[] USING "events"::text[]::"public"."webhook_event"[];--> statement-breakpoint
9
+ ALTER TABLE "webhook_deliveries" ALTER COLUMN "canonical_event" SET DATA TYPE "public"."webhook_event" USING "canonical_event"::text::"public"."webhook_event";--> statement-breakpoint
10
+ DROP TYPE "public"."webhook_event_0003";--> statement-breakpoint
11
+ -- Resend emits email.invalid as `email.failed` (D280): a Resend endpoint subscribed to it keeps
12
+ -- receiving every event of that name.
13
+ UPDATE "webhook_endpoints" SET "events" = array_append("events", 'email.invalid')
14
+ WHERE "payload_format" = 'resend' AND 'email.failed' = ANY("events")
15
+ AND NOT 'email.invalid' = ANY("events");--> statement-breakpoint
16
+ -- Credentials written in a brevo endpoint URL before D278 move to brevo_auth basic,
17
+ -- percent-decoded like decodeURIComponent (a part that does not decode is kept as written),
18
+ -- as create and PATCH do now (D281). Other rows keep the send-time fallback.
19
+ CREATE FUNCTION pg_temp.mailsink_percent_decode(value text) RETURNS text LANGUAGE plpgsql AS $$
20
+ BEGIN
21
+ IF value = '' THEN
22
+ RETURN '';
23
+ END IF;
24
+ RETURN (
25
+ SELECT convert_from(string_agg(
26
+ CASE WHEN t.m[1] IS NOT NULL THEN decode(substr(t.m[1], 2), 'hex')
27
+ ELSE convert_to(t.m[2], 'UTF8') END, ''::bytea ORDER BY t.n), 'UTF8')
28
+ FROM regexp_matches(value, '(%[0-9A-Fa-f]{2})|([^%]+|%)', 'g') WITH ORDINALITY AS t(m, n)
29
+ );
30
+ EXCEPTION WHEN OTHERS THEN
31
+ RETURN value;
32
+ END
33
+ $$;--> statement-breakpoint
34
+ WITH "split" AS (
35
+ SELECT "id", regexp_match("url", '^([A-Za-z][A-Za-z0-9+.-]*://)([^/?#]*)@(.*)$') AS "m"
36
+ FROM "webhook_endpoints"
37
+ WHERE "payload_format" = 'brevo' AND "brevo_auth" = 'none'
38
+ AND "url" ~ '^[A-Za-z][A-Za-z0-9+.-]*://[^/?#]*@'
39
+ )
40
+ UPDATE "webhook_endpoints" AS "e" SET
41
+ "url" = "s"."m"[1] || "s"."m"[3],
42
+ "brevo_auth" = 'basic',
43
+ "secret" = pg_temp.mailsink_percent_decode(split_part("s"."m"[2], ':', 1)) || ':' ||
44
+ pg_temp.mailsink_percent_decode(CASE WHEN position(':' in "s"."m"[2]) > 0
45
+ THEN substr("s"."m"[2], position(':' in "s"."m"[2]) + 1) ELSE '' END)
46
+ FROM "split" AS "s" WHERE "e"."id" = "s"."id";--> statement-breakpoint
47
+ DROP FUNCTION pg_temp.mailsink_percent_decode(text);