easy-ping 0.1.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/LICENSE +21 -0
- package/README.md +374 -0
- package/dist/adapter-f0OR2DhY.d.cts +200 -0
- package/dist/adapter-f0OR2DhY.d.ts +200 -0
- package/dist/adapters/drizzle.cjs +440 -0
- package/dist/adapters/drizzle.cjs.map +1 -0
- package/dist/adapters/drizzle.d.cts +991 -0
- package/dist/adapters/drizzle.d.ts +991 -0
- package/dist/adapters/drizzle.js +409 -0
- package/dist/adapters/drizzle.js.map +1 -0
- package/dist/adapters/mongodb.cjs +458 -0
- package/dist/adapters/mongodb.cjs.map +1 -0
- package/dist/adapters/mongodb.d.cts +32 -0
- package/dist/adapters/mongodb.d.ts +32 -0
- package/dist/adapters/mongodb.js +376 -0
- package/dist/adapters/mongodb.js.map +1 -0
- package/dist/browser.cjs +96 -0
- package/dist/browser.cjs.map +1 -0
- package/dist/browser.d.cts +45 -0
- package/dist/browser.d.ts +45 -0
- package/dist/browser.js +89 -0
- package/dist/browser.js.map +1 -0
- package/dist/chunk-BV3U542P.js +11 -0
- package/dist/chunk-BV3U542P.js.map +1 -0
- package/dist/chunk-NYDVNMKG.js +62 -0
- package/dist/chunk-NYDVNMKG.js.map +1 -0
- package/dist/chunk-OZSOIX23.js +120 -0
- package/dist/chunk-OZSOIX23.js.map +1 -0
- package/dist/chunk-PTGHMCCG.js +23 -0
- package/dist/chunk-PTGHMCCG.js.map +1 -0
- package/dist/chunk-W3BMEPPQ.js +50 -0
- package/dist/chunk-W3BMEPPQ.js.map +1 -0
- package/dist/client.cjs +160 -0
- package/dist/client.cjs.map +1 -0
- package/dist/client.d.cts +42 -0
- package/dist/client.d.ts +42 -0
- package/dist/client.js +158 -0
- package/dist/client.js.map +1 -0
- package/dist/index.cjs +920 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +203 -0
- package/dist/index.d.ts +203 -0
- package/dist/index.js +723 -0
- package/dist/index.js.map +1 -0
- package/dist/node.cjs +49 -0
- package/dist/node.cjs.map +1 -0
- package/dist/node.d.cts +8 -0
- package/dist/node.d.ts +8 -0
- package/dist/node.js +46 -0
- package/dist/node.js.map +1 -0
- package/dist/plugin-Bqj9xAOS.d.cts +217 -0
- package/dist/plugin-bTJKmnlq.d.ts +217 -0
- package/dist/plugins/digests.cjs +206 -0
- package/dist/plugins/digests.cjs.map +1 -0
- package/dist/plugins/digests.d.cts +68 -0
- package/dist/plugins/digests.d.ts +68 -0
- package/dist/plugins/digests.js +201 -0
- package/dist/plugins/digests.js.map +1 -0
- package/dist/plugins/preferences-client.cjs +23 -0
- package/dist/plugins/preferences-client.cjs.map +1 -0
- package/dist/plugins/preferences-client.d.cts +29 -0
- package/dist/plugins/preferences-client.d.ts +29 -0
- package/dist/plugins/preferences-client.js +18 -0
- package/dist/plugins/preferences-client.js.map +1 -0
- package/dist/plugins/preferences-react.cjs +125 -0
- package/dist/plugins/preferences-react.cjs.map +1 -0
- package/dist/plugins/preferences-react.d.cts +40 -0
- package/dist/plugins/preferences-react.d.ts +40 -0
- package/dist/plugins/preferences-react.js +101 -0
- package/dist/plugins/preferences-react.js.map +1 -0
- package/dist/plugins/preferences.cjs +147 -0
- package/dist/plugins/preferences.cjs.map +1 -0
- package/dist/plugins/preferences.d.cts +22 -0
- package/dist/plugins/preferences.d.ts +22 -0
- package/dist/plugins/preferences.js +119 -0
- package/dist/plugins/preferences.js.map +1 -0
- package/dist/plugins/push.cjs +146 -0
- package/dist/plugins/push.cjs.map +1 -0
- package/dist/plugins/push.d.cts +60 -0
- package/dist/plugins/push.d.ts +60 -0
- package/dist/plugins/push.js +144 -0
- package/dist/plugins/push.js.map +1 -0
- package/dist/provider-CA45WVqt.d.cts +23 -0
- package/dist/provider-CA45WVqt.d.ts +23 -0
- package/dist/providers/resend.cjs +69 -0
- package/dist/providers/resend.cjs.map +1 -0
- package/dist/providers/resend.d.cts +20 -0
- package/dist/providers/resend.d.ts +20 -0
- package/dist/providers/resend.js +66 -0
- package/dist/providers/resend.js.map +1 -0
- package/dist/providers/web-push.cjs +211 -0
- package/dist/providers/web-push.cjs.map +1 -0
- package/dist/providers/web-push.d.cts +33 -0
- package/dist/providers/web-push.d.ts +33 -0
- package/dist/providers/web-push.js +193 -0
- package/dist/providers/web-push.js.map +1 -0
- package/dist/react.cjs +218 -0
- package/dist/react.cjs.map +1 -0
- package/dist/react.d.cts +57 -0
- package/dist/react.d.ts +57 -0
- package/dist/react.js +193 -0
- package/dist/react.js.map +1 -0
- package/dist/schema.cjs +263 -0
- package/dist/schema.cjs.map +1 -0
- package/dist/schema.d.cts +180 -0
- package/dist/schema.d.ts +180 -0
- package/dist/schema.js +200 -0
- package/dist/schema.js.map +1 -0
- package/dist/testing.cjs +342 -0
- package/dist/testing.cjs.map +1 -0
- package/dist/testing.d.cts +38 -0
- package/dist/testing.d.ts +38 -0
- package/dist/testing.js +340 -0
- package/dist/testing.js.map +1 -0
- package/package.json +168 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/base64url.ts","../src/core/definition.ts","../src/core/errors.ts","../src/core/tokens.ts","../src/core/handler.ts","../src/core/backoff.ts","../src/core/runner.ts","../src/core/send.ts","../src/schema/declaration.ts","../src/core/store.ts","../src/core/instance.ts","../src/core/plugin.ts"],"names":["message","encoder"],"mappings":";;;AAEO,SAAS,gBAAgB,KAAA,EAAoC;AAClE,EAAA,MAAM,KAAA,GAAQ,OAAO,KAAA,KAAU,QAAA,GAAW,IAAI,WAAA,EAAY,CAAE,MAAA,CAAO,KAAK,CAAA,GAAI,KAAA;AAC5E,EAAA,IAAI,MAAA,GAAS,EAAA;AACb,EAAA,KAAA,MAAW,IAAA,IAAQ,KAAA,EAAO,MAAA,IAAU,MAAA,CAAO,aAAa,IAAI,CAAA;AAC5D,EAAA,OAAO,IAAA,CAAK,MAAM,CAAA,CAAE,OAAA,CAAQ,KAAA,EAAO,GAAG,CAAA,CAAE,OAA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64Url(input: string | Uint8Array): string {\n const bytes = typeof input === \"string\" ? new TextEncoder().encode(input) : input;\n let binary = \"\";\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\n// Uint8Array<ArrayBuffer>: bare Uint8Array widens and is not a BufferSource.\nexport function decodeBase64UrlBytes(value: string): Uint8Array<ArrayBuffer> | null {\n try {\n const binary = atob(value.replace(/-/g, \"+\").replace(/_/g, \"/\"));\n return Uint8Array.from(binary, (char) => char.charCodeAt(0));\n } catch {\n return null;\n }\n}\n\nexport function decodeBase64Url(value: string): string | null {\n const bytes = decodeBase64UrlBytes(value);\n return bytes ? new TextDecoder().decode(bytes) : null;\n}\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { Channel } from \"./types\";\n\nexport type PayloadFromSchema<TSchema> = TSchema extends StandardSchemaV1\n ? StandardSchemaV1.InferOutput<TSchema>\n : Record<string, unknown>;\n\nexport type EmailTemplate<TPayload> = {\n subject: (payload: TPayload) => string;\n /** Rendered HTML. react-email users wrap: `(p) => render(<Email {...p} />)`. */\n template: (payload: TPayload) => string | Promise<string>;\n};\n\nexport type NotificationDefinition<\n TSchema extends StandardSchemaV1 | undefined = StandardSchemaV1 | undefined,\n> = {\n schema?: TSchema;\n channels: readonly Channel[];\n maxAttempts?: number;\n email?: EmailTemplate<PayloadFromSchema<TSchema>>;\n};\n\n/** Binds TSchema so email callbacks infer the payload; TS cannot infer from a sibling property. */\nexport function defineNotification<TSchema extends StandardSchemaV1 | undefined = undefined>(\n definition: NotificationDefinition<TSchema>,\n): NotificationDefinition<TSchema> {\n return definition;\n}\n\n/**\n * Erased form. `EmailTemplate<never>` because callbacks are contravariant —\n * anything else makes every schema-typed definition fail to assign.\n */\nexport type AnyNotificationDefinition = {\n schema?: StandardSchemaV1 | undefined;\n channels: readonly Channel[];\n maxAttempts?: number | undefined;\n email?: EmailTemplate<never> | undefined;\n};\n\nexport type NotificationDefinitions = Record<string, AnyNotificationDefinition>;\n\nexport type PayloadOf<TDef> = TDef extends { schema: infer TSchema extends StandardSchemaV1 }\n ? StandardSchemaV1.InferOutput<TSchema>\n : Record<string, unknown>;\n","export class EasyPingError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"EasyPingError\";\n }\n}\n\n/** Thrown when a payload fails its Standard Schema. Developer error. */\nexport class ValidationError extends EasyPingError {\n readonly issues: readonly { message: string; path?: string }[];\n\n constructor(type: string, issues: readonly { message: string; path?: string }[]) {\n super(`Payload for \"${type}\" failed validation: ${issues.map((i) => i.message).join(\"; \")}`);\n this.name = \"ValidationError\";\n this.issues = issues;\n }\n}\n\n/** Thrown at startup for a malformed config. Never at send time. */\nexport class ConfigError extends EasyPingError {\n constructor(message: string) {\n super(message);\n this.name = \"ConfigError\";\n }\n}\n\nexport type Logger = {\n warn: (message: string, meta?: Record<string, unknown>) => void;\n error: (message: string, meta?: Record<string, unknown>) => void;\n};\n\nexport const consoleLogger: Logger = {\n warn: (message, meta) => console.warn(`[easy-ping] ${message}`, meta ?? \"\"),\n error: (message, meta) => console.error(`[easy-ping] ${message}`, meta ?? \"\"),\n};\n","import { decodeBase64Url, decodeBase64UrlBytes, encodeBase64Url } from \"./base64url\";\n\nexport type TokenClaims = {\n /** Subject — the user the token acts for. */\n uid: string;\n /** What the token is allowed to do. Verification requires an exact match. */\n purpose: string;\n /** Expiry, epoch seconds. */\n exp: number;\n /** Free-form, purpose-specific. */\n data?: Record<string, string>;\n};\n\nconst encoder = new TextEncoder();\n\nasync function hmacKey(secret: string): Promise<CryptoKey> {\n return crypto.subtle.importKey(\n \"raw\",\n encoder.encode(secret),\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\", \"verify\"],\n );\n}\n\nexport async function signToken(secret: string, claims: TokenClaims): Promise<string> {\n const body = encodeBase64Url(JSON.stringify(claims));\n const signature = await crypto.subtle.sign(\"HMAC\", await hmacKey(secret), encoder.encode(body));\n return `${body}.${encodeBase64Url(new Uint8Array(signature))}`;\n}\n\n/** null for every failure mode. Distinguishing them tells an attacker which part to fix. */\nexport async function verifyToken(\n secret: string,\n token: string,\n purpose: string,\n now: Date = new Date(),\n): Promise<TokenClaims | null> {\n const separator = token.lastIndexOf(\".\");\n if (separator <= 0) return null;\n\n const body = token.slice(0, separator);\n const signature = decodeBase64UrlBytes(token.slice(separator + 1));\n if (!signature) return null;\n\n // crypto.subtle.verify is constant-time.\n const valid = await crypto.subtle.verify(\n \"HMAC\",\n await hmacKey(secret),\n signature,\n encoder.encode(body),\n );\n if (!valid) return null;\n\n const decoded = decodeBase64Url(body);\n if (!decoded) return null;\n\n let claims: TokenClaims;\n try {\n claims = JSON.parse(decoded) as TokenClaims;\n } catch {\n return null;\n }\n\n if (typeof claims?.uid !== \"string\" || typeof claims.exp !== \"number\") return null;\n // Scoped so an unsubscribe token can never be replayed against another route.\n if (claims.purpose !== purpose) return null;\n if (claims.exp * 1000 <= now.getTime()) return null;\n\n return claims;\n}\n\nexport const DEFAULT_TOKEN_TTL_SECONDS = 30 * 24 * 60 * 60;\n\nexport const expiresIn = (seconds: number, now: Date = new Date()): number =>\n Math.floor(now.getTime() / 1000) + seconds;\n","import type { DatabaseAdapter } from \"./adapter\";\nimport type { SessionConfig } from \"./config\";\nimport type { Logger } from \"./errors\";\nimport type { RouteDefinition } from \"./plugin\";\nimport type { Runner } from \"./runner\";\nimport { verifyToken } from \"./tokens\";\n\nexport type HandlerDeps = {\n adapter: DatabaseAdapter;\n session: SessionConfig;\n runner: Runner;\n logger: Logger;\n basePath: string;\n secret: string;\n cronSecret?: string | undefined;\n pluginRoutes?: readonly RouteDefinition[] | undefined;\n};\n\nconst json = (body: unknown, status = 200) =>\n new Response(JSON.stringify(body), {\n status,\n headers: { \"content-type\": \"application/json\" },\n });\n\nconst empty = (status: number) => new Response(null, { status });\n\nconst MAX_READ_IDS = 200;\n\n/**\n * Constant-time comparison. Node's timingSafeEqual is unavailable on edge\n * runtimes, and `===` on a secret leaks its length and prefix through timing.\n */\nfunction timingSafeEqual(a: string, b: string): boolean {\n const encoder = new TextEncoder();\n const left = encoder.encode(a);\n const right = encoder.encode(b);\n\n let diff = left.length ^ right.length;\n const length = Math.max(left.length, right.length);\n for (let i = 0; i < length; i += 1) {\n diff |= (left[i] ?? 0) ^ (right[i] ?? 0);\n }\n return diff === 0;\n}\n\nfunction routePath(url: URL, basePath: string): string {\n const index = url.pathname.indexOf(basePath);\n if (index < 0) return url.pathname;\n return url.pathname.slice(index + basePath.length) || \"/\";\n}\n\nasync function readJson(request: Request): Promise<Record<string, unknown>> {\n try {\n const body = await request.json();\n return body && typeof body === \"object\" ? (body as Record<string, unknown>) : {};\n } catch {\n return {};\n }\n}\n\nexport function createHandler(deps: HandlerDeps) {\n async function resolveUserId(request: Request): Promise<string | null | \"error\"> {\n try {\n return await deps.session.getUserId(request);\n } catch (error) {\n // A broken session lookup is a 500, never a 401. Collapsing them makes\n // an outage look like a mass logout. RFC 0002 §1.\n deps.logger.error(\"session.getUserId threw\", { error });\n return \"error\";\n }\n }\n\n async function handleCron(request: Request): Promise<Response> {\n if (!deps.cronSecret) return empty(404);\n\n const header = request.headers.get(\"authorization\") ?? \"\";\n const presented = header.startsWith(\"Bearer \") ? header.slice(7) : header;\n\n if (!timingSafeEqual(presented, deps.cronSecret)) return empty(401);\n\n const result = await deps.runner.drain();\n return json(result);\n }\n\n /**\n * Plugin routes are dispatched before core ones and carry their scope with\n * them. Authentication happens here rather than in the plugin handler, so a\n * plugin physically cannot forget to check a signature or scope a query.\n */\n async function handlePluginRoute(\n route: RouteDefinition,\n request: Request,\n url: URL,\n ): Promise<Response> {\n if (route.scope.type === \"user\") {\n const userId = await resolveUserId(request);\n if (userId === \"error\") return empty(500);\n if (userId === null) return empty(401);\n return route.handler({ request, userId, claims: null, params: {} });\n }\n\n if (route.scope.type === \"machine\") {\n if (!deps.cronSecret) return empty(404);\n const header = request.headers.get(\"authorization\") ?? \"\";\n const presented = header.startsWith(\"Bearer \") ? header.slice(7) : header;\n if (!timingSafeEqual(presented, deps.cronSecret)) return empty(401);\n return route.handler({ request, userId: null, claims: null, params: {} });\n }\n\n if (route.scope.type === \"signed\") {\n const token =\n url.searchParams.get(\"token\") ??\n (request.headers.get(\"authorization\") ?? \"\").replace(/^Bearer /, \"\");\n\n const claims = await verifyToken(deps.secret, token, route.scope.purpose);\n // One response for every failure mode. Distinguishing expired from\n // forged tells an attacker which part to fix. RFC 0002 §5.\n if (!claims) return empty(400);\n\n return route.handler({ request, userId: claims.uid, claims, params: {} });\n }\n\n return route.handler({ request, userId: null, claims: null, params: {} });\n }\n\n async function handle(request: Request): Promise<Response> {\n const url = new URL(request.url);\n const path = routePath(url, deps.basePath);\n\n if (path === \"/cron\") {\n if (request.method !== \"POST\") return empty(405);\n return handleCron(request);\n }\n\n const pluginRoute = deps.pluginRoutes?.find(\n (route) => route.path === path && route.method === request.method,\n );\n if (pluginRoute) return handlePluginRoute(pluginRoute, request, url);\n\n const userId = await resolveUserId(request);\n if (userId === \"error\") return empty(500);\n if (userId === null) return empty(401);\n\n if (request.method === \"GET\" && path === \"/\") {\n const limitParam = Number(url.searchParams.get(\"limit\") ?? 20);\n const limit = Number.isFinite(limitParam) ? Math.min(Math.max(limitParam, 1), 100) : 20;\n const cursor = url.searchParams.get(\"cursor\");\n\n const page = await deps.adapter.listNotifications({\n userId,\n limit,\n ...(cursor ? { cursor } : {}),\n ...(url.searchParams.get(\"unreadOnly\") === \"true\" ? { unreadOnly: true } : {}),\n });\n return json(page);\n }\n\n if (request.method === \"GET\" && path === \"/count\") {\n return json({ unseen: await deps.adapter.countUnseen(userId) });\n }\n\n if (request.method === \"POST\" && path === \"/seen\") {\n const body = await readJson(request);\n const before = typeof body.before === \"string\" ? new Date(body.before) : null;\n\n // Defaults to now, but a client should send the timestamp of the newest\n // notification it has actually rendered. Otherwise anything that arrived\n // between the last poll and the click is marked seen without ever having\n // produced a badge — the user silently misses it.\n //\n // +1ms because Postgres keeps microseconds while an ISO string carries\n // only milliseconds. Without it the truncated cutoff falls *before* the\n // very row it was taken from, and markSeen matches nothing at all.\n const cutoff =\n before && !Number.isNaN(before.getTime()) ? new Date(before.getTime() + 1) : new Date();\n\n await deps.adapter.markSeen(userId, cutoff);\n return json({ ok: true });\n }\n\n if (request.method === \"POST\" && path === \"/read\") {\n const body = await readJson(request);\n const ids = Array.isArray(body.ids) ? body.ids.filter((id) => typeof id === \"string\") : [];\n if (ids.length === 0) return json({ error: \"ids must be a non-empty string array\" }, 400);\n\n // Unbounded, this builds a query with as many bind parameters as the\n // caller cares to send. Postgres caps at 65535 and degrades long before.\n if (ids.length > MAX_READ_IDS) {\n return json({ error: `at most ${MAX_READ_IDS} ids per request` }, 400);\n }\n\n // Scoped by userId in the adapter. A miss is 404, not 403 — a 403 would\n // confirm the row exists and belongs to someone else. RFC 0002 §2.\n const updated = await deps.adapter.markRead(userId, ids);\n return updated === 0 ? empty(404) : json({ updated });\n }\n\n if (request.method === \"POST\" && path === \"/read-all\") {\n return json({ updated: await deps.adapter.markAllRead(userId) });\n }\n\n return empty(404);\n }\n\n return {\n handle,\n GET: handle,\n POST: handle,\n };\n}\n","/**\n * Exponential backoff with ±20% jitter. RFC 0001 §4.\n *\n * These are minimums, not promises — the sweep interval floors them. Under an\n * hourly cron a 30s backoff is an hour.\n */\nconst SCHEDULE_MS = [30_000, 120_000, 480_000, 1_920_000] as const;\n\nexport type Backoff = \"exponential\" | ((attempt: number) => number);\n\nexport function backoffMs(attempt: number, strategy: Backoff = \"exponential\"): number {\n if (typeof strategy === \"function\") return Math.max(0, strategy(attempt));\n\n const index = Math.min(Math.max(attempt, 1), SCHEDULE_MS.length) - 1;\n const base = SCHEDULE_MS[index] ?? SCHEDULE_MS[SCHEDULE_MS.length - 1] ?? 30_000;\n return Math.round(base * (0.8 + Math.random() * 0.4));\n}\n\nexport const nextAttemptAt = (attempt: number, strategy?: Backoff, now = new Date()): Date =>\n new Date(now.getTime() + backoffMs(attempt, strategy));\n","import type { ClaimedDelivery, DatabaseAdapter, DeliveryOutcome, DeliveryRelease } from \"./adapter\";\nimport { type Backoff, nextAttemptAt } from \"./backoff\";\nimport type { ChannelsConfig, Worker } from \"./config\";\nimport type { NotificationDefinitions } from \"./definition\";\nimport type { Logger } from \"./errors\";\nimport type { AnyPlugin } from \"./plugin\";\nimport type { Channel, Recipient } from \"./types\";\n\nexport type RunnerDeps = {\n adapter: DatabaseAdapter;\n definitions: NotificationDefinitions;\n channels: ChannelsConfig;\n plugins: readonly AnyPlugin[];\n getRecipients: (userIds: readonly string[]) => Promise<readonly Recipient[]>;\n logger: Logger;\n leaseMs: number;\n batchSize: number;\n backoff: Backoff;\n};\n\nexport type SweepResult = {\n claimed: number;\n sent: number;\n failed: number;\n};\n\nconst sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));\n\nasync function withTimeout<T>(\n run: (signal: AbortSignal) => Promise<T>,\n ms: number,\n label: string,\n): Promise<T> {\n const controller = new AbortController();\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n const timeout = new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n // Abort first: racing a promise leaves the original request running.\n controller.abort();\n reject(new Error(`${label} timed out after ${ms}ms`));\n }, ms);\n });\n\n try {\n return await Promise.race([run(controller.signal), timeout]);\n } finally {\n clearTimeout(timer);\n }\n}\n\nconst message = (error: unknown) => (error instanceof Error ? error.message : String(error));\n\nexport function createRunner(deps: RunnerDeps) {\n async function deliverOne(\n delivery: ClaimedDelivery,\n recipient: Recipient | undefined,\n ): Promise<DeliveryOutcome> {\n if (!recipient) {\n return { result: \"failed\", error: \"recipient could not be resolved\", retryable: false };\n }\n\n if (delivery.channel === \"inApp\") {\n // The notification row is the delivery. Nothing to transmit.\n return { result: \"sent\" };\n }\n\n if (delivery.channel === \"email\") {\n const provider = deps.channels.email?.provider;\n if (!provider) {\n return { result: \"failed\", error: \"no email provider configured\", retryable: false };\n }\n // Captured before the closure below: narrowing does not survive into it.\n const to = recipient.email;\n if (!to) {\n return { result: \"failed\", error: \"recipient has no email address\", retryable: false };\n }\n\n const email = deps.definitions[delivery.notification.type]?.email;\n if (!email) {\n return {\n result: \"failed\",\n error: `notification type \"${delivery.notification.type}\" has no email template`,\n retryable: false,\n };\n }\n\n try {\n const payload = delivery.notification.payload as never;\n const html = await email.template(payload);\n\n await withTimeout(\n (signal) =>\n provider.send({\n to,\n subject: email.subject(payload),\n html,\n // Delivery is at-least-once; the provider dedupes on this.\n idempotencyKey: delivery.id,\n signal,\n }),\n provider.timeoutMs ?? 30_000,\n `${provider.name} send`,\n );\n\n return { result: \"sent\" };\n } catch (error) {\n return {\n result: \"failed\",\n error: message(error),\n retryable: provider.isRetryable(error),\n };\n }\n }\n\n const owner = deps.plugins.find(\n (plugin) => plugin.channels?.includes(delivery.channel) && plugin.hooks?.deliver,\n );\n if (!owner?.hooks?.deliver) {\n return {\n result: \"failed\",\n error: `no plugin delivers channel \"${delivery.channel}\"`,\n retryable: false,\n };\n }\n\n try {\n return await withTimeout(\n (signal) =>\n Promise.resolve(\n // biome-ignore lint/style/noNonNullAssertion: guarded directly above\n owner.hooks!.deliver!({\n channel: delivery.channel,\n deliveryId: delivery.id,\n attempt: delivery.attempts + 1,\n recipient,\n notification: {\n id: delivery.notificationId,\n userId: delivery.notification.userId,\n type: delivery.notification.type,\n payload: delivery.notification.payload,\n },\n signal,\n }),\n ),\n 30_000,\n `plugin \"${owner.id}\" deliver`,\n );\n } catch (error) {\n return { result: \"failed\", error: message(error), retryable: true };\n }\n }\n\n async function notifyAfterDeliver(delivery: ClaimedDelivery, outcome: DeliveryOutcome) {\n const isTerminal =\n outcome.result === \"sent\" ||\n !outcome.retryable ||\n delivery.attempts + 1 >= delivery.maxAttempts;\n\n for (const plugin of deps.plugins) {\n const hook = plugin.hooks?.afterDeliver;\n if (!hook) continue;\n try {\n await hook({\n deliveryId: delivery.id,\n notificationId: delivery.notificationId,\n userId: delivery.notification.userId,\n channel: delivery.channel,\n outcome,\n attempt: delivery.attempts + 1,\n isTerminal,\n });\n } catch (error) {\n // Fail open. The message is already sent; a broken analytics hook must\n // not mark it failed and trigger a retry. RFC 0004 §5.\n deps.logger.error(`plugin \"${plugin.id}\" afterDeliver threw; ignoring`, {\n deliveryId: delivery.id,\n error,\n });\n }\n }\n }\n\n async function runOnce(\n options: { limit?: number; channels?: readonly Channel[]; ids?: readonly string[] } = {},\n ): Promise<SweepResult> {\n const claimToken = crypto.randomUUID();\n\n const claimed = await deps.adapter.claimPendingDeliveries({\n limit: options.limit ?? deps.batchSize,\n leaseMs: deps.leaseMs,\n claimToken,\n ...(options.channels ? { channels: options.channels } : {}),\n ...(options.ids ? { ids: options.ids } : {}),\n });\n\n if (claimed.length === 0) return { claimed: 0, sent: 0, failed: 0 };\n\n const userIds = [...new Set(claimed.map((row) => row.notification.userId))];\n const recipients = await deps.getRecipients(userIds);\n const byUserId = new Map(recipients.map((recipient) => [recipient.userId, recipient]));\n\n const releases: DeliveryRelease[] = [];\n let sent = 0;\n let failed = 0;\n\n for (const delivery of claimed) {\n const outcome = await deliverOne(delivery, byUserId.get(delivery.notification.userId));\n\n if (outcome.result === \"sent\") sent += 1;\n else failed += 1;\n\n releases.push({\n id: delivery.id,\n claimToken,\n outcome,\n ...(outcome.result === \"failed\" && outcome.retryable\n ? { nextAttemptAt: nextAttemptAt(delivery.attempts + 1, deps.backoff) }\n : {}),\n });\n\n await notifyAfterDeliver(delivery, outcome);\n }\n\n await deps.adapter.releaseDeliveries(releases);\n return { claimed: claimed.length, sent, failed };\n }\n\n /** Drains until empty. Pass `ids` to bound it to one send. */\n async function drain(\n options: { maxSweeps?: number; ids?: readonly string[] } = {},\n ): Promise<SweepResult> {\n const maxSweeps = options.maxSweeps ?? 50;\n const total: SweepResult = { claimed: 0, sent: 0, failed: 0 };\n\n for (let sweep = 0; sweep < maxSweeps; sweep += 1) {\n const result = await runOnce(options.ids ? { ids: options.ids } : {});\n total.claimed += result.claimed;\n total.sent += result.sent;\n total.failed += result.failed;\n if (result.claimed === 0) break;\n }\n\n return total;\n }\n\n let warnedMissingWaitUntil = false;\n\n function scheduleDeferred(\n waitUntil?: (promise: Promise<unknown>) => void,\n ids?: readonly string[],\n ): void {\n if (waitUntil) {\n waitUntil(\n drain({ maxSweeps: 10, ...(ids ? { ids } : {}) }).catch((error) =>\n deps.logger.error(\"deferred sweep failed\", { error }),\n ),\n );\n return;\n }\n\n if (!warnedMissingWaitUntil) {\n warnedMissingWaitUntil = true;\n deps.logger.warn(\n \"delivery.mode is 'deferred' but no delivery.waitUntil was supplied — \" +\n \"falling back to the cron sweep. Notifications are not lost, but they \" +\n \"will not be delivered until POST /cron runs.\",\n );\n }\n }\n\n function startWorker(options: { intervalMs?: number; batchSize?: number } = {}): Worker {\n const intervalMs = options.intervalMs ?? 1_000;\n let stopped = false;\n\n const loop = (async () => {\n while (!stopped) {\n try {\n const result = await runOnce({ limit: options.batchSize ?? deps.batchSize });\n // Only idle when there was nothing to do; otherwise keep draining.\n if (result.claimed === 0) await sleep(intervalMs);\n } catch (error) {\n deps.logger.error(\"worker sweep failed\", { error });\n await sleep(intervalMs);\n }\n }\n })();\n\n return {\n stop: async () => {\n stopped = true;\n // Awaiting the loop lets the in-flight sweep finish and release its\n // leases, rather than leaving rows claimed until they expire.\n await loop;\n },\n };\n }\n\n return { runOnce, drain, scheduleDeferred, startWorker };\n}\n\nexport type Runner = ReturnType<typeof createRunner>;\n","import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { DatabaseAdapter, InsertDelivery, InsertNotification } from \"./adapter\";\nimport type { ChannelsConfig, SendResult } from \"./config\";\nimport type { NotificationDefinitions } from \"./definition\";\nimport { type Logger, ValidationError } from \"./errors\";\nimport type { AnyPlugin, BeforeSendResult, ChannelDecision } from \"./plugin\";\nimport type { Channel, Recipient, SkipReason } from \"./types\";\n\nexport type SendPipelineDeps = {\n adapter: DatabaseAdapter;\n definitions: NotificationDefinitions;\n channels: ChannelsConfig;\n plugins: readonly AnyPlugin[];\n getRecipients: (userIds: readonly string[]) => Promise<readonly Recipient[]>;\n maxAttempts: number;\n logger: Logger;\n generateId?: () => string;\n};\n\nexport type SendInput = {\n to: string | readonly string[];\n payload: unknown;\n actorId?: string | undefined;\n dedupeKey?: string | undefined;\n overrides?: { channels?: readonly Channel[] } | undefined;\n};\n\nasync function validatePayload(type: string, schema: StandardSchemaV1, payload: unknown) {\n const result = await schema[\"~standard\"].validate(payload);\n if (result.issues) {\n throw new ValidationError(\n type,\n result.issues.map((issue) => ({\n message: issue.message,\n ...(issue.path ? { path: issue.path.map(String).join(\".\") } : {}),\n })),\n );\n }\n return result.value;\n}\n\n/**\n * A channel is deliverable only if something can actually carry it.\n *\n * inApp defaults to on when unconfigured — it needs no provider, it is the\n * library's core feature, and making every app write `inApp: { enabled: true }`\n * is noise. Every other channel is off until given a provider, so a type\n * declaring `channels: [\"email\"]` with no email provider silently degrades to\n * in-app rather than throwing at send time.\n */\nexport function isChannelUsable(\n channel: Channel,\n channels: ChannelsConfig,\n plugins: readonly AnyPlugin[] = [],\n): boolean {\n if (channel === \"inApp\") return channels.inApp?.enabled !== false;\n if (channel === \"email\") return Boolean(channels.email?.provider);\n // Anything else is usable only if a plugin claims it and can deliver it.\n return plugins.some((plugin) => plugin.channels?.includes(channel) && plugin.hooks?.deliver);\n}\n\n/** One prepare() per plugin per send, keyed by plugin id. */\nasync function runPrepare(\n plugins: readonly AnyPlugin[],\n ctx: { type: string; recipients: readonly Recipient[] },\n logger: Logger,\n): Promise<Map<string, unknown>> {\n const prepared = new Map<string, unknown>();\n\n for (const plugin of plugins) {\n const hook = plugin.hooks?.prepare;\n if (!hook) continue;\n try {\n prepared.set(plugin.id, await hook(ctx));\n } catch (error) {\n // Fail closed, consistent with the hooks that consume this: a plugin\n // whose bulk load failed must not then decide with stale assumptions.\n logger.error(`plugin \"${plugin.id}\" prepare threw; its hooks will see undefined`, {\n type: ctx.type,\n error,\n });\n prepared.set(plugin.id, undefined);\n }\n }\n\n return prepared;\n}\n\nasync function runBeforeSend(\n plugins: readonly AnyPlugin[],\n base: { type: string; recipient: Recipient; actorId: string | null },\n payload: unknown,\n dedupeKey: string | null,\n prepared: Map<string, unknown>,\n logger: Logger,\n): Promise<BeforeSendResult> {\n let currentPayload = payload;\n let currentDedupeKey = dedupeKey;\n\n for (const plugin of plugins) {\n const hook = plugin.hooks?.beforeSend;\n if (!hook) continue;\n\n let result: BeforeSendResult;\n try {\n result = await hook({\n ...base,\n payload: currentPayload,\n dedupeKey: currentDedupeKey,\n prepared: prepared.get(plugin.id),\n });\n } catch (error) {\n // Fail closed. A crashed preferences hook failing open would email\n // people who opted out — a compliance incident. RFC 0004 §5.\n logger.error(`plugin \"${plugin.id}\" beforeSend threw; cancelling send`, {\n type: base.type,\n userId: base.recipient.userId,\n error,\n });\n return { action: \"cancel\", reason: `plugin \"${plugin.id}\" beforeSend threw` };\n }\n\n if (result.action === \"cancel\") return result;\n if (result.payload !== undefined) currentPayload = result.payload;\n if (result.dedupeKey !== undefined) currentDedupeKey = result.dedupeKey;\n }\n\n return {\n action: \"continue\",\n payload: currentPayload,\n ...(currentDedupeKey === null ? {} : { dedupeKey: currentDedupeKey }),\n };\n}\n\nasync function runResolveChannels(\n plugins: readonly AnyPlugin[],\n base: { type: string; recipient: Recipient; payload: unknown },\n initial: readonly ChannelDecision[],\n prepared: Map<string, unknown>,\n logger: Logger,\n): Promise<readonly ChannelDecision[]> {\n let decisions = initial;\n\n for (const plugin of plugins) {\n const hook = plugin.hooks?.resolveChannels;\n if (!hook) continue;\n\n try {\n decisions = [...(await hook({ ...base, decisions, prepared: prepared.get(plugin.id) }))];\n } catch (error) {\n // Fail closed: keep the decisions already made rather than falling back\n // to the permissive default. RFC 0004 §5.\n logger.error(`plugin \"${plugin.id}\" resolveChannels threw; keeping prior decisions`, {\n type: base.type,\n userId: base.recipient.userId,\n error,\n });\n return decisions;\n }\n }\n\n return decisions;\n}\n\nexport async function runSend(\n type: string,\n input: SendInput,\n deps: SendPipelineDeps,\n): Promise<SendResult> {\n const definition = deps.definitions[type];\n if (!definition) {\n throw new ValidationError(type, [{ message: `unknown notification type \"${type}\"` }]);\n }\n\n const payload = definition.schema\n ? await validatePayload(type, definition.schema, input.payload)\n : input.payload;\n\n const userIds = [...new Set(Array.isArray(input.to) ? input.to : [input.to as string])];\n const recipients = await deps.getRecipients(userIds);\n const byUserId = new Map(recipients.map((recipient) => [recipient.userId, recipient]));\n\n const newId = deps.generateId ?? (() => crypto.randomUUID());\n const skipped: { userId: string; reason: SkipReason }[] = [];\n const rows: InsertNotification[] = [];\n const actorId = input.actorId ?? null;\n\n const declared = input.overrides?.channels ?? definition.channels;\n const requested = declared.filter((channel) =>\n isChannelUsable(channel, deps.channels, deps.plugins),\n );\n\n // Distinguished from \"no-channels\" so a missing provider does not look\n // identical to a user having opted out of everything.\n if (declared.length > 0 && requested.length === 0) {\n return {\n notifications: [],\n skipped: userIds.map((userId) => ({ userId, reason: \"channel-unavailable\" as const })),\n };\n }\n\n const prepared = await runPrepare(deps.plugins, { type, recipients }, deps.logger);\n\n for (const userId of userIds) {\n const recipient = byUserId.get(userId);\n if (!recipient) {\n skipped.push({ userId, reason: \"no-recipient\" });\n continue;\n }\n\n const before = await runBeforeSend(\n deps.plugins,\n { type, recipient, actorId },\n payload,\n input.dedupeKey ?? null,\n prepared,\n deps.logger,\n );\n\n if (before.action === \"cancel\") {\n skipped.push({ userId, reason: \"no-channels\" });\n continue;\n }\n\n const resolved = await runResolveChannels(\n deps.plugins,\n { type, recipient, payload: before.payload ?? payload },\n requested.map((channel) => ({ channel, action: \"send\" as const })),\n prepared,\n deps.logger,\n );\n\n const now = new Date();\n const deliveries: InsertDelivery[] = resolved\n .filter((decision) => decision.action !== \"skip\")\n .filter((decision) => isChannelUsable(decision.channel, deps.channels, deps.plugins))\n .map((decision) => ({\n id: newId(),\n channel: decision.channel,\n maxAttempts: definition.maxAttempts ?? deps.maxAttempts,\n // `defer` needs no machinery beyond not_before — the claim query\n // already refuses rows whose time has not come. RFC 0004 §4.2.\n notBefore: decision.action === \"defer\" && decision.notBefore ? decision.notBefore : now,\n }));\n\n if (deliveries.length === 0) {\n skipped.push({ userId, reason: \"no-channels\" });\n continue;\n }\n\n const dedupeKey = before.action === \"continue\" ? before.dedupeKey : undefined;\n\n rows.push({\n id: newId(),\n userId,\n type,\n payload: before.payload ?? payload,\n ...(actorId ? { actorId } : {}),\n ...(dedupeKey ? { dedupeKey } : {}),\n deliveries,\n });\n }\n\n if (rows.length === 0) return { notifications: [], skipped };\n\n const { created, deduped } = await deps.adapter.createNotifications(rows);\n const createdSet = new Set(created);\n\n for (const row of rows) {\n if (deduped.includes(row.id)) skipped.push({ userId: row.userId, reason: \"deduped\" });\n }\n\n const notifications = rows\n .filter((row) => createdSet.has(row.id))\n .map((row) => ({\n id: row.id,\n userId: row.userId,\n deliveries: row.deliveries.map((delivery) => ({\n id: delivery.id,\n channel: delivery.channel,\n })),\n }));\n\n for (const plugin of deps.plugins) {\n const hook = plugin.hooks?.afterSend;\n if (!hook) continue;\n try {\n await hook({\n type,\n payload,\n notifications: notifications.map(({ id, userId }) => ({ id, userId })),\n prepared: prepared.get(plugin.id),\n });\n } catch (error) {\n // Fails open: the rows are committed, and throwing here would report a\n // send that actually happened as a failure.\n deps.logger.error(`plugin \"${plugin.id}\" afterSend threw; ignoring`, { type, error });\n }\n }\n\n return { notifications, skipped };\n}\n","import type { SchemaDeclaration } from \"../core/plugin\";\n\nexport const toSnakeCase = (value: string) => value.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`);\n\n/**\n * Core tables in the format plugins use. Less expressive than the hand-written\n * Drizzle schema (no partial indexes, ordering or cascade) — a drift test\n * asserts the two agree on the fields they share.\n */\nexport const coreSchema = {\n notification: {\n tableName: \"notification\",\n fields: {\n id: { type: \"string\", required: true },\n userId: { type: \"string\", required: true },\n type: { type: \"string\", required: true },\n payload: { type: \"json\", required: true },\n actorId: { type: \"string\" },\n groupKey: { type: \"string\" },\n dedupeKey: { type: \"string\" },\n seenAt: { type: \"date\" },\n readAt: { type: \"date\" },\n archivedAt: { type: \"date\" },\n createdAt: { type: \"date\", required: true, defaultNow: true },\n },\n primaryKey: [\"id\"],\n indexes: [\n { on: [\"userId\", \"createdAt\"], name: \"notification_feed_idx\" },\n { on: [\"userId\", \"groupKey\"], name: \"notification_group_idx\" },\n { on: [\"userId\", \"dedupeKey\"], unique: true, name: \"notification_dedupe_idx\" },\n ],\n },\n\n notificationDelivery: {\n tableName: \"notification_delivery\",\n fields: {\n id: { type: \"string\", required: true },\n notificationId: { type: \"string\", required: true },\n channel: { type: \"string\", required: true },\n status: { type: \"string\", required: true, default: \"pending\" },\n attempts: { type: \"number\", required: true, default: 0 },\n maxAttempts: { type: \"number\", required: true, default: 5 },\n notBefore: { type: \"date\", required: true, defaultNow: true },\n claimedAt: { type: \"date\" },\n claimedBy: { type: \"string\" },\n lastError: { type: \"string\" },\n updatedAt: { type: \"date\", required: true, defaultNow: true },\n },\n primaryKey: [\"id\"],\n indexes: [\n { on: [\"status\", \"notBefore\"], name: \"delivery_claim_idx\" },\n { on: [\"notificationId\"], name: \"delivery_notification_idx\" },\n ],\n },\n\n notificationPreference: {\n tableName: \"notification_preference\",\n fields: {\n userId: { type: \"string\", required: true },\n type: { type: \"string\", required: true },\n channel: { type: \"string\", required: true },\n enabled: { type: \"boolean\", required: true, default: true },\n frequency: { type: \"string\", required: true, default: \"instant\" },\n },\n primaryKey: [\"userId\", \"type\", \"channel\"],\n },\n} satisfies SchemaDeclaration;\n","import { toSnakeCase } from \"../schema/declaration\";\nimport { ConfigError } from \"./errors\";\nimport type { SchemaDeclaration, TableDeclaration } from \"./plugin\";\n\nexport type Scalar = string | number | boolean | Date | null;\n\n/**\n * One operator per condition. Operators are tagged objects so a bare value is\n * always an equality test; json columns therefore cannot be filtered, since an\n * object value would be ambiguous.\n */\nexport type WhereCondition =\n | Scalar\n | { in: readonly (string | number)[] }\n | { lt: Date | number }\n | { lte: Date | number }\n | { gt: Date | number }\n | { gte: Date | number }\n | { not: Scalar };\n\nexport type WhereClause = Record<string, WhereCondition>;\n\nexport type QueryOptions = {\n limit?: number;\n orderBy?: { field: string; direction: \"asc\" | \"desc\" };\n};\n\nexport type UpsertOptions = { onConflict: readonly string[] };\n\n/**\n * Table access for plugins, scoped to the tables that plugin declared.\n *\n * Plugins could always declare tables via schema() but had no way to read\n * them, so preferences had to bolt its queries onto the core adapter. That\n * does not generalise to digests or push.\n */\nexport type PluginStore = {\n find<T = Record<string, unknown>>(\n table: string,\n where?: WhereClause,\n options?: QueryOptions,\n ): Promise<T[]>;\n insert(table: string, rows: readonly Record<string, unknown>[]): Promise<number>;\n upsert(\n table: string,\n rows: readonly Record<string, unknown>[],\n options: UpsertOptions,\n ): Promise<number>;\n update(table: string, where: WhereClause, set: Record<string, unknown>): Promise<number>;\n remove(table: string, where: WhereClause): Promise<number>;\n};\n\nexport type TableStorage = {\n readonly naming?: \"snake_case\" | \"preserve\";\n readonly serializesJson?: boolean;\n\n queryTable(\n table: string,\n where: WhereClause,\n options: QueryOptions,\n ): Promise<Record<string, unknown>[]>;\n insertRows(\n table: string,\n rows: readonly Record<string, unknown>[],\n onConflict?: readonly string[],\n ): Promise<number>;\n updateRows(table: string, where: WhereClause, set: Record<string, unknown>): Promise<number>;\n deleteRows(table: string, where: WhereClause): Promise<number>;\n};\n\nconst OPERATORS = [\"in\", \"lt\", \"lte\", \"gt\", \"gte\", \"not\"] as const;\n\nexport const isOperator = (value: unknown): boolean =>\n typeof value === \"object\" &&\n value !== null &&\n !(value instanceof Date) &&\n OPERATORS.some((op) => op in value);\n\n/**\n * Every table and column a plugin touches is checked against its own\n * declaration. Without this a plugin could read the notification table, and\n * unvalidated identifiers would reach the SQL builder.\n */\nexport function createPluginStore(\n pluginId: string,\n schema: SchemaDeclaration | undefined,\n storage: TableStorage,\n prefix: string,\n): PluginStore {\n const byTableName = new Map<string, TableDeclaration>();\n for (const declaration of Object.values(schema ?? {})) {\n byTableName.set(declaration.tableName, declaration);\n }\n\n function resolve(table: string): TableDeclaration {\n const declaration = byTableName.get(table);\n if (!declaration) {\n throw new ConfigError(\n `plugin \"${pluginId}\" accessed table \"${table}\", which it does not declare in schema().`,\n );\n }\n return declaration;\n }\n\n function checkFields(table: TableDeclaration, fields: Iterable<string>, context: string) {\n for (const field of fields) {\n const spec = table.fields[field];\n if (!spec) {\n throw new ConfigError(\n `plugin \"${pluginId}\" used unknown field \"${field}\" on \"${table.tableName}\" (${context}).`,\n );\n }\n if (context === \"where\" && spec.type === \"json\") {\n throw new ConfigError(\n `plugin \"${pluginId}\" cannot filter on json field \"${field}\"; ` +\n \"a bare object value is indistinguishable from an operator.\",\n );\n }\n }\n }\n\n const qualified = (table: TableDeclaration) => prefix + table.tableName;\n\n // A document store keeps the declared names; a SQL adapter wants columns.\n const column = (field: string) => (storage.naming === \"preserve\" ? field : toSnakeCase(field));\n\n /**\n * json columns must be handed to the driver as text; postgres-js cannot bind\n * a plain object and the insert fails outright.\n */\n const serialize = (table: TableDeclaration, row: Record<string, unknown>) => {\n if (storage.serializesJson === false) return row;\n\n const out: Record<string, unknown> = {};\n for (const [field, value] of Object.entries(row)) {\n out[field] =\n table.fields[field]?.type === \"json\" && value !== null && value !== undefined\n ? JSON.stringify(value)\n : value;\n }\n return out;\n };\n\n return {\n async find(table, where = {}, options = {}) {\n const declaration = resolve(table);\n checkFields(declaration, Object.keys(where), \"where\");\n if (options.orderBy) checkFields(declaration, [options.orderBy.field], \"orderBy\");\n\n const rows = await storage.queryTable(qualified(declaration), where, options);\n\n // SELECT * returns snake_case columns; plugins declare camelCase fields\n // and type their reads that way. Without this every property is\n // undefined at runtime while typechecking perfectly.\n return rows.map((row) => {\n const mapped: Record<string, unknown> = {};\n for (const field of Object.keys(declaration.fields)) {\n const value = row[column(field)];\n // Drivers differ: some hand back parsed jsonb, some raw text.\n mapped[field] =\n declaration.fields[field]?.type === \"json\" && typeof value === \"string\"\n ? JSON.parse(value)\n : value;\n }\n return mapped;\n }) as never;\n },\n\n async insert(table, rows) {\n const declaration = resolve(table);\n for (const row of rows) checkFields(declaration, Object.keys(row), \"insert\");\n return storage.insertRows(\n qualified(declaration),\n rows.map((row) => serialize(declaration, row)),\n );\n },\n\n async upsert(table, rows, options) {\n const declaration = resolve(table);\n for (const row of rows) checkFields(declaration, Object.keys(row), \"upsert\");\n checkFields(declaration, options.onConflict, \"onConflict\");\n return storage.insertRows(\n qualified(declaration),\n rows.map((row) => serialize(declaration, row)),\n options.onConflict,\n );\n },\n\n async update(table, where, set) {\n const declaration = resolve(table);\n checkFields(declaration, Object.keys(where), \"where\");\n checkFields(declaration, Object.keys(set), \"update\");\n return storage.updateRows(qualified(declaration), where, serialize(declaration, set));\n },\n\n async remove(table, where) {\n const declaration = resolve(table);\n checkFields(declaration, Object.keys(where), \"where\");\n return storage.deleteRows(qualified(declaration), where);\n },\n };\n}\n","import type { Backoff } from \"./backoff\";\nimport type { EasyPing, EasyPingConfig, HealthReport, SendArgs, SendResult } from \"./config\";\nimport type { NotificationDefinitions } from \"./definition\";\nimport { ConfigError, consoleLogger } from \"./errors\";\nimport { createHandler } from \"./handler\";\nimport type { AnyPlugin } from \"./plugin\";\nimport { createRunner } from \"./runner\";\nimport { isChannelUsable, runSend } from \"./send\";\nimport { createPluginStore } from \"./store\";\nimport type { DeliveryMode } from \"./types\";\n\nconst DEFAULTS = {\n maxAttempts: 5,\n leaseMs: 60_000,\n batchSize: 20,\n basePath: \"/api/notifications\",\n mode: \"cron\" as DeliveryMode,\n};\n\nfunction validate(config: EasyPingConfig<NotificationDefinitions>, plugins: readonly AnyPlugin[]) {\n if (!config.database) throw new ConfigError(\"`database` is required.\");\n if (!config.notifications) throw new ConfigError(\"`notifications` is required.\");\n\n // No default resolver and no dev bypass: the inbox endpoints serve per-user\n // data, and an insecure default ships where a startup crash does not.\n if (typeof config.session?.getUserId !== \"function\") {\n throw new ConfigError(\n \"`session.getUserId` is required — the mounted endpoints serve a user's private inbox \" +\n \"and must resolve the caller. See RFC 0002.\",\n );\n }\n\n if (!config.secret) {\n throw new ConfigError(\n \"`secret` is required — it signs unsubscribe and other session-less links. \" +\n \"Adding it later is a breaking change, so it is mandatory from the start.\",\n );\n }\n\n if (typeof config.getRecipients !== \"function\") {\n throw new ConfigError(\"`getRecipients` is required to resolve emails and timezones.\");\n }\n\n const seen = new Set<string>();\n for (const plugin of plugins) {\n if (seen.has(plugin.id)) {\n throw new ConfigError(`duplicate plugin id \"${plugin.id}\" — ids must be unique.`);\n }\n seen.add(plugin.id);\n }\n\n for (const plugin of plugins) {\n for (const dependency of plugin.dependsOn ?? []) {\n if (!seen.has(dependency)) {\n throw new ConfigError(\n `plugin \"${plugin.id}\" requires \"${dependency}\", which is not registered.`,\n );\n }\n }\n }\n\n // Two plugins claiming the same route silently shadow each other otherwise,\n // and which one wins depends on registration order.\n const routes = new Set<string>();\n for (const plugin of plugins) {\n for (const route of plugin.routes ?? []) {\n const signature = `${route.method} ${route.path}`;\n if (routes.has(signature)) {\n throw new ConfigError(`route collision: two plugins both registered \"${signature}\".`);\n }\n routes.add(signature);\n }\n }\n\n const mode = config.delivery?.mode ?? DEFAULTS.mode;\n if ((mode === \"cron\" || mode === \"deferred\") && !config.cron?.secret) {\n throw new ConfigError(\n `delivery.mode \"${mode}\" relies on the cron sweep, so \\`cron.secret\\` is required. ` +\n \"Left unset the endpoint would be unauthenticated — a free flush-everything trigger \" +\n \"against your email provider. See RFC 0002 §4.\",\n );\n }\n}\n\nexport function easyPing<TDefs extends NotificationDefinitions>(\n config: EasyPingConfig<TDefs>,\n): EasyPing<TDefs> {\n const plugins = config.plugins ?? [];\n validate(config as EasyPingConfig<NotificationDefinitions>, plugins);\n\n const logger = config.logger ?? consoleLogger;\n const tablePrefix = config.tablePrefix ?? \"\";\n const mode = config.delivery?.mode ?? DEFAULTS.mode;\n const leaseMs = config.delivery?.leaseMs ?? DEFAULTS.leaseMs;\n const warnings: string[] = [];\n\n // Below this ratio a slow send is re-claimed mid-flight, and duplicates stop\n // being occasional and become systematic. RFC 0003 §7.\n const providerTimeout = config.channels.email?.provider?.timeoutMs;\n if (providerTimeout !== undefined && providerTimeout >= leaseMs / 2) {\n warnings.push(\n `email provider timeout (${providerTimeout}ms) is at least half of delivery.leaseMs ` +\n `(${leaseMs}ms); raise leaseMs or duplicate sends become systematic.`,\n );\n }\n\n // Declaring `channels: [\"push\"]` used to do nothing at all: no warning, and\n // a skip reason indistinguishable from the user having opted out.\n const unusable = new Map<string, string[]>();\n for (const [type, definition] of Object.entries(config.notifications)) {\n const missing = definition.channels.filter(\n (channel) => !isChannelUsable(channel, config.channels, plugins),\n );\n if (missing.length > 0) unusable.set(type, [...missing]);\n }\n\n for (const [type, channels] of unusable) {\n const dead = channels.length === config.notifications[type]?.channels.length;\n warnings.push(\n `notification \"${type}\" declares ${channels.map((c) => `\"${c}\"`).join(\", \")} ` +\n `but no provider is configured for ${channels.length > 1 ? \"them\" : \"it\"}` +\n (dead ? \" — this type can never be delivered.\" : \"; those channels will be skipped.\"),\n );\n }\n\n if (mode === \"deferred\" && !config.delivery?.waitUntil) {\n warnings.push(\n \"delivery.mode is 'deferred' but no delivery.waitUntil was supplied; \" +\n \"delivery will wait for the cron sweep.\",\n );\n }\n\n for (const warning of warnings) logger.warn(warning);\n\n const runner = createRunner({\n adapter: config.database,\n definitions: config.notifications,\n channels: config.channels,\n plugins,\n getRecipients: config.getRecipients,\n logger,\n leaseMs,\n batchSize: config.delivery?.batchSize ?? DEFAULTS.batchSize,\n backoff: (config.delivery?.backoff ?? \"exponential\") as Backoff,\n });\n\n const pluginRoutes = plugins.flatMap((plugin) => plugin.routes ?? []);\n\n const handler = createHandler({\n adapter: config.database,\n session: config.session,\n runner,\n logger,\n secret: config.secret,\n basePath: config.basePath ?? DEFAULTS.basePath,\n pluginRoutes,\n ...(config.cron?.secret ? { cronSecret: config.cron.secret } : {}),\n });\n\n async function send<TKey extends keyof TDefs & string>(\n type: TKey,\n args: SendArgs<TDefs, TKey>,\n ): Promise<SendResult> {\n const result = await runSend(\n type,\n {\n to: args.to,\n payload: args.payload,\n actorId: args.actorId,\n dedupeKey: args.dedupeKey,\n overrides: args.overrides,\n },\n {\n adapter: config.database,\n definitions: config.notifications,\n channels: config.channels,\n plugins,\n getRecipients: config.getRecipients,\n maxAttempts: config.delivery?.maxAttempts ?? DEFAULTS.maxAttempts,\n logger,\n },\n );\n\n // The rows are committed by this point, so every branch below only affects\n // latency — never whether the notification survives. RFC 0001 §8.1.\n if (result.notifications.length > 0) {\n // Scoped to this send's deliveries. Unscoped, a single inline send in a\n // request handler flushes the whole backlog.\n const ids = result.notifications.flatMap((notification) =>\n notification.deliveries.map((delivery) => delivery.id),\n );\n\n if (mode === \"inline\") await runner.drain({ ids });\n else if (mode === \"deferred\") runner.scheduleDeferred(config.delivery?.waitUntil, ids);\n }\n\n return result;\n }\n\n // After send() exists, before any hook or route can run.\n for (const plugin of plugins) {\n plugin.init?.({\n store: createPluginStore(plugin.id, plugin.schema, config.database, tablePrefix),\n secret: config.secret,\n logger,\n getRecipients: config.getRecipients,\n send: (type, args) => send(type as keyof TDefs & string, args as never) as Promise<unknown>,\n });\n }\n\n return {\n send,\n handler,\n\n startWorker: (options) => runner.startWorker(options ?? {}),\n\n getFailedDeliveries: (options = {}) =>\n config.database.getFailedDeliveries({\n since: options.since ?? new Date(Date.now() - 24 * 3600_000),\n limit: Math.min(options.limit ?? 100, 1000),\n }),\n\n healthCheck: async (): Promise<HealthReport> => {\n const cronMounted = Boolean(config.cron?.secret);\n return {\n mode,\n cronMounted,\n cronRequiredButMissing:\n !cronMounted && (mode === \"cron\" || mode === \"deferred\" || mode === \"inline\"),\n warnings,\n };\n },\n };\n}\n","import type { DeliveryOutcome } from \"./adapter\";\nimport type { Logger } from \"./errors\";\nimport type { PluginStore } from \"./store\";\nimport type { Channel, Recipient } from \"./types\";\n\nexport type Promisable<T> = T | Promise<T>;\n\nexport type PrepareContext = {\n type: string;\n recipients: readonly Recipient[];\n};\n\nexport type BeforeSendContext = {\n type: string;\n recipient: Recipient;\n payload: unknown;\n actorId: string | null;\n dedupeKey: string | null;\n /** Whatever this plugin's own prepare() returned for this send. */\n prepared: unknown;\n};\n\nexport type BeforeSendResult =\n | { action: \"continue\"; payload?: unknown; dedupeKey?: string }\n | { action: \"cancel\"; reason: string };\n\nexport type ChannelDecision = {\n channel: Channel;\n action: \"send\" | \"skip\" | \"defer\";\n /** defer only. Written to notification_delivery.not_before. */\n notBefore?: Date | undefined;\n};\n\nexport type ResolveChannelsContext = {\n type: string;\n recipient: Recipient;\n payload: unknown;\n decisions: readonly ChannelDecision[];\n /** Whatever this plugin's own prepare() returned for this send. */\n prepared: unknown;\n};\n\nexport type DeliverContext = {\n channel: Channel;\n deliveryId: string;\n attempt: number;\n recipient: Recipient;\n notification: { id: string; userId: string; type: string; payload: unknown };\n /** Aborted on the runner's timeout. */\n signal: AbortSignal;\n};\n\nexport type AfterSendContext = {\n type: string;\n payload: unknown;\n /** Committed rows. Ids exist only at this point. */\n notifications: readonly { id: string; userId: string }[];\n /** Whatever this plugin's own prepare() returned for this send. */\n prepared: unknown;\n};\n\nexport type AfterDeliverContext = {\n deliveryId: string;\n notificationId: string;\n userId: string;\n channel: Channel;\n outcome: DeliveryOutcome;\n attempt: number;\n isTerminal: boolean;\n};\n\n/** beforeSend and resolveChannels fail closed; afterDeliver fails open. */\nexport type PluginHooks = {\n /** Once per send, for bulk loading — the per-recipient hooks would be an N+1. */\n prepare?: (ctx: PrepareContext) => Promisable<unknown>;\n beforeSend?: (ctx: BeforeSendContext) => Promisable<BeforeSendResult>;\n resolveChannels?: (ctx: ResolveChannelsContext) => Promisable<readonly ChannelDecision[]>;\n /**\n * Once per send, after the rows are committed. The only hook that sees\n * notification ids, which digests needs to bucket an entry against one.\n * Fails open: the notification is already written.\n */\n afterSend?: (ctx: AfterSendContext) => Promisable<void>;\n /**\n * Delivers one of the plugin's declared `channels`. Core carries inApp and\n * email; everything else arrives here, which is how push, sms and slack are\n * added without core learning about them.\n */\n deliver?: (ctx: DeliverContext) => Promisable<DeliveryOutcome>;\n afterDeliver?: (ctx: AfterDeliverContext) => Promisable<void>;\n};\n\nexport type FieldType = \"string\" | \"number\" | \"boolean\" | \"date\" | \"json\";\n\nexport type FieldDeclaration = {\n type: FieldType;\n required?: boolean;\n default?: string | number | boolean;\n /** date fields only. Renders as defaultNow() / CURRENT_TIMESTAMP. */\n defaultNow?: boolean;\n};\n\nexport type IndexDeclaration = {\n on: readonly string[];\n unique?: boolean;\n name?: string;\n};\n\nexport type TableDeclaration = {\n tableName: string;\n fields: Record<string, FieldDeclaration>;\n primaryKey?: readonly string[];\n indexes?: readonly IndexDeclaration[];\n};\n\nexport type SchemaDeclaration = Record<string, TableDeclaration>;\n\nexport type RouteScope =\n | { type: \"user\" }\n | { type: \"machine\" }\n | { type: \"signed\"; purpose: string }\n | { type: \"custom\"; justification: string };\n\nexport type RouteContext = {\n request: Request;\n /** Resolved for user-scoped routes, so a handler cannot forget to scope. */\n userId: string | null;\n /** Verified before dispatch, so a handler cannot forget to check. */\n claims: { uid: string; purpose: string; exp: number; data?: Record<string, string> } | null;\n params: Record<string, string>;\n};\n\nexport type RouteDefinition = {\n path: string;\n method: \"GET\" | \"POST\";\n scope: RouteScope;\n handler: (ctx: RouteContext) => Promise<Response>;\n};\n\n/** Handed to a plugin at startup so it need not be given the database twice. */\nexport type PluginInitContext = {\n /** Scoped to the tables this plugin declares in schema(). */\n store: PluginStore;\n /** The top-level signing secret, for plugins issuing signed links. */\n secret: string;\n logger: Logger;\n /** The app's resolver, for plugins that need timezones or addresses. */\n getRecipients: (userIds: readonly string[]) => Promise<readonly Recipient[]>;\n /**\n * The instance's own send(). A plugin composing a message (a digest, say)\n * routes it back through the pipeline rather than reaching for a provider,\n * so it inherits retry, backoff and idempotency for free.\n */\n send: (\n type: string,\n args: { to: string | readonly string[]; payload: unknown; dedupeKey?: string },\n ) => Promise<unknown>;\n};\n\nexport type EasyPingPlugin<\n TId extends string = string,\n TSchema extends SchemaDeclaration = SchemaDeclaration,\n> = {\n id: TId;\n dependsOn?: readonly string[];\n schema?: TSchema;\n routes?: readonly RouteDefinition[];\n hooks?: PluginHooks;\n /** Channels this plugin delivers. Makes them usable in a notification. */\n channels?: readonly Channel[];\n /** Called once by easyPing() before any hook or route can run. */\n init?: (ctx: PluginInitContext) => void;\n};\n\nexport type AnyPlugin = EasyPingPlugin<string, SchemaDeclaration>;\n\nexport function definePlugin<TId extends string, TSchema extends SchemaDeclaration>(\n plugin: EasyPingPlugin<TId, TSchema>,\n): EasyPingPlugin<TId, TSchema> {\n return plugin;\n}\n\nexport type ClientFetch = (path: string, init?: RequestInit) => Promise<unknown>;\n\nexport type ClientPlugin<\n TId extends string = string,\n TActions extends Record<string, unknown> = Record<string, unknown>,\n> = {\n id: TId;\n /** Phantom. Links client types to the server plugin so a mismatch is a type error. */\n $InferServerPlugin?: AnyPlugin;\n actions: (fetch: ClientFetch) => TActions;\n};\n\nexport type AnyClientPlugin = ClientPlugin<string, Record<string, unknown>>;\n\nexport function defineClientPlugin<TId extends string, TActions extends Record<string, unknown>>(\n plugin: ClientPlugin<TId, TActions>,\n): ClientPlugin<TId, TActions> {\n return plugin;\n}\n\nexport type UnionToIntersection<U> = (U extends unknown ? (k: U) => void : never) extends (\n k: infer I,\n) => void\n ? I\n : never;\n\n/** Naked type parameter, so the conditional distributes over the union. */\ntype ExtractActions<TPlugin> = TPlugin extends { actions: (fetch: never) => infer TActions }\n ? TActions\n : never;\n\n/** Indexes the tuple rather than recursing: a fold blows the instantiation depth limit. */\nexport type ActionsOf<TPlugins extends readonly AnyClientPlugin[]> = UnionToIntersection<\n ExtractActions<TPlugins[number]>\n>;\n"]}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
import { C as Channel, b as DeliveryMode, S as SkipReason, c as DeliveryRecord, D as DatabaseAdapter, R as Recipient } from './adapter-f0OR2DhY.cjs';
|
|
2
|
+
export { d as ClaimArgs, e as ClaimedDelivery, f as DeliveryOutcome, g as DeliveryRelease, a as DeliveryStatus, h as FeedPage, i as FeedQuery, F as Frequency, I as InsertDelivery, j as InsertNotification, N as NotificationRecord, P as PreferenceRecord } from './adapter-f0OR2DhY.cjs';
|
|
3
|
+
import { StandardSchemaV1 } from '@standard-schema/spec';
|
|
4
|
+
import { A as AnyPlugin, L as Logger } from './plugin-Bqj9xAOS.cjs';
|
|
5
|
+
export { a as ActionsOf, b as AfterDeliverContext, c as AnyClientPlugin, B as BeforeSendContext, d as BeforeSendResult, C as ChannelDecision, e as ClientFetch, f as ClientPlugin, g as ConfigError, E as EasyPingError, h as EasyPingPlugin, F as FieldDeclaration, i as FieldType, P as PluginHooks, j as PrepareContext, k as Promisable, R as ResolveChannelsContext, l as RouteContext, m as RouteDefinition, n as RouteScope, S as SchemaDeclaration, T as TableDeclaration, U as UnionToIntersection, V as ValidationError, o as consoleLogger, p as defineClientPlugin, q as definePlugin } from './plugin-Bqj9xAOS.cjs';
|
|
6
|
+
import { E as EmailProvider } from './provider-CA45WVqt.cjs';
|
|
7
|
+
export { a as EmailMessage, P as ProviderSendResult } from './provider-CA45WVqt.cjs';
|
|
8
|
+
|
|
9
|
+
declare function encodeBase64Url(input: string | Uint8Array): string;
|
|
10
|
+
declare function decodeBase64Url(value: string): string | null;
|
|
11
|
+
|
|
12
|
+
type PayloadFromSchema<TSchema> = TSchema extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<TSchema> : Record<string, unknown>;
|
|
13
|
+
type EmailTemplate<TPayload> = {
|
|
14
|
+
subject: (payload: TPayload) => string;
|
|
15
|
+
/** Rendered HTML. react-email users wrap: `(p) => render(<Email {...p} />)`. */
|
|
16
|
+
template: (payload: TPayload) => string | Promise<string>;
|
|
17
|
+
};
|
|
18
|
+
type NotificationDefinition<TSchema extends StandardSchemaV1 | undefined = StandardSchemaV1 | undefined> = {
|
|
19
|
+
schema?: TSchema;
|
|
20
|
+
channels: readonly Channel[];
|
|
21
|
+
maxAttempts?: number;
|
|
22
|
+
email?: EmailTemplate<PayloadFromSchema<TSchema>>;
|
|
23
|
+
};
|
|
24
|
+
/** Binds TSchema so email callbacks infer the payload; TS cannot infer from a sibling property. */
|
|
25
|
+
declare function defineNotification<TSchema extends StandardSchemaV1 | undefined = undefined>(definition: NotificationDefinition<TSchema>): NotificationDefinition<TSchema>;
|
|
26
|
+
/**
|
|
27
|
+
* Erased form. `EmailTemplate<never>` because callbacks are contravariant —
|
|
28
|
+
* anything else makes every schema-typed definition fail to assign.
|
|
29
|
+
*/
|
|
30
|
+
type AnyNotificationDefinition = {
|
|
31
|
+
schema?: StandardSchemaV1 | undefined;
|
|
32
|
+
channels: readonly Channel[];
|
|
33
|
+
maxAttempts?: number | undefined;
|
|
34
|
+
email?: EmailTemplate<never> | undefined;
|
|
35
|
+
};
|
|
36
|
+
type NotificationDefinitions = Record<string, AnyNotificationDefinition>;
|
|
37
|
+
type PayloadOf<TDef> = TDef extends {
|
|
38
|
+
schema: infer TSchema extends StandardSchemaV1;
|
|
39
|
+
} ? StandardSchemaV1.InferOutput<TSchema> : Record<string, unknown>;
|
|
40
|
+
|
|
41
|
+
type SessionConfig = {
|
|
42
|
+
/** null yields 401; throwing yields 500. Deliberately distinct. */
|
|
43
|
+
getUserId: (request: Request) => string | null | Promise<string | null>;
|
|
44
|
+
};
|
|
45
|
+
type DeliveryConfig = {
|
|
46
|
+
mode?: DeliveryMode;
|
|
47
|
+
maxAttempts?: number;
|
|
48
|
+
/** Must exceed the slowest provider timeout, or duplicates are systematic. */
|
|
49
|
+
leaseMs?: number;
|
|
50
|
+
batchSize?: number;
|
|
51
|
+
/** inline mode only. */
|
|
52
|
+
throwOnError?: boolean;
|
|
53
|
+
backoff?: "exponential" | ((attempt: number) => number);
|
|
54
|
+
/**
|
|
55
|
+
* Next.js `after`, Cloudflare `ctx.waitUntil`, or @vercel/functions.
|
|
56
|
+
* Injected, not detected: importing a maybe-absent package breaks bundlers.
|
|
57
|
+
*/
|
|
58
|
+
waitUntil?: (promise: Promise<unknown>) => void;
|
|
59
|
+
};
|
|
60
|
+
type ChannelsConfig = {
|
|
61
|
+
inApp?: {
|
|
62
|
+
enabled: boolean;
|
|
63
|
+
};
|
|
64
|
+
email?: {
|
|
65
|
+
provider: EmailProvider;
|
|
66
|
+
};
|
|
67
|
+
};
|
|
68
|
+
type EasyPingConfig<TDefs extends NotificationDefinitions> = {
|
|
69
|
+
database: DatabaseAdapter;
|
|
70
|
+
session: SessionConfig;
|
|
71
|
+
/** Signs unsubscribe and other tokenised links. See RFC 0002 §5. */
|
|
72
|
+
secret: string;
|
|
73
|
+
getRecipients: (userIds: readonly string[]) => Promise<readonly Recipient[]>;
|
|
74
|
+
notifications: TDefs;
|
|
75
|
+
channels: ChannelsConfig;
|
|
76
|
+
delivery?: DeliveryConfig;
|
|
77
|
+
/** Required by `cron` and `deferred` modes. See RFC 0002 §4. */
|
|
78
|
+
cron?: {
|
|
79
|
+
secret: string;
|
|
80
|
+
};
|
|
81
|
+
plugins?: readonly AnyPlugin[];
|
|
82
|
+
/** Where the handler is mounted, used to strip the prefix off incoming URLs. */
|
|
83
|
+
basePath?: string;
|
|
84
|
+
/** Table-name prefix; must match the one given to the adapter. */
|
|
85
|
+
tablePrefix?: string;
|
|
86
|
+
logger?: Logger;
|
|
87
|
+
};
|
|
88
|
+
type SendArgs<TDefs extends NotificationDefinitions, TKey extends keyof TDefs> = {
|
|
89
|
+
to: string | readonly string[];
|
|
90
|
+
payload: PayloadOf<TDefs[TKey]>;
|
|
91
|
+
actorId?: string;
|
|
92
|
+
dedupeKey?: string;
|
|
93
|
+
overrides?: {
|
|
94
|
+
channels?: readonly Channel[];
|
|
95
|
+
};
|
|
96
|
+
};
|
|
97
|
+
type SendResult = {
|
|
98
|
+
notifications: readonly {
|
|
99
|
+
id: string;
|
|
100
|
+
userId: string;
|
|
101
|
+
deliveries: readonly {
|
|
102
|
+
id: string;
|
|
103
|
+
channel: Channel;
|
|
104
|
+
}[];
|
|
105
|
+
}[];
|
|
106
|
+
skipped: readonly {
|
|
107
|
+
userId: string;
|
|
108
|
+
reason: SkipReason;
|
|
109
|
+
}[];
|
|
110
|
+
};
|
|
111
|
+
type Worker = {
|
|
112
|
+
stop: () => Promise<void>;
|
|
113
|
+
};
|
|
114
|
+
type HealthReport = {
|
|
115
|
+
mode: DeliveryMode;
|
|
116
|
+
cronMounted: boolean;
|
|
117
|
+
/** True when the chosen mode relies on a cron sweep that is not wired up. */
|
|
118
|
+
cronRequiredButMissing: boolean;
|
|
119
|
+
warnings: readonly string[];
|
|
120
|
+
};
|
|
121
|
+
type EasyPing<TDefs extends NotificationDefinitions> = {
|
|
122
|
+
send<TKey extends keyof TDefs & string>(type: TKey, args: SendArgs<TDefs, TKey>): Promise<SendResult>;
|
|
123
|
+
handler: {
|
|
124
|
+
/** Method-agnostic entry, for toNodeHandler and single-dispatch frameworks. */
|
|
125
|
+
handle: (request: Request) => Promise<Response>;
|
|
126
|
+
GET: (request: Request) => Promise<Response>;
|
|
127
|
+
POST: (request: Request) => Promise<Response>;
|
|
128
|
+
};
|
|
129
|
+
startWorker(options?: {
|
|
130
|
+
intervalMs?: number;
|
|
131
|
+
batchSize?: number;
|
|
132
|
+
}): Worker;
|
|
133
|
+
healthCheck(): Promise<HealthReport>;
|
|
134
|
+
/**
|
|
135
|
+
* Deliveries that exhausted their attempts, newest first.
|
|
136
|
+
*
|
|
137
|
+
* The retry machinery is otherwise a black box: rows go quiet and the only
|
|
138
|
+
* way to ask what happened is SQL against tables the library owns. Wire this
|
|
139
|
+
* to an admin page or an alert.
|
|
140
|
+
*/
|
|
141
|
+
getFailedDeliveries(options?: {
|
|
142
|
+
/** Defaults to the last 24 hours. */
|
|
143
|
+
since?: Date;
|
|
144
|
+
/** Defaults to 100. */
|
|
145
|
+
limit?: number;
|
|
146
|
+
}): Promise<readonly DeliveryRecord[]>;
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
declare function easyPing<TDefs extends NotificationDefinitions>(config: EasyPingConfig<TDefs>): EasyPing<TDefs>;
|
|
150
|
+
|
|
151
|
+
type Backoff = "exponential" | ((attempt: number) => number);
|
|
152
|
+
|
|
153
|
+
type RunnerDeps = {
|
|
154
|
+
adapter: DatabaseAdapter;
|
|
155
|
+
definitions: NotificationDefinitions;
|
|
156
|
+
channels: ChannelsConfig;
|
|
157
|
+
plugins: readonly AnyPlugin[];
|
|
158
|
+
getRecipients: (userIds: readonly string[]) => Promise<readonly Recipient[]>;
|
|
159
|
+
logger: Logger;
|
|
160
|
+
leaseMs: number;
|
|
161
|
+
batchSize: number;
|
|
162
|
+
backoff: Backoff;
|
|
163
|
+
};
|
|
164
|
+
type SweepResult = {
|
|
165
|
+
claimed: number;
|
|
166
|
+
sent: number;
|
|
167
|
+
failed: number;
|
|
168
|
+
};
|
|
169
|
+
declare function createRunner(deps: RunnerDeps): {
|
|
170
|
+
runOnce: (options?: {
|
|
171
|
+
limit?: number;
|
|
172
|
+
channels?: readonly Channel[];
|
|
173
|
+
ids?: readonly string[];
|
|
174
|
+
}) => Promise<SweepResult>;
|
|
175
|
+
drain: (options?: {
|
|
176
|
+
maxSweeps?: number;
|
|
177
|
+
ids?: readonly string[];
|
|
178
|
+
}) => Promise<SweepResult>;
|
|
179
|
+
scheduleDeferred: (waitUntil?: (promise: Promise<unknown>) => void, ids?: readonly string[]) => void;
|
|
180
|
+
startWorker: (options?: {
|
|
181
|
+
intervalMs?: number;
|
|
182
|
+
batchSize?: number;
|
|
183
|
+
}) => Worker;
|
|
184
|
+
};
|
|
185
|
+
type Runner = ReturnType<typeof createRunner>;
|
|
186
|
+
|
|
187
|
+
type TokenClaims = {
|
|
188
|
+
/** Subject — the user the token acts for. */
|
|
189
|
+
uid: string;
|
|
190
|
+
/** What the token is allowed to do. Verification requires an exact match. */
|
|
191
|
+
purpose: string;
|
|
192
|
+
/** Expiry, epoch seconds. */
|
|
193
|
+
exp: number;
|
|
194
|
+
/** Free-form, purpose-specific. */
|
|
195
|
+
data?: Record<string, string>;
|
|
196
|
+
};
|
|
197
|
+
declare function signToken(secret: string, claims: TokenClaims): Promise<string>;
|
|
198
|
+
/** null for every failure mode. Distinguishing them tells an attacker which part to fix. */
|
|
199
|
+
declare function verifyToken(secret: string, token: string, purpose: string, now?: Date): Promise<TokenClaims | null>;
|
|
200
|
+
declare const DEFAULT_TOKEN_TTL_SECONDS: number;
|
|
201
|
+
declare const expiresIn: (seconds: number, now?: Date) => number;
|
|
202
|
+
|
|
203
|
+
export { type AnyNotificationDefinition, AnyPlugin, Channel, type ChannelsConfig, DEFAULT_TOKEN_TTL_SECONDS, DatabaseAdapter, type DeliveryConfig, DeliveryMode, DeliveryRecord, type EasyPing, type EasyPingConfig, EmailProvider, type EmailTemplate, type HealthReport, Logger, type NotificationDefinition, type NotificationDefinitions, type PayloadFromSchema, type PayloadOf, Recipient, type Runner, type RunnerDeps, type SendArgs, type SendResult, type SessionConfig, SkipReason, type SweepResult, type TokenClaims, type Worker, createRunner, decodeBase64Url, defineNotification, easyPing, encodeBase64Url, expiresIn, signToken, verifyToken };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
import { C as Channel, b as DeliveryMode, S as SkipReason, c as DeliveryRecord, D as DatabaseAdapter, R as Recipient } from './adapter-f0OR2DhY.js';
|
|
2
|
+
export { d as ClaimArgs, e as ClaimedDelivery, f as DeliveryOutcome, g as DeliveryRelease, a as DeliveryStatus, h as FeedPage, i as FeedQuery, F as Frequency, I as InsertDelivery, j as InsertNotification, N as NotificationRecord, P as PreferenceRecord } from './adapter-f0OR2DhY.js';
|
|
3
|
+
import { StandardSchemaV1 } from '@standard-schema/spec';
|
|
4
|
+
import { A as AnyPlugin, L as Logger } from './plugin-bTJKmnlq.js';
|
|
5
|
+
export { a as ActionsOf, b as AfterDeliverContext, c as AnyClientPlugin, B as BeforeSendContext, d as BeforeSendResult, C as ChannelDecision, e as ClientFetch, f as ClientPlugin, g as ConfigError, E as EasyPingError, h as EasyPingPlugin, F as FieldDeclaration, i as FieldType, P as PluginHooks, j as PrepareContext, k as Promisable, R as ResolveChannelsContext, l as RouteContext, m as RouteDefinition, n as RouteScope, S as SchemaDeclaration, T as TableDeclaration, U as UnionToIntersection, V as ValidationError, o as consoleLogger, p as defineClientPlugin, q as definePlugin } from './plugin-bTJKmnlq.js';
|
|
6
|
+
import { E as EmailProvider } from './provider-CA45WVqt.js';
|
|
7
|
+
export { a as EmailMessage, P as ProviderSendResult } from './provider-CA45WVqt.js';
|
|
8
|
+
|
|
9
|
+
declare function encodeBase64Url(input: string | Uint8Array): string;
|
|
10
|
+
declare function decodeBase64Url(value: string): string | null;
|
|
11
|
+
|
|
12
|
+
type PayloadFromSchema<TSchema> = TSchema extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<TSchema> : Record<string, unknown>;
|
|
13
|
+
type EmailTemplate<TPayload> = {
|
|
14
|
+
subject: (payload: TPayload) => string;
|
|
15
|
+
/** Rendered HTML. react-email users wrap: `(p) => render(<Email {...p} />)`. */
|
|
16
|
+
template: (payload: TPayload) => string | Promise<string>;
|
|
17
|
+
};
|
|
18
|
+
type NotificationDefinition<TSchema extends StandardSchemaV1 | undefined = StandardSchemaV1 | undefined> = {
|
|
19
|
+
schema?: TSchema;
|
|
20
|
+
channels: readonly Channel[];
|
|
21
|
+
maxAttempts?: number;
|
|
22
|
+
email?: EmailTemplate<PayloadFromSchema<TSchema>>;
|
|
23
|
+
};
|
|
24
|
+
/** Binds TSchema so email callbacks infer the payload; TS cannot infer from a sibling property. */
|
|
25
|
+
declare function defineNotification<TSchema extends StandardSchemaV1 | undefined = undefined>(definition: NotificationDefinition<TSchema>): NotificationDefinition<TSchema>;
|
|
26
|
+
/**
|
|
27
|
+
* Erased form. `EmailTemplate<never>` because callbacks are contravariant —
|
|
28
|
+
* anything else makes every schema-typed definition fail to assign.
|
|
29
|
+
*/
|
|
30
|
+
type AnyNotificationDefinition = {
|
|
31
|
+
schema?: StandardSchemaV1 | undefined;
|
|
32
|
+
channels: readonly Channel[];
|
|
33
|
+
maxAttempts?: number | undefined;
|
|
34
|
+
email?: EmailTemplate<never> | undefined;
|
|
35
|
+
};
|
|
36
|
+
type NotificationDefinitions = Record<string, AnyNotificationDefinition>;
|
|
37
|
+
type PayloadOf<TDef> = TDef extends {
|
|
38
|
+
schema: infer TSchema extends StandardSchemaV1;
|
|
39
|
+
} ? StandardSchemaV1.InferOutput<TSchema> : Record<string, unknown>;
|
|
40
|
+
|
|
41
|
+
type SessionConfig = {
|
|
42
|
+
/** null yields 401; throwing yields 500. Deliberately distinct. */
|
|
43
|
+
getUserId: (request: Request) => string | null | Promise<string | null>;
|
|
44
|
+
};
|
|
45
|
+
type DeliveryConfig = {
|
|
46
|
+
mode?: DeliveryMode;
|
|
47
|
+
maxAttempts?: number;
|
|
48
|
+
/** Must exceed the slowest provider timeout, or duplicates are systematic. */
|
|
49
|
+
leaseMs?: number;
|
|
50
|
+
batchSize?: number;
|
|
51
|
+
/** inline mode only. */
|
|
52
|
+
throwOnError?: boolean;
|
|
53
|
+
backoff?: "exponential" | ((attempt: number) => number);
|
|
54
|
+
/**
|
|
55
|
+
* Next.js `after`, Cloudflare `ctx.waitUntil`, or @vercel/functions.
|
|
56
|
+
* Injected, not detected: importing a maybe-absent package breaks bundlers.
|
|
57
|
+
*/
|
|
58
|
+
waitUntil?: (promise: Promise<unknown>) => void;
|
|
59
|
+
};
|
|
60
|
+
type ChannelsConfig = {
|
|
61
|
+
inApp?: {
|
|
62
|
+
enabled: boolean;
|
|
63
|
+
};
|
|
64
|
+
email?: {
|
|
65
|
+
provider: EmailProvider;
|
|
66
|
+
};
|
|
67
|
+
};
|
|
68
|
+
type EasyPingConfig<TDefs extends NotificationDefinitions> = {
|
|
69
|
+
database: DatabaseAdapter;
|
|
70
|
+
session: SessionConfig;
|
|
71
|
+
/** Signs unsubscribe and other tokenised links. See RFC 0002 §5. */
|
|
72
|
+
secret: string;
|
|
73
|
+
getRecipients: (userIds: readonly string[]) => Promise<readonly Recipient[]>;
|
|
74
|
+
notifications: TDefs;
|
|
75
|
+
channels: ChannelsConfig;
|
|
76
|
+
delivery?: DeliveryConfig;
|
|
77
|
+
/** Required by `cron` and `deferred` modes. See RFC 0002 §4. */
|
|
78
|
+
cron?: {
|
|
79
|
+
secret: string;
|
|
80
|
+
};
|
|
81
|
+
plugins?: readonly AnyPlugin[];
|
|
82
|
+
/** Where the handler is mounted, used to strip the prefix off incoming URLs. */
|
|
83
|
+
basePath?: string;
|
|
84
|
+
/** Table-name prefix; must match the one given to the adapter. */
|
|
85
|
+
tablePrefix?: string;
|
|
86
|
+
logger?: Logger;
|
|
87
|
+
};
|
|
88
|
+
type SendArgs<TDefs extends NotificationDefinitions, TKey extends keyof TDefs> = {
|
|
89
|
+
to: string | readonly string[];
|
|
90
|
+
payload: PayloadOf<TDefs[TKey]>;
|
|
91
|
+
actorId?: string;
|
|
92
|
+
dedupeKey?: string;
|
|
93
|
+
overrides?: {
|
|
94
|
+
channels?: readonly Channel[];
|
|
95
|
+
};
|
|
96
|
+
};
|
|
97
|
+
type SendResult = {
|
|
98
|
+
notifications: readonly {
|
|
99
|
+
id: string;
|
|
100
|
+
userId: string;
|
|
101
|
+
deliveries: readonly {
|
|
102
|
+
id: string;
|
|
103
|
+
channel: Channel;
|
|
104
|
+
}[];
|
|
105
|
+
}[];
|
|
106
|
+
skipped: readonly {
|
|
107
|
+
userId: string;
|
|
108
|
+
reason: SkipReason;
|
|
109
|
+
}[];
|
|
110
|
+
};
|
|
111
|
+
type Worker = {
|
|
112
|
+
stop: () => Promise<void>;
|
|
113
|
+
};
|
|
114
|
+
type HealthReport = {
|
|
115
|
+
mode: DeliveryMode;
|
|
116
|
+
cronMounted: boolean;
|
|
117
|
+
/** True when the chosen mode relies on a cron sweep that is not wired up. */
|
|
118
|
+
cronRequiredButMissing: boolean;
|
|
119
|
+
warnings: readonly string[];
|
|
120
|
+
};
|
|
121
|
+
type EasyPing<TDefs extends NotificationDefinitions> = {
|
|
122
|
+
send<TKey extends keyof TDefs & string>(type: TKey, args: SendArgs<TDefs, TKey>): Promise<SendResult>;
|
|
123
|
+
handler: {
|
|
124
|
+
/** Method-agnostic entry, for toNodeHandler and single-dispatch frameworks. */
|
|
125
|
+
handle: (request: Request) => Promise<Response>;
|
|
126
|
+
GET: (request: Request) => Promise<Response>;
|
|
127
|
+
POST: (request: Request) => Promise<Response>;
|
|
128
|
+
};
|
|
129
|
+
startWorker(options?: {
|
|
130
|
+
intervalMs?: number;
|
|
131
|
+
batchSize?: number;
|
|
132
|
+
}): Worker;
|
|
133
|
+
healthCheck(): Promise<HealthReport>;
|
|
134
|
+
/**
|
|
135
|
+
* Deliveries that exhausted their attempts, newest first.
|
|
136
|
+
*
|
|
137
|
+
* The retry machinery is otherwise a black box: rows go quiet and the only
|
|
138
|
+
* way to ask what happened is SQL against tables the library owns. Wire this
|
|
139
|
+
* to an admin page or an alert.
|
|
140
|
+
*/
|
|
141
|
+
getFailedDeliveries(options?: {
|
|
142
|
+
/** Defaults to the last 24 hours. */
|
|
143
|
+
since?: Date;
|
|
144
|
+
/** Defaults to 100. */
|
|
145
|
+
limit?: number;
|
|
146
|
+
}): Promise<readonly DeliveryRecord[]>;
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
declare function easyPing<TDefs extends NotificationDefinitions>(config: EasyPingConfig<TDefs>): EasyPing<TDefs>;
|
|
150
|
+
|
|
151
|
+
type Backoff = "exponential" | ((attempt: number) => number);
|
|
152
|
+
|
|
153
|
+
type RunnerDeps = {
|
|
154
|
+
adapter: DatabaseAdapter;
|
|
155
|
+
definitions: NotificationDefinitions;
|
|
156
|
+
channels: ChannelsConfig;
|
|
157
|
+
plugins: readonly AnyPlugin[];
|
|
158
|
+
getRecipients: (userIds: readonly string[]) => Promise<readonly Recipient[]>;
|
|
159
|
+
logger: Logger;
|
|
160
|
+
leaseMs: number;
|
|
161
|
+
batchSize: number;
|
|
162
|
+
backoff: Backoff;
|
|
163
|
+
};
|
|
164
|
+
type SweepResult = {
|
|
165
|
+
claimed: number;
|
|
166
|
+
sent: number;
|
|
167
|
+
failed: number;
|
|
168
|
+
};
|
|
169
|
+
declare function createRunner(deps: RunnerDeps): {
|
|
170
|
+
runOnce: (options?: {
|
|
171
|
+
limit?: number;
|
|
172
|
+
channels?: readonly Channel[];
|
|
173
|
+
ids?: readonly string[];
|
|
174
|
+
}) => Promise<SweepResult>;
|
|
175
|
+
drain: (options?: {
|
|
176
|
+
maxSweeps?: number;
|
|
177
|
+
ids?: readonly string[];
|
|
178
|
+
}) => Promise<SweepResult>;
|
|
179
|
+
scheduleDeferred: (waitUntil?: (promise: Promise<unknown>) => void, ids?: readonly string[]) => void;
|
|
180
|
+
startWorker: (options?: {
|
|
181
|
+
intervalMs?: number;
|
|
182
|
+
batchSize?: number;
|
|
183
|
+
}) => Worker;
|
|
184
|
+
};
|
|
185
|
+
type Runner = ReturnType<typeof createRunner>;
|
|
186
|
+
|
|
187
|
+
type TokenClaims = {
|
|
188
|
+
/** Subject — the user the token acts for. */
|
|
189
|
+
uid: string;
|
|
190
|
+
/** What the token is allowed to do. Verification requires an exact match. */
|
|
191
|
+
purpose: string;
|
|
192
|
+
/** Expiry, epoch seconds. */
|
|
193
|
+
exp: number;
|
|
194
|
+
/** Free-form, purpose-specific. */
|
|
195
|
+
data?: Record<string, string>;
|
|
196
|
+
};
|
|
197
|
+
declare function signToken(secret: string, claims: TokenClaims): Promise<string>;
|
|
198
|
+
/** null for every failure mode. Distinguishing them tells an attacker which part to fix. */
|
|
199
|
+
declare function verifyToken(secret: string, token: string, purpose: string, now?: Date): Promise<TokenClaims | null>;
|
|
200
|
+
declare const DEFAULT_TOKEN_TTL_SECONDS: number;
|
|
201
|
+
declare const expiresIn: (seconds: number, now?: Date) => number;
|
|
202
|
+
|
|
203
|
+
export { type AnyNotificationDefinition, AnyPlugin, Channel, type ChannelsConfig, DEFAULT_TOKEN_TTL_SECONDS, DatabaseAdapter, type DeliveryConfig, DeliveryMode, DeliveryRecord, type EasyPing, type EasyPingConfig, EmailProvider, type EmailTemplate, type HealthReport, Logger, type NotificationDefinition, type NotificationDefinitions, type PayloadFromSchema, type PayloadOf, Recipient, type Runner, type RunnerDeps, type SendArgs, type SendResult, type SessionConfig, SkipReason, type SweepResult, type TokenClaims, type Worker, createRunner, decodeBase64Url, defineNotification, easyPing, encodeBase64Url, expiresIn, signToken, verifyToken };
|