@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 +12 -255
- package/dist/index.js +248 -13
- package/dist/index.js.map +1 -1
- package/dist/memory.d.ts +14 -0
- package/dist/memory.js +204 -0
- package/dist/memory.js.map +1 -0
- package/dist/store-D-yCqAN7.d.ts +261 -0
- package/dist/testing.d.ts +19 -0
- package/dist/testing.js +411 -0
- package/dist/testing.js.map +1 -0
- package/package.json +17 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/errors.ts","../src/herald.ts","../src/events.ts"],"sourcesContent":["export type HeraldErrorCode =\n | \"invalid_config\"\n | \"unknown_event\"\n | \"channel_not_allowed\"\n | \"missing_template\"\n | \"not_implemented\";\n\n/** Every error Herald throws on its own behalf. Channel failures never surface through here. */\nexport class HeraldError extends Error {\n readonly code: HeraldErrorCode;\n\n constructor(code: HeraldErrorCode, message: string) {\n super(message);\n this.name = \"HeraldError\";\n this.code = code;\n }\n}\n","import type { Channel } from \"./channel.js\";\r\nimport { HeraldError } from \"./errors.js\";\r\nimport type { AllowedChannel, AnyEventDef, ChannelMap, Conform, PayloadOf } from \"./events.js\";\r\nimport type { InboxPage, InboxQuery, Store } from \"./store.js\";\r\nimport type {\r\n Hooks,\r\n Logger,\r\n ProcessOptions,\r\n ProcessSummary,\r\n ResolveAddress,\r\n ResolvePreferences,\r\n RetryPolicy,\r\n Targets,\r\n} from \"./types.js\";\r\n\r\nexport interface HeraldConfig<Ch extends ChannelMap, Ev extends Record<string, AnyEventDef>> {\r\n store: Store;\r\n channels: Ch;\r\n /** Each event must conform to the channel map: registered channels, matching message types. */\r\n events: Ev & { [E in keyof Ev]: Conform<Ev[E], Ch> };\r\n resolvePreferences?: ResolvePreferences;\r\n resolveAddress?: ResolveAddress;\r\n hooks?: Hooks;\r\n logger?: Logger;\r\n retry?: Partial<RetryPolicy>;\r\n /** Clock override for tests. */\r\n now?: () => Date;\r\n}\r\n\r\nexport interface Herald<Ev extends Record<string, AnyEventDef>> {\r\n /** Queue a notification. Resolves with its id; channel failures never reach the caller. */\r\n notify<E extends keyof Ev & string>(\r\n event: E,\r\n payload: PayloadOf<Ev[E]>,\r\n targets: Targets<AllowedChannel<Ev[E]>>,\r\n ): Promise<string>;\r\n /** Claim and deliver due work. The host schedules this (interval, cron, queue trigger). */\r\n processPending(opts?: ProcessOptions): Promise<ProcessSummary>;\r\n inbox: {\r\n list(q: InboxQuery): Promise<InboxPage>;\r\n markRead(recipientId: string, ids: readonly string[]): Promise<void>;\r\n };\r\n}\r\n\r\nexport const defaultRetry: RetryPolicy = {\r\n maxAttempts: 5,\r\n baseMs: 30_000,\r\n maxMs: 3_600_000,\r\n jitter: true,\r\n};\r\n\r\nconst fn = (v: unknown): boolean => typeof v === \"function\";\r\n\r\nconst STORE_METHODS = [\r\n \"enqueue\",\r\n \"claim\",\r\n \"recordResult\",\r\n \"listDeliveries\",\r\n \"retryDelivery\",\r\n \"cancel\",\r\n \"purge\",\r\n \"getNotification\",\r\n \"inboxAdd\",\r\n \"inboxList\",\r\n \"inboxMarkRead\",\r\n \"inboxUnreadCount\",\r\n \"inboxMarkAllRead\",\r\n] as const;\r\n\r\nfunction validate(config: HeraldConfig<ChannelMap, Record<string, AnyEventDef>>): void {\r\n const bad = (msg: string): never => {\r\n throw new HeraldError(\"invalid_config\", msg);\r\n };\r\n\r\n const { store, channels, events } = config;\r\n for (const m of STORE_METHODS) {\r\n if (!fn((store as unknown as Record<string, unknown> | undefined)?.[m]))\r\n bad(`store.${m} is not a function`);\r\n }\r\n\r\n for (const [name, ch] of Object.entries(channels ?? {})) {\r\n const c = ch as Channel | undefined;\r\n if (!c || !fn(c.send) || !fn(c.classifyError))\r\n bad(`channel \"${name}\" must implement send() and classifyError()`);\r\n }\r\n\r\n const names = Object.keys(events ?? {});\r\n if (names.length === 0) bad(\"at least one event is required\");\r\n\r\n for (const [event, def] of Object.entries(events)) {\r\n if (!def.channels?.length) bad(`event \"${event}\" must allow at least one channel`);\r\n for (const ch of def.channels) {\r\n if (!(ch in channels)) bad(`event \"${event}\" allows unregistered channel \"${ch}\"`);\r\n if (!fn((def.templates as Record<string, unknown> | undefined)?.[ch]))\r\n throw new HeraldError(\"missing_template\", `event \"${event}\" has no template for channel \"${ch}\"`);\r\n }\r\n for (const ch of Object.keys(def.templates ?? {})) {\r\n if (!def.channels.includes(ch))\r\n bad(`event \"${event}\" has a template for \"${ch}\" which is not in its allowed channels`);\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Validates config at startup (missing templates, unregistered channels are\r\n * errors here, not at send time). Behavior lands in later releases: `notify`,\r\n * `processPending` and `inbox` are typed but throw `not_implemented` for now.\r\n */\r\nexport function createHerald<\r\n const Ch extends ChannelMap,\r\n Ev extends Record<string, AnyEventDef>,\r\n>(config: HeraldConfig<Ch, Ev>): Herald<Ev> {\r\n validate(config as unknown as HeraldConfig<ChannelMap, Record<string, AnyEventDef>>);\r\n\r\n const notImplemented = (what: string): never => {\r\n throw new HeraldError(\"not_implemented\", `${what} is not implemented yet`);\r\n };\r\n\r\n return {\r\n async notify(event, _payload, targets) {\r\n const def = config.events[event] as AnyEventDef | undefined;\r\n if (!def) throw new HeraldError(\"unknown_event\", `unknown event \"${event}\"`);\r\n for (const ch of targets.channels ?? []) {\r\n if (!def.channels.includes(ch))\r\n throw new HeraldError(\r\n \"channel_not_allowed\",\r\n `event \"${event}\" does not allow channel \"${ch}\"`,\r\n );\r\n }\r\n return notImplemented(\"notify()\");\r\n },\r\n async processPending() {\r\n return notImplemented(\"processPending()\");\r\n },\r\n inbox: {\r\n async list() {\r\n return notImplemented(\"inbox.list()\");\r\n },\r\n async markRead() {\r\n return notImplemented(\"inbox.markRead()\");\r\n },\r\n },\r\n };\r\n}\r\n","import type { Channel } from \"./channel.js\";\r\n\r\n/* eslint-disable @typescript-eslint/no-explicit-any -- `any` is how Channel<M, A> is matched regardless of its params */\r\nexport type ChannelMap = Record<string, Channel<any, any>>;\r\n\r\n/** The message type a channel expects from its templates. */\r\nexport type MessageOf<C> = C extends Channel<infer M, any> ? M : never;\r\n\r\n/**\r\n * An event: its allowed channels and one template per channel. `P` is the\r\n * payload type (type-only, via `__payload`); templates are plain functions.\r\n */\r\nexport interface EventDef<\r\n P = unknown,\r\n K extends string = string,\r\n T extends { readonly [C in K]: (payload: P) => unknown } = {\r\n readonly [C in K]: (payload: P) => unknown;\r\n },\r\n> {\r\n readonly channels: readonly K[];\r\n readonly templates: T;\r\n readonly __payload?: P;\r\n}\r\n\r\nexport type AnyEventDef = EventDef<any, string, any>;\r\nexport type PayloadOf<D> = D extends EventDef<infer P, any, any> ? P : never;\r\nexport type AllowedChannel<D> = D extends EventDef<any, infer K, any> ? K : never;\r\n\r\n/**\r\n * Curried so the payload type is explicit while channel names are inferred:\r\n * `defineEvent<{ name: string }>()({ channels: [\"slack\"], templates: { slack: (p) => ... } })`.\r\n */\r\nexport function defineEvent<P>() {\r\n return <const K extends string, T extends { [C in K]: (payload: P) => unknown }>(def: {\r\n channels: readonly K[];\r\n templates: T;\r\n }): EventDef<P, K, T> => def;\r\n}\r\n\r\n/**\r\n * What an event must look like against a concrete channel map: every allowed\r\n * channel is registered, and each template returns that channel's message type.\r\n */\r\nexport type Conform<D, Ch extends ChannelMap> =\r\n D extends EventDef<infer P, infer K, any>\r\n ? {\r\n readonly channels: readonly (K & keyof Ch)[];\r\n readonly templates: {\r\n readonly [C in K]: C extends keyof Ch ? (payload: P) => MessageOf<Ch[C]> : never;\r\n };\r\n }\r\n : never;\r\n"],"mappings":";AAQO,IAAM,cAAN,cAA0B,MAAM;AAAA,EAC5B;AAAA,EAET,YAAY,MAAuB,SAAiB;AAClD,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACd;AACF;;;AC4BO,IAAM,eAA4B;AAAA,EACvC,aAAa;AAAA,EACb,QAAQ;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G;AACjD,UAAI,CAAC,IAAI,SAAS,SAAS,EAAE;AAC3B,YAAI,UAAU,KAAK,yBAAyB,EAAE,wCAAwC;AAAA,IAC1F;AAAA,EACF;AACF;AAOO,SAAS,aAGd,QAA0C;AAC1C,WAAS,MAA0E;AAEnF,QAAM,iBAAiB,CAAC,SAAwB;AAC9C,UAAM,IAAI,YAAY,mBAAmB,GAAG,IAAI,yBAAyB;AAAA,EAC3E;AAEA,SAAO;AAAA,IACL,MAAM,OAAO,OAAO,UAAU,SAAS;AACrC,YAAM,MAAM,OAAO,OAAO,KAAK;AAC/B,UAAI,CAAC,IAAK,OAAM,IAAI,YAAY,iBAAiB,kBAAkB,KAAK,GAAG;AAC3E,iBAAW,MAAM,QAAQ,YAAY,CAAC,GAAG;AACvC,YAAI,CAAC,IAAI,SAAS,SAAS,EAAE;AAC3B,gBAAM,IAAI;AAAA,YACR;AAAA,YACA,UAAU,KAAK,6BAA6B,EAAE;AAAA,UAChD;AAAA,MACJ;AACA,aAAO,eAAe,UAAU;AAAA,IAClC;AAAA,IACA,MAAM,iBAAiB;AACrB,aAAO,eAAe,kBAAkB;AAAA,IAC1C;AAAA,IACA,OAAO;AAAA,MACL,MAAM,OAAO;AACX,eAAO,eAAe,cAAc;AAAA,MACtC;AAAA,MACA,MAAM,WAAW;AACf,eAAO,eAAe,kBAAkB;AAAA,MAC1C;AAAA,IACF;AAAA,EACF;AACF;;;AC/GO,SAAS,cAAiB;AAC/B,SAAO,CAA0E,QAGxD;AAC3B;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/notify.ts","../src/process.ts","../src/herald.ts","../src/events.ts"],"sourcesContent":["export type HeraldErrorCode =\r\n | \"invalid_config\"\r\n | \"unknown_event\"\r\n | \"channel_not_allowed\"\r\n | \"invalid_targets\"\r\n | \"missing_template\"\r\n | \"not_implemented\";\r\n\r\n/** Every error Herald throws on its own behalf. Channel failures never surface through here. */\r\nexport class HeraldError extends Error {\r\n readonly code: HeraldErrorCode;\r\n\r\n constructor(code: HeraldErrorCode, message: string) {\r\n super(message);\r\n this.name = \"HeraldError\";\r\n this.code = code;\r\n }\r\n}\r\n","import { HeraldError } from \"./errors.js\";\nimport type { AnyEventDef } from \"./events.js\";\nimport type { NewDelivery, Store } from \"./store.js\";\nimport type {\n Logger,\n RawTarget,\n RecipientRef,\n ResolveAddress,\n ResolvePreferences,\n Targets,\n} from \"./types.js\";\n\nexport interface NotifyDeps {\n store: Store;\n events: Record<string, AnyEventDef>;\n resolvePreferences?: ResolvePreferences;\n resolveAddress?: ResolveAddress;\n logger?: Logger;\n /** Sends one notification's deliveries now (`targets.inline`). */\n sendInline?: (notificationId: string) => Promise<unknown>;\n}\n\nconst isRaw = (t: RecipientRef | RawTarget): t is RawTarget => \"channel\" in t;\n\n/**\n * Validate, narrow by preferences, resolve addresses, and durably queue.\n * Returns the notification id. Resolver failures propagate and nothing is\n * queued (fail closed: never notify someone who may have opted out).\n */\nexport async function notify(\n deps: NotifyDeps,\n event: string,\n payload: unknown,\n targets: Targets,\n): Promise<string> {\n const def = deps.events[event];\n if (!def) throw new HeraldError(\"unknown_event\", `unknown event \"${event}\"`);\n if (!targets.to?.length)\n throw new HeraldError(\"invalid_targets\", `notify(\"${event}\") needs at least one target in \"to\"`);\n\n const channels = [...new Set(targets.channels ?? def.channels)];\n for (const ch of channels) {\n if (!def.channels.includes(ch))\n throw new HeraldError(\"channel_not_allowed\", `event \"${event}\" does not allow channel \"${ch}\"`);\n }\n\n const raws = targets.to.filter(isRaw);\n for (const r of raws) {\n if (!channels.includes(r.channel))\n throw new HeraldError(\n \"channel_not_allowed\",\n `raw target channel \"${r.channel}\" is not in the channels requested for \"${event}\"`,\n );\n }\n\n const seen = new Set<string>();\n const recipients: RecipientRef[] = [];\n for (const t of targets.to) {\n if (isRaw(t) || seen.has(t.id)) continue;\n seen.add(t.id);\n recipients.push(t);\n }\n\n const priority = targets.priority ?? \"normal\";\n\n // Preferences: one batched call; only narrows; critical bypasses.\n let prefs: ReadonlyMap<string, readonly string[]> | undefined;\n if (deps.resolvePreferences && priority !== \"critical\" && recipients.length > 0) {\n prefs = await deps.resolvePreferences(recipients, event);\n }\n\n const pairs = recipients.flatMap((r) => {\n const allowed = prefs?.get(r.id);\n return channels\n .filter((ch) => !allowed || allowed.includes(ch))\n .map((ch) => ({ r, ch }));\n });\n\n const resolved = await Promise.all(\n pairs.map(async ({ r, ch }): Promise<NewDelivery> => {\n // No resolver configured: the recipient id is the address.\n const address = deps.resolveAddress ? await deps.resolveAddress(r, ch) : r.id;\n return address === null || address === undefined\n ? { channel: ch, address: null, recipientId: r.id, status: \"skipped\" }\n : { channel: ch, address, recipientId: r.id, status: \"pending\" };\n }),\n );\n\n const rawDeliveries: NewDelivery[] = raws.map((r) => ({\n channel: r.channel,\n address: r.address,\n status: \"pending\",\n }));\n\n const { id, created } = await deps.store.enqueue({\n event,\n payload,\n priority,\n idempotencyKey: targets.idempotencyKey ?? globalThis.crypto.randomUUID(),\n subject: targets.subject ?? null,\n deliveries: [...resolved, ...rawDeliveries],\n });\n\n deps.logger?.debug(\"notification queued\", { id, event, created });\n\n // A duplicate key was already queued (and maybe sent): never send it twice.\n if (targets.inline && created && deps.sendInline) {\n try {\n await deps.sendInline(id);\n } catch (err) {\n // Queued durably already; processPending() picks it up. Never surface to the caller.\n deps.logger?.error(\"inline send failed; left for processPending()\", {\n id,\n error: err instanceof Error ? err.message : String(err),\n });\n }\n }\n return id;\n}\n","import type { Channel } from \"./channel.js\";\nimport type { AnyEventDef, ChannelMap } from \"./events.js\";\nimport type { ClaimedDelivery, DeliveryResult, Store } from \"./store.js\";\nimport type {\n DeliveryInfo,\n Hooks,\n Logger,\n ProcessOptions,\n ProcessSummary,\n RetryPolicy,\n} from \"./types.js\";\n\nexport interface EngineDeps {\n store: Store;\n channels: ChannelMap;\n events: Record<string, AnyEventDef>;\n hooks?: Hooks;\n logger?: Logger;\n retry: RetryPolicy;\n now: () => Date;\n leaseMs: number;\n sendTimeoutMs: number;\n /** Injectable for deterministic jitter in tests. */\n random?: () => number;\n}\n\nexport const PROCESS_DEFAULTS = { batchSize: 50, budgetMs: 20_000, concurrency: 10 } as const;\n\nconst MAX_ERROR = 1_000;\n\nconst errorText = (err: unknown): string =>\n (err instanceof Error ? err.message : String(err)).slice(0, MAX_ERROR);\n\n/**\n * Delay before retry number `attempt + 1`. Exponential, capped, with equal\n * jitter (half fixed, half random) so it never collapses to zero.\n */\nexport function backoffMs(attempt: number, policy: RetryPolicy, random = Math.random): number {\n const delay = Math.min(policy.maxMs, policy.baseMs * 2 ** (attempt - 1));\n return policy.jitter ? delay / 2 + random() * (delay / 2) : delay;\n}\n\ntype Outcome = \"sent\" | \"retried\" | \"dead\" | \"unrecorded\";\n\n/** Render and send one claimed row. Returns the result to record plus the raw error, if any. */\nasync function attempt(\n deps: EngineDeps,\n row: ClaimedDelivery,\n): Promise<{ result: DeliveryResult; error?: unknown }> {\n const n = row.notification;\n const def = deps.events[n.event];\n if (!def) return { result: { status: \"dead\", error: `unknown event \"${n.event}\"` } };\n\n const channel = deps.channels[row.channel] as Channel | undefined;\n const template = (def.templates as Record<string, ((p: unknown) => unknown) | undefined>)[row.channel];\n if (!channel || !template)\n return { result: { status: \"dead\", error: `unknown channel \"${row.channel}\" for event \"${n.event}\"` } };\n\n let message: unknown;\n try {\n message = template(n.payload);\n } catch (error) {\n // Same payload + same code fails every time: retrying only burns budget.\n return { result: { status: \"dead\", error: `template failed: ${errorText(error)}` }, error };\n }\n\n const signal = AbortSignal.timeout(deps.sendTimeoutMs);\n // Enforce the timeout even if the adapter ignores `signal`: a hung send must not outlive its lease.\n const timedOut = new Promise<never>((_, reject) =>\n signal.addEventListener(\"abort\", () => reject(signal.reason), { once: true }),\n );\n try {\n const res = await Promise.race([\n channel.send(message, row.address, {\n idempotencyKey: `${n.idempotencyKey}:${row.id}`,\n attempt: row.attempts,\n signal,\n }),\n timedOut,\n ]);\n return { result: { status: \"sent\", ...(res?.providerId !== undefined && { providerId: res.providerId }) } };\n } catch (error) {\n return { result: failure(deps, row, channel, error, signal.aborted), error };\n }\n}\n\nasync function deliver(deps: EngineDeps, row: ClaimedDelivery): Promise<Outcome> {\n const { result, error } = await attempt(deps, row);\n\n try {\n await deps.store.recordResult(row.id, result);\n } catch (err) {\n // Row stays leased; lease expiry hands it to a later run.\n deps.logger?.error(\"recordResult failed; delivery will be retried after its lease\", {\n deliveryId: row.id,\n error: errorText(err),\n });\n return \"unrecorded\";\n }\n\n const info: DeliveryInfo = {\n notificationId: row.notification.id,\n deliveryId: row.id,\n event: row.notification.event,\n channel: row.channel,\n ...(row.recipientId !== undefined && { recipientId: row.recipientId }),\n attempt: row.attempts,\n };\n const meta = { deliveryId: row.id, channel: row.channel, attempt: row.attempts };\n\n if (result.status === \"sent\") {\n await runHook(deps, \"onSent\", () => deps.hooks?.onSent?.(info));\n return \"sent\";\n }\n const failed = { ...info, error: error ?? result.error };\n if (result.status === \"retry\") {\n const nextAttemptAt = result.nextAttemptAt;\n deps.logger?.warn(\"delivery failed, will retry\", { ...meta, error: result.error, nextAttemptAt: nextAttemptAt.toISOString() });\n await runHook(deps, \"onFailed\", () => deps.hooks?.onFailed?.({ ...failed, nextAttemptAt }));\n return \"retried\";\n }\n deps.logger?.error(\"delivery dead\", { ...meta, error: result.error });\n await runHook(deps, \"onDead\", () => deps.hooks?.onDead?.(failed));\n return \"dead\";\n}\n\nfunction failure(\n deps: EngineDeps,\n row: ClaimedDelivery,\n channel: Channel,\n err: unknown,\n timedOut: boolean,\n): DeliveryResult {\n let retryable = true;\n let retryAfterMs: number | undefined;\n let text = errorText(err);\n\n if (timedOut) {\n // The provider may or may not have accepted it; at-least-once says retry.\n text = `send timed out after ${deps.sendTimeoutMs}ms: ${text}`.slice(0, MAX_ERROR);\n } else {\n try {\n const cls = channel.classifyError(err);\n retryable = cls.retryable;\n // Ignore nonsense (NaN, negative, Infinity) and fall back to backoff.\n if (Number.isFinite(cls.retryAfterMs) && (cls.retryAfterMs as number) >= 0)\n retryAfterMs = cls.retryAfterMs;\n } catch (clsErr) {\n deps.logger?.warn(\"classifyError threw; treating the error as retryable\", {\n channel: row.channel,\n error: errorText(clsErr),\n });\n }\n }\n\n if (!retryable || row.attempts >= deps.retry.maxAttempts) return { status: \"dead\", error: text };\n\n // ponytail: a 429 still counts as an attempt (claim already incremented it), so a long\n // rate-limit storm can dead-letter rows. Upgrade: a Store result that refunds the attempt.\n // At least 1ms, so the row is due strictly after the claim snapshot of the current run.\n const delay = Math.max(1, retryAfterMs ?? backoffMs(row.attempts, deps.retry, deps.random));\n return { status: \"retry\", nextAttemptAt: new Date(deps.now().getTime() + delay), error: text };\n}\n\nasync function runHook(deps: EngineDeps, name: keyof Hooks, call: () => unknown): Promise<void> {\n try {\n await call();\n } catch (err) {\n try {\n deps.logger?.error(`${name} hook threw; delivery state is unaffected`, { error: errorText(err) });\n } catch {\n // A broken logger must not break delivery either.\n }\n }\n}\n\n/**\n * Claim due work in chunks of `concurrency`, send each chunk in parallel, and\n * stop at `batchSize` deliveries or when `budgetMs` has passed (checked before\n * each claim, so every claimed row is sent; in-flight sends are bounded by\n * `sendTimeoutMs`). Never throws for channel failures.\n */\nexport async function processPending(\n deps: EngineDeps,\n opts: ProcessOptions & { notificationId?: string } = {},\n): Promise<ProcessSummary> {\n const batchSize = opts.batchSize ?? PROCESS_DEFAULTS.batchSize;\n const concurrency = opts.concurrency ?? PROCESS_DEFAULTS.concurrency;\n // Due-ness is judged against the call's start time, so a row this call just\n // retried is never re-claimed by the same call (no tight loop on Retry-After: 0).\n const startedAt = deps.now();\n const deadline = startedAt.getTime() + (opts.budgetMs ?? PROCESS_DEFAULTS.budgetMs);\n const summary: ProcessSummary = { claimed: 0, sent: 0, retried: 0, dead: 0 };\n\n while (summary.claimed < batchSize && deps.now().getTime() < deadline) {\n const elapsed = deps.now().getTime() - startedAt.getTime();\n const rows = await deps.store.claim({\n limit: Math.min(concurrency, batchSize - summary.claimed),\n now: startedAt,\n leaseMs: deps.leaseMs + elapsed, // lease still ends leaseMs from *now*\n ...(opts.notificationId !== undefined && { notificationId: opts.notificationId }),\n });\n if (rows.length === 0) break;\n summary.claimed += rows.length;\n deps.logger?.debug(\"claimed deliveries\", { count: rows.length });\n\n const outcomes = await Promise.all(\n rows.map((r) => deliver(deps, r).catch((): Outcome => \"unrecorded\")),\n );\n for (const outcome of outcomes) {\n if (outcome !== \"unrecorded\") summary[outcome] += 1;\n }\n }\n return summary;\n}\n","import type { Channel } from \"./channel.js\";\r\nimport { HeraldError } from \"./errors.js\";\r\nimport { notify as runNotify } from \"./notify.js\";\r\nimport { processPending as runProcess, type EngineDeps } from \"./process.js\";\r\nimport type { AllowedChannel, AnyEventDef, ChannelMap, Conform, PayloadOf } from \"./events.js\";\r\nimport type { InboxPage, InboxQuery, Store } from \"./store.js\";\r\nimport type {\r\n Hooks,\r\n Logger,\r\n ProcessOptions,\r\n ProcessSummary,\r\n ResolveAddress,\r\n ResolvePreferences,\r\n RetryPolicy,\r\n Targets,\r\n} from \"./types.js\";\r\n\r\nexport interface HeraldConfig<Ch extends ChannelMap, Ev extends Record<string, AnyEventDef>> {\r\n store: Store;\r\n channels: Ch;\r\n /** Each event must conform to the channel map: registered channels, matching message types. */\r\n events: Ev & { [E in keyof Ev]: Conform<Ev[E], Ch> };\r\n resolvePreferences?: ResolvePreferences;\r\n resolveAddress?: ResolveAddress;\r\n hooks?: Hooks;\r\n logger?: Logger;\r\n retry?: Partial<RetryPolicy>;\r\n /** Per-send timeout; aborts `ctx.signal`. Default 15_000. */\r\n sendTimeoutMs?: number;\r\n /** How long a claimed delivery stays leased. Must exceed `sendTimeoutMs`. Default 60_000. */\r\n leaseMs?: number;\r\n /** Clock override for tests. */\r\n now?: () => Date;\r\n}\r\n\r\nexport interface Herald<Ev extends Record<string, AnyEventDef>> {\r\n /** Queue a notification. Resolves with its id; channel failures never reach the caller. */\r\n notify<E extends keyof Ev & string>(\r\n event: E,\r\n payload: PayloadOf<Ev[E]>,\r\n targets: Targets<AllowedChannel<Ev[E]>>,\r\n ): Promise<string>;\r\n /** Claim and deliver due work. The host schedules this (interval, cron, queue trigger). */\r\n processPending(opts?: ProcessOptions): Promise<ProcessSummary>;\r\n inbox: {\r\n list(q: InboxQuery): Promise<InboxPage>;\r\n markRead(recipientId: string, ids: readonly string[]): Promise<void>;\r\n };\r\n}\r\n\r\nexport const defaultRetry: RetryPolicy = {\r\n maxAttempts: 5,\r\n baseMs: 30_000,\r\n maxMs: 3_600_000,\r\n jitter: true,\r\n};\r\n\r\nconst DEFAULT_SEND_TIMEOUT_MS = 15_000;\r\nconst DEFAULT_LEASE_MS = 60_000;\r\n\r\nconst fn = (v: unknown): boolean => typeof v === \"function\";\r\n\r\nconst STORE_METHODS = [\r\n \"enqueue\",\r\n \"claim\",\r\n \"recordResult\",\r\n \"listDeliveries\",\r\n \"retryDelivery\",\r\n \"cancel\",\r\n \"purge\",\r\n \"getNotification\",\r\n \"inboxAdd\",\r\n \"inboxList\",\r\n \"inboxMarkRead\",\r\n \"inboxUnreadCount\",\r\n \"inboxMarkAllRead\",\r\n] as const;\r\n\r\nfunction validate(config: HeraldConfig<ChannelMap, Record<string, AnyEventDef>>): void {\r\n const bad = (msg: string): never => {\r\n throw new HeraldError(\"invalid_config\", msg);\r\n };\r\n\r\n const { store, channels, events } = config;\r\n for (const m of STORE_METHODS) {\r\n if (!fn((store as unknown as Record<string, unknown> | undefined)?.[m]))\r\n bad(`store.${m} is not a function`);\r\n }\r\n\r\n for (const [name, ch] of Object.entries(channels ?? {})) {\r\n const c = ch as Channel | undefined;\r\n if (!c || !fn(c.send) || !fn(c.classifyError))\r\n bad(`channel \"${name}\" must implement send() and classifyError()`);\r\n }\r\n\r\n const sendTimeoutMs = config.sendTimeoutMs ?? DEFAULT_SEND_TIMEOUT_MS;\r\n const leaseMs = config.leaseMs ?? DEFAULT_LEASE_MS;\r\n if (!(sendTimeoutMs > 0)) bad(\"sendTimeoutMs must be a positive number\");\r\n if (!(leaseMs > sendTimeoutMs))\r\n bad(`leaseMs (${leaseMs}) must exceed sendTimeoutMs (${sendTimeoutMs}), or a lease can expire mid-send`);\r\n\r\n const r = { ...defaultRetry, ...config.retry };\r\n if (!(Number.isInteger(r.maxAttempts) && r.maxAttempts >= 1)) bad(\"retry.maxAttempts must be an integer >= 1\");\r\n if (!(Number.isFinite(r.baseMs) && r.baseMs >= 0)) bad(\"retry.baseMs must be a finite number >= 0\");\r\n if (!(Number.isFinite(r.maxMs) && r.maxMs >= r.baseMs)) bad(\"retry.maxMs must be finite and >= retry.baseMs\");\r\n\r\n const names = Object.keys(events ?? {});\r\n if (names.length === 0) bad(\"at least one event is required\");\r\n\r\n for (const [event, def] of Object.entries(events)) {\r\n if (!def.channels?.length) bad(`event \"${event}\" must allow at least one channel`);\r\n for (const ch of def.channels) {\r\n if (!(ch in channels)) bad(`event \"${event}\" allows unregistered channel \"${ch}\"`);\r\n if (!fn((def.templates as Record<string, unknown> | undefined)?.[ch]))\r\n throw new HeraldError(\"missing_template\", `event \"${event}\" has no template for channel \"${ch}\"`);\r\n }\r\n for (const ch of Object.keys(def.templates ?? {})) {\r\n if (!def.channels.includes(ch))\r\n bad(`event \"${event}\" has a template for \"${ch}\" which is not in its allowed channels`);\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Validates config at startup (missing templates, unregistered channels are\r\n * errors here, not at send time). `notify` queues durably (and sends inline on\r\n * request); `processPending` delivers. `inbox` throws `not_implemented` until\r\n * a later release.\r\n */\r\nexport function createHerald<\r\n const Ch extends ChannelMap,\r\n Ev extends Record<string, AnyEventDef>,\r\n>(config: HeraldConfig<Ch, Ev>): Herald<Ev> {\r\n validate(config as unknown as HeraldConfig<ChannelMap, Record<string, AnyEventDef>>);\r\n\r\n const engine: EngineDeps = {\r\n store: config.store,\r\n channels: config.channels,\r\n events: config.events as Record<string, AnyEventDef>,\r\n ...(config.hooks && { hooks: config.hooks }),\r\n ...(config.logger && { logger: config.logger }),\r\n retry: { ...defaultRetry, ...config.retry },\r\n now: config.now ?? (() => new Date()),\r\n leaseMs: config.leaseMs ?? DEFAULT_LEASE_MS,\r\n sendTimeoutMs: config.sendTimeoutMs ?? DEFAULT_SEND_TIMEOUT_MS,\r\n };\r\n\r\n const notImplemented = (what: string): never => {\r\n throw new HeraldError(\"not_implemented\", `${what} is not implemented yet`);\r\n };\r\n\r\n return {\r\n notify(event, payload, targets) {\r\n return runNotify(\r\n {\r\n store: config.store,\r\n events: config.events as Record<string, AnyEventDef>,\r\n resolvePreferences: config.resolvePreferences,\r\n resolveAddress: config.resolveAddress,\r\n logger: config.logger,\r\n // Inline gets one send-timeout of budget: notify() should not block like a worker run.\r\n sendInline: (notificationId) =>\r\n runProcess(engine, {\r\n notificationId,\r\n batchSize: Number.POSITIVE_INFINITY,\r\n budgetMs: engine.sendTimeoutMs,\r\n }),\r\n },\r\n event,\r\n payload,\r\n targets as Targets,\r\n );\r\n },\r\n processPending(opts) {\r\n return runProcess(engine, opts);\r\n },\r\n inbox: {\r\n async list() {\r\n return notImplemented(\"inbox.list()\");\r\n },\r\n async markRead() {\r\n return notImplemented(\"inbox.markRead()\");\r\n },\r\n },\r\n };\r\n}\r\n","import type { Channel } from \"./channel.js\";\r\n\r\n/* eslint-disable @typescript-eslint/no-explicit-any -- `any` is how Channel<M, A> is matched regardless of its params */\r\nexport type ChannelMap = Record<string, Channel<any, any>>;\r\n\r\n/** The message type a channel expects from its templates. */\r\nexport type MessageOf<C> = C extends Channel<infer M, any> ? M : never;\r\n\r\n/**\r\n * An event: its allowed channels and one template per channel. `P` is the\r\n * payload type (type-only, via `__payload`); templates are plain functions.\r\n */\r\nexport interface EventDef<\r\n P = unknown,\r\n K extends string = string,\r\n T extends { readonly [C in K]: (payload: P) => unknown } = {\r\n readonly [C in K]: (payload: P) => unknown;\r\n },\r\n> {\r\n readonly channels: readonly K[];\r\n readonly templates: T;\r\n readonly __payload?: P;\r\n}\r\n\r\nexport type AnyEventDef = EventDef<any, string, any>;\r\nexport type PayloadOf<D> = D extends EventDef<infer P, any, any> ? P : never;\r\nexport type AllowedChannel<D> = D extends EventDef<any, infer K, any> ? K : never;\r\n\r\n/**\r\n * Curried so the payload type is explicit while channel names are inferred:\r\n * `defineEvent<{ name: string }>()({ channels: [\"slack\"], templates: { slack: (p) => ... } })`.\r\n */\r\nexport function defineEvent<P>() {\r\n return <const K extends string, T extends { [C in K]: (payload: P) => unknown }>(def: {\r\n channels: readonly K[];\r\n templates: T;\r\n }): EventDef<P, K, T> => def;\r\n}\r\n\r\n/**\r\n * What an event must look like against a concrete channel map: every allowed\r\n * channel is registered, and each template returns that channel's message type.\r\n */\r\nexport type Conform<D, Ch extends ChannelMap> =\r\n D extends EventDef<infer P, infer K, any>\r\n ? {\r\n readonly channels: readonly (K & keyof Ch)[];\r\n readonly templates: {\r\n readonly [C in K]: C extends keyof Ch ? (payload: P) => MessageOf<Ch[C]> : never;\r\n };\r\n }\r\n : never;\r\n"],"mappings":";AASO,IAAM,cAAN,cAA0B,MAAM;AAAA,EAC5B;AAAA,EAET,YAAY,MAAuB,SAAiB;AAClD,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACd;AACF;;;ACKA,IAAM,QAAQ,CAAC,MAAgD,aAAa;AAO5E,eAAsB,OACpB,MACA,OACA,SACA,SACiB;AACjB,QAAM,MAAM,KAAK,OAAO,KAAK;AAC7B,MAAI,CAAC,IAAK,OAAM,IAAI,YAAY,iBAAiB,kBAAkB,KAAK,GAAG;AAC3E,MAAI,CAAC,QAAQ,IAAI;AACf,UAAM,IAAI,YAAY,mBAAmB,WAAW,KAAK,sCAAsC;AAEjG,QAAM,WAAW,CAAC,GAAG,IAAI,IAAI,QAAQ,YAAY,IAAI,QAAQ,CAAC;AAC9D,aAAW,MAAM,UAAU;AACzB,QAAI,CAAC,IAAI,SAAS,SAAS,EAAE;AAC3B,YAAM,IAAI,YAAY,uBAAuB,UAAU,KAAK,6BAA6B,EAAE,GAAG;AAAA,EAClG;AAEA,Q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ACF;;;ACzJO,SAAS,cAAiB;AAC/B,SAAO,CAA0E,QAGxD;AAC3B;","names":["attempt"]}
|
package/dist/memory.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { S as Store } from './store-D-yCqAN7.js';
|
|
2
|
+
|
|
3
|
+
interface MemoryStoreOptions {
|
|
4
|
+
/** Clock override for tests. */
|
|
5
|
+
now?: () => Date;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* Complete in-process Store. Reference implementation of the Store contract,
|
|
9
|
+
* for tests and local development. Not durable and not shared across processes.
|
|
10
|
+
* `claim` is atomic because JS is single-threaded; the contract suite still proves it.
|
|
11
|
+
*/
|
|
12
|
+
declare function memoryStore(options?: MemoryStoreOptions): Store;
|
|
13
|
+
|
|
14
|
+
export { type MemoryStoreOptions, memoryStore };
|
package/dist/memory.js
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
// src/memory.ts
|
|
2
|
+
var TERMINAL = ["sent", "dead", "skipped", "cancelled"];
|
|
3
|
+
var DEFAULT_PAGE = 50;
|
|
4
|
+
var pad = (n) => String(n).padStart(12, "0");
|
|
5
|
+
var newestFirst = (a, b) => b.createdAt.getTime() - a.createdAt.getTime() || (a.id < b.id ? 1 : a.id > b.id ? -1 : 0);
|
|
6
|
+
var encodeCursor = (x) => btoa(`${x.createdAt.getTime()}|${x.id}`);
|
|
7
|
+
function afterCursor(x, cursor) {
|
|
8
|
+
const [ms, id] = atob(cursor).split("|");
|
|
9
|
+
const t = x.createdAt.getTime();
|
|
10
|
+
const c = Number(ms);
|
|
11
|
+
return t < c || t === c && x.id < id;
|
|
12
|
+
}
|
|
13
|
+
function page(rows, limit, cursor) {
|
|
14
|
+
const size = limit ?? DEFAULT_PAGE;
|
|
15
|
+
const sorted = rows.sort(newestFirst).filter((r) => !cursor || afterCursor(r, cursor));
|
|
16
|
+
const items = sorted.slice(0, size);
|
|
17
|
+
const last = items[items.length - 1];
|
|
18
|
+
return { items, nextCursor: sorted.length > size && last ? encodeCursor(last) : null };
|
|
19
|
+
}
|
|
20
|
+
function memoryStore(options = {}) {
|
|
21
|
+
const clock = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
22
|
+
let seq = 0;
|
|
23
|
+
const nextId = (p) => `${p}_${pad(++seq)}`;
|
|
24
|
+
const notifications = /* @__PURE__ */ new Map();
|
|
25
|
+
const byKey = /* @__PURE__ */ new Map();
|
|
26
|
+
const deliveries = /* @__PURE__ */ new Map();
|
|
27
|
+
const inbox = /* @__PURE__ */ new Map();
|
|
28
|
+
const out = (v) => structuredClone(v);
|
|
29
|
+
const claimedView = (d) => {
|
|
30
|
+
const notification = notifications.get(d.notificationId);
|
|
31
|
+
return out({ ...d, notification });
|
|
32
|
+
};
|
|
33
|
+
return {
|
|
34
|
+
async enqueue(n) {
|
|
35
|
+
const existing = byKey.get(n.idempotencyKey);
|
|
36
|
+
if (existing) return { id: existing, created: false };
|
|
37
|
+
const createdAt = clock();
|
|
38
|
+
const id = nextId("n");
|
|
39
|
+
notifications.set(id, {
|
|
40
|
+
id,
|
|
41
|
+
event: n.event,
|
|
42
|
+
payload: out(n.payload),
|
|
43
|
+
priority: n.priority,
|
|
44
|
+
idempotencyKey: n.idempotencyKey,
|
|
45
|
+
subject: n.subject,
|
|
46
|
+
createdAt
|
|
47
|
+
});
|
|
48
|
+
byKey.set(n.idempotencyKey, id);
|
|
49
|
+
for (const d of n.deliveries) {
|
|
50
|
+
const did = nextId("d");
|
|
51
|
+
deliveries.set(did, {
|
|
52
|
+
id: did,
|
|
53
|
+
notificationId: id,
|
|
54
|
+
channel: d.channel,
|
|
55
|
+
address: out(d.address),
|
|
56
|
+
...d.recipientId !== void 0 && { recipientId: d.recipientId },
|
|
57
|
+
status: d.status,
|
|
58
|
+
attempts: 0,
|
|
59
|
+
nextAttemptAt: null,
|
|
60
|
+
// null = due immediately
|
|
61
|
+
leaseUntil: null,
|
|
62
|
+
lastError: null,
|
|
63
|
+
createdAt
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
return { id, created: true };
|
|
67
|
+
},
|
|
68
|
+
async claim({ limit, now, leaseMs, notificationId }) {
|
|
69
|
+
const due = [...deliveries.values()].filter((d) => {
|
|
70
|
+
if (notificationId !== void 0 && d.notificationId !== notificationId) return false;
|
|
71
|
+
if (d.status === "pending" || d.status === "retry")
|
|
72
|
+
return d.nextAttemptAt === null || d.nextAttemptAt <= now;
|
|
73
|
+
return d.status === "sending" && d.leaseUntil !== null && d.leaseUntil <= now;
|
|
74
|
+
}).sort(
|
|
75
|
+
(a, b) => (a.nextAttemptAt?.getTime() ?? 0) - (b.nextAttemptAt?.getTime() ?? 0) || a.createdAt.getTime() - b.createdAt.getTime() || (a.id < b.id ? -1 : 1)
|
|
76
|
+
).slice(0, limit);
|
|
77
|
+
return due.map((d) => {
|
|
78
|
+
d.status = "sending";
|
|
79
|
+
d.attempts += 1;
|
|
80
|
+
d.leaseUntil = new Date(now.getTime() + leaseMs);
|
|
81
|
+
return claimedView(d);
|
|
82
|
+
});
|
|
83
|
+
},
|
|
84
|
+
async recordResult(deliveryId, result) {
|
|
85
|
+
const d = deliveries.get(deliveryId);
|
|
86
|
+
if (!d || d.status !== "sending") return;
|
|
87
|
+
d.leaseUntil = null;
|
|
88
|
+
if (result.status === "sent") {
|
|
89
|
+
d.status = "sent";
|
|
90
|
+
d.nextAttemptAt = null;
|
|
91
|
+
d.lastError = null;
|
|
92
|
+
} else if (result.status === "retry") {
|
|
93
|
+
d.status = "retry";
|
|
94
|
+
d.nextAttemptAt = new Date(result.nextAttemptAt);
|
|
95
|
+
d.lastError = result.error;
|
|
96
|
+
} else {
|
|
97
|
+
d.status = "dead";
|
|
98
|
+
d.nextAttemptAt = null;
|
|
99
|
+
d.lastError = result.error;
|
|
100
|
+
}
|
|
101
|
+
},
|
|
102
|
+
async getNotification(id) {
|
|
103
|
+
const notification = notifications.get(id);
|
|
104
|
+
if (!notification) return null;
|
|
105
|
+
return out({
|
|
106
|
+
notification,
|
|
107
|
+
deliveries: [...deliveries.values()].filter((d) => d.notificationId === id)
|
|
108
|
+
});
|
|
109
|
+
},
|
|
110
|
+
async listDeliveries(q) {
|
|
111
|
+
const rows = [];
|
|
112
|
+
for (const d of deliveries.values()) {
|
|
113
|
+
const n = notifications.get(d.notificationId);
|
|
114
|
+
if (q.recipientId !== void 0 && d.recipientId !== q.recipientId) continue;
|
|
115
|
+
if (q.event !== void 0 && n.event !== q.event) continue;
|
|
116
|
+
if (q.channel !== void 0 && d.channel !== q.channel) continue;
|
|
117
|
+
if (q.status !== void 0 && d.status !== q.status) continue;
|
|
118
|
+
if (q.subject !== void 0 && n.subject !== q.subject) continue;
|
|
119
|
+
if (q.since && d.createdAt < q.since) continue;
|
|
120
|
+
if (q.until && d.createdAt >= q.until) continue;
|
|
121
|
+
rows.push({ ...d, event: n.event, subject: n.subject });
|
|
122
|
+
}
|
|
123
|
+
return out(page(rows, q.limit, q.cursor));
|
|
124
|
+
},
|
|
125
|
+
async retryDelivery(deliveryId) {
|
|
126
|
+
const d = deliveries.get(deliveryId);
|
|
127
|
+
if (!d || d.status !== "dead") return false;
|
|
128
|
+
d.status = "pending";
|
|
129
|
+
d.attempts = 0;
|
|
130
|
+
d.nextAttemptAt = null;
|
|
131
|
+
d.leaseUntil = null;
|
|
132
|
+
return true;
|
|
133
|
+
},
|
|
134
|
+
async cancel({ subject }) {
|
|
135
|
+
const ids = new Set(
|
|
136
|
+
[...notifications.values()].filter((n) => n.subject === subject).map((n) => n.id)
|
|
137
|
+
);
|
|
138
|
+
let count = 0;
|
|
139
|
+
for (const d of deliveries.values()) {
|
|
140
|
+
if (!ids.has(d.notificationId)) continue;
|
|
141
|
+
if (d.status !== "pending" && d.status !== "retry") continue;
|
|
142
|
+
d.status = "cancelled";
|
|
143
|
+
d.nextAttemptAt = null;
|
|
144
|
+
d.leaseUntil = null;
|
|
145
|
+
count += 1;
|
|
146
|
+
}
|
|
147
|
+
return count;
|
|
148
|
+
},
|
|
149
|
+
async purge({ olderThan, statuses }) {
|
|
150
|
+
const allowed = statuses ?? TERMINAL;
|
|
151
|
+
let count = 0;
|
|
152
|
+
for (const [id, d] of deliveries) {
|
|
153
|
+
if (d.createdAt < olderThan && TERMINAL.includes(d.status) && allowed.includes(d.status)) {
|
|
154
|
+
deliveries.delete(id);
|
|
155
|
+
count += 1;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
const withDeliveries = new Set([...deliveries.values()].map((d) => d.notificationId));
|
|
159
|
+
for (const [id, n] of notifications) {
|
|
160
|
+
if (n.createdAt < olderThan && !withDeliveries.has(id)) {
|
|
161
|
+
notifications.delete(id);
|
|
162
|
+
byKey.delete(n.idempotencyKey);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
return count;
|
|
166
|
+
},
|
|
167
|
+
async inboxAdd(item) {
|
|
168
|
+
const created = { ...out(item), id: nextId("i"), createdAt: clock(), readAt: null };
|
|
169
|
+
inbox.set(created.id, created);
|
|
170
|
+
return out(created);
|
|
171
|
+
},
|
|
172
|
+
async inboxList(q) {
|
|
173
|
+
const rows = [...inbox.values()].filter(
|
|
174
|
+
(i) => i.recipientId === q.recipientId && (!q.unreadOnly || i.readAt === null)
|
|
175
|
+
);
|
|
176
|
+
return out(page(rows, q.limit, q.cursor));
|
|
177
|
+
},
|
|
178
|
+
async inboxMarkRead(recipientId, ids) {
|
|
179
|
+
const now = clock();
|
|
180
|
+
for (const id of ids) {
|
|
181
|
+
const i = inbox.get(id);
|
|
182
|
+
if (i && i.recipientId === recipientId && i.readAt === null) i.readAt = now;
|
|
183
|
+
}
|
|
184
|
+
},
|
|
185
|
+
async inboxUnreadCount(recipientId) {
|
|
186
|
+
return [...inbox.values()].filter((i) => i.recipientId === recipientId && i.readAt === null).length;
|
|
187
|
+
},
|
|
188
|
+
async inboxMarkAllRead(recipientId) {
|
|
189
|
+
const now = clock();
|
|
190
|
+
let count = 0;
|
|
191
|
+
for (const i of inbox.values()) {
|
|
192
|
+
if (i.recipientId === recipientId && i.readAt === null) {
|
|
193
|
+
i.readAt = now;
|
|
194
|
+
count += 1;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
return count;
|
|
198
|
+
}
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
export {
|
|
202
|
+
memoryStore
|
|
203
|
+
};
|
|
204
|
+
//# sourceMappingURL=memory.js.map
|
|
@@ -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, notificationId }) {\n const due = [...deliveries.values()]\n .filter((d) => {\n if (notificationId !== undefined && d.notificationId !== notificationId) return false;\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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AI,KAAK,EAAE,gBAAgB,eAAe,EAAE,WAAW,KAAM,GAAE,SAAS;AAAA,MAC1E;AAAA,IACF;AAAA,IAEA,MAAM,iBAAiB,aAAa;AAClC,aAAO,CAAC,GAAG,MAAM,OAAO,CAAC,EAAE,OAAO,CAAC,MAAM,EAAE,gBAAgB,eAAe,EAAE,WAAW,IAAI,EACxF;AAAA,IACL;AAAA,IAEA,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,261 @@
|
|
|
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
|
+
* Send this notification's deliveries before `notify()` resolves. Failures
|
|
26
|
+
* still never reach the caller: they become retries for `processPending()`.
|
|
27
|
+
*/
|
|
28
|
+
inline?: boolean;
|
|
29
|
+
}
|
|
30
|
+
type DeliveryStatus = "pending" | "sending" | "sent" | "retry" | "dead" | "skipped" | "cancelled";
|
|
31
|
+
/** Statuses a delivery never leaves on its own. Only these can be purged. */
|
|
32
|
+
type TerminalStatus = "sent" | "dead" | "skipped" | "cancelled";
|
|
33
|
+
/** What hooks receive after each attempt outcome. */
|
|
34
|
+
interface DeliveryInfo {
|
|
35
|
+
notificationId: string;
|
|
36
|
+
deliveryId: string;
|
|
37
|
+
event: string;
|
|
38
|
+
channel: string;
|
|
39
|
+
recipientId?: string;
|
|
40
|
+
attempt: number;
|
|
41
|
+
error?: unknown;
|
|
42
|
+
}
|
|
43
|
+
interface Hooks {
|
|
44
|
+
onSent?(info: DeliveryInfo): void | Promise<void>;
|
|
45
|
+
onFailed?(info: DeliveryInfo & {
|
|
46
|
+
nextAttemptAt: Date;
|
|
47
|
+
}): void | Promise<void>;
|
|
48
|
+
onDead?(info: DeliveryInfo): void | Promise<void>;
|
|
49
|
+
}
|
|
50
|
+
interface Logger {
|
|
51
|
+
debug(msg: string, meta?: Record<string, unknown>): void;
|
|
52
|
+
info(msg: string, meta?: Record<string, unknown>): void;
|
|
53
|
+
warn(msg: string, meta?: Record<string, unknown>): void;
|
|
54
|
+
error(msg: string, meta?: Record<string, unknown>): void;
|
|
55
|
+
}
|
|
56
|
+
interface RetryPolicy {
|
|
57
|
+
/** Total attempts including the first. Default 5. */
|
|
58
|
+
maxAttempts: number;
|
|
59
|
+
/** First retry delay. Doubles each attempt. Default 30_000. */
|
|
60
|
+
baseMs: number;
|
|
61
|
+
/** Delay ceiling. Default 3_600_000. */
|
|
62
|
+
maxMs: number;
|
|
63
|
+
/** Randomize delays to avoid thundering herds. Default true. */
|
|
64
|
+
jitter: boolean;
|
|
65
|
+
}
|
|
66
|
+
/** Narrows channels per recipient. Called once per `notify()` with all recipients. Never adds channels. */
|
|
67
|
+
type ResolvePreferences = (recipients: readonly RecipientRef[], event: string) => Promise<ReadonlyMap<string, readonly string[]>> | ReadonlyMap<string, readonly string[]>;
|
|
68
|
+
/** Maps a recipient to a channel address. `null` skips that delivery (recorded as `skipped`). */
|
|
69
|
+
type ResolveAddress = (recipient: RecipientRef, channel: string) => Promise<unknown | null> | unknown | null;
|
|
70
|
+
interface ProcessOptions {
|
|
71
|
+
/** Max deliveries to claim this call. Default 50. */
|
|
72
|
+
batchSize?: number;
|
|
73
|
+
/** Stop claiming new work after this many ms (fits function timeouts). Default 20_000. */
|
|
74
|
+
budgetMs?: number;
|
|
75
|
+
/** Deliveries claimed and sent in parallel at a time. Default 10. */
|
|
76
|
+
concurrency?: number;
|
|
77
|
+
}
|
|
78
|
+
interface ProcessSummary {
|
|
79
|
+
claimed: number;
|
|
80
|
+
sent: number;
|
|
81
|
+
retried: number;
|
|
82
|
+
dead: number;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
interface NewDelivery {
|
|
86
|
+
channel: string;
|
|
87
|
+
/** Resolved address, or the raw target's address. `null` when resolution skipped it. */
|
|
88
|
+
address: unknown;
|
|
89
|
+
recipientId?: string;
|
|
90
|
+
status: "pending" | "skipped";
|
|
91
|
+
}
|
|
92
|
+
interface NewNotification {
|
|
93
|
+
event: string;
|
|
94
|
+
payload: unknown;
|
|
95
|
+
priority: Priority;
|
|
96
|
+
idempotencyKey: string;
|
|
97
|
+
/** Plain nullable indexed column, e.g. `"lead:42"`. Never part of the idempotency key. */
|
|
98
|
+
subject: string | null;
|
|
99
|
+
/** Final channels per recipient, after preferences. Retries never change them. */
|
|
100
|
+
deliveries: readonly NewDelivery[];
|
|
101
|
+
}
|
|
102
|
+
interface NotificationRecord {
|
|
103
|
+
id: string;
|
|
104
|
+
event: string;
|
|
105
|
+
payload: unknown;
|
|
106
|
+
priority: Priority;
|
|
107
|
+
idempotencyKey: string;
|
|
108
|
+
subject: string | null;
|
|
109
|
+
createdAt: Date;
|
|
110
|
+
}
|
|
111
|
+
interface DeliveryRecord {
|
|
112
|
+
id: string;
|
|
113
|
+
notificationId: string;
|
|
114
|
+
channel: string;
|
|
115
|
+
address: unknown;
|
|
116
|
+
recipientId?: string;
|
|
117
|
+
status: DeliveryStatus;
|
|
118
|
+
attempts: number;
|
|
119
|
+
nextAttemptAt: Date | null;
|
|
120
|
+
leaseUntil: Date | null;
|
|
121
|
+
lastError: string | null;
|
|
122
|
+
createdAt: Date;
|
|
123
|
+
}
|
|
124
|
+
/** A delivery leased to this worker, with the notification data needed to render it. */
|
|
125
|
+
interface ClaimedDelivery extends DeliveryRecord {
|
|
126
|
+
notification: NotificationRecord;
|
|
127
|
+
}
|
|
128
|
+
type DeliveryResult = {
|
|
129
|
+
status: "sent";
|
|
130
|
+
providerId?: string;
|
|
131
|
+
} | {
|
|
132
|
+
status: "retry";
|
|
133
|
+
nextAttemptAt: Date;
|
|
134
|
+
error: string;
|
|
135
|
+
} | {
|
|
136
|
+
status: "dead";
|
|
137
|
+
error: string;
|
|
138
|
+
};
|
|
139
|
+
interface DeliveryQuery {
|
|
140
|
+
recipientId?: string;
|
|
141
|
+
event?: string;
|
|
142
|
+
channel?: string;
|
|
143
|
+
status?: DeliveryStatus;
|
|
144
|
+
subject?: string;
|
|
145
|
+
/** Inclusive lower bound on delivery `createdAt`. */
|
|
146
|
+
since?: Date;
|
|
147
|
+
/** Exclusive upper bound on delivery `createdAt`. */
|
|
148
|
+
until?: Date;
|
|
149
|
+
limit?: number;
|
|
150
|
+
/** Opaque. Pass the previous page's `nextCursor`. Keyset on (createdAt, id), newest first. */
|
|
151
|
+
cursor?: string;
|
|
152
|
+
}
|
|
153
|
+
/** A delivery with the notification fields an admin page needs. */
|
|
154
|
+
interface ListedDelivery extends DeliveryRecord {
|
|
155
|
+
event: string;
|
|
156
|
+
subject: string | null;
|
|
157
|
+
}
|
|
158
|
+
interface DeliveryPage {
|
|
159
|
+
items: ListedDelivery[];
|
|
160
|
+
nextCursor: string | null;
|
|
161
|
+
}
|
|
162
|
+
interface InboxItem {
|
|
163
|
+
id: string;
|
|
164
|
+
recipientId: string;
|
|
165
|
+
notificationId: string;
|
|
166
|
+
title: string;
|
|
167
|
+
body: string;
|
|
168
|
+
data?: unknown;
|
|
169
|
+
createdAt: Date;
|
|
170
|
+
readAt: Date | null;
|
|
171
|
+
}
|
|
172
|
+
interface InboxQuery {
|
|
173
|
+
recipientId: string;
|
|
174
|
+
unreadOnly?: boolean;
|
|
175
|
+
limit?: number;
|
|
176
|
+
cursor?: string;
|
|
177
|
+
}
|
|
178
|
+
interface InboxPage {
|
|
179
|
+
items: InboxItem[];
|
|
180
|
+
nextCursor: string | null;
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Persistence contract. Herald never sees a driver type. A store never sees
|
|
184
|
+
* templates, channels or preferences.
|
|
185
|
+
*/
|
|
186
|
+
interface Store {
|
|
187
|
+
/**
|
|
188
|
+
* Atomically insert the notification and its delivery rows. Unique on
|
|
189
|
+
* `idempotencyKey`: a repeat returns the existing id with `created: false`.
|
|
190
|
+
*/
|
|
191
|
+
enqueue(n: NewNotification): Promise<{
|
|
192
|
+
id: string;
|
|
193
|
+
created: boolean;
|
|
194
|
+
}>;
|
|
195
|
+
/**
|
|
196
|
+
* Lease up to `limit` deliveries that are due (`pending`/`retry` with
|
|
197
|
+
* `nextAttemptAt <= now`) or whose lease expired. Sets `leaseUntil = now + leaseMs`
|
|
198
|
+
* and status `sending`. Concurrent callers must never receive the same row
|
|
199
|
+
* (Postgres: `FOR UPDATE SKIP LOCKED`). Lease expiry is what makes a killed
|
|
200
|
+
* worker's rows reappear: delivery is at-least-once. `notificationId`, when
|
|
201
|
+
* given, restricts the claim to that notification's deliveries (inline send).
|
|
202
|
+
*/
|
|
203
|
+
claim(opts: {
|
|
204
|
+
limit: number;
|
|
205
|
+
now: Date;
|
|
206
|
+
leaseMs: number;
|
|
207
|
+
notificationId?: string;
|
|
208
|
+
}): Promise<ClaimedDelivery[]>;
|
|
209
|
+
/**
|
|
210
|
+
* Record an attempt outcome: status, attempts, error; clears the lease.
|
|
211
|
+
* Must only apply to a row that is still `sending` (`WHERE status = 'sending'`);
|
|
212
|
+
* otherwise it is a silent no-op. This is what stops a late worker result from
|
|
213
|
+
* un-cancelling a row.
|
|
214
|
+
*/
|
|
215
|
+
recordResult(deliveryId: string, result: DeliveryResult): Promise<void>;
|
|
216
|
+
/**
|
|
217
|
+
* Admin and support visibility. Newest first, keyset-paginated on
|
|
218
|
+
* (createdAt, id), never by offset. Filters combine with AND.
|
|
219
|
+
*/
|
|
220
|
+
listDeliveries(q: DeliveryQuery): Promise<DeliveryPage>;
|
|
221
|
+
/**
|
|
222
|
+
* Re-queue a `dead` delivery: status `pending`, attempts reset to 0 (fresh
|
|
223
|
+
* retry budget), due now. Returns false if the delivery was not `dead`.
|
|
224
|
+
*/
|
|
225
|
+
retryDelivery(deliveryId: string): Promise<boolean>;
|
|
226
|
+
/**
|
|
227
|
+
* Cancel every `pending` or `retry` delivery of notifications with this
|
|
228
|
+
* subject. `sending` rows are already out the door and are left alone, as are
|
|
229
|
+
* terminal rows. Sets status `cancelled` (distinct from `skipped`).
|
|
230
|
+
* Returns the number of deliveries cancelled.
|
|
231
|
+
*/
|
|
232
|
+
cancel(q: {
|
|
233
|
+
subject: string;
|
|
234
|
+
}): Promise<number>;
|
|
235
|
+
/**
|
|
236
|
+
* Retention. Deletes deliveries created before `olderThan` whose status is
|
|
237
|
+
* terminal (default: all terminal statuses), then notifications left with no
|
|
238
|
+
* deliveries. Never deletes `pending`, `retry` or `sending` rows. Does not
|
|
239
|
+
* touch the inbox. Returns the number of deliveries deleted.
|
|
240
|
+
*/
|
|
241
|
+
purge(opts: {
|
|
242
|
+
olderThan: Date;
|
|
243
|
+
statuses?: readonly TerminalStatus[];
|
|
244
|
+
}): Promise<number>;
|
|
245
|
+
getNotification(id: string): Promise<{
|
|
246
|
+
notification: NotificationRecord;
|
|
247
|
+
deliveries: DeliveryRecord[];
|
|
248
|
+
} | null>;
|
|
249
|
+
inboxAdd(item: Omit<InboxItem, "id" | "createdAt" | "readAt">): Promise<InboxItem>;
|
|
250
|
+
inboxList(q: InboxQuery): Promise<InboxPage>;
|
|
251
|
+
inboxMarkRead(recipientId: string, ids: readonly string[]): Promise<void>;
|
|
252
|
+
/** Unread items for the bell badge. */
|
|
253
|
+
inboxUnreadCount(recipientId: string): Promise<number>;
|
|
254
|
+
/** Marks every unread item read. Returns the number of rows updated. */
|
|
255
|
+
inboxMarkAllRead(recipientId: string): Promise<number>;
|
|
256
|
+
/** Create or upgrade Herald's tables. Optional: apps may manage schema themselves. */
|
|
257
|
+
migrate?(): Promise<void>;
|
|
258
|
+
close?(): Promise<void>;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
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-D-yCqAN7.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 };
|