@useherald/core 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,3 +1,6 @@
1
+ import { T as Targets, P as ProcessOptions, a as ProcessSummary, I as InboxQuery, b as InboxPage, S as Store, R as ResolvePreferences, c as ResolveAddress, H as Hooks, L as Logger, d as RetryPolicy } from './store-D-yCqAN7.js';
2
+ export { C as ClaimedDelivery, D as DeliveryInfo, e as DeliveryPage, f as DeliveryQuery, g as DeliveryRecord, h as DeliveryResult, i as DeliveryStatus, j as InboxItem, k as ListedDelivery, N as NewDelivery, l as NewNotification, m as NotificationRecord, n as Priority, o as RawTarget, p as RecipientRef, q as TerminalStatus } from './store-D-yCqAN7.js';
3
+
1
4
  interface SendContext {
2
5
  /** Stable per delivery across retries. Pass to providers that dedupe. */
3
6
  idempotencyKey: string;
@@ -63,257 +66,6 @@ type Conform<D, Ch extends ChannelMap> = D extends EventDef<infer P, infer K, an
63
66
  };
64
67
  } : never;
65
68
 
66
- type Priority = "normal" | "critical";
67
- /** The app's own recipient. Herald only needs a stable id; apps carry extra fields freely. */
68
- interface RecipientRef {
69
- id: string;
70
- }
71
- /** A destination given directly, bypassing address resolution (e.g. a Slack channel id). */
72
- interface RawTarget<C extends string = string> {
73
- channel: C;
74
- address: unknown;
75
- }
76
- interface Targets<C extends string = string> {
77
- to: ReadonlyArray<RecipientRef | RawTarget<C>>;
78
- /** Subset of the event's allowed channels. Omitted = all of them. */
79
- channels?: readonly C[];
80
- /** `critical` bypasses recipient preferences. */
81
- priority?: Priority;
82
- /** Herald generates one when omitted. */
83
- idempotencyKey?: string;
84
- /**
85
- * Opaque tag for what this notification is about, e.g. `"lead:42"`. Not part of
86
- * the idempotency key. Lets you `cancel({ subject })` and filter `listDeliveries`.
87
- */
88
- subject?: string;
89
- }
90
- type DeliveryStatus = "pending" | "sending" | "sent" | "retry" | "dead" | "skipped" | "cancelled";
91
- /** Statuses a delivery never leaves on its own. Only these can be purged. */
92
- type TerminalStatus = "sent" | "dead" | "skipped" | "cancelled";
93
- /** What hooks receive after each attempt outcome. */
94
- interface DeliveryInfo {
95
- notificationId: string;
96
- deliveryId: string;
97
- event: string;
98
- channel: string;
99
- recipientId?: string;
100
- attempt: number;
101
- error?: unknown;
102
- }
103
- interface Hooks {
104
- onSent?(info: DeliveryInfo): void | Promise<void>;
105
- onFailed?(info: DeliveryInfo & {
106
- nextAttemptAt: Date;
107
- }): void | Promise<void>;
108
- onDead?(info: DeliveryInfo): void | Promise<void>;
109
- }
110
- interface Logger {
111
- debug(msg: string, meta?: Record<string, unknown>): void;
112
- info(msg: string, meta?: Record<string, unknown>): void;
113
- warn(msg: string, meta?: Record<string, unknown>): void;
114
- error(msg: string, meta?: Record<string, unknown>): void;
115
- }
116
- interface RetryPolicy {
117
- /** Total attempts including the first. Default 5. */
118
- maxAttempts: number;
119
- /** First retry delay. Doubles each attempt. Default 30_000. */
120
- baseMs: number;
121
- /** Delay ceiling. Default 3_600_000. */
122
- maxMs: number;
123
- /** Randomize delays to avoid thundering herds. Default true. */
124
- jitter: boolean;
125
- }
126
- /** Narrows channels per recipient. Called once per `notify()` with all recipients. Never adds channels. */
127
- type ResolvePreferences = (recipients: readonly RecipientRef[], event: string) => Promise<ReadonlyMap<string, readonly string[]>> | ReadonlyMap<string, readonly string[]>;
128
- /** Maps a recipient to a channel address. `null` skips that delivery (recorded as `skipped`). */
129
- type ResolveAddress = (recipient: RecipientRef, channel: string) => Promise<unknown | null> | unknown | null;
130
- interface ProcessOptions {
131
- /** Max deliveries to claim this call. Default 50. */
132
- batchSize?: number;
133
- /** Stop starting new sends after this many ms (fits function timeouts). Default 20_000. */
134
- budgetMs?: number;
135
- }
136
- interface ProcessSummary {
137
- claimed: number;
138
- sent: number;
139
- retried: number;
140
- dead: number;
141
- }
142
-
143
- interface NewDelivery {
144
- channel: string;
145
- /** Resolved address, or the raw target's address. `null` when resolution skipped it. */
146
- address: unknown;
147
- recipientId?: string;
148
- status: "pending" | "skipped";
149
- }
150
- interface NewNotification {
151
- event: string;
152
- payload: unknown;
153
- priority: Priority;
154
- idempotencyKey: string;
155
- /** Plain nullable indexed column, e.g. `"lead:42"`. Never part of the idempotency key. */
156
- subject: string | null;
157
- /** Final channels per recipient, after preferences. Retries never change them. */
158
- deliveries: readonly NewDelivery[];
159
- }
160
- interface NotificationRecord {
161
- id: string;
162
- event: string;
163
- payload: unknown;
164
- priority: Priority;
165
- idempotencyKey: string;
166
- subject: string | null;
167
- createdAt: Date;
168
- }
169
- interface DeliveryRecord {
170
- id: string;
171
- notificationId: string;
172
- channel: string;
173
- address: unknown;
174
- recipientId?: string;
175
- status: DeliveryStatus;
176
- attempts: number;
177
- nextAttemptAt: Date | null;
178
- leaseUntil: Date | null;
179
- lastError: string | null;
180
- createdAt: Date;
181
- }
182
- /** A delivery leased to this worker, with the notification data needed to render it. */
183
- interface ClaimedDelivery extends DeliveryRecord {
184
- notification: NotificationRecord;
185
- }
186
- type DeliveryResult = {
187
- status: "sent";
188
- providerId?: string;
189
- } | {
190
- status: "retry";
191
- nextAttemptAt: Date;
192
- error: string;
193
- } | {
194
- status: "dead";
195
- error: string;
196
- };
197
- interface DeliveryQuery {
198
- recipientId?: string;
199
- event?: string;
200
- channel?: string;
201
- status?: DeliveryStatus;
202
- subject?: string;
203
- /** Inclusive lower bound on delivery `createdAt`. */
204
- since?: Date;
205
- /** Exclusive upper bound on delivery `createdAt`. */
206
- until?: Date;
207
- limit?: number;
208
- /** Opaque. Pass the previous page's `nextCursor`. Keyset on (createdAt, id), newest first. */
209
- cursor?: string;
210
- }
211
- /** A delivery with the notification fields an admin page needs. */
212
- interface ListedDelivery extends DeliveryRecord {
213
- event: string;
214
- subject: string | null;
215
- }
216
- interface DeliveryPage {
217
- items: ListedDelivery[];
218
- nextCursor: string | null;
219
- }
220
- interface InboxItem {
221
- id: string;
222
- recipientId: string;
223
- notificationId: string;
224
- title: string;
225
- body: string;
226
- data?: unknown;
227
- createdAt: Date;
228
- readAt: Date | null;
229
- }
230
- interface InboxQuery {
231
- recipientId: string;
232
- unreadOnly?: boolean;
233
- limit?: number;
234
- cursor?: string;
235
- }
236
- interface InboxPage {
237
- items: InboxItem[];
238
- nextCursor: string | null;
239
- }
240
- /**
241
- * Persistence contract. Herald never sees a driver type. A store never sees
242
- * templates, channels or preferences.
243
- */
244
- interface Store {
245
- /**
246
- * Atomically insert the notification and its delivery rows. Unique on
247
- * `idempotencyKey`: a repeat returns the existing id with `created: false`.
248
- */
249
- enqueue(n: NewNotification): Promise<{
250
- id: string;
251
- created: boolean;
252
- }>;
253
- /**
254
- * Lease up to `limit` deliveries that are due (`pending`/`retry` with
255
- * `nextAttemptAt <= now`) or whose lease expired. Sets `leaseUntil = now + leaseMs`
256
- * and status `sending`. Concurrent callers must never receive the same row
257
- * (Postgres: `FOR UPDATE SKIP LOCKED`). Lease expiry is what makes a killed
258
- * worker's rows reappear: delivery is at-least-once.
259
- */
260
- claim(opts: {
261
- limit: number;
262
- now: Date;
263
- leaseMs: number;
264
- }): Promise<ClaimedDelivery[]>;
265
- /**
266
- * Record an attempt outcome: status, attempts, error; clears the lease.
267
- * Must only apply to a row that is still `sending` (`WHERE status = 'sending'`);
268
- * otherwise it is a silent no-op. This is what stops a late worker result from
269
- * un-cancelling a row.
270
- */
271
- recordResult(deliveryId: string, result: DeliveryResult): Promise<void>;
272
- /**
273
- * Admin and support visibility. Newest first, keyset-paginated on
274
- * (createdAt, id), never by offset. Filters combine with AND.
275
- */
276
- listDeliveries(q: DeliveryQuery): Promise<DeliveryPage>;
277
- /**
278
- * Re-queue a `dead` delivery: status `pending`, attempts reset to 0 (fresh
279
- * retry budget), due now. Returns false if the delivery was not `dead`.
280
- */
281
- retryDelivery(deliveryId: string): Promise<boolean>;
282
- /**
283
- * Cancel every `pending` or `retry` delivery of notifications with this
284
- * subject. `sending` rows are already out the door and are left alone, as are
285
- * terminal rows. Sets status `cancelled` (distinct from `skipped`).
286
- * Returns the number of deliveries cancelled.
287
- */
288
- cancel(q: {
289
- subject: string;
290
- }): Promise<number>;
291
- /**
292
- * Retention. Deletes deliveries created before `olderThan` whose status is
293
- * terminal (default: all terminal statuses), then notifications left with no
294
- * deliveries. Never deletes `pending`, `retry` or `sending` rows. Does not
295
- * touch the inbox. Returns the number of deliveries deleted.
296
- */
297
- purge(opts: {
298
- olderThan: Date;
299
- statuses?: readonly TerminalStatus[];
300
- }): Promise<number>;
301
- getNotification(id: string): Promise<{
302
- notification: NotificationRecord;
303
- deliveries: DeliveryRecord[];
304
- } | null>;
305
- inboxAdd(item: Omit<InboxItem, "id" | "createdAt" | "readAt">): Promise<InboxItem>;
306
- inboxList(q: InboxQuery): Promise<InboxPage>;
307
- inboxMarkRead(recipientId: string, ids: readonly string[]): Promise<void>;
308
- /** Unread items for the bell badge. */
309
- inboxUnreadCount(recipientId: string): Promise<number>;
310
- /** Marks every unread item read. Returns the number of rows updated. */
311
- inboxMarkAllRead(recipientId: string): Promise<number>;
312
- /** Create or upgrade Herald's tables. Optional: apps may manage schema themselves. */
313
- migrate?(): Promise<void>;
314
- close?(): Promise<void>;
315
- }
316
-
317
69
  interface HeraldConfig<Ch extends ChannelMap, Ev extends Record<string, AnyEventDef>> {
318
70
  store: Store;
319
71
  channels: Ch;
@@ -326,6 +78,10 @@ interface HeraldConfig<Ch extends ChannelMap, Ev extends Record<string, AnyEvent
326
78
  hooks?: Hooks;
327
79
  logger?: Logger;
328
80
  retry?: Partial<RetryPolicy>;
81
+ /** Per-send timeout; aborts `ctx.signal`. Default 15_000. */
82
+ sendTimeoutMs?: number;
83
+ /** How long a claimed delivery stays leased. Must exceed `sendTimeoutMs`. Default 60_000. */
84
+ leaseMs?: number;
329
85
  /** Clock override for tests. */
330
86
  now?: () => Date;
331
87
  }
