@crvouga/mockingbird-notifications 0.12.0 → 0.14.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.
Files changed (38) hide show
  1. package/README.md +25 -14
  2. package/dist/admin-gateway.d.ts +19 -0
  3. package/dist/admin-gateway.js +10 -0
  4. package/dist/browser.bundle-MOA3BSWW.js +6 -0
  5. package/dist/browser.bundle-MOA3BSWW.js.map +7 -0
  6. package/dist/chunk-5MRZJQ6J.js +1254 -0
  7. package/dist/chunk-5MRZJQ6J.js.map +7 -0
  8. package/dist/chunk-NMW2EZL2.js +200 -0
  9. package/dist/chunk-NMW2EZL2.js.map +7 -0
  10. package/dist/chunk-T6QHUV5K.js +206 -0
  11. package/dist/chunk-T6QHUV5K.js.map +7 -0
  12. package/dist/chunk-ZIE3JCV6.js +26 -0
  13. package/dist/chunk-ZIE3JCV6.js.map +7 -0
  14. package/dist/cli.js +4 -4
  15. package/dist/client.bundle-YOZJSCGX.js +6 -0
  16. package/dist/client.bundle-YOZJSCGX.js.map +7 -0
  17. package/dist/{document-OSYEGZSQ.js → document-JPNN2BT5.js} +2 -2
  18. package/dist/document-JPNN2BT5.js.map +7 -0
  19. package/dist/index.js +4 -6
  20. package/dist/index.js.map +1 -1
  21. package/dist/{chunk-QQK27AFM.js → page-J3NUKUUA.js} +34 -306
  22. package/dist/page-J3NUKUUA.js.map +7 -0
  23. package/dist/server-Q5XLVMT2.js +17378 -0
  24. package/dist/server-Q5XLVMT2.js.map +7 -0
  25. package/dist/server.d.ts +4 -18
  26. package/dist/server.js +7 -6
  27. package/dist/ui.d.ts +36 -46
  28. package/dist/ui.js +21530 -2526
  29. package/dist/ui.js.map +4 -4
  30. package/package.json +40 -13
  31. package/dist/chunk-5DUELOZW.js +0 -1202
  32. package/dist/chunk-5DUELOZW.js.map +0 -7
  33. package/dist/chunk-5KZ24SHQ.js +0 -26
  34. package/dist/chunk-5KZ24SHQ.js.map +0 -7
  35. package/dist/chunk-JECNH6UB.js +0 -393
  36. package/dist/chunk-JECNH6UB.js.map +0 -7
  37. package/dist/chunk-QQK27AFM.js.map +0 -7
  38. /package/dist/{document-OSYEGZSQ.js.map → admin-gateway.js.map} +0 -0
