@useherald/core 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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/memory.ts"],"sourcesContent":["import type {\n ClaimedDelivery,\n DeliveryPage,\n DeliveryQuery,\n DeliveryRecord,\n DeliveryResult,\n InboxItem,\n InboxPage,\n InboxQuery,\n ListedDelivery,\n NewNotification,\n NotificationRecord,\n Store,\n} from \"./store.js\";\nimport type { TerminalStatus } from \"./types.js\";\n\nexport interface MemoryStoreOptions {\n /** Clock override for tests. */\n now?: () => Date;\n}\n\nconst TERMINAL: readonly TerminalStatus[] = [\"sent\", \"dead\", \"skipped\", \"cancelled\"];\nconst DEFAULT_PAGE = 50;\n\nconst pad = (n: number) => String(n).padStart(12, \"0\");\n\n/** Newest first: (createdAt desc, id desc). */\nconst newestFirst = (a: { createdAt: Date; id: string }, b: { createdAt: Date; id: string }) =>\n b.createdAt.getTime() - a.createdAt.getTime() || (a.id < b.id ? 1 : a.id > b.id ? -1 : 0);\n\nconst encodeCursor = (x: { createdAt: Date; id: string }) => btoa(`${x.createdAt.getTime()}|${x.id}`);\n\n/** True when `x` sorts strictly after the cursor position in newest-first order. */\nfunction afterCursor(x: { createdAt: Date; id: string }, cursor: string): boolean {\n const [ms, id] = atob(cursor).split(\"|\") as [string, string];\n const t = x.createdAt.getTime();\n const c = Number(ms);\n return t < c || (t === c && x.id < id);\n}\n\nfunction page<T extends { createdAt: Date; id: string }>(\n rows: T[],\n limit: number | undefined,\n cursor: string | undefined,\n): { items: T[]; nextCursor: string | null } {\n const size = limit ?? DEFAULT_PAGE;\n const sorted = rows.sort(newestFirst).filter((r) => !cursor || afterCursor(r, cursor));\n const items = sorted.slice(0, size);\n const last = items[items.length - 1];\n return { items, nextCursor: sorted.length > size && last ? encodeCursor(last) : null };\n}\n\n/**\n * Complete in-process Store. Reference implementation of the Store contract,\n * for tests and local development. Not durable and not shared across processes.\n * `claim` is atomic because JS is single-threaded; the contract suite still proves it.\n */\nexport function memoryStore(options: MemoryStoreOptions = {}): Store {\n const clock = options.now ?? (() => new Date());\n let seq = 0;\n const nextId = (p: string) => `${p}_${pad(++seq)}`;\n\n const notifications = new Map<string, NotificationRecord>();\n const byKey = new Map<string, string>();\n const deliveries = new Map<string, DeliveryRecord>();\n const inbox = new Map<string, InboxItem>();\n\n const out = <T>(v: T): T => structuredClone(v);\n\n const claimedView = (d: DeliveryRecord): ClaimedDelivery => {\n const notification = notifications.get(d.notificationId) as NotificationRecord;\n return out({ ...d, notification });\n };\n\n return {\n async enqueue(n: NewNotification) {\n const existing = byKey.get(n.idempotencyKey);\n if (existing) return { id: existing, created: false };\n\n const createdAt = clock();\n const id = nextId(\"n\");\n notifications.set(id, {\n id,\n event: n.event,\n payload: out(n.payload),\n priority: n.priority,\n idempotencyKey: n.idempotencyKey,\n subject: n.subject,\n createdAt,\n });\n byKey.set(n.idempotencyKey, id);\n\n for (const d of n.deliveries) {\n const did = nextId(\"d\");\n deliveries.set(did, {\n id: did,\n notificationId: id,\n channel: d.channel,\n address: out(d.address),\n ...(d.recipientId !== undefined && { recipientId: d.recipientId }),\n status: d.status,\n attempts: 0,\n nextAttemptAt: null, // null = due immediately\n leaseUntil: null,\n lastError: null,\n createdAt,\n });\n }\n return { id, created: true };\n },\n\n async claim({ limit, now, leaseMs }) {\n const due = [...deliveries.values()]\n .filter((d) => {\n if (d.status === \"pending\" || d.status === \"retry\")\n return d.nextAttemptAt === null || d.nextAttemptAt <= now;\n return d.status === \"sending\" && d.leaseUntil !== null && d.leaseUntil <= now;\n })\n .sort(\n (a, b) =>\n (a.nextAttemptAt?.getTime() ?? 0) - (b.nextAttemptAt?.getTime() ?? 0) ||\n a.createdAt.getTime() - b.createdAt.getTime() ||\n (a.id < b.id ? -1 : 1),\n )\n .slice(0, limit);\n\n return due.map((d) => {\n d.status = \"sending\";\n d.attempts += 1; // attempts = the number of the attempt being made\n d.leaseUntil = new Date(now.getTime() + leaseMs);\n return claimedView(d);\n });\n },\n\n async recordResult(deliveryId: string, result: DeliveryResult) {\n const d = deliveries.get(deliveryId);\n if (!d || d.status !== \"sending\") return; // e.g. cancelled while in flight\n d.leaseUntil = null;\n if (result.status === \"sent\") {\n d.status = \"sent\";\n d.nextAttemptAt = null;\n d.lastError = null;\n } else if (result.status === \"retry\") {\n d.status = \"retry\";\n d.nextAttemptAt = new Date(result.nextAttemptAt);\n d.lastError = result.error;\n } else {\n d.status = \"dead\";\n d.nextAttemptAt = null;\n d.lastError = result.error;\n }\n },\n\n async getNotification(id: string) {\n const notification = notifications.get(id);\n if (!notification) return null;\n return out({\n notification,\n deliveries: [...deliveries.values()].filter((d) => d.notificationId === id),\n });\n },\n\n async listDeliveries(q: DeliveryQuery): Promise<DeliveryPage> {\n const rows: ListedDelivery[] = [];\n for (const d of deliveries.values()) {\n const n = notifications.get(d.notificationId) as NotificationRecord;\n if (q.recipientId !== undefined && d.recipientId !== q.recipientId) continue;\n if (q.event !== undefined && n.event !== q.event) continue;\n if (q.channel !== undefined && d.channel !== q.channel) continue;\n if (q.status !== undefined && d.status !== q.status) continue;\n if (q.subject !== undefined && n.subject !== q.subject) continue;\n if (q.since && d.createdAt < q.since) continue;\n if (q.until && d.createdAt >= q.until) continue;\n rows.push({ ...d, event: n.event, subject: n.subject });\n }\n return out(page(rows, q.limit, q.cursor));\n },\n\n async retryDelivery(deliveryId: string) {\n const d = deliveries.get(deliveryId);\n if (!d || d.status !== \"dead\") return false;\n d.status = \"pending\";\n d.attempts = 0;\n d.nextAttemptAt = null;\n d.leaseUntil = null;\n return true;\n },\n\n async cancel({ subject }) {\n const ids = new Set(\n [...notifications.values()].filter((n) => n.subject === subject).map((n) => n.id),\n );\n let count = 0;\n for (const d of deliveries.values()) {\n if (!ids.has(d.notificationId)) continue;\n if (d.status !== \"pending\" && d.status !== \"retry\") continue;\n d.status = \"cancelled\";\n d.nextAttemptAt = null;\n d.leaseUntil = null;\n count += 1;\n }\n return count;\n },\n\n async purge({ olderThan, statuses }) {\n const allowed: readonly string[] = statuses ?? TERMINAL;\n let count = 0;\n for (const [id, d] of deliveries) {\n if (d.createdAt < olderThan && TERMINAL.includes(d.status as TerminalStatus) && allowed.includes(d.status)) {\n deliveries.delete(id);\n count += 1;\n }\n }\n const withDeliveries = new Set([...deliveries.values()].map((d) => d.notificationId));\n for (const [id, n] of notifications) {\n if (n.createdAt < olderThan && !withDeliveries.has(id)) {\n notifications.delete(id);\n byKey.delete(n.idempotencyKey);\n }\n }\n return count;\n },\n\n async inboxAdd(item) {\n const created: InboxItem = { ...out(item), id: nextId(\"i\"), createdAt: clock(), readAt: null };\n inbox.set(created.id, created);\n return out(created);\n },\n\n async inboxList(q: InboxQuery): Promise<InboxPage> {\n const rows = [...inbox.values()].filter(\n (i) => i.recipientId === q.recipientId && (!q.unreadOnly || i.readAt === null),\n );\n return out(page(rows, q.limit, q.cursor));\n },\n\n async inboxMarkRead(recipientId, ids) {\n const now = clock();\n for (const id of ids) {\n const i = inbox.get(id);\n if (i && i.recipientId === recipientId && i.readAt === null) i.readAt = now;\n }\n },\n\n async inboxUnreadCount(recipientId) {\n return [...inbox.values()].filter((i) => i.recipientId === recipientId && i.readAt === null)\n .length;\n },\n\n async inboxMarkAllRead(recipientId) {\n const now = clock();\n let count = 0;\n for (const i of inbox.values()) {\n if (i.recipientId === recipientId && i.readAt === null) {\n i.readAt = now;\n count += 1;\n }\n }\n return count;\n },\n };\n}\n"],"mappings":";AAqBA,IAAM,WAAsC,CAAC,QAAQ,QAAQ,WAAW,WAAW;AACnF,IAAM,eAAe;AAErB,IAAM,MAAM,CAAC,MAAc,OAAO,CAAC,EAAE,SAAS,IAAI,GAAG;AAGrD,IAAM,cAAc,CAAC,GAAoC,MACvD,EAAE,UAAU,QAAQ,IAAI,EAAE,UAAU,QAAQ,MAAM,EAAE,KAAK,EAAE,KAAK,IAAI,EAAE,KAAK,EAAE,KAAK,KAAK;AAEzF,IAAM,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EA,MAAM,iBAAiB,aAAa;AAClC,YAAM,MAAM,MAAM;AAClB,UAAI,QAAQ;AACZ,iBAAW,KAAK,MAAM,OAAO,GAAG;AAC9B,YAAI,EAAE,gBAAgB,eAAe,EAAE,WAAW,MAAM;AACtD,YAAE,SAAS;AACX,mBAAS;AAAA,QACX;AAAA,MACF;AACA,aAAO;AAAA,IACT;AAAA,EACF;AACF;","names":[]}
@@ -0,0 +1,252 @@
1
+ type Priority = "normal" | "critical";
2
+ /** The app's own recipient. Herald only needs a stable id; apps carry extra fields freely. */
3
+ interface RecipientRef {
4
+ id: string;
5
+ }
6
+ /** A destination given directly, bypassing address resolution (e.g. a Slack channel id). */
7
+ interface RawTarget<C extends string = string> {
8
+ channel: C;
9
+ address: unknown;
10
+ }
11
+ interface Targets<C extends string = string> {
12
+ to: ReadonlyArray<RecipientRef | RawTarget<C>>;
13
+ /** Subset of the event's allowed channels. Omitted = all of them. */
14
+ channels?: readonly C[];
15
+ /** `critical` bypasses recipient preferences. */
16
+ priority?: Priority;
17
+ /** Herald generates one when omitted. */
18
+ idempotencyKey?: string;
19
+ /**
20
+ * Opaque tag for what this notification is about, e.g. `"lead:42"`. Not part of
21
+ * the idempotency key. Lets you `cancel({ subject })` and filter `listDeliveries`.
22
+ */
23
+ subject?: string;
24
+ }
25
+ type DeliveryStatus = "pending" | "sending" | "sent" | "retry" | "dead" | "skipped" | "cancelled";
26
+ /** Statuses a delivery never leaves on its own. Only these can be purged. */
27
+ type TerminalStatus = "sent" | "dead" | "skipped" | "cancelled";
28
+ /** What hooks receive after each attempt outcome. */
29
+ interface DeliveryInfo {
30
+ notificationId: string;
31
+ deliveryId: string;
32
+ event: string;
33
+ channel: string;
34
+ recipientId?: string;
35
+ attempt: number;
36
+ error?: unknown;
37
+ }
38
+ interface Hooks {
39
+ onSent?(info: DeliveryInfo): void | Promise<void>;
40
+ onFailed?(info: DeliveryInfo & {
41
+ nextAttemptAt: Date;
42
+ }): void | Promise<void>;
43
+ onDead?(info: DeliveryInfo): void | Promise<void>;
44
+ }
45
+ interface Logger {
46
+ debug(msg: string, meta?: Record<string, unknown>): void;
47
+ info(msg: string, meta?: Record<string, unknown>): void;
48
+ warn(msg: string, meta?: Record<string, unknown>): void;
49
+ error(msg: string, meta?: Record<string, unknown>): void;
50
+ }
51
+ interface RetryPolicy {
52
+ /** Total attempts including the first. Default 5. */
53
+ maxAttempts: number;
54
+ /** First retry delay. Doubles each attempt. Default 30_000. */
55
+ baseMs: number;
56
+ /** Delay ceiling. Default 3_600_000. */
57
+ maxMs: number;
58
+ /** Randomize delays to avoid thundering herds. Default true. */
59
+ jitter: boolean;
60
+ }
61
+ /** Narrows channels per recipient. Called once per `notify()` with all recipients. Never adds channels. */
62
+ type ResolvePreferences = (recipients: readonly RecipientRef[], event: string) => Promise<ReadonlyMap<string, readonly string[]>> | ReadonlyMap<string, readonly string[]>;
63
+ /** Maps a recipient to a channel address. `null` skips that delivery (recorded as `skipped`). */
64
+ type ResolveAddress = (recipient: RecipientRef, channel: string) => Promise<unknown | null> | unknown | null;
65
+ interface ProcessOptions {
66
+ /** Max deliveries to claim this call. Default 50. */
67
+ batchSize?: number;
68
+ /** Stop starting new sends after this many ms (fits function timeouts). Default 20_000. */
69
+ budgetMs?: number;
70
+ }
71
+ interface ProcessSummary {
72
+ claimed: number;
73
+ sent: number;
74
+ retried: number;
75
+ dead: number;
76
+ }
77
+
78
+ interface NewDelivery {
79
+ channel: string;
80
+ /** Resolved address, or the raw target's address. `null` when resolution skipped it. */
81
+ address: unknown;
82
+ recipientId?: string;
83
+ status: "pending" | "skipped";
84
+ }
85
+ interface NewNotification {
86
+ event: string;
87
+ payload: unknown;
88
+ priority: Priority;
89
+ idempotencyKey: string;
90
+ /** Plain nullable indexed column, e.g. `"lead:42"`. Never part of the idempotency key. */
91
+ subject: string | null;
92
+ /** Final channels per recipient, after preferences. Retries never change them. */
93
+ deliveries: readonly NewDelivery[];
94
+ }
95
+ interface NotificationRecord {
96
+ id: string;
97
+ event: string;
98
+ payload: unknown;
99
+ priority: Priority;
100
+ idempotencyKey: string;
101
+ subject: string | null;
102
+ createdAt: Date;
103
+ }
104
+ interface DeliveryRecord {
105
+ id: string;
106
+ notificationId: string;
107
+ channel: string;
108
+ address: unknown;
109
+ recipientId?: string;
110
+ status: DeliveryStatus;
111
+ attempts: number;
112
+ nextAttemptAt: Date | null;
113
+ leaseUntil: Date | null;
114
+ lastError: string | null;
115
+ createdAt: Date;
116
+ }
117
+ /** A delivery leased to this worker, with the notification data needed to render it. */
118
+ interface ClaimedDelivery extends DeliveryRecord {
119
+ notification: NotificationRecord;
120
+ }
121
+ type DeliveryResult = {
122
+ status: "sent";
123
+ providerId?: string;
124
+ } | {
125
+ status: "retry";
126
+ nextAttemptAt: Date;
127
+ error: string;
128
+ } | {
129
+ status: "dead";
130
+ error: string;
131
+ };
132
+ interface DeliveryQuery {
133
+ recipientId?: string;
134
+ event?: string;
135
+ channel?: string;
136
+ status?: DeliveryStatus;
137
+ subject?: string;
138
+ /** Inclusive lower bound on delivery `createdAt`. */
139
+ since?: Date;
140
+ /** Exclusive upper bound on delivery `createdAt`. */
141
+ until?: Date;
142
+ limit?: number;
143
+ /** Opaque. Pass the previous page's `nextCursor`. Keyset on (createdAt, id), newest first. */
144
+ cursor?: string;
145
+ }
146
+ /** A delivery with the notification fields an admin page needs. */
147
+ interface ListedDelivery extends DeliveryRecord {
148
+ event: string;
149
+ subject: string | null;
150
+ }
151
+ interface DeliveryPage {
152
+ items: ListedDelivery[];
153
+ nextCursor: string | null;
154
+ }
155
+ interface InboxItem {
156
+ id: string;
157
+ recipientId: string;
158
+ notificationId: string;
159
+ title: string;
160
+ body: string;
161
+ data?: unknown;
162
+ createdAt: Date;
163
+ readAt: Date | null;
164
+ }
165
+ interface InboxQuery {
166
+ recipientId: string;
167
+ unreadOnly?: boolean;
168
+ limit?: number;
169
+ cursor?: string;
170
+ }
171
+ interface InboxPage {
172
+ items: InboxItem[];
173
+ nextCursor: string | null;
174
+ }
175
+ /**
176
+ * Persistence contract. Herald never sees a driver type. A store never sees
177
+ * templates, channels or preferences.
178
+ */
179
+ interface Store {
180
+ /**
181
+ * Atomically insert the notification and its delivery rows. Unique on
182
+ * `idempotencyKey`: a repeat returns the existing id with `created: false`.
183
+ */
184
+ enqueue(n: NewNotification): Promise<{
185
+ id: string;
186
+ created: boolean;
187
+ }>;
188
+ /**
189
+ * Lease up to `limit` deliveries that are due (`pending`/`retry` with
190
+ * `nextAttemptAt <= now`) or whose lease expired. Sets `leaseUntil = now + leaseMs`
191
+ * and status `sending`. Concurrent callers must never receive the same row
192
+ * (Postgres: `FOR UPDATE SKIP LOCKED`). Lease expiry is what makes a killed
193
+ * worker's rows reappear: delivery is at-least-once.
194
+ */
195
+ claim(opts: {
196
+ limit: number;
197
+ now: Date;
198
+ leaseMs: number;
199
+ }): Promise<ClaimedDelivery[]>;
200
+ /**
201
+ * Record an attempt outcome: status, attempts, error; clears the lease.
202
+ * Must only apply to a row that is still `sending` (`WHERE status = 'sending'`);
203
+ * otherwise it is a silent no-op. This is what stops a late worker result from
204
+ * un-cancelling a row.
205
+ */
206
+ recordResult(deliveryId: string, result: DeliveryResult): Promise<void>;
207
+ /**
208
+ * Admin and support visibility. Newest first, keyset-paginated on
209
+ * (createdAt, id), never by offset. Filters combine with AND.
210
+ */
211
+ listDeliveries(q: DeliveryQuery): Promise<DeliveryPage>;
212
+ /**
213
+ * Re-queue a `dead` delivery: status `pending`, attempts reset to 0 (fresh
214
+ * retry budget), due now. Returns false if the delivery was not `dead`.
215
+ */
216
+ retryDelivery(deliveryId: string): Promise<boolean>;
217
+ /**
218
+ * Cancel every `pending` or `retry` delivery of notifications with this
219
+ * subject. `sending` rows are already out the door and are left alone, as are
220
+ * terminal rows. Sets status `cancelled` (distinct from `skipped`).
221
+ * Returns the number of deliveries cancelled.
222
+ */
223
+ cancel(q: {
224
+ subject: string;
225
+ }): Promise<number>;
226
+ /**
227
+ * Retention. Deletes deliveries created before `olderThan` whose status is
228
+ * terminal (default: all terminal statuses), then notifications left with no
229
+ * deliveries. Never deletes `pending`, `retry` or `sending` rows. Does not
230
+ * touch the inbox. Returns the number of deliveries deleted.
231
+ */
232
+ purge(opts: {
233
+ olderThan: Date;
234
+ statuses?: readonly TerminalStatus[];
235
+ }): Promise<number>;
236
+ getNotification(id: string): Promise<{
237
+ notification: NotificationRecord;
238
+ deliveries: DeliveryRecord[];
239
+ } | null>;
240
+ inboxAdd(item: Omit<InboxItem, "id" | "createdAt" | "readAt">): Promise<InboxItem>;
241
+ inboxList(q: InboxQuery): Promise<InboxPage>;
242
+ inboxMarkRead(recipientId: string, ids: readonly string[]): Promise<void>;
243
+ /** Unread items for the bell badge. */
244
+ inboxUnreadCount(recipientId: string): Promise<number>;
245
+ /** Marks every unread item read. Returns the number of rows updated. */
246
+ inboxMarkAllRead(recipientId: string): Promise<number>;
247
+ /** Create or upgrade Herald's tables. Optional: apps may manage schema themselves. */
248
+ migrate?(): Promise<void>;
249
+ close?(): Promise<void>;
250
+ }
251
+
252
+ export type { ClaimedDelivery as C, DeliveryInfo as D, Hooks as H, InboxQuery as I, Logger as L, NewDelivery as N, ProcessOptions as P, ResolvePreferences as R, Store as S, Targets as T, ProcessSummary as a, InboxPage as b, ResolveAddress as c, RetryPolicy as d, DeliveryPage as e, DeliveryQuery as f, DeliveryRecord as g, DeliveryResult as h, DeliveryStatus as i, InboxItem as j, ListedDelivery as k, NewNotification as l, NotificationRecord as m, Priority as n, RawTarget as o, RecipientRef as p, TerminalStatus as q };
@@ -0,0 +1,19 @@
1
+ import { S as Store } from './store-BaqPfkS_.js';
2
+
3
+ interface StoreContractOptions {
4
+ /** Shown in the suite title. */
5
+ name: string;
6
+ /** Fresh, empty store for every test. */
7
+ create: () => Promise<{
8
+ store: Store;
9
+ cleanup?: () => Promise<void>;
10
+ }>;
11
+ }
12
+ /**
13
+ * The Store contract. Every adapter must pass it. Run it from your own test
14
+ * file: `runStoreContract({ name: "postgres", create })`. Asserts behavior, not
15
+ * id formats: ids are opaque.
16
+ */
17
+ declare function runStoreContract({ name, create }: StoreContractOptions): void;
18
+
19
+ export { type StoreContractOptions, runStoreContract };