@@ -342,16 +98,17 @@ interface Herald<Ev extends Record<string, AnyEventDef>> {
342
98
  declare const defaultRetry: RetryPolicy;
343
99
  /**
344
100
  * Validates config at startup (missing templates, unregistered channels are
345
- * errors here, not at send time). Behavior lands in later releases: `notify`,
346
- * `processPending` and `inbox` are typed but throw `not_implemented` for now.
101
+ * errors here, not at send time). `notify` queues durably (and sends inline on
102
+ * request); `processPending` delivers. `inbox` throws `not_implemented` until
103
+ * a later release.
347
104
  */
348
105
  declare function createHerald<const Ch extends ChannelMap, Ev extends Record<string, AnyEventDef>>(config: HeraldConfig<Ch, Ev>): Herald<Ev>;
349
106
 
350
- type HeraldErrorCode = "invalid_config" | "unknown_event" | "channel_not_allowed" | "missing_template" | "not_implemented";
107
+ type HeraldErrorCode = "invalid_config" | "unknown_event" | "channel_not_allowed" | "invalid_targets" | "missing_template" | "not_implemented";
351
108
  /** Every error Herald throws on its own behalf. Channel failures never surface through here. */
352
109
  declare class HeraldError extends Error {
353
110
  readonly code: HeraldErrorCode;
354
111
  constructor(code: HeraldErrorCode, message: string);
355
112
  }
356
113
 
357
- export { type AllowedChannel, type Channel, type ChannelMap, type ClaimedDelivery, type DeliveryInfo, type DeliveryPage, type DeliveryQuery, type DeliveryRecord, type DeliveryResult, type DeliveryStatus, type ErrorClass, type EventDef, type Herald, type HeraldConfig, HeraldError, type HeraldErrorCode, type Hooks, type InboxItem, type InboxPage, type InboxQuery, type ListedDelivery, type Logger, type MessageOf, type NewDelivery, type NewNotification, type NotificationRecord, type PayloadOf, type Priority, type ProcessOptions, type ProcessSummary, type RawTarget, type RecipientRef, type ResolveAddress, type ResolvePreferences, type RetryPolicy, type SendContext, type SendResult, type Store, type Targets, type TerminalStatus, createHerald, defaultRetry, defineEvent };
114
+ export { type AllowedChannel, type Channel, type ChannelMap, type ErrorClass, type EventDef, type Herald, type HeraldConfig, HeraldError, type HeraldErrorCode, Hooks, InboxPage, InboxQuery, Logger, type MessageOf, type PayloadOf, ProcessOptions, ProcessSummary, ResolveAddress, ResolvePreferences, RetryPolicy, type SendContext, type SendResult, Store, Targets, createHerald, defaultRetry, defineEvent };
package/dist/index.js CHANGED
@@ -8,6 +8,211 @@ var HeraldError = class extends Error {
8
8
  }
9
9
  };