@@ -0,0 +1,1254 @@
1
+ // src/model.ts
2
+ var CHANNELS = ["sms", "push", "email", "chat"];
3
+ var SERVICE_KINDS = [
4
+ "twilio",
5
+ "resend",
6
+ "fcm",
7
+ "ses",
8
+ "sns",
9
+ "customerio",
10
+ "mailosaur",
11
+ "slack",
12
+ "cognito"
13
+ ];
14
+ var SERVICE_LABELS = {
15
+ twilio: "Twilio",
16
+ resend: "Resend",
17
+ fcm: "Firebase Cloud Messaging",
18
+ ses: "Amazon SES",
19
+ sns: "Amazon SNS",
20
+ customerio: "Customer.io",
21
+ mailosaur: "Mailosaur",
22
+ slack: "Slack",
23
+ cognito: "Amazon Cognito"
24
+ };
25
+ var toMs = (value) => typeof value === "number" ? value : /^\d+$/.test(value) ? Number(value) : Date.parse(value);
26
+ var searchable = (n) => [
27
+ n.to,
28
+ n.from.address,
29
+ n.from.name ?? "",
30
+ n.preview,
31
+ n.sms?.body ?? "",
32
+ n.email?.subject ?? "",
33
+ n.email?.text ?? "",
34
+ n.push?.title ?? "",
35
+ n.push?.body ?? "",
36
+ n.chat?.text ?? ""
37
+ ].join("\n").toLowerCase();
38
+ var matches = (n, filter) => {
39
+ if (filter.channel && n.channel !== filter.channel) return false;
40
+ if (filter.service && n.service !== filter.service) return false;
41
+ if (filter.source && n.source !== filter.source) return false;
42
+ if (filter.namespace && n.namespace !== filter.namespace) return false;
43
+ if (filter.to && n.to.toLowerCase() !== filter.to.toLowerCase()) return false;
44
+ if (filter.contains && !searchable(n).includes(filter.contains.toLowerCase())) return false;
45
+ if (filter.since !== void 0 && Date.parse(n.createdAt) < toMs(filter.since)) return false;
46
+ return true;
47
+ };
48
+ var filterFromSearch = (params) => {
49
+ const filter = {};
50
+ const channel = params.get("channel");
51
+ if (channel) {
52
+ if (!CHANNELS.includes(channel))
53
+ throw new Error(`channel: expected sms, email, push or chat, got ${JSON.stringify(channel)}`);
54
+ filter.channel = channel;
55
+ }
56
+ const service = params.get("service");
57
+ if (service) {
58
+ if (!SERVICE_KINDS.includes(service))
59
+ throw new Error(`service: expected one of ${SERVICE_KINDS.join(", ")}`);
60
+ filter.service = service;
61
+ }
62
+ for (const key of ["source", "namespace", "to", "contains"]) {
63
+ const value = params.get(key);
64
+ if (value) filter[key] = value;
65
+ }
66
+ const since = params.get("since");
67
+ if (since) {
68
+ if (Number.isNaN(toMs(since))) throw new Error("since: expected ISO-8601 or epoch milliseconds");
69
+ filter.since = since;
70
+ }
71
+ return filter;
72
+ };
73
+ var filterToSearch = (filter) => {
74
+ const params = new URLSearchParams();
75
+ for (const [key, value] of Object.entries(filter))
76
+ if (value !== void 0 && value !== "") params.set(key, String(value));
77
+ return params;
78
+ };
79
+
80
+ // src/mime.ts
81
+ var utf8 = new TextDecoder();
82
+ var base64Bytes = (value) => {
83
+ const binary = atob(value.replace(/[^A-Za-z0-9+/=]/g, ""));
84
+ const bytes = new Uint8Array(binary.length);
85
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
86
+ return bytes;
87
+ };
88
+ var quotedPrintableBytes = (value, underscoreSpace = false) => {
89
+ const source = value.replace(/=\r?\n/g, "");
90
+ const out = [];
91
+ for (let i = 0; i < source.length; i++) {
92
+ const ch = source[i] ?? "";
93
+ const hex = source.slice(i + 1, i + 3);
94
+ if (ch === "=" && /^[0-9A-Fa-f]{2}$/.test(hex)) {
95
+ out.push(Number.parseInt(hex, 16));
96
+ i += 2;
97
+ } else if (underscoreSpace && ch === "_") out.push(32);
98
+ else for (const byte of new TextEncoder().encode(ch)) out.push(byte);
99
+ }
100
+ return new Uint8Array(out);
101
+ };
102
+ var decodeWords = (value) => value.replace(/\?=\s+=\?/g, "?==?").replace(
103
+ /=\?([^?]+)\?([BbQq])\?([^?]*)\?=/g,
104
+ (_, _charset, kind, text) => utf8.decode(
105
+ kind.toUpperCase() === "B" ? base64Bytes(text) : quotedPrintableBytes(text, true)
106
+ )
107
+ );
108
+ var splitHead = (raw) => {
109
+ const normalized = raw.replace(/\r\n/g, "\n");
110
+ const end = normalized.indexOf("\n\n");
111
+ const head = end < 0 ? normalized : normalized.slice(0, end);
112
+ const body = end < 0 ? "" : normalized.slice(end + 2);
113
+ const headers = {};
114
+ for (const line of head.replace(/\n[ \t]+/g, " ").split("\n")) {
115
+ const colon = line.indexOf(":");
116
+ if (colon <= 0) continue;
117
+ const name = line.slice(0, colon).trim().toLowerCase();
118
+ const value = decodeWords(line.slice(colon + 1).trim());
119
+ headers[name] = headers[name] ? `${headers[name]}, ${value}` : value;
120
+ }
121
+ return { headers, body };
122
+ };
123
+ var param = (header, name) => {
124
+ if (!header) return null;
125
+ const match = new RegExp(`${name}\\*?=(?:"([^"]*)"|([^;\\s]+))`, "i").exec(header);
126
+ return match ? match[1] ?? match[2] ?? null : null;
127
+ };
128
+ var decodeBody = (part) => {
129
+ const encoding = (part.headers["content-transfer-encoding"] ?? "").toLowerCase();
130
+ if (encoding === "base64") return base64Bytes(part.body);
131
+ if (encoding === "quoted-printable") return quotedPrintableBytes(part.body);
132
+ return new TextEncoder().encode(part.body);
133
+ };
134
+ var walk = (part, out) => {
135
+ const type = (part.headers["content-type"] ?? "text/plain").toLowerCase();
136
+ const boundary = param(part.headers["content-type"], "boundary");
137
+ if (type.startsWith("multipart/") && boundary) {
138
+ const sections = part.body.split(`--${boundary}`);
139
+ for (const section of sections.slice(1)) {
140
+ if (section.startsWith("--")) break;
141
+ walk(splitHead(section.replace(/^\n/, "")), out);
142
+ }
143
+ return;
144
+ }
145
+ const disposition = part.headers["content-disposition"] ?? "";
146
+ const filename = param(disposition, "filename") ?? param(part.headers["content-type"], "name");
147
+ if (/^attachment/i.test(disposition) || filename && !type.startsWith("text/")) {
148
+ out.attachments.push({
149
+ filename: filename ?? "attachment",
150
+ contentType: type.split(";")[0]?.trim() ?? null,
151
+ size: decodeBody(part).byteLength
152
+ });
153
+ return;
154
+ }
155
+ const text = utf8.decode(decodeBody(part)).replace(/\n$/, "");
156
+ if (type.startsWith("text/html") && out.html === null) out.html = text;
157
+ else if (type.startsWith("text/plain") && out.text === null) out.text = text;
158
+ };
159
+ var addressList = (value) => (value ?? "").split(/,(?=(?:[^"]*"[^"]*")*[^"]*$)/).map((item) => item.trim()).filter(Boolean);
160
+ var parseMime = (raw) => {
161
+ const root = splitHead(raw);
162
+ const out = {
163
+ headers: root.headers,
164
+ subject: root.headers.subject ?? "",
165
+ from: root.headers.from ?? null,
166
+ to: addressList(root.headers.to),
167
+ cc: addressList(root.headers.cc),
168
+ html: null,
169
+ text: null,
170
+ attachments: []
171
+ };
172
+ walk(root, out);
173
+ return out;
174
+ };
175
+ var decodeRawMessage = (data) => {
176
+ const compact = data.replace(/\s+/g, "");
177
+ if (/^[A-Za-z0-9+/]+=*$/.test(compact) && compact.length % 4 === 0) {
178
+ const decoded = utf8.decode(base64Bytes(compact));
179
+ if (/^[\x20-\x7e]+:/m.test(decoded)) return decoded;
180
+ }
181
+ return data;
182
+ };
183
+
184
+ // src/discovery.ts
185
+ var asServiceKind = (value) => typeof value === "string" && SERVICE_KINDS.includes(value) ? value : null;
186
+ var trimSlash = (url) => url.replace(/\/+$/, "");
187
+ var endpointsFromServices = (services, fetchImpl) => Object.entries(services).map(([name, input]) => {
188
+ if (typeof input === "string")
189
+ return {
190
+ name,
191
+ service: asServiceKind(name),
192
+ adminUrl: `${trimSlash(input)}/__admin`,
193
+ fetch: fetchImpl
194
+ };
195
+ if ("fetch" in input)
196
+ return {
197
+ name,
198
+ service: input.service ?? asServiceKind(name),
199
+ adminUrl: `http://${name}.mockingbird.local${input.adminPrefix ?? "/__admin"}`,
200
+ fetch: input.fetch
201
+ };
202
+ return {
203
+ name,
204
+ service: input.service ?? asServiceKind(name),
205
+ adminUrl: input.adminUrl ? trimSlash(input.adminUrl) : `${trimSlash(input.url)}/__admin`,
206
+ fetch: fetchImpl
207
+ };
208
+ });
209
+ var endpointsFromManifest = (manifest, fetchImpl, targets = {}) => Object.entries(manifest.services ?? {}).flatMap(([name, entry]) => {
210
+ if (!entry || entry.protocol && entry.protocol !== "http" || !entry.url) return [];
211
+ const service = asServiceKind(targets[name] ?? entry.target ?? name);
212
+ if (!service && (targets[name] ?? entry.target)) return [];
213
+ return [
214
+ {
215
+ name,
216
+ service,
217
+ adminUrl: entry.adminUrl ? trimSlash(entry.adminUrl) : `${trimSlash(entry.url)}/__admin`,
218
+ fetch: fetchImpl
219
+ }
220
+ ];
221
+ });
222
+ var adminTargetsFromServices = (services, fetchImpl) => endpointsFromServices(services, fetchImpl).map((endpoint) => ({
223
+ name: endpoint.name,
224
+ target: endpoint.service ?? endpoint.name,
225
+ adminUrl: endpoint.adminUrl,
226
+ fetch: endpoint.fetch
227
+ }));
228
+ var adminTargetsFromManifest = (manifest, fetchImpl, targets = {}) => Object.entries(manifest.services ?? {}).flatMap(([name, entry]) => {
229
+ if (!entry || entry.protocol && entry.protocol !== "http" || !entry.url) return [];
230
+ return [
231
+ {
232
+ name,
233
+ target: targets[name] ?? entry.target ?? name,
234
+ adminUrl: entry.adminUrl ? trimSlash(entry.adminUrl) : `${trimSlash(entry.url)}/__admin`,
235
+ fetch: fetchImpl
236
+ }
237
+ ];
238
+ });
239
+ var discoverFleet = async (adminBase, fetchImpl, headers) => {
240
+ const base2 = trimSlash(adminBase);
241
+ const get = async (path) => {
242
+ const response = await fetchImpl(new Request(`${base2}${path}`, { headers }));
243
+ if (!response.ok) throw new Error(`fleet ${base2}${path}: HTTP ${response.status}`);
244
+ return await response.json();
245
+ };
246
+ const [root, namespaces] = await Promise.all([
247
+ get(""),
248
+ get("/namespaces").catch(() => ({}))
249
+ ]);
250
+ const manifest = root.manifest;
251
+ if (!manifest?.services) throw new Error(`fleet ${base2}: discovery has no manifest`);
252
+ const described = root.services ?? {};
253
+ const targets = Object.fromEntries(
254
+ Object.entries(described).map(([name, entry]) => [name, entry?.target])
255
+ );
256
+ const names = Array.isArray(namespaces.namespaces) ? namespaces.namespaces.map((n) => n.namespace).filter((n) => typeof n === "string") : [];
257
+ return {
258
+ endpoints: endpointsFromManifest(manifest, fetchImpl, targets),
259
+ admins: adminTargetsFromManifest(manifest, fetchImpl, targets),
260
+ namespaces: names
261
+ };
262
+ };
263
+
264
+ // src/sources.ts
265
+ var isRow = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
266
+ var row = (value) => isRow(value) ? value : {};
267
+ var str = (value) => typeof value === "string" ? value : typeof value === "number" ? String(value) : null;
268
+ var strings = (value) => Array.isArray(value) ? value.map(str).filter((v) => v !== null && v !== "") : typeof value === "string" && value !== "" ? [value] : [];
269
+ var list = (value, key) => {
270
+ const items = isRow(value) ? value[key] : value;
271
+ return Array.isArray(items) ? items.filter(isRow) : [];
272
+ };
273
+ var iso = (value) => {
274
+ if (typeof value === "number") return new Date(value < 1e11 ? value * 1e3 : value).toISOString();
275
+ if (typeof value === "string" && !Number.isNaN(Date.parse(value)))
276
+ return new Date(value).toISOString();
277
+ return (/* @__PURE__ */ new Date(0)).toISOString();
278
+ };
279
+ var parseAddress = (value) => {
280
+ const match = /^\s*"?([^"<]*?)"?\s*<([^>]+)>\s*$/.exec(value);
281
+ if (match) return { name: match[1]?.trim() || null, address: (match[2] ?? "").trim() };
282
+ return { name: null, address: value.trim() };
283
+ };
284
+ var bare = (value) => parseAddress(value).address.toLowerCase();
285
+ var stripHtml = (html) => html.replace(/<(style|script|head)[^>]*>[\s\S]*?<\/\1>/gi, " ").replace(/<br\s*\/?>/gi, "\n").replace(/<[^>]+>/g, " ").replace(/&nbsp;/g, " ").replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/[ \t]+/g, " ").replace(/\s*\n\s*/g, "\n").trim();
286
+ var preview = (text) => text.replace(/\s+/g, " ").trim().slice(0, 240);
287
+ var base = (input, channel) => ({
288
+ id: `${input.context.source}:${input.context.namespace}:${input.providerId}${channel === "email" ? `#${input.to.toLowerCase()}` : ""}`,
289
+ providerId: input.providerId,
290
+ channel,
291
+ source: input.context.source,
292
+ service: input.service,
293
+ namespace: input.context.namespace,
294
+ to: input.to,
295
+ from: input.from,
296
+ createdAt: input.createdAt,
297
+ status: input.status ?? null,
298
+ raw: input.raw
299
+ });
300
+ var smsNotification = (input, sms) => ({
301
+ ...base(input, "sms"),
302
+ preview: preview(sms.body),
303
+ sms: {
304
+ body: sms.body,
305
+ code: sms.code ?? null,
306
+ media: sms.media ?? [],
307
+ ...sms.via === "whatsapp" ? { via: sms.via } : {}
308
+ },
309
+ email: null,
310
+ push: null,
311
+ chat: null
312
+ });
313
+ var emailNotifications = (input, recipients, email) => {
314
+ const content = {
315
+ subject: email.subject,
316
+ html: email.html ?? null,
317
+ text: email.text ?? null,
318
+ cc: email.cc ?? [],
319
+ bcc: email.bcc ?? [],
320
+ replyTo: email.replyTo ?? [],
321
+ attachments: email.attachments ?? [],
322
+ headers: email.headers ?? {}
323
+ };
324
+ const body = content.text ?? (content.html ? stripHtml(content.html) : "");
325
+ const seen = /* @__PURE__ */ new Set();
326
+ return recipients.flatMap((recipient) => {
327
+ const to = bare(recipient);
328
+ if (!to || seen.has(to)) return [];
329
+ seen.add(to);
330
+ return [
331
+ {
332
+ ...base({ ...input, to }, "email"),
333
+ preview: preview(body),
334
+ sms: null,
335
+ email: content,
336
+ push: null,
337
+ chat: null
338
+ }
339
+ ];
340
+ });
341
+ };
342
+ var pushNotification = (input, push) => ({
343
+ ...base(input, "push"),
344
+ preview: preview([push.title, push.body].filter(Boolean).join(" \u2014 ")),
345
+ sms: null,
346
+ email: null,
347
+ push,
348
+ chat: null
349
+ });
350
+ var chatNotification = (input, chat, summary) => ({
351
+ ...base(input, "chat"),
352
+ preview: preview(summary),
353
+ sms: null,
354
+ email: null,
355
+ push: null,
356
+ chat
357
+ });
358
+ var WHATSAPP = /^whatsapp:/i;
359
+ var twilio = async (context) => {
360
+ const messages = list(await context.read("/outbox"), "messages");
361
+ return messages.flatMap((m) => {
362
+ const providerId = str(m.id) ?? str(m.sid) ?? "";
363
+ const body = str(m.body) ?? "";
364
+ const recipient = str(m.to) ?? "";
365
+ const verify = m.kind === "verify";
366
+ const whatsapp = m.channel === "whatsapp" || WHATSAPP.test(recipient) || WHATSAPP.test(str(m.from) ?? "");
367
+ const to = recipient.replace(WHATSAPP, "");
368
+ const origin = str(m.from) ?? str(m.messagingServiceSid) ?? (verify ? "Verify" : "Twilio");
369
+ const sender = whatsapp ? `whatsapp:${origin.replace(WHATSAPP, "")}` : origin;
370
+ const common = {
371
+ context,
372
+ service: "twilio",
373
+ providerId,
374
+ from: { name: verify && !m.from ? "Verify" : null, address: sender },
375
+ createdAt: iso(m.createdAt),
376
+ status: str(m.status),
377
+ raw: m
378
+ };
379
+ if (m.channel === "email")
380
+ return emailNotifications(common, [to], {
381
+ subject: "Your verification code",
382
+ text: body
383
+ });
384
+ return [
385
+ smsNotification(
386
+ { ...common, to },
387
+ {
388
+ body,
389
+ code: str(m.code),
390
+ media: strings(m.mediaUrls),
391
+ ...whatsapp ? { via: "whatsapp" } : {}
392
+ }
393
+ )
394
+ ];
395
+ });
396
+ };
397
+ var resend = async (context) => list(await context.read("/outbox"), "messages").flatMap((m) => {
398
+ const cc = strings(m.cc);
399
+ const bcc = strings(m.bcc);
400
+ return emailNotifications(
401
+ {
402
+ context,
403
+ service: "resend",
404
+ providerId: str(m.id) ?? "",
405
+ from: parseAddress(str(m.from) ?? ""),
406
+ createdAt: iso(m.createdAt),
407
+ status: m.scheduledAt ? "scheduled" : "delivered",
408
+ raw: m
409
+ },
410
+ [...strings(m.to), ...cc, ...bcc],
411
+ {
412
+ subject: str(m.subject) ?? "",
413
+ html: str(m.html),
414
+ text: str(m.text),
415
+ cc,
416
+ bcc,
417
+ replyTo: strings(m.replyTo),
418
+ headers: Object.fromEntries(Object.entries(row(m.headers)).map(([k, v]) => [k, String(v)])),
419
+ attachments: list(m.attachments, "").map((a) => ({
420
+ filename: str(a.filename) ?? "attachment",
421
+ contentType: str(a.contentType),
422
+ size: typeof a.size === "number" ? a.size : null
423
+ }))
424
+ }
425
+ );
426
+ });
427
+ var platformOf = (value) => value === "android" || value === "ios" || value === "web" ? value : "unknown";
428
+ var fcm = async (context) => list(await context.read("/outbox"), "messages").map((m) => {
429
+ const wire = row(m.wire);
430
+ const notification = row(m.notification ?? wire.notification);
431
+ const android = row(row(m.android ?? wire.android).notification);
432
+ const aps = row(row(row(m.apns ?? wire.apns).payload).aps);
433
+ const alert = isRow(aps.alert) ? aps.alert : { body: aps.alert };
434
+ const webpush = row(row(wire.webpush).notification);
435
+ const platform = platformOf(m.platform);
436
+ const pick = (key) => (platform === "android" ? str(android[key]) : null) ?? (platform === "ios" ? str(alert[key]) : null) ?? (platform === "web" ? str(webpush[key]) : null) ?? str(notification[key]);
437
+ const image = (platform === "android" ? str(android.image) : null) ?? str(row(row(m.apns ?? wire.apns).fcm_options).image) ?? str(notification.image);
438
+ const project = str(m.project) ?? "app";
439
+ return pushNotification(
440
+ {
441
+ context,
442
+ service: "fcm",
443
+ providerId: str(m.id) ?? str(m.name) ?? "",
444
+ to: str(m.token) ?? "",
445
+ from: { name: project, address: str(m.name) ?? project },
446
+ createdAt: iso(m.acceptedAt),
447
+ status: str(m.state),
448
+ raw: m
449
+ },
450
+ {
451
+ title: pick("title"),
452
+ body: pick("body"),
453
+ imageUrl: image,
454
+ app: project,
455
+ platform,
456
+ data: Object.fromEntries(
457
+ Object.entries(row(m.data ?? wire.data)).map(([k, v]) => [k, String(v)])
458
+ ),
459
+ badge: typeof aps.badge === "number" ? aps.badge : null,
460
+ sound: str(aps.sound) ?? str(android.sound)
461
+ }
462
+ );
463
+ });
464
+ var stateRecords = async (read, collection) => {
465
+ const out = [];
466
+ let after = null;
467
+ for (let page = 0; page < 100; page++) {
468
+ const query = after === null ? "" : `&after=${encodeURIComponent(String(after))}`;
469
+ const result = row(await read(`/state/${collection}?limit=200&order=oldest${query}`));
470
+ for (const record of list(result, "records")) out.push(record);
471
+ if (result.next === null || result.next === void 0) break;
472
+ after = result.next;
473
+ }
474
+ return out;
475
+ };
476
+ var ses = async (context) => (await stateRecords(context.read, "ses_messages")).flatMap((record) => {
477
+ const v = row(record.value);
478
+ const destination = row(v.Destination);
479
+ const common = {
480
+ context,
481
+ service: "ses",
482
+ providerId: str(v.MessageId) ?? str(record.id) ?? "",
483
+ createdAt: iso(v.Timestamp),
484
+ status: "delivered",
485
+ raw: v
486
+ };
487
+ const raw = row(v.RawMessage);
488
+ if (raw.Data !== void 0) {
489
+ const mime = parseMime(decodeRawMessage(str(raw.Data) ?? ""));
490
+ const recipients = strings(v.Destinations);
491
+ return emailNotifications(
492
+ { ...common, from: parseAddress(str(v.Source) ?? mime.from ?? "") },
493
+ recipients.length ? recipients : [...mime.to, ...mime.cc],
494
+ {
495
+ subject: mime.subject,
496
+ html: mime.html,
497
+ text: mime.text,
498
+ cc: mime.cc,
499
+ attachments: mime.attachments,
500
+ headers: mime.headers,
501
+ replyTo: addressList(mime.headers["reply-to"])
502
+ }
503
+ );
504
+ }
505
+ const message = row(v.Message);
506
+ const body = row(message.Body);
507
+ const cc = strings(destination.CcAddresses);
508
+ const bcc = strings(destination.BccAddresses);
509
+ return emailNotifications(
510
+ { ...common, from: parseAddress(str(v.Source) ?? "") },
511
+ [...strings(destination.ToAddresses), ...cc, ...bcc],
512
+ {
513
+ subject: str(row(message.Subject).Data) ?? "",
514
+ html: str(row(body.Html).Data),
515
+ text: str(row(body.Text).Data),
516
+ cc,
517
+ bcc,
518
+ replyTo: strings(v.ReplyToAddresses)
519
+ }
520
+ );
521
+ });
522
+ var snsBody = (v, protocol) => {
523
+ const message = str(v.Message) ?? "";
524
+ if (v.MessageStructure !== "json") return message;
525
+ try {
526
+ const parsed = row(JSON.parse(message));
527
+ return str(parsed[protocol]) ?? str(parsed.default) ?? message;
528
+ } catch {
529
+ return message;
530
+ }
531
+ };
532
+ var sns = async (context) => {
533
+ const [messages, subscriptions] = await Promise.all([
534
+ stateRecords(context.read, "sns_messages"),
535
+ stateRecords(context.read, "sns_subscriptions")
536
+ ]);
537
+ return messages.flatMap((record) => {
538
+ const v = row(record.value);
539
+ const providerId = str(v.MessageId) ?? str(record.id) ?? "";
540
+ const common = { context, service: "sns", createdAt: iso(v.Timestamp), raw: v };
541
+ const phone = str(v.PhoneNumber);
542
+ if (phone)
543
+ return [
544
+ smsNotification(
545
+ {
546
+ ...common,
547
+ providerId,
548
+ to: phone,
549
+ from: { name: null, address: "SNS" },
550
+ status: "delivered"
551
+ },
552
+ { body: snsBody(v, "sms") }
553
+ )
554
+ ];
555
+ const topicArn = str(v.TopicArn) ?? "";
556
+ const topicName = topicArn.split(":").at(-1) ?? "SNS";
557
+ return subscriptions.flatMap((sub) => {
558
+ const s = row(sub.value);
559
+ if (s.TopicArn !== topicArn) return [];
560
+ const endpoint = str(s.Endpoint) ?? "";
561
+ const subId = `${providerId}@${str(s.SubscriptionArn) ?? endpoint}`;
562
+ if (s.Protocol === "sms")
563
+ return [
564
+ smsNotification(
565
+ {
566
+ ...common,
567
+ providerId: subId,
568
+ to: endpoint,
569
+ from: { name: topicName, address: topicName },
570
+ status: "delivered"
571
+ },
572
+ { body: snsBody(v, "sms") }
573
+ )
574
+ ];
575
+ if (s.Protocol === "email" || s.Protocol === "email-json") {
576
+ const text = s.Protocol === "email-json" ? JSON.stringify(
577
+ {
578
+ Type: "Notification",
579
+ MessageId: providerId,
580
+ TopicArn: topicArn,
581
+ Subject: v.Subject ?? null,
582
+ Message: snsBody(v, "email-json")
583
+ },
584
+ null,
585
+ 2
586
+ ) : `${snsBody(v, "email")}
587
+
588
+ --
589
+ If you wish to stop receiving notifications from this topic, please unsubscribe.
590
+
591
+ Please do not reply directly to this email. If you have any questions or comments regarding this email, please contact us at https://aws.amazon.com/support`;
592
+ return emailNotifications(
593
+ {
594
+ ...common,
595
+ providerId: subId,
596
+ from: { name: "AWS Notifications", address: "no-reply@sns.amazonaws.com" },
597
+ status: "delivered"
598
+ },
599
+ [endpoint],
600
+ { subject: str(v.Subject) ?? "AWS Notification Message", text }
601
+ );
602
+ }
603
+ return [];
604
+ });
605
+ });
606
+ };
607
+ var escapeHtml = (value) => value.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
608
+ var templatePreview = (m) => {
609
+ const data = Object.entries(row(m.messageData));
610
+ const rows = data.map(
611
+ ([k, v]) => `<tr><td style="padding:6px 12px;color:#6b7280;font:13px system-ui">${escapeHtml(k)}</td><td style="padding:6px 12px;font:13px ui-monospace,monospace">${escapeHtml(typeof v === "string" ? v : JSON.stringify(v))}</td></tr>`
612
+ ).join("");
613
+ const links = strings(m.links).map(
614
+ (href) => `<p style="font:13px system-ui"><a href="${escapeHtml(href)}">${escapeHtml(href)}</a></p>`
615
+ ).join("");
616
+ return `<div style="font:14px system-ui;color:#111827;padding:8px"><p style="margin:0 0 4px;color:#6b7280;font-size:12px">Customer.io transactional message <b>${escapeHtml(str(m.transactionalMessageId) ?? "")}</b></p><p style="margin:0 0 12px;color:#6b7280;font-size:12px">The template body is rendered by Customer.io; these are the <code>message_data</code> values it was sent with.</p>${rows ? `<table style="border-collapse:collapse;border:1px solid #e5e7eb;border-radius:8px">${rows}</table>` : "<p><i>No message_data.</i></p>"}${links}</div>`;
617
+ };
618
+ var customerio = async (context) => list(await context.read("/outbox"), "messages").flatMap((m) => {
619
+ const identifiers = row(m.identifiers);
620
+ const to = str(m.to) ?? str(identifiers.email) ?? str(identifiers.id) ?? "";
621
+ const state = str(m.state);
622
+ const common = {
623
+ context,
624
+ service: "customerio",
625
+ providerId: str(m.id) ?? "",
626
+ createdAt: iso(m.createdAt),
627
+ status: state,
628
+ raw: m
629
+ };
630
+ const templateId = str(m.transactionalMessageId) ?? "message";
631
+ if (m.channel === "sms") {
632
+ const data = row(m.messageData);
633
+ const body = str(data.body) ?? str(data.message) ?? str(data.text) ?? `[${templateId}] ${Object.entries(data).map(([k, v]) => `${k}: ${typeof v === "string" ? v : JSON.stringify(v)}`).join(", ")}`.trim();
634
+ return [
635
+ smsNotification(
636
+ { ...common, to, from: { name: null, address: str(m.from) ?? "Customer.io" } },
637
+ { body }
638
+ )
639
+ ];
640
+ }
641
+ if (m.channel === "email")
642
+ return emailNotifications(
643
+ { ...common, from: parseAddress(str(m.from) ?? "Customer.io <no-reply@customer.io>") },
644
+ [to],
645
+ {
646
+ subject: str(m.subject) ?? `Transactional message ${templateId}`,
647
+ html: templatePreview(m),
648
+ attachments: strings(m.attachments).map((filename) => ({
649
+ filename,
650
+ contentType: null,
651
+ size: null
652
+ }))
653
+ }
654
+ );
655
+ return [];
656
+ });
657
+ var mailosaurAddress = (value) => {
658
+ const a = row(value);
659
+ return str(a.email) ?? str(a.phone) ?? str(a.phoneNumber) ?? "";
660
+ };
661
+ var mailosaur = async (context) => list(await context.read("/outbox"), "messages").flatMap((entry) => {
662
+ const m = row(entry.message);
663
+ const from = row(list(m.from, "")[0]);
664
+ const recipients = list(m.to, "").map(mailosaurAddress).filter(Boolean);
665
+ const common = {
666
+ context,
667
+ service: "mailosaur",
668
+ providerId: str(entry.id) ?? str(m.id) ?? "",
669
+ createdAt: iso(m.received ?? entry.createdAt),
670
+ status: "received",
671
+ raw: entry
672
+ };
673
+ const html = str(row(m.html).body);
674
+ const text = str(row(m.text).body);
675
+ if (m.type === "SMS")
676
+ return recipients.map(
677
+ (to) => smsNotification(
678
+ {
679
+ ...common,
680
+ to,
681
+ from: { name: str(from.name) || null, address: mailosaurAddress(from) }
682
+ },
683
+ { body: text ?? (html ? stripHtml(html) : "") }
684
+ )
685
+ );
686
+ return emailNotifications(
687
+ { ...common, from: { name: str(from.name) || null, address: mailosaurAddress(from) } },
688
+ [...recipients, ...list(m.cc, "").map(mailosaurAddress)],
689
+ {
690
+ subject: str(m.subject) ?? "",
691
+ html,
692
+ text,
693
+ cc: list(m.cc, "").map(mailosaurAddress),
694
+ attachments: list(m.attachments, "").map((a) => ({
695
+ filename: str(a.fileName) ?? str(a.filename) ?? "attachment",
696
+ contentType: str(a.contentType),
697
+ size: typeof a.length === "number" ? a.length : null
698
+ }))
699
+ }
700
+ );
701
+ });
702
+ var mrkdwnText = (text, names) => text.replace(/<@([A-Z0-9]+)(?:\|([^>]*))?>/g, (_, id, label) => {
703
+ return `@${label || names.get(id) || id}`;
704
+ }).replace(/<#([A-Z0-9]+)(?:\|([^>]*))?>/g, (_, id, label) => {
705
+ return `#${label || names.get(id) || id}`;
706
+ }).replace(/<!(here|channel|everyone)(?:\|[^>]*)?>/g, "@$1").replace(/<([^|>]+)\|([^>]*)>/g, "$2").replace(/<([^>]+)>/g, "$1").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&");
707
+ var blockText = (value, out = []) => {
708
+ if (Array.isArray(value)) for (const item of value) blockText(item, out);
709
+ if (!isRow(value)) return out;
710
+ for (const key of ["pretext", "title", "text", "alt_text", "footer"]) {
711
+ const text = value[key];
712
+ if (typeof text === "string" && text.trim() !== "") out.push(text);
713
+ else blockText(text, out);
714
+ }
715
+ for (const field of list(value.fields, "")) {
716
+ const pair = [str(field.title), str(field.value)].filter(Boolean).join(": ");
717
+ if (pair) out.push(pair);
718
+ else blockText(field, out);
719
+ }
720
+ blockText(value.elements, out);
721
+ blockText(value.blocks, out);
722
+ return out;
723
+ };
724
+ var optional = (read, path) => read(path).catch(() => null);
725
+ var slack = async (context) => {
726
+ const [outbox, channelList, userList, settings] = await Promise.all([
727
+ context.read("/outbox"),
728
+ optional(context.read, "/channels"),
729
+ optional(context.read, "/users"),
730
+ optional(context.read, "/settings")
731
+ ]);
732
+ const team = row(settings);
733
+ const names = /* @__PURE__ */ new Map();
734
+ const people = /* @__PURE__ */ new Map();
735
+ for (const channel of list(channelList, "channels"))
736
+ if (str(channel.id) && str(channel.name))
737
+ names.set(str(channel.id) ?? "", str(channel.name) ?? "");
738
+ for (const user of list(userList, "users")) {
739
+ const id = str(user.id) ?? "";
740
+ people.set(id, user);
741
+ names.set(id, str(user.name) ?? id);
742
+ }
743
+ const bot = str(team.botUserId);
744
+ return list(outbox, "messages").map((m) => {
745
+ const webhook = str(m.webhook);
746
+ const channel = str(m.channel) ?? webhook ?? "";
747
+ const name = strings(m.to).find((entry) => entry.startsWith("#")) ?? names.get(channel);
748
+ const ephemeral = m.ephemeral === true;
749
+ const author = webhook ? null : ephemeral ? bot : str(m.user) ?? bot;
750
+ const person = row(author ? people.get(author) : null);
751
+ const text = str(m.text) ?? "";
752
+ const blocks = Array.isArray(m.blocks) ? m.blocks : [];
753
+ const attachments = Array.isArray(m.attachments) ? m.attachments : [];
754
+ const summary = text || [...blockText(blocks), ...blockText(attachments)].join(" ");
755
+ const body = JSON.stringify([text, blocks, attachments]);
756
+ const mentioned = Object.fromEntries([...names].filter(([id]) => id && body.includes(id)));
757
+ return chatNotification(
758
+ {
759
+ context,
760
+ service: "slack",
761
+ providerId: str(m.id) ?? `${channel}:${str(m.ts) ?? ""}`,
762
+ to: webhook ?? (name ? `#${name.replace(/^#/, "")}` : channel),
763
+ from: webhook ? { name: "Incoming Webhook", address: "incoming-webhook" } : {
764
+ name: str(person.real_name) ?? str(person.name) ?? null,
765
+ address: author ?? "bot"
766
+ },
767
+ createdAt: iso(m.createdAt),
768
+ status: ephemeral ? "ephemeral" : null,
769
+ raw: m
770
+ },
771
+ {
772
+ text,
773
+ workspace: str(team.teamName) ?? str(m.workspace),
774
+ method: str(m.method) ?? (webhook ? "incoming-webhook" : "chat.postMessage"),
775
+ blocks,
776
+ attachments,
777
+ threadTs: str(m.thread_ts),
778
+ ephemeral,
779
+ edited: isRow(m.edited),
780
+ reactions: list(m.reactions, "").map((reaction) => ({
781
+ name: str(reaction.name) ?? "",
782
+ count: typeof reaction.count === "number" ? reaction.count : 1
783
+ })),
784
+ names: mentioned
785
+ },
786
+ mrkdwnText(summary, names)
787
+ );
788
+ });
789
+ };
790
+ var cognito = async (context) => list(await context.read("/outbox"), "messages").flatMap((m) => {
791
+ const to = str(m.to) ?? "";
792
+ const body = str(m.body) ?? "";
793
+ const common = {
794
+ context,
795
+ service: "cognito",
796
+ providerId: str(m.id) ?? "",
797
+ createdAt: iso(m.createdAt),
798
+ status: "delivered",
799
+ raw: m
800
+ };
801
+ if (m.channel === "sms")
802
+ return [
803
+ smsNotification(
804
+ { ...common, to, from: { name: null, address: str(m.from) ?? "Cognito" } },
805
+ { body, code: str(m.code) }
806
+ )
807
+ ];
808
+ return emailNotifications(
809
+ { ...common, from: parseAddress(str(m.from) ?? "no-reply@verificationemail.com") },
810
+ [to],
811
+ { subject: str(m.subject) ?? "Your verification code", text: body }
812
+ );
813
+ });
814
+ var READERS = {
815
+ twilio,
816
+ resend,
817
+ fcm,
818
+ ses,
819
+ sns,
820
+ customerio,
821
+ mailosaur,
822
+ slack,
823
+ cognito
824
+ };
825
+
826
+ // src/harness.ts
827
+ var json = (status, body, headers = {}) => new Response(JSON.stringify(body, null, 2), {
828
+ status,
829
+ headers: { "content-type": "application/json; charset=utf-8", ...headers }
830
+ });
831
+ var errorBody = (status, message) => json(status, { error: { type: "mockingbird_notifications", message } });
832
+ var REDISCOVER_MS = 2e3;
833
+ var DUPLICATE_WINDOW_MS = 1e4;
834
+ var fingerprint = (n) => [
835
+ n.channel,
836
+ n.namespace,
837
+ n.to.toLowerCase(),
838
+ n.from.address.toLowerCase(),
839
+ n.email?.subject ?? "",
840
+ n.preview
841
+ ].join("\0");
842
+ var dedupe = (items) => {
843
+ const senders = /* @__PURE__ */ new Map();
844
+ for (const n of items)
845
+ if (n.service !== "mailosaur") {
846
+ const key = fingerprint(n);
847
+ senders.set(key, [...senders.get(key) ?? [], Date.parse(n.createdAt)]);
848
+ }
849
+ return items.filter((n) => {
850
+ if (n.service !== "mailosaur") return true;
851
+ const at = Date.parse(n.createdAt);
852
+ return !(senders.get(fingerprint(n)) ?? []).some((t) => Math.abs(t - at) <= DUPLICATE_WINDOW_MS);
853
+ });
854
+ };
855
+ var byTime = (a, b) => a.createdAt === b.createdAt ? a.id.localeCompare(b.id) : a.createdAt < b.createdAt ? -1 : 1;
856
+ var createNotificationHarness = (options = {}) => {
857
+ if (!options.fleet && !options.manifest && !options.services)
858
+ throw new Error("createNotificationHarness: pass fleet, manifest or services");
859
+ const fetchImpl = options.fetch ?? ((request) => fetch(request));
860
+ const authHeaders = options.adminKey ? { "x-mockingbird-admin-key": options.adminKey } : {};
861
+ const headersFor = (name) => {
862
+ const key = options.adminKeys?.[name];
863
+ return key ? { "x-mockingbird-admin-key": key } : authHeaders;
864
+ };
865
+ const followAll = (options.namespaces ?? (options.fleet ? "all" : void 0)) === "all";
866
+ const watched = new Set(
867
+ Array.isArray(options.namespaces) ? options.namespaces : ["default"]
868
+ );
869
+ const buckets = /* @__PURE__ */ new Map();
870
+ const statuses = /* @__PURE__ */ new Map();
871
+ const listeners = /* @__PURE__ */ new Set();
872
+ const explicit = options.services ? endpointsFromServices(options.services, fetchImpl) : [];
873
+ let endpoints = explicit;
874
+ const explicitAdmins = options.services ? adminTargetsFromServices(options.services, fetchImpl) : [];
875
+ let admins = explicitAdmins;
876
+ let discoveredAt = 0;
877
+ let discoveryError = null;
878
+ let discovering = null;
879
+ const rejected = /* @__PURE__ */ new Set();
880
+ const rediscover = async (force = false) => {
881
+ if (!options.fleet && !options.manifest) return;
882
+ if (!force && Date.now() - discoveredAt < REDISCOVER_MS) return;
883
+ discovering ??= (async () => {
884
+ try {
885
+ let found = [];
886
+ let foundAdmins = [];
887
+ if (options.fleet) {
888
+ const fleet = await discoverFleet(options.fleet, fetchImpl, authHeaders);
889
+ found = fleet.endpoints;
890
+ foundAdmins = fleet.admins;
891
+ if (followAll) for (const ns of fleet.namespaces) watched.add(ns);
892
+ } else if (options.manifest) {
893
+ const manifest = typeof options.manifest === "function" ? await options.manifest() : options.manifest;
894
+ found = endpointsFromManifest(manifest, fetchImpl);
895
+ foundAdmins = adminTargetsFromManifest(manifest, fetchImpl);
896
+ }
897
+ admins = [
898
+ ...explicitAdmins,
899
+ ...foundAdmins.filter((a) => !explicitAdmins.some((x) => x.name === a.name))
900
+ ];
901
+ const known = new Map(endpoints.map((e) => [`${e.name}|${e.adminUrl}`, e.service]));
902
+ endpoints = [
903
+ ...explicit,
904
+ ...found.filter(
905
+ (e) => !explicit.some((x) => x.name === e.name) && !rejected.has(`${e.name}|${e.adminUrl}`)
906
+ ).map((e) => ({
907
+ ...e,
908
+ service: e.service ?? known.get(`${e.name}|${e.adminUrl}`) ?? null
909
+ }))
910
+ ];
911
+ discoveryError = null;
912
+ } catch (error) {
913
+ discoveryError = error instanceof Error ? error.message : String(error);
914
+ } finally {
915
+ discoveredAt = Date.now();
916
+ discovering = null;
917
+ }
918
+ })();
919
+ await discovering;
920
+ };
921
+ const adminGet = (endpoint, namespace) => async (path) => {
922
+ const response = await endpoint.fetch(
923
+ new Request(`${endpoint.adminUrl}${path}`, {
924
+ headers: {
925
+ ...headersFor(endpoint.name),
926
+ "x-mockingbird-namespace": namespace,
927
+ accept: "application/json"
928
+ }
929
+ })
930
+ );
931
+ if (!response.ok) {
932
+ const text = await response.text().catch(() => "");
933
+ throw new Error(`GET ${path}: HTTP ${response.status} ${text.slice(0, 200)}`);
934
+ }
935
+ return response.json();
936
+ };
937
+ const identify = async (endpoint) => {
938
+ if (endpoint.service) return;
939
+ const health = await adminGet(endpoint, "default")("/health");
940
+ endpoint.service = asServiceKind(health.service);
941
+ if (!endpoint.service) throw new Error(`not a messaging emulator (${String(health.service)})`);
942
+ };
943
+ const bucket = (namespace) => {
944
+ let b = buckets.get(namespace);
945
+ if (!b) {
946
+ b = { notifications: /* @__PURE__ */ new Map(), inFlight: null, queued: null, version: 0 };
947
+ buckets.set(namespace, b);
948
+ }
949
+ return b;
950
+ };
951
+ const readAll = async (namespace) => {
952
+ await rediscover();
953
+ const results = await Promise.all(
954
+ endpoints.map(async (endpoint) => {
955
+ const key = endpoint.name;
956
+ const status = statuses.get(key) ?? {
957
+ name: endpoint.name,
958
+ service: endpoint.service,
959
+ url: endpoint.adminUrl,
960
+ ok: false,
961
+ error: null,
962
+ count: 0,
963
+ lastSyncAt: null
964
+ };
965
+ statuses.set(key, status);
966
+ try {
967
+ await identify(endpoint);
968
+ const service = endpoint.service;
969
+ if (!service) return { ok: false };
970
+ const items = await READERS[service]({
971
+ source: endpoint.name,
972
+ namespace,
973
+ read: adminGet(endpoint, namespace)
974
+ });
975
+ Object.assign(status, {
976
+ service,
977
+ url: endpoint.adminUrl,
978
+ ok: true,
979
+ error: null,
980
+ lastSyncAt: (/* @__PURE__ */ new Date()).toISOString()
981
+ });
982
+ return { ok: true, items };
983
+ } catch (error) {
984
+ const message = error instanceof Error ? error.message : String(error);
985
+ if (message.startsWith("not a messaging emulator")) {
986
+ statuses.delete(key);
987
+ rejected.add(`${endpoint.name}|${endpoint.adminUrl}`);
988
+ endpoints = endpoints.filter((e) => e !== endpoint);
989
+ return { ok: false };
990
+ }
991
+ Object.assign(status, { url: endpoint.adminUrl, ok: false, error: message });
992
+ discoveredAt = 0;
993
+ return { ok: false, source: endpoint.name };
994
+ }
995
+ })
996
+ );
997
+ const b = bucket(namespace);
998
+ const failed = new Set(results.flatMap((r) => "source" in r && r.source ? [r.source] : []));
999
+ const fresh = dedupe(results.flatMap((r) => r.ok ? r.items : []));
1000
+ const next = /* @__PURE__ */ new Map();
1001
+ for (const n of b.notifications.values()) if (failed.has(n.source)) next.set(n.id, n);
1002
+ for (const n of fresh) next.set(n.id, n);
1003
+ const added = [...next.values()].filter((n) => !b.notifications.has(n.id)).sort(byTime);
1004
+ const removed = [...b.notifications.keys()].some((id) => !next.has(id));
1005
+ const changed = added.length > 0 || removed || [...next.values()].some((n) => b.notifications.get(n.id)?.status !== n.status);
1006
+ b.notifications = next;
1007
+ for (const status of statuses.values())
1008
+ status.count = [...buckets.values()].reduce(
1009
+ (sum, bk) => sum + [...bk.notifications.values()].filter((n) => n.source === status.name).length,
1010
+ 0
1011
+ );
1012
+ if (changed) {
1013
+ b.version++;
1014
+ for (const listener of listeners) listener({ namespace, added, version: b.version });
1015
+ }
1016
+ };
1017
+ const sync = (namespace = "default") => {
1018
+ watched.add(namespace);
1019
+ const b = bucket(namespace);
1020
+ if (!b.inFlight) {
1021
+ b.inFlight = readAll(namespace).finally(() => {
1022
+ b.inFlight = null;
1023
+ });
1024
+ return b.inFlight;
1025
+ }
1026
+ b.queued ??= b.inFlight.then(() => {
1027
+ b.queued = null;
1028
+ return sync(namespace);
1029
+ });
1030
+ return b.queued;
1031
+ };
1032
+ const list2 = async (filter = {}) => {
1033
+ const namespace = filter.namespace ?? "default";
1034
+ await sync(namespace);
1035
+ return [...bucket(namespace).notifications.values()].filter((n) => matches(n, { ...filter, namespace })).sort(byTime);
1036
+ };
1037
+ const waitFor = async (filter, wait = {}) => {
1038
+ const timeoutMs = wait.timeoutMs ?? 1e4;
1039
+ const count = wait.count ?? 1;
1040
+ const deadline = Date.now() + timeoutMs;
1041
+ for (; ; ) {
1042
+ const found = await list2(filter);
1043
+ if (found.length >= count) return found;
1044
+ if (Date.now() >= deadline) {
1045
+ const error = new Error(
1046
+ `timed out after ${timeoutMs}ms waiting for ${count} notification(s) matching ${JSON.stringify(filter)}; found ${found.length}`
1047
+ );
1048
+ Object.assign(error, { found });
1049
+ throw error;
1050
+ }
1051
+ await new Promise(
1052
+ (resolve) => setTimeout(resolve, Math.min(100, Math.max(0, deadline - Date.now())))
1053
+ );
1054
+ }
1055
+ };
1056
+ const interval = options.pollIntervalMs ?? 750;
1057
+ const timer = interval > 0 ? setInterval(() => {
1058
+ for (const namespace of watched) void sync(namespace).catch(() => {
1059
+ });
1060
+ }, interval) : null;
1061
+ timer?.unref?.();
1062
+ const events = (namespace, signal) => {
1063
+ watched.add(namespace);
1064
+ const encoder = new TextEncoder();
1065
+ let cleanup = () => {
1066
+ };
1067
+ return new ReadableStream({
1068
+ start(controller) {
1069
+ const send = (event, data) => {
1070
+ try {
1071
+ controller.enqueue(encoder.encode(`event: ${event}
1072
+ data: ${JSON.stringify(data)}
1073
+
1074
+ `));
1075
+ } catch {
1076
+ cleanup();
1077
+ }
1078
+ };
1079
+ const listener = (event) => {
1080
+ if (event.namespace === namespace) send("change", event);
1081
+ };
1082
+ listeners.add(listener);
1083
+ const heartbeat = setInterval(() => send("sources", [...statuses.values()]), 2e3);
1084
+ cleanup = () => {
1085
+ listeners.delete(listener);
1086
+ clearInterval(heartbeat);
1087
+ };
1088
+ signal.addEventListener("abort", () => {
1089
+ cleanup();
1090
+ try {
1091
+ controller.close();
1092
+ } catch {
1093
+ }
1094
+ });
1095
+ send("hello", { namespace, version: bucket(namespace).version });
1096
+ void sync(namespace).catch(() => {
1097
+ });
1098
+ },
1099
+ cancel() {
1100
+ cleanup();
1101
+ }
1102
+ });
1103
+ };
1104
+ const namespacesList = () => [.../* @__PURE__ */ new Set([...watched, ...buckets.keys()])].sort();
1105
+ const title = options.title ?? "Notifications";
1106
+ const gateway = options.admin ? options.admin({
1107
+ targets: async () => {
1108
+ await rediscover();
1109
+ return admins;
1110
+ },
1111
+ headers: headersFor,
1112
+ title
1113
+ }) : null;
1114
+ const handle = async (request) => {
1115
+ const url = new URL(request.url);
1116
+ const path = url.pathname.replace(/\/+$/, "") || "/";
1117
+ if (path === "/admin" || path.startsWith("/admin/"))
1118
+ return gateway ? gateway.fetch(request) : errorBody(404, `no route ${path}`);
1119
+ if (request.method !== "GET" && request.method !== "HEAD")
1120
+ return errorBody(405, "the notification harness is read-only");
1121
+ if (path === "/" || path === "/index.html") {
1122
+ const { renderPage } = await import("./page-J3NUKUUA.js");
1123
+ return new Response(
1124
+ renderPage({ title, defaultTab: options.defaultTab ?? "notifications" }),
1125
+ {
1126
+ headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" }
1127
+ }
1128
+ );
1129
+ }
1130
+ if (path === "/api/admin") {
1131
+ await rediscover();
1132
+ const fleet = options.fleet?.replace(/\/+$/, "");
1133
+ return json(200, {
1134
+ admin: gateway ? await gateway.config() : null,
1135
+ emulators: admins.map((a) => ({ name: a.name, target: a.target, adminUrl: a.adminUrl })),
1136
+ fleet: fleet ? {
1137
+ adminBase: fleet,
1138
+ consoleUrl: fleet.replace(/\/fleet$/, "/ui"),
1139
+ error: discoveryError
1140
+ } : null
1141
+ });
1142
+ }
1143
+ if (path === "/ui.js") {
1144
+ const { BUNDLE } = await import("./browser.bundle-MOA3BSWW.js");
1145
+ return new Response(BUNDLE, {
1146
+ headers: { "content-type": "text/javascript; charset=utf-8", "cache-control": "no-store" }
1147
+ });
1148
+ }
1149
+ if (path === "/api/health") return json(200, { status: "ok", sources: [...statuses.values()] });
1150
+ if (path === "/api/sources") {
1151
+ await rediscover();
1152
+ return json(200, {
1153
+ discoveryError,
1154
+ sources: endpoints.map(
1155
+ (e) => statuses.get(e.name) ?? {
1156
+ name: e.name,
1157
+ service: e.service,
1158
+ url: e.adminUrl,
1159
+ ok: false,
1160
+ error: null,
1161
+ count: 0,
1162
+ lastSyncAt: null
1163
+ }
1164
+ ),
1165
+ services: SERVICE_KINDS
1166
+ });
1167
+ }
1168
+ if (path === "/api/namespaces") {
1169
+ await rediscover();
1170
+ return json(200, { namespaces: namespacesList() });
1171
+ }
1172
+ let filter;
1173
+ try {
1174
+ filter = filterFromSearch(url.searchParams);
1175
+ } catch (error) {
1176
+ return errorBody(400, error instanceof Error ? error.message : String(error));
1177
+ }
1178
+ const namespace = filter.namespace ?? "default";
1179
+ if (path === "/api/events")
1180
+ return new Response(events(namespace, request.signal), {
1181
+ headers: {
1182
+ "content-type": "text/event-stream",
1183
+ "cache-control": "no-store",
1184
+ connection: "keep-alive"
1185
+ }
1186
+ });
1187
+ if (path === "/api/notifications") {
1188
+ const found = await list2(filter);
1189
+ if (url.searchParams.get("order") === "newest") found.reverse();
1190
+ return json(200, { namespace, version: bucket(namespace).version, notifications: found });
1191
+ }
1192
+ if (path === "/api/notifications/latest") {
1193
+ const found = await list2(filter);
1194
+ const latest = found.at(-1);
1195
+ return latest ? json(200, latest) : errorBody(404, "no notification matches");
1196
+ }
1197
+ if (path === "/api/wait") {
1198
+ const timeoutMs = Number(url.searchParams.get("timeoutMs") ?? 1e4);
1199
+ const count = Number(url.searchParams.get("count") ?? 1);
1200
+ if (!Number.isFinite(timeoutMs) || timeoutMs < 0 || timeoutMs > 12e4)
1201
+ return errorBody(400, "timeoutMs: expected 0\u2013120000");
1202
+ if (!Number.isInteger(count) || count < 1)
1203
+ return errorBody(400, "count: expected a positive integer");
1204
+ try {
1205
+ return json(200, { namespace, notifications: await waitFor(filter, { timeoutMs, count }) });
1206
+ } catch (error) {
1207
+ return json(408, {
1208
+ error: {
1209
+ type: "mockingbird_notifications",
1210
+ message: error instanceof Error ? error.message : String(error)
1211
+ },
1212
+ notifications: error.found ?? []
1213
+ });
1214
+ }
1215
+ }
1216
+ const one = /^\/api\/notifications\/(.+)$/.exec(path);
1217
+ if (one) {
1218
+ const id = decodeURIComponent(one[1] ?? "");
1219
+ const ns = id.split(":")[1] ?? namespace;
1220
+ await sync(ns);
1221
+ const found = bucket(ns).notifications.get(id);
1222
+ return found ? json(200, found) : errorBody(404, `no notification ${id}`);
1223
+ }
1224
+ return errorBody(404, `no route ${path}`);
1225
+ };
1226
+ return {
1227
+ fetch: async (request) => {
1228
+ try {
1229
+ return await handle(request);
1230
+ } catch (error) {
1231
+ return errorBody(500, error instanceof Error ? error.message : String(error));
1232
+ }
1233
+ },
1234
+ sync,
1235
+ list: list2,
1236
+ waitFor,
1237
+ sources: () => [...statuses.values()],
1238
+ close: () => {
1239
+ if (timer) clearInterval(timer);
1240
+ listeners.clear();
1241
+ }
1242
+ };
1243
+ };
1244
+
1245
+ export {
1246
+ CHANNELS,
1247
+ SERVICE_KINDS,
1248
+ SERVICE_LABELS,
1249
+ matches,
1250
+ filterToSearch,
1251
+ parseMime,
1252
+ createNotificationHarness
1253
+ };
1254
+ //# sourceMappingURL=chunk-5MRZJQ6J.js.map