10
10
 
11
+ // src/notify.ts
12
+ var isRaw = (t) => "channel" in t;
13
+ async function notify(deps, event, payload, targets) {
14
+ const def = deps.events[event];
15
+ if (!def) throw new HeraldError("unknown_event", `unknown event "${event}"`);
16
+ if (!targets.to?.length)
17
+ throw new HeraldError("invalid_targets", `notify("${event}") needs at least one target in "to"`);
18
+ const channels = [...new Set(targets.channels ?? def.channels)];
19
+ for (const ch of channels) {
20
+ if (!def.channels.includes(ch))
21
+ throw new HeraldError("channel_not_allowed", `event "${event}" does not allow channel "${ch}"`);
22
+ }
23
+ const raws = targets.to.filter(isRaw);
24
+ for (const r of raws) {
25
+ if (!channels.includes(r.channel))
26
+ throw new HeraldError(
27
+ "channel_not_allowed",
28
+ `raw target channel "${r.channel}" is not in the channels requested for "${event}"`
29
+ );
30
+ }
31
+ const seen = /* @__PURE__ */ new Set();
32
+ const recipients = [];
33
+ for (const t of targets.to) {
34
+ if (isRaw(t) || seen.has(t.id)) continue;
35
+ seen.add(t.id);
36
+ recipients.push(t);
37
+ }
38
+ const priority = targets.priority ?? "normal";
39
+ let prefs;
40
+ if (deps.resolvePreferences && priority !== "critical" && recipients.length > 0) {
41
+ prefs = await deps.resolvePreferences(recipients, event);
42
+ }
43
+ const pairs = recipients.flatMap((r) => {
44
+ const allowed = prefs?.get(r.id);
45
+ return channels.filter((ch) => !allowed || allowed.includes(ch)).map((ch) => ({ r, ch }));
46
+ });
47
+ const resolved = await Promise.all(
48
+ pairs.map(async ({ r, ch }) => {
49
+ const address = deps.resolveAddress ? await deps.resolveAddress(r, ch) : r.id;
50
+ return address === null || address === void 0 ? { channel: ch, address: null, recipientId: r.id, status: "skipped" } : { channel: ch, address, recipientId: r.id, status: "pending" };
51
+ })
52
+ );
53
+ const rawDeliveries = raws.map((r) => ({
54
+ channel: r.channel,
55
+ address: r.address,
56
+ status: "pending"
57
+ }));
58
+ const { id, created } = await deps.store.enqueue({
59
+ event,
60
+ payload,
61
+ priority,
62
+ idempotencyKey: targets.idempotencyKey ?? globalThis.crypto.randomUUID(),
63
+ subject: targets.subject ?? null,
64
+ deliveries: [...resolved, ...rawDeliveries]
65
+ });
66
+ deps.logger?.debug("notification queued", { id, event, created });
67
+ if (targets.inline && created && deps.sendInline) {
68
+ try {
69
+ await deps.sendInline(id);
70
+ } catch (err) {
71
+ deps.logger?.error("inline send failed; left for processPending()", {
72
+ id,
73
+ error: err instanceof Error ? err.message : String(err)
74
+ });
75
+ }
76
+ }
77
+ return id;
78
+ }
79
+
80
+ // src/process.ts
81
+ var PROCESS_DEFAULTS = { batchSize: 50, budgetMs: 2e4, concurrency: 10 };
82
+ var MAX_ERROR = 1e3;
83
+ var errorText = (err) => (err instanceof Error ? err.message : String(err)).slice(0, MAX_ERROR);
84
+ function backoffMs(attempt2, policy, random = Math.random) {
85
+ const delay = Math.min(policy.maxMs, policy.baseMs * 2 ** (attempt2 - 1));
86
+ return policy.jitter ? delay / 2 + random() * (delay / 2) : delay;
87
+ }
88
+ async function attempt(deps, row) {
89
+ const n = row.notification;
90
+ const def = deps.events[n.event];
91
+ if (!def) return { result: { status: "dead", error: `unknown event "${n.event}"` } };
92
+ const channel = deps.channels[row.channel];
93
+ const template = def.templates[row.channel];
94
+ if (!channel || !template)
95
+ return { result: { status: "dead", error: `unknown channel "${row.channel}" for event "${n.event}"` } };
96
+ let message;
97
+ try {
98
+ message = template(n.payload);
99
+ } catch (error) {
100
+ return { result: { status: "dead", error: `template failed: ${errorText(error)}` }, error };
101
+ }
102
+ const signal = AbortSignal.timeout(deps.sendTimeoutMs);
103
+ const timedOut = new Promise(
104
+ (_, reject) => signal.addEventListener("abort", () => reject(signal.reason), { once: true })
105
+ );
106
+ try {
107
+ const res = await Promise.race([
108
+ channel.send(message, row.address, {
109
+ idempotencyKey: `${n.idempotencyKey}:${row.id}`,
110
+ attempt: row.attempts,
111
+ signal
112
+ }),
113
+ timedOut
114
+ ]);
115
+ return { result: { status: "sent", ...res?.providerId !== void 0 && { providerId: res.providerId } } };
116
+ } catch (error) {
117
+ return { result: failure(deps, row, channel, error, signal.aborted), error };
118
+ }
119
+ }
120
+ async function deliver(deps, row) {
121
+ const { result, error } = await attempt(deps, row);
122
+ try {
123
+ await deps.store.recordResult(row.id, result);
124
+ } catch (err) {
125
+ deps.logger?.error("recordResult failed; delivery will be retried after its lease", {
126
+ deliveryId: row.id,
127
+ error: errorText(err)
128
+ });
129
+ return "unrecorded";
130
+ }
131
+ const info = {
132
+ notificationId: row.notification.id,
133
+ deliveryId: row.id,
134
+ event: row.notification.event,
135
+ channel: row.channel,
136
+ ...row.recipientId !== void 0 && { recipientId: row.recipientId },
137
+ attempt: row.attempts
138
+ };
139
+ const meta = { deliveryId: row.id, channel: row.channel, attempt: row.attempts };
140
+ if (result.status === "sent") {
141
+ await runHook(deps, "onSent", () => deps.hooks?.onSent?.(info));
142
+ return "sent";
143
+ }
144
+ const failed = { ...info, error: error ?? result.error };
145
+ if (result.status === "retry") {
146
+ const nextAttemptAt = result.nextAttemptAt;
147
+ deps.logger?.warn("delivery failed, will retry", { ...meta, error: result.error, nextAttemptAt: nextAttemptAt.toISOString() });
148
+ await runHook(deps, "onFailed", () => deps.hooks?.onFailed?.({ ...failed, nextAttemptAt }));
149
+ return "retried";
150
+ }
151
+ deps.logger?.error("delivery dead", { ...meta, error: result.error });
152
+ await runHook(deps, "onDead", () => deps.hooks?.onDead?.(failed));
153
+ return "dead";
154
+ }
155
+ function failure(deps, row, channel, err, timedOut) {
156
+ let retryable = true;
157
+ let retryAfterMs;
158
+ let text = errorText(err);
159
+ if (timedOut) {
160
+ text = `send timed out after ${deps.sendTimeoutMs}ms: ${text}`.slice(0, MAX_ERROR);
161
+ } else {
162
+ try {
163
+ const cls = channel.classifyError(err);
164
+ retryable = cls.retryable;
165
+ if (Number.isFinite(cls.retryAfterMs) && cls.retryAfterMs >= 0)
166
+ retryAfterMs = cls.retryAfterMs;
167
+ } catch (clsErr) {
168
+ deps.logger?.warn("classifyError threw; treating the error as retryable", {
169
+ channel: row.channel,
170
+ error: errorText(clsErr)
171
+ });
172
+ }
173
+ }
174
+ if (!retryable || row.attempts >= deps.retry.maxAttempts) return { status: "dead", error: text };
175
+ const delay = Math.max(1, retryAfterMs ?? backoffMs(row.attempts, deps.retry, deps.random));
176
+ return { status: "retry", nextAttemptAt: new Date(deps.now().getTime() + delay), error: text };
177
+ }
178
+ async function runHook(deps, name, call) {
179
+ try {
180
+ await call();
181
+ } catch (err) {
182
+ try {
183
+ deps.logger?.error(`${name} hook threw; delivery state is unaffected`, { error: errorText(err) });
184
+ } catch {
185
+ }
186
+ }
187
+ }
188
+ async function processPending(deps, opts = {}) {
189
+ const batchSize = opts.batchSize ?? PROCESS_DEFAULTS.batchSize;
190
+ const concurrency = opts.concurrency ?? PROCESS_DEFAULTS.concurrency;
191
+ const startedAt = deps.now();
192
+ const deadline = startedAt.getTime() + (opts.budgetMs ?? PROCESS_DEFAULTS.budgetMs);
193
+ const summary = { claimed: 0, sent: 0, retried: 0, dead: 0 };
194
+ while (summary.claimed < batchSize && deps.now().getTime() < deadline) {
195
+ const elapsed = deps.now().getTime() - startedAt.getTime();
196
+ const rows = await deps.store.claim({
197
+ limit: Math.min(concurrency, batchSize - summary.claimed),
198
+ now: startedAt,
199
+ leaseMs: deps.leaseMs + elapsed,
200
+ // lease still ends leaseMs from *now*
201
+ ...opts.notificationId !== void 0 && { notificationId: opts.notificationId }
202
+ });
203
+ if (rows.length === 0) break;
204
+ summary.claimed += rows.length;
205
+ deps.logger?.debug("claimed deliveries", { count: rows.length });
206
+ const outcomes = await Promise.all(
207
+ rows.map((r) => deliver(deps, r).catch(() => "unrecorded"))
208
+ );
209
+ for (const outcome of outcomes) {
210
+ if (outcome !== "unrecorded") summary[outcome] += 1;
211
+ }
212
+ }
213
+ return summary;
214
+ }
215
+
11
216
  // src/herald.ts
12
217
  var defaultRetry = {
13
218
  maxAttempts: 5,
@@ -15,6 +220,8 @@ var defaultRetry = {
15
220
  maxMs: 36e5,
16
221
  jitter: true
17
222
  };
223
+ var DEFAULT_SEND_TIMEOUT_MS = 15e3;
224
+ var DEFAULT_LEASE_MS = 6e4;
18
225
  var fn = (v) => typeof v === "function";
19
226
  var STORE_METHODS = [
20
227
  "enqueue",
@@ -45,6 +252,15 @@ function validate(config) {
45
252
  if (!c || !fn(c.send) || !fn(c.classifyError))
46
253
  bad(`channel "${name}" must implement send() and classifyError()`);
47
254
  }
255
+ const sendTimeoutMs = config.sendTimeoutMs ?? DEFAULT_SEND_TIMEOUT_MS;
256
+ const leaseMs = config.leaseMs ?? DEFAULT_LEASE_MS;
257
+ if (!(sendTimeoutMs > 0)) bad("sendTimeoutMs must be a positive number");
258
+ if (!(leaseMs > sendTimeoutMs))
259
+ bad(`leaseMs (${leaseMs}) must exceed sendTimeoutMs (${sendTimeoutMs}), or a lease can expire mid-send`);
260
+ const r = { ...defaultRetry, ...config.retry };
261
+ if (!(Number.isInteger(r.maxAttempts) && r.maxAttempts >= 1)) bad("retry.maxAttempts must be an integer >= 1");
262
+ if (!(Number.isFinite(r.baseMs) && r.baseMs >= 0)) bad("retry.baseMs must be a finite number >= 0");
263
+ if (!(Number.isFinite(r.maxMs) && r.maxMs >= r.baseMs)) bad("retry.maxMs must be finite and >= retry.baseMs");
48
264
  const names = Object.keys(events ?? {});
49
265
  if (names.length === 0) bad("at least one event is required");
50
266
  for (const [event, def] of Object.entries(events)) {
@@ -62,24 +278,43 @@ function validate(config) {
62
278
  }
63
279
  function createHerald(config) {
64
280
  validate(config);
281
+ const engine = {
282
+ store: config.store,
283
+ channels: config.channels,
284
+ events: config.events,
285
+ ...config.hooks && { hooks: config.hooks },
286
+ ...config.logger && { logger: config.logger },
287
+ retry: { ...defaultRetry, ...config.retry },
288
+ now: config.now ?? (() => /* @__PURE__ */ new Date()),
289
+ leaseMs: config.leaseMs ?? DEFAULT_LEASE_MS,
290
+ sendTimeoutMs: config.sendTimeoutMs ?? DEFAULT_SEND_TIMEOUT_MS
291
+ };
65
292
  const notImplemented = (what) => {
66
293
  throw new HeraldError("not_implemented", `${what} is not implemented yet`);
67
294
  };
68
295
  return {
69
- async notify(event, _payload, targets) {
70
- const def = config.events[event];
71
- if (!def) throw new HeraldError("unknown_event", `unknown event "${event}"`);
72
- for (const ch of targets.channels ?? []) {
73
- if (!def.channels.includes(ch))
74
- throw new HeraldError(
75
- "channel_not_allowed",
76
- `event "${event}" does not allow channel "${ch}"`
77
- );
78
- }
79
- return notImplemented("notify()");
296
+ notify(event, payload, targets) {
297
+ return notify(
298
+ {
299
+ store: config.store,
300
+ events: config.events,
301
+ resolvePreferences: config.resolvePreferences,
302
+ resolveAddress: config.resolveAddress,
303
+ logger: config.logger,
304
+ // Inline gets one send-timeout of budget: notify() should not block like a worker run.
305
+ sendInline: (notificationId) => processPending(engine, {
306
+ notificationId,
307
+ batchSize: Number.POSITIVE_INFINITY,
308
+ budgetMs: engine.sendTimeoutMs
309
+ })
310
+ },
311
+ event,
312
+ payload,
313
+ targets
314
+ );
80
315
  },
81
- async processPending() {
82
- return notImplemented("processPending()");
316
+ processPending(opts) {
317
+ return processPending(engine, opts);
83
318
  },
84
319
  inbox: {
85
320
  async list() {