easy-ping 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/README.md +21 -5
  2. package/dist/{adapter-D3lTy-4E.d.cts → adapter-BJ8Iejvs.d.cts} +1 -1
  3. package/dist/{adapter-D3lTy-4E.d.ts → adapter-BJ8Iejvs.d.ts} +1 -1
  4. package/dist/adapters/drizzle.d.cts +1 -1
  5. package/dist/adapters/drizzle.d.ts +1 -1
  6. package/dist/adapters/mongodb.d.cts +2 -2
  7. package/dist/adapters/mongodb.d.ts +2 -2
  8. package/dist/adapters/mysql.d.cts +2 -2
  9. package/dist/adapters/mysql.d.ts +2 -2
  10. package/dist/adapters/postgres.d.cts +2 -2
  11. package/dist/adapters/postgres.d.ts +2 -2
  12. package/dist/adapters/sqlite.d.cts +2 -2
  13. package/dist/adapters/sqlite.d.ts +2 -2
  14. package/dist/{chunk-USQ6CQTJ.js → chunk-JOVIZXO6.js} +105 -54
  15. package/dist/chunk-JOVIZXO6.js.map +1 -0
  16. package/dist/chunk-R3BE67L7.js +13 -0
  17. package/dist/chunk-R3BE67L7.js.map +1 -0
  18. package/dist/chunk-SSHVZHSJ.js +100 -0
  19. package/dist/chunk-SSHVZHSJ.js.map +1 -0
  20. package/dist/client.cjs +12 -3
  21. package/dist/client.cjs.map +1 -1
  22. package/dist/client.d.cts +6 -0
  23. package/dist/client.d.ts +6 -0
  24. package/dist/client.js +12 -3
  25. package/dist/client.js.map +1 -1
  26. package/dist/index.cjs +106 -53
  27. package/dist/index.cjs.map +1 -1
  28. package/dist/index.d.cts +8 -4
  29. package/dist/index.d.ts +8 -4
  30. package/dist/index.js +7 -14
  31. package/dist/index.js.map +1 -1
  32. package/dist/node.cjs.map +1 -1
  33. package/dist/node.js +1 -1
  34. package/dist/{plugin-Cg9usuUi.d.ts → plugin-CSLKKgXT.d.ts} +1 -1
  35. package/dist/{plugin-CHd2ZiGC.d.cts → plugin-Wwp1nvo0.d.cts} +1 -1
  36. package/dist/plugins/digests.d.cts +2 -2
  37. package/dist/plugins/digests.d.ts +2 -2
  38. package/dist/plugins/preferences-client.d.cts +2 -2
  39. package/dist/plugins/preferences-client.d.ts +2 -2
  40. package/dist/plugins/preferences-react.d.cts +1 -1
  41. package/dist/plugins/preferences-react.d.ts +1 -1
  42. package/dist/plugins/preferences.cjs +3 -3
  43. package/dist/plugins/preferences.cjs.map +1 -1
  44. package/dist/plugins/preferences.d.cts +2 -2
  45. package/dist/plugins/preferences.d.ts +2 -2
  46. package/dist/plugins/preferences.js +2 -2
  47. package/dist/plugins/preferences.js.map +1 -1
  48. package/dist/plugins/push.cjs +2 -2
  49. package/dist/plugins/push.cjs.map +1 -1
  50. package/dist/plugins/push.d.cts +2 -2
  51. package/dist/plugins/push.d.ts +2 -2
  52. package/dist/plugins/push.js +1 -1
  53. package/dist/plugins/telegram.cjs +379 -0
  54. package/dist/plugins/telegram.cjs.map +1 -0
  55. package/dist/plugins/telegram.d.cts +153 -0
  56. package/dist/plugins/telegram.d.ts +153 -0
  57. package/dist/plugins/telegram.js +313 -0
  58. package/dist/plugins/telegram.js.map +1 -0
  59. package/dist/providers/telegram.cjs +103 -0
  60. package/dist/providers/telegram.cjs.map +1 -0
  61. package/dist/providers/telegram.d.cts +83 -0
  62. package/dist/providers/telegram.d.ts +83 -0
  63. package/dist/providers/telegram.js +3 -0
  64. package/dist/providers/telegram.js.map +1 -0
  65. package/dist/providers/web-push.d.cts +2 -2
  66. package/dist/providers/web-push.d.ts +2 -2
  67. package/dist/react.cjs +12 -3
  68. package/dist/react.cjs.map +1 -1
  69. package/dist/react.d.cts +6 -0
  70. package/dist/react.d.ts +6 -0
  71. package/dist/react.js +12 -3
  72. package/dist/react.js.map +1 -1
  73. package/dist/schema.d.cts +2 -2
  74. package/dist/schema.d.ts +2 -2
  75. package/dist/testing.d.cts +1 -1
  76. package/dist/testing.d.ts +1 -1
  77. package/package.json +16 -4
  78. package/dist/chunk-USQ6CQTJ.js.map +0 -1
package/dist/index.d.cts CHANGED
@@ -1,8 +1,8 @@
1
- import { C as Channel, b as DeliveryMode, S as SkipReason, c as DeliveryRecord, D as DatabaseAdapter, R as Recipient } from './adapter-D3lTy-4E.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-D3lTy-4E.cjs';
1
+ import { C as Channel, b as DeliveryMode, S as SkipReason, c as DeliveryRecord, D as DatabaseAdapter, R as Recipient } from './adapter-BJ8Iejvs.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-BJ8Iejvs.cjs';
3
3
  import { StandardSchemaV1 } from '@standard-schema/spec';
4
- import { R as RouteScope, A as AnyPlugin, P as Promisable, L as Logger } from './plugin-CHd2ZiGC.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, D as DEFAULT_TOKEN_TTL_SECONDS, E as EasyPingError, h as EasyPingPlugin, F as FieldDeclaration, i as FieldType, M as MAX_TOKEN_TTL_SECONDS, j as PluginHooks, k as PrepareContext, l as ResolveChannelsContext, m as RouteContext, n as RouteDefinition, S as SchemaDeclaration, o as SignRequest, T as TableDeclaration, p as TokenClaims, U as UnionToIntersection, V as ValidationError, q as consoleLogger, r as defineClientPlugin, s as definePlugin, t as expiresIn, u as signToken, v as verifyToken } from './plugin-CHd2ZiGC.cjs';
4
+ import { R as RouteScope, A as AnyPlugin, P as Promisable, L as Logger } from './plugin-Wwp1nvo0.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, D as DEFAULT_TOKEN_TTL_SECONDS, E as EasyPingError, h as EasyPingPlugin, F as FieldDeclaration, i as FieldType, M as MAX_TOKEN_TTL_SECONDS, j as PluginHooks, k as PrepareContext, l as ResolveChannelsContext, m as RouteContext, n as RouteDefinition, S as SchemaDeclaration, o as SignRequest, T as TableDeclaration, p as TokenClaims, U as UnionToIntersection, V as ValidationError, q as consoleLogger, r as defineClientPlugin, s as definePlugin, t as expiresIn, u as signToken, v as verifyToken } from './plugin-Wwp1nvo0.cjs';
6
6
  import { E as EmailProvider } from './provider-CA45WVqt.cjs';
7
7
  export { a as EmailMessage, P as ProviderSendResult } from './provider-CA45WVqt.cjs';
8
8
  import { S as Signals } from './signals-kPmOlKDX.cjs';
@@ -80,6 +80,10 @@ type EventsConfig = {
80
80
  * for changes this often on its subscriber's behalf. Default 30 s; 0 disables.
81
81
  */
82
82
  probeIntervalMs?: number;
83
+ /** Concurrent streams one user may hold in this process before a 429. Default 10. */
84
+ maxStreamsPerUser?: number;
85
+ /** Concurrent streams this process holds in total before a 503. Default 5000. */
86
+ maxStreams?: number;
83
87
  /** Close the stream after this long; the client reconnects. 0 (default) leaves it open. */
84
88
  maxDurationMs?: number;
85
89
  };
package/dist/index.d.ts CHANGED
@@ -1,8 +1,8 @@
1
- import { C as Channel, b as DeliveryMode, S as SkipReason, c as DeliveryRecord, D as DatabaseAdapter, R as Recipient } from './adapter-D3lTy-4E.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-D3lTy-4E.js';
1
+ import { C as Channel, b as DeliveryMode, S as SkipReason, c as DeliveryRecord, D as DatabaseAdapter, R as Recipient } from './adapter-BJ8Iejvs.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-BJ8Iejvs.js';
3
3
  import { StandardSchemaV1 } from '@standard-schema/spec';
4
- import { R as RouteScope, A as AnyPlugin, P as Promisable, L as Logger } from './plugin-Cg9usuUi.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, D as DEFAULT_TOKEN_TTL_SECONDS, E as EasyPingError, h as EasyPingPlugin, F as FieldDeclaration, i as FieldType, M as MAX_TOKEN_TTL_SECONDS, j as PluginHooks, k as PrepareContext, l as ResolveChannelsContext, m as RouteContext, n as RouteDefinition, S as SchemaDeclaration, o as SignRequest, T as TableDeclaration, p as TokenClaims, U as UnionToIntersection, V as ValidationError, q as consoleLogger, r as defineClientPlugin, s as definePlugin, t as expiresIn, u as signToken, v as verifyToken } from './plugin-Cg9usuUi.js';
4
+ import { R as RouteScope, A as AnyPlugin, P as Promisable, L as Logger } from './plugin-CSLKKgXT.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, D as DEFAULT_TOKEN_TTL_SECONDS, E as EasyPingError, h as EasyPingPlugin, F as FieldDeclaration, i as FieldType, M as MAX_TOKEN_TTL_SECONDS, j as PluginHooks, k as PrepareContext, l as ResolveChannelsContext, m as RouteContext, n as RouteDefinition, S as SchemaDeclaration, o as SignRequest, T as TableDeclaration, p as TokenClaims, U as UnionToIntersection, V as ValidationError, q as consoleLogger, r as defineClientPlugin, s as definePlugin, t as expiresIn, u as signToken, v as verifyToken } from './plugin-CSLKKgXT.js';
6
6
  import { E as EmailProvider } from './provider-CA45WVqt.js';
7
7
  export { a as EmailMessage, P as ProviderSendResult } from './provider-CA45WVqt.js';
8
8
  import { S as Signals } from './signals-kPmOlKDX.js';
@@ -80,6 +80,10 @@ type EventsConfig = {
80
80
  * for changes this often on its subscriber's behalf. Default 30 s; 0 disables.
81
81
  */
82
82
  probeIntervalMs?: number;
83
+ /** Concurrent streams one user may hold in this process before a 429. Default 10. */
84
+ maxStreamsPerUser?: number;
85
+ /** Concurrent streams this process holds in total before a 503. Default 5000. */
86
+ maxStreams?: number;
83
87
  /** Close the stream after this long; the client reconnects. 0 (default) leaves it open. */
84
88
  maxDurationMs?: number;
85
89
  };
package/dist/index.js CHANGED
@@ -1,8 +1,9 @@
1
1
  import { createRunner } from './chunk-JKTMUMQK.js';
2
2
  export { createRunner, redactErrorMessage } from './chunk-JKTMUMQK.js';
3
+ export { escapeHtml } from './chunk-R3BE67L7.js';
3
4
  export { defineClientPlugin, definePlugin } from './chunk-E4IZ2CQC.js';
4
- import { createHandler, createScopedSigner } from './chunk-USQ6CQTJ.js';
5
- export { DEFAULT_TOKEN_TTL_SECONDS, MAX_BODY_BYTES, MAX_TOKEN_TTL_SECONDS, expiresIn, readJsonBody, signToken, verifyToken } from './chunk-USQ6CQTJ.js';
5
+ import { createHandler, createScopedSigner } from './chunk-JOVIZXO6.js';
6
+ export { DEFAULT_TOKEN_TTL_SECONDS, MAX_BODY_BYTES, MAX_TOKEN_TTL_SECONDS, expiresIn, readJsonBody, signToken, verifyToken } from './chunk-JOVIZXO6.js';
6
7
  import { createMemorySignals, inboxChannel, DELIVERIES_CHANNEL } from './chunk-ORZKH224.js';
7
8
  export { DELIVERIES_CHANNEL, createBridgedSignals, createMemorySignals, inboxChannel } from './chunk-ORZKH224.js';
8
9
  import { consoleLogger, ConfigError, createPluginStore, ValidationError } from './chunk-3VOQOGDR.js';
@@ -18,16 +19,6 @@ function defineNotification(definition) {
18
19
  return definition;
19
20
  }
20
21
 
21
- // src/core/html.ts
22
- var ESCAPES = {
23
- "&": "&",
24
- "<": "&lt;",
25
- ">": "&gt;",
26
- '"': "&quot;",
27
- "'": "&#39;"
28
- };
29
- var escapeHtml = (value) => String(value ?? "").replace(/[&<>"']/g, (char) => ESCAPES[char] ?? char);
30
-
31
22
  // src/core/rate-limit.ts
32
23
  var clientAddress = (request) => {
33
24
  const headers = request.headers;
@@ -413,7 +404,9 @@ function easyPing(config) {
413
404
  const events = config.events === false ? false : {
414
405
  heartbeatMs: config.events?.heartbeatMs ?? 25e3,
415
406
  probeIntervalMs: config.events?.probeIntervalMs ?? 3e4,
416
- maxDurationMs: config.events?.maxDurationMs ?? 0
407
+ maxDurationMs: config.events?.maxDurationMs ?? 0,
408
+ maxStreamsPerUser: config.events?.maxStreamsPerUser ?? 10,
409
+ maxStreams: config.events?.maxStreams ?? 5e3
417
410
  };
418
411
  const sweepConfig = config.delivery?.sweepOnRequest;
419
412
  let lastRequestSweep = 0;
@@ -533,6 +526,6 @@ function easyPing(config) {
533
526
  };
534
527
  }
535
528
 
536
- export { INBOX_VERSION_HEADER, MIN_SECRET_LENGTH, createRateLimiter, defineNotification, easyPing, escapeHtml };
529
+ export { INBOX_VERSION_HEADER, MIN_SECRET_LENGTH, createRateLimiter, defineNotification, easyPing };
537
530
  //# sourceMappingURL=index.js.map
538
531
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/core/config.ts","../src/core/definition.ts","../src/core/html.ts","../src/core/rate-limit.ts","../src/core/send.ts","../src/core/instance.ts"],"names":["bucket","handler"],"mappings":";;;;;;;;;;;;;AAkIO,IAAM,oBAAA,GAAuB;;;AC3G7B,SAAS,mBACd,UAAA,EACiC;AACjC,EAAA,OAAO,UAAA;AACT;;;AC3BA,IAAM,OAAA,GAAkC;AAAA,EACtC,GAAA,EAAK,OAAA;AAAA,EACL,GAAA,EAAK,MAAA;AAAA,EACL,GAAA,EAAK,MAAA;AAAA,EACL,GA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AA,IAAS,KAAK,GAAI;AAAA,KAC3C,CAAA;AAAA,IAEH,aAAa,YAAmC;AAC9C,MAAA,MAAM,WAAA,GAAc,OAAA,CAAQ,MAAA,CAAO,IAAA,EAAM,MAAM,CAAA;AAC/C,MAAA,OAAO;AAAA,QACL,IAAA;AAAA,QACA,WAAA;AAAA,QACA,wBACE,CAAC,WAAA,KAAgB,SAAS,MAAA,IAAU,IAAA,KAAS,cAAc,IAAA,KAAS,QAAA,CAAA;AAAA,QACtE;AAAA,OACF;AAAA,IACF;AAAA,GACF;AACF","file":"index.js","sourcesContent":["import type { DatabaseAdapter } from \"./adapter\";\nimport type { NotificationDefinitions, PayloadOf } from \"./definition\";\nimport type { Logger } from \"./errors\";\nimport type { AnyPlugin, Promisable, RouteScope } from \"./plugin\";\nimport type { EmailProvider } from \"./provider\";\nimport type { RateLimitConfig } from \"./rate-limit\";\nimport type { Signals } from \"./signals\";\nimport type { Channel, DeliveryMode, DeliveryRecord, Recipient, SkipReason } from \"./types\";\n\nexport type SessionConfig = {\n /** null yields 401; throwing yields 500. Deliberately distinct. */\n getUserId: (request: Request) => string | null | Promise<string | null>;\n};\n\nexport type DeliveryConfig = {\n mode?: DeliveryMode;\n maxAttempts?: number;\n /** Must exceed the slowest provider timeout, or duplicates are systematic. */\n leaseMs?: number;\n batchSize?: number;\n /** inline mode only. */\n throwOnError?: boolean;\n backoff?: \"exponential\" | ((attempt: number) => number);\n /** Next.js `after` or Cloudflare `ctx.waitUntil`. Injected, not detected. */\n waitUntil?: (promise: Promise<unknown>) => void;\n /**\n * Run one small claim-and-deliver pass after any request the handler serves,\n * at most once per `everyMs` per process. Delivery then rides on your own\n * traffic and the cron becomes a backstop. Ignored in `inline` mode. RFC 0006 idea 5.\n */\n sweepOnRequest?: true | { everyMs?: number; limit?: number };\n};\n\nexport type EventsConfig = {\n /** Comment line keeping proxies from closing an idle stream. Default 25 s. */\n heartbeatMs?: number;\n /**\n * Without a cross-process signal source, each stream checks the database\n * for changes this often on its subscriber's behalf. Default 30 s; 0 disables.\n */\n probeIntervalMs?: number;\n /** Close the stream after this long; the client reconnects. 0 (default) leaves it open. */\n maxDurationMs?: number;\n};\n\nexport type ChannelsConfig = {\n inApp?: { enabled: boolean };\n email?: { provider: EmailProvider };\n};\n\nexport type EasyPingConfig<TDefs extends NotificationDefinitions> = {\n database: DatabaseAdapter;\n session: SessionConfig;\n /** Signs unsubscribe and other tokenised links. See RFC 0002 §5. */\n secret: string;\n getRecipients: (userIds: readonly string[]) => Promise<readonly Recipient[]>;\n notifications: TDefs;\n channels: ChannelsConfig;\n delivery?: DeliveryConfig;\n /** Required by `cron` and `deferred` modes. See RFC 0002 §4. */\n cron?: {\n secret: string;\n /** Sweeps one POST /cron may run before returning. Defaults to 50. */\n maxSweeps?: number;\n };\n /** Bearer secret for plugin machine routes. Falls back to `cron.secret`. */\n machineSecret?: string;\n /** In-process fixed-window limiter, applied before routing. */\n rateLimit?: RateLimitConfig;\n /**\n * How \"something changed\" travels between the sender, the worker and open\n * event streams. Defaults to in-process. Supply a LISTEN/NOTIFY or change\n * stream implementation to cross replicas. RFC 0006 §4C.\n */\n signals?: Signals;\n /** `GET /events`, a Server-Sent Events stream per user. `false` unmounts it. */\n events?: EventsConfig | false;\n plugins?: readonly AnyPlugin[];\n /** Where the handler is mounted, used to strip the prefix off incoming URLs. */\n basePath?: string;\n /** Origins other than the request host that may POST. `\"*.example.com\"` matches subdomains. */\n trustedOrigins?: readonly string[];\n /** Runs before routing. Return a Response to short-circuit — a rate limiter's 429, say. */\n // biome-ignore lint/suspicious/noConfusingVoidType: a hook that returns nothing is the common case\n onRequest?: (request: Request) => Promisable<Response | undefined | void>;\n /** Defaults to 64 KiB. */\n maxBodyBytes?: number;\n /** Table-name prefix; must match the one given to the adapter. */\n tablePrefix?: string;\n logger?: Logger;\n};\n\nexport type SendArgs<TDefs extends NotificationDefinitions, TKey extends keyof TDefs> = {\n to: string | readonly string[];\n payload: PayloadOf<TDefs[TKey]>;\n actorId?: string;\n dedupeKey?: string;\n overrides?: { channels?: readonly Channel[] };\n};\n\nexport type SendResult = {\n notifications: readonly {\n id: string;\n userId: string;\n deliveries: readonly { id: string; channel: Channel }[];\n }[];\n skipped: readonly { userId: string; reason: SkipReason }[];\n};\n\nexport type Worker = {\n stop: () => Promise<void>;\n};\n\nexport type MountedRoute = {\n method: \"GET\" | \"POST\";\n path: string;\n scope: RouteScope;\n /** \"core\" for the built-in routes, otherwise the plugin id. */\n owner: string;\n};\n\nexport type HealthReport = {\n mode: DeliveryMode;\n cronMounted: boolean;\n /** True when the chosen mode relies on a cron sweep that is not wired up. */\n cronRequiredButMissing: boolean;\n warnings: readonly string[];\n};\n\n/** Response header carrying a per-user inbox version, so app traffic can replace polling. */\nexport const INBOX_VERSION_HEADER = \"x-easy-ping-inbox\";\n\nexport type EasyPing<TDefs extends NotificationDefinitions> = {\n send<TKey extends keyof TDefs & string>(\n type: TKey,\n args: SendArgs<TDefs, TKey>,\n ): Promise<SendResult>;\n\n handler: {\n /** Method-agnostic entry, for toNodeHandler and single-dispatch frameworks. */\n handle: (request: Request) => Promise<Response>;\n GET: (request: Request) => Promise<Response>;\n POST: (request: Request) => Promise<Response>;\n };\n\n /** Idle interval defaults to 10 s; a send in this process wakes the loop at once. */\n startWorker(options?: { intervalMs?: number; batchSize?: number }): Worker;\n healthCheck(): Promise<HealthReport>;\n\n /** Every mounted route with its auth scope, so `custom`-scoped ones stay visible. RFC 0002 §3. */\n listRoutes(): readonly MountedRoute[];\n\n /**\n * Headers to attach to any response your app sends this user. The client's\n * `instrument(fetch)` reads them and refreshes only when the version moved,\n * so an active user never needs a dedicated poll. RFC 0006 idea 1.\n */\n inboxHeaders(userId: string): Record<string, string>;\n\n /** Deliveries that exhausted their attempts, newest first. Wire it to an admin page or an alert. */\n getFailedDeliveries(options?: {\n /** Defaults to the last 24 hours. */\n since?: Date;\n /** Defaults to 100. */\n limit?: number;\n }): Promise<readonly DeliveryRecord[]>;\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/** Erased form. `EmailTemplate<never>` because callbacks are contravariant. */\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","const ESCAPES: Record<string, string> = {\n \"&\": \"&amp;\",\n \"<\": \"&lt;\",\n \">\": \"&gt;\",\n '\"': \"&quot;\",\n \"'\": \"&#39;\",\n};\n\n/** For template literals: anything a user typed goes through this, or their HTML ships from your domain. */\nexport const escapeHtml = (value: unknown): string =>\n String(value ?? \"\").replace(/[&<>\"']/g, (char) => ESCAPES[char] ?? char);\n","export type RateLimitConfig = {\n /** Requests allowed per key per window. */\n max: number;\n windowMs: number;\n /** Bucket key. Defaults to the client address from proxy headers; null exempts the request. */\n key?: (request: Request) => string | null;\n};\n\nconst clientAddress = (request: Request): string | null => {\n const headers = request.headers;\n return (\n headers.get(\"cf-connecting-ip\") ??\n headers.get(\"x-real-ip\") ??\n headers.get(\"x-forwarded-for\")?.split(\",\")[0]?.trim() ??\n null\n );\n};\n\n/** Fixed window in process memory: per isolate or replica, so a bound rather than a quota. */\nexport function createRateLimiter(config: RateLimitConfig): (request: Request) => Response | null {\n const keyOf = config.key ?? clientAddress;\n const buckets = new Map<string, { count: number; resetAt: number }>();\n let lastSweep = 0;\n\n return (request) => {\n const key = keyOf(request);\n if (key === null) return null;\n\n const now = Date.now();\n\n // Sweep expired buckets at most once per window.\n if (now - lastSweep > config.windowMs) {\n for (const [id, bucket] of buckets) if (bucket.resetAt <= now) buckets.delete(id);\n lastSweep = now;\n }\n\n let bucket = buckets.get(key);\n if (!bucket || bucket.resetAt <= now) {\n bucket = { count: 0, resetAt: now + config.windowMs };\n buckets.set(key, bucket);\n }\n\n bucket.count += 1;\n if (bucket.count <= config.max) return null;\n\n return new Response(null, {\n status: 429,\n headers: {\n \"retry-after\": String(Math.max(1, Math.ceil((bucket.resetAt - now) / 1000))),\n \"cache-control\": \"private, no-store\",\n },\n });\n };\n}\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/** inApp is on unless disabled; every other channel needs a provider or a plugin that delivers it. */\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: a failed bulk load must not 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: failing open would email people who opted out. 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. 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 // Distinct from \"no-channels\": a missing provider is not an opt-out.\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 is just not_before; the claim query 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.\n deps.logger.error(`plugin \"${plugin.id}\" afterSend threw; ignoring`, { type, error });\n }\n }\n\n return { notifications, skipped };\n}\n","import type { Backoff } from \"./backoff\";\nimport {\n type EasyPing,\n type EasyPingConfig,\n type HealthReport,\n INBOX_VERSION_HEADER,\n type MountedRoute,\n type SendArgs,\n type SendResult,\n} from \"./config\";\nimport type { NotificationDefinitions } from \"./definition\";\nimport { ConfigError, consoleLogger } from \"./errors\";\nimport { createHandler } from \"./handler\";\nimport type { AnyPlugin } from \"./plugin\";\nimport { createRateLimiter } from \"./rate-limit\";\nimport { createRunner } from \"./runner\";\nimport { isChannelUsable, runSend } from \"./send\";\nimport { createMemorySignals, DELIVERIES_CHANNEL, inboxChannel, type Signals } from \"./signals\";\nimport { createPluginStore } from \"./store\";\nimport { createScopedSigner } from \"./tokens\";\nimport type { DeliveryMode } from \"./types\";\n\nconst CORE_ROUTES: readonly MountedRoute[] = [\n { method: \"GET\", path: \"/\", scope: { type: \"user\" }, owner: \"core\" },\n { method: \"GET\", path: \"/count\", scope: { type: \"user\" }, owner: \"core\" },\n { method: \"POST\", path: \"/seen\", scope: { type: \"user\" }, owner: \"core\" },\n { method: \"POST\", path: \"/read\", scope: { type: \"user\" }, owner: \"core\" },\n { method: \"POST\", path: \"/read-all\", scope: { type: \"user\" }, owner: \"core\" },\n { method: \"GET\", path: \"/events\", scope: { type: \"user\" }, owner: \"core\" },\n { method: \"POST\", path: \"/cron\", scope: { type: \"machine\" }, owner: \"core\" },\n];\n\nconst DEFAULTS = {\n maxAttempts: 5,\n leaseMs: 60_000,\n batchSize: 20,\n basePath: \"/api/notifications\",\n mode: \"cron\" as DeliveryMode,\n};\n\nexport const MIN_SECRET_LENGTH = 16;\n\nconst PLACEHOLDER_SECRETS = new Set([\n \"secret\",\n \"changeme\",\n \"change-me\",\n \"replace-me\",\n \"replace-me-too\",\n \"password\",\n \"demo-signing-secret\",\n \"demo-cron-secret\",\n]);\n\nfunction checkSecretStrength(name: string, value: string) {\n if (value.length < MIN_SECRET_LENGTH || PLACEHOLDER_SECRETS.has(value.toLowerCase())) {\n throw new ConfigError(\n `\\`${name}\\` must be at least ${MIN_SECRET_LENGTH} characters and not a placeholder. ` +\n \"Generate one with `openssl rand -base64 32`.\",\n );\n }\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: an insecure default ships, a 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 checkSecretStrength(\"secret\", config.secret);\n if (config.cron?.secret) checkSecretStrength(\"cron.secret\", config.cron.secret);\n if (config.machineSecret) checkSecretStrength(\"machineSecret\", config.machineSecret);\n\n if (config.rateLimit && (config.rateLimit.max < 1 || config.rateLimit.windowMs < 1)) {\n throw new ConfigError(\"`rateLimit.max` and `rateLimit.windowMs` must both be positive.\");\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 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. 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 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 // Custom-scoped routes are named at startup with their justification. RFC 0002 §3.\n for (const plugin of plugins) {\n for (const route of plugin.routes ?? []) {\n if (route.scope.type === \"custom\") {\n warnings.push(\n `plugin \"${plugin.id}\" mounts ${route.method} ${route.path} with custom auth: ` +\n route.scope.justification,\n );\n }\n }\n }\n\n for (const warning of warnings) logger.warn(warning);\n\n const baseSignals = config.signals ?? createMemorySignals();\n\n // Per-user inbox versions for the piggyback header. In-process counters, so\n // another replica's number differs; the client treats any change as \"look\",\n // which costs a spurious refresh, never a missed one.\n const inboxVersions = new Map<string, number>();\n const signals: Signals = {\n crossProcess: baseSignals.crossProcess,\n publish(channel) {\n if (channel.startsWith(\"inbox:\")) {\n if (inboxVersions.size > 50_000) inboxVersions.clear();\n const userId = channel.slice(\"inbox:\".length);\n inboxVersions.set(userId, (inboxVersions.get(userId) ?? 0) + 1);\n }\n baseSignals.publish(channel);\n },\n subscribe: (channel, handler) => baseSignals.subscribe(channel, handler),\n };\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 signals,\n });\n\n const pluginRoutes = plugins.flatMap((plugin) => plugin.routes ?? []);\n\n const events =\n config.events === false\n ? false\n : {\n heartbeatMs: config.events?.heartbeatMs ?? 25_000,\n probeIntervalMs: config.events?.probeIntervalMs ?? 30_000,\n maxDurationMs: config.events?.maxDurationMs ?? 0,\n };\n\n const sweepConfig = config.delivery?.sweepOnRequest;\n let lastRequestSweep = 0;\n const sweepOnRequest =\n sweepConfig && mode !== \"inline\"\n ? () => {\n const settings = sweepConfig === true ? {} : sweepConfig;\n const now = Date.now();\n if (now - lastRequestSweep < (settings.everyMs ?? 5_000)) return;\n lastRequestSweep = now;\n const pass = runner\n .runOnce({ limit: settings.limit ?? 5 })\n .catch((error) => logger.error(\"request-driven sweep failed\", { error }));\n config.delivery?.waitUntil?.(pass);\n }\n : undefined;\n\n const handler = createHandler({\n adapter: config.database,\n session: config.session,\n runner,\n logger,\n secret: config.secret,\n signals,\n events,\n sweepOnRequest,\n basePath: config.basePath ?? DEFAULTS.basePath,\n pluginRoutes,\n trustedOrigins: config.trustedOrigins,\n onRequest: config.onRequest,\n maxBodyBytes: config.maxBodyBytes,\n rateLimit: config.rateLimit ? createRateLimiter(config.rateLimit) : undefined,\n cronMaxSweeps: config.cron?.maxSweeps,\n ...(config.cron?.secret ? { cronSecret: config.cron.secret } : {}),\n ...((config.machineSecret ?? config.cron?.secret)\n ? { machineSecret: config.machineSecret ?? config.cron?.secret }\n : {}),\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 // Rows are committed; everything below only affects latency. RFC 0001 §8.1.\n if (result.notifications.length > 0) {\n for (const notification of result.notifications) {\n signals.publish(inboxChannel(notification.userId));\n }\n signals.publish(DELIVERIES_CHANNEL);\n\n // Scoped to this send, or an inline send 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 const purposes = new Set(\n (plugin.routes ?? []).flatMap((route) =>\n route.scope.type === \"signed\" ? [route.scope.purpose] : [],\n ),\n );\n plugin.init?.({\n store: createPluginStore(plugin.id, plugin.schema, config.database, tablePrefix),\n sign: createScopedSigner(\n config.secret,\n plugin.id,\n purposes,\n (message) => new ConfigError(message),\n ),\n logger,\n notificationTypes: Object.keys(config.notifications),\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 inboxHeaders: (userId) => ({\n [INBOX_VERSION_HEADER]: String(inboxVersions.get(userId) ?? 0),\n }),\n\n listRoutes: () => [\n ...CORE_ROUTES.filter(\n (route) =>\n (route.path !== \"/cron\" || Boolean(config.cron?.secret)) &&\n (route.path !== \"/events\" || events !== false),\n ),\n ...plugins.flatMap((plugin) =>\n (plugin.routes ?? []).map((route) => ({\n method: route.method,\n path: route.path,\n scope: route.scope,\n owner: plugin.id,\n })),\n ),\n ],\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"]}
1
+ {"version":3,"sources":["../src/core/config.ts","../src/core/definition.ts","../src/core/rate-limit.ts","../src/core/send.ts","../src/core/instance.ts"],"names":["bucket","handler"],"mappings":";;;;;;;;;;;;;;AAsIO,IAAM,oBAAA,GAAuB;;;AC/G7B,SAAS,mBACd,UAAA,EACiC;AACjC,EAAA,OAAO,UAAA;AACT;;;ACnBA,IAAM,aAAA,GAAgB,CAAC,OAAA,KAAoC;AACzD,EAAA,MAAM,UAAU,OAAA,CAAQ,OAAA;AACxB,EAAA,OACE,QAAQ,GAAA,CAAI,kBAAkB,KAC9B,OAAA,CAAQ,GAAA,CAAI,WAAW,CAAA,IACvB,OAAA,CAAQ,GAAA,CAAI,iBAAiB,GAAG,KAAA,CAAM,GAAG,EAAE,CAAC,CAAA,EAAG,MAAK,IACpD,IAAA;AAEJ,CAAA;AAGO,SAAS,kBAAkB,MAAA,EAAgE;AAChG,EAAA,MAAM,KAAA,GAAQ,OAAO,GAAA,IAAO,aAAA;AAC5B,EAAA,MAAM,OAAA,uBAAc,GAAA,EAAgD;AACpE,EAAA,IAAI,SAAA,GAAY,CAAA;AAEhB,EAAA,OAAO,CAAC,OAAA,KAAY;AAClB,IAAA,MAAM,GAAA,GAAM,MAAM,OAAO,CAAA;AACzB,IAAA,IAAI,GAAA,KAAQ,MAAM,OAAO,IAAA;AAEzB,IAAA,MAAM,GAAA,GAAM,KAAK,GAAA,EAAI;AAGrB,IAAA,IAAI,GAAA,GAAM,SAAA,GAAY,MAAA,CAAO,QAAA,EAAU;AACrC,MAAA,KAAA,MAAW,CAAC,EAAA,EAAIA,OAAM,CAAA,IAAK,OAAA,EAAS,IAAIA,OAAAA,CAAO,OAAA,IAAW,GAAA,EAAK,OAAA,CAAQ,MAAA,CAAO,EAAE,CAAA;AAChF,MAAA,SAAA,GAAY,GAAA;AAAA,IACd;AAEA,IAAA,IAAI,MAAA,GAAS,OAAA,CAAQ,GAAA,CAAI,GAAG,CAAA;AAC5B,IAAA,IAAI,CAAC,MAAA,IAAU,MAAA,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AQ,KAAA,IAAS,IAAI,KAAK,IAAA,CAAK,GAAA,EAAI,GAAI,EAAA,GAAK,IAAQ,CAAA;AAAA,MAC3D,OAAO,IAAA,CAAK,GAAA,CAAI,OAAA,CAAQ,KAAA,IAAS,KAAK,GAAI;AAAA,KAC3C,CAAA;AAAA,IAEH,aAAa,YAAmC;AAC9C,MAAA,MAAM,WAAA,GAAc,OAAA,CAAQ,MAAA,CAAO,IAAA,EAAM,MAAM,CAAA;AAC/C,MAAA,OAAO;AAAA,QACL,IAAA;AAAA,QACA,WAAA;AAAA,QACA,wBACE,CAAC,WAAA,KAAgB,SAAS,MAAA,IAAU,IAAA,KAAS,cAAc,IAAA,KAAS,QAAA,CAAA;AAAA,QACtE;AAAA,OACF;AAAA,IACF;AAAA,GACF;AACF","file":"index.js","sourcesContent":["import type { DatabaseAdapter } from \"./adapter\";\nimport type { NotificationDefinitions, PayloadOf } from \"./definition\";\nimport type { Logger } from \"./errors\";\nimport type { AnyPlugin, Promisable, RouteScope } from \"./plugin\";\nimport type { EmailProvider } from \"./provider\";\nimport type { RateLimitConfig } from \"./rate-limit\";\nimport type { Signals } from \"./signals\";\nimport type { Channel, DeliveryMode, DeliveryRecord, Recipient, SkipReason } from \"./types\";\n\nexport type SessionConfig = {\n /** null yields 401; throwing yields 500. Deliberately distinct. */\n getUserId: (request: Request) => string | null | Promise<string | null>;\n};\n\nexport type DeliveryConfig = {\n mode?: DeliveryMode;\n maxAttempts?: number;\n /** Must exceed the slowest provider timeout, or duplicates are systematic. */\n leaseMs?: number;\n batchSize?: number;\n /** inline mode only. */\n throwOnError?: boolean;\n backoff?: \"exponential\" | ((attempt: number) => number);\n /** Next.js `after` or Cloudflare `ctx.waitUntil`. Injected, not detected. */\n waitUntil?: (promise: Promise<unknown>) => void;\n /**\n * Run one small claim-and-deliver pass after any request the handler serves,\n * at most once per `everyMs` per process. Delivery then rides on your own\n * traffic and the cron becomes a backstop. Ignored in `inline` mode. RFC 0006 idea 5.\n */\n sweepOnRequest?: true | { everyMs?: number; limit?: number };\n};\n\nexport type EventsConfig = {\n /** Comment line keeping proxies from closing an idle stream. Default 25 s. */\n heartbeatMs?: number;\n /**\n * Without a cross-process signal source, each stream checks the database\n * for changes this often on its subscriber's behalf. Default 30 s; 0 disables.\n */\n probeIntervalMs?: number;\n /** Concurrent streams one user may hold in this process before a 429. Default 10. */\n maxStreamsPerUser?: number;\n /** Concurrent streams this process holds in total before a 503. Default 5000. */\n maxStreams?: number;\n /** Close the stream after this long; the client reconnects. 0 (default) leaves it open. */\n maxDurationMs?: number;\n};\n\nexport type ChannelsConfig = {\n inApp?: { enabled: boolean };\n email?: { provider: EmailProvider };\n};\n\nexport type EasyPingConfig<TDefs extends NotificationDefinitions> = {\n database: DatabaseAdapter;\n session: SessionConfig;\n /** Signs unsubscribe and other tokenised links. See RFC 0002 §5. */\n secret: string;\n getRecipients: (userIds: readonly string[]) => Promise<readonly Recipient[]>;\n notifications: TDefs;\n channels: ChannelsConfig;\n delivery?: DeliveryConfig;\n /** Required by `cron` and `deferred` modes. See RFC 0002 §4. */\n cron?: {\n secret: string;\n /** Sweeps one POST /cron may run before returning. Defaults to 50. */\n maxSweeps?: number;\n };\n /** Bearer secret for plugin machine routes. Falls back to `cron.secret`. */\n machineSecret?: string;\n /** In-process fixed-window limiter, applied before routing. */\n rateLimit?: RateLimitConfig;\n /**\n * How \"something changed\" travels between the sender, the worker and open\n * event streams. Defaults to in-process. Supply a LISTEN/NOTIFY or change\n * stream implementation to cross replicas. RFC 0006 §4C.\n */\n signals?: Signals;\n /** `GET /events`, a Server-Sent Events stream per user. `false` unmounts it. */\n events?: EventsConfig | false;\n plugins?: readonly AnyPlugin[];\n /** Where the handler is mounted, used to strip the prefix off incoming URLs. */\n basePath?: string;\n /** Origins other than the request host that may POST. `\"*.example.com\"` matches subdomains. */\n trustedOrigins?: readonly string[];\n /** Runs before routing. Return a Response to short-circuit — a rate limiter's 429, say. */\n // biome-ignore lint/suspicious/noConfusingVoidType: a hook that returns nothing is the common case\n onRequest?: (request: Request) => Promisable<Response | undefined | void>;\n /** Defaults to 64 KiB. */\n maxBodyBytes?: number;\n /** Table-name prefix; must match the one given to the adapter. */\n tablePrefix?: string;\n logger?: Logger;\n};\n\nexport type SendArgs<TDefs extends NotificationDefinitions, TKey extends keyof TDefs> = {\n to: string | readonly string[];\n payload: PayloadOf<TDefs[TKey]>;\n actorId?: string;\n dedupeKey?: string;\n overrides?: { channels?: readonly Channel[] };\n};\n\nexport type SendResult = {\n notifications: readonly {\n id: string;\n userId: string;\n deliveries: readonly { id: string; channel: Channel }[];\n }[];\n skipped: readonly { userId: string; reason: SkipReason }[];\n};\n\nexport type Worker = {\n stop: () => Promise<void>;\n};\n\nexport type MountedRoute = {\n method: \"GET\" | \"POST\";\n path: string;\n scope: RouteScope;\n /** \"core\" for the built-in routes, otherwise the plugin id. */\n owner: string;\n};\n\nexport type HealthReport = {\n mode: DeliveryMode;\n cronMounted: boolean;\n /** True when the chosen mode relies on a cron sweep that is not wired up. */\n cronRequiredButMissing: boolean;\n warnings: readonly string[];\n};\n\n/** Response header carrying a per-user inbox version, so app traffic can replace polling. */\nexport const INBOX_VERSION_HEADER = \"x-easy-ping-inbox\";\n\nexport type EasyPing<TDefs extends NotificationDefinitions> = {\n send<TKey extends keyof TDefs & string>(\n type: TKey,\n args: SendArgs<TDefs, TKey>,\n ): Promise<SendResult>;\n\n handler: {\n /** Method-agnostic entry, for toNodeHandler and single-dispatch frameworks. */\n handle: (request: Request) => Promise<Response>;\n GET: (request: Request) => Promise<Response>;\n POST: (request: Request) => Promise<Response>;\n };\n\n /** Idle interval defaults to 10 s; a send in this process wakes the loop at once. */\n startWorker(options?: { intervalMs?: number; batchSize?: number }): Worker;\n healthCheck(): Promise<HealthReport>;\n\n /** Every mounted route with its auth scope, so `custom`-scoped ones stay visible. RFC 0002 §3. */\n listRoutes(): readonly MountedRoute[];\n\n /**\n * Headers to attach to any response your app sends this user. The client's\n * `instrument(fetch)` reads them and refreshes only when the version moved,\n * so an active user never needs a dedicated poll. RFC 0006 idea 1.\n */\n inboxHeaders(userId: string): Record<string, string>;\n\n /** Deliveries that exhausted their attempts, newest first. Wire it to an admin page or an alert. */\n getFailedDeliveries(options?: {\n /** Defaults to the last 24 hours. */\n since?: Date;\n /** Defaults to 100. */\n limit?: number;\n }): Promise<readonly DeliveryRecord[]>;\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/** Erased form. `EmailTemplate<never>` because callbacks are contravariant. */\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 type RateLimitConfig = {\n /** Requests allowed per key per window. */\n max: number;\n windowMs: number;\n /** Bucket key. Defaults to the client address from proxy headers; null exempts the request. */\n key?: (request: Request) => string | null;\n};\n\nconst clientAddress = (request: Request): string | null => {\n const headers = request.headers;\n return (\n headers.get(\"cf-connecting-ip\") ??\n headers.get(\"x-real-ip\") ??\n headers.get(\"x-forwarded-for\")?.split(\",\")[0]?.trim() ??\n null\n );\n};\n\n/** Fixed window in process memory: per isolate or replica, so a bound rather than a quota. */\nexport function createRateLimiter(config: RateLimitConfig): (request: Request) => Response | null {\n const keyOf = config.key ?? clientAddress;\n const buckets = new Map<string, { count: number; resetAt: number }>();\n let lastSweep = 0;\n\n return (request) => {\n const key = keyOf(request);\n if (key === null) return null;\n\n const now = Date.now();\n\n // Sweep expired buckets at most once per window.\n if (now - lastSweep > config.windowMs) {\n for (const [id, bucket] of buckets) if (bucket.resetAt <= now) buckets.delete(id);\n lastSweep = now;\n }\n\n let bucket = buckets.get(key);\n if (!bucket || bucket.resetAt <= now) {\n bucket = { count: 0, resetAt: now + config.windowMs };\n buckets.set(key, bucket);\n }\n\n bucket.count += 1;\n if (bucket.count <= config.max) return null;\n\n return new Response(null, {\n status: 429,\n headers: {\n \"retry-after\": String(Math.max(1, Math.ceil((bucket.resetAt - now) / 1000))),\n \"cache-control\": \"private, no-store\",\n },\n });\n };\n}\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/** inApp is on unless disabled; every other channel needs a provider or a plugin that delivers it. */\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: a failed bulk load must not 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: failing open would email people who opted out. 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. 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 // Distinct from \"no-channels\": a missing provider is not an opt-out.\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 is just not_before; the claim query 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.\n deps.logger.error(`plugin \"${plugin.id}\" afterSend threw; ignoring`, { type, error });\n }\n }\n\n return { notifications, skipped };\n}\n","import type { Backoff } from \"./backoff\";\nimport {\n type EasyPing,\n type EasyPingConfig,\n type HealthReport,\n INBOX_VERSION_HEADER,\n type MountedRoute,\n type SendArgs,\n type SendResult,\n} from \"./config\";\nimport type { NotificationDefinitions } from \"./definition\";\nimport { ConfigError, consoleLogger } from \"./errors\";\nimport { createHandler } from \"./handler\";\nimport type { AnyPlugin } from \"./plugin\";\nimport { createRateLimiter } from \"./rate-limit\";\nimport { createRunner } from \"./runner\";\nimport { isChannelUsable, runSend } from \"./send\";\nimport { createMemorySignals, DELIVERIES_CHANNEL, inboxChannel, type Signals } from \"./signals\";\nimport { createPluginStore } from \"./store\";\nimport { createScopedSigner } from \"./tokens\";\nimport type { DeliveryMode } from \"./types\";\n\nconst CORE_ROUTES: readonly MountedRoute[] = [\n { method: \"GET\", path: \"/\", scope: { type: \"user\" }, owner: \"core\" },\n { method: \"GET\", path: \"/count\", scope: { type: \"user\" }, owner: \"core\" },\n { method: \"POST\", path: \"/seen\", scope: { type: \"user\" }, owner: \"core\" },\n { method: \"POST\", path: \"/read\", scope: { type: \"user\" }, owner: \"core\" },\n { method: \"POST\", path: \"/read-all\", scope: { type: \"user\" }, owner: \"core\" },\n { method: \"GET\", path: \"/events\", scope: { type: \"user\" }, owner: \"core\" },\n { method: \"POST\", path: \"/cron\", scope: { type: \"machine\" }, owner: \"core\" },\n];\n\nconst DEFAULTS = {\n maxAttempts: 5,\n leaseMs: 60_000,\n batchSize: 20,\n basePath: \"/api/notifications\",\n mode: \"cron\" as DeliveryMode,\n};\n\nexport const MIN_SECRET_LENGTH = 16;\n\nconst PLACEHOLDER_SECRETS = new Set([\n \"secret\",\n \"changeme\",\n \"change-me\",\n \"replace-me\",\n \"replace-me-too\",\n \"password\",\n \"demo-signing-secret\",\n \"demo-cron-secret\",\n]);\n\nfunction checkSecretStrength(name: string, value: string) {\n if (value.length < MIN_SECRET_LENGTH || PLACEHOLDER_SECRETS.has(value.toLowerCase())) {\n throw new ConfigError(\n `\\`${name}\\` must be at least ${MIN_SECRET_LENGTH} characters and not a placeholder. ` +\n \"Generate one with `openssl rand -base64 32`.\",\n );\n }\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: an insecure default ships, a 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 checkSecretStrength(\"secret\", config.secret);\n if (config.cron?.secret) checkSecretStrength(\"cron.secret\", config.cron.secret);\n if (config.machineSecret) checkSecretStrength(\"machineSecret\", config.machineSecret);\n\n if (config.rateLimit && (config.rateLimit.max < 1 || config.rateLimit.windowMs < 1)) {\n throw new ConfigError(\"`rateLimit.max` and `rateLimit.windowMs` must both be positive.\");\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 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. 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 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 // Custom-scoped routes are named at startup with their justification. RFC 0002 §3.\n for (const plugin of plugins) {\n for (const route of plugin.routes ?? []) {\n if (route.scope.type === \"custom\") {\n warnings.push(\n `plugin \"${plugin.id}\" mounts ${route.method} ${route.path} with custom auth: ` +\n route.scope.justification,\n );\n }\n }\n }\n\n for (const warning of warnings) logger.warn(warning);\n\n const baseSignals = config.signals ?? createMemorySignals();\n\n // Per-user inbox versions for the piggyback header. In-process counters, so\n // another replica's number differs; the client treats any change as \"look\",\n // which costs a spurious refresh, never a missed one.\n const inboxVersions = new Map<string, number>();\n const signals: Signals = {\n crossProcess: baseSignals.crossProcess,\n publish(channel) {\n if (channel.startsWith(\"inbox:\")) {\n if (inboxVersions.size > 50_000) inboxVersions.clear();\n const userId = channel.slice(\"inbox:\".length);\n inboxVersions.set(userId, (inboxVersions.get(userId) ?? 0) + 1);\n }\n baseSignals.publish(channel);\n },\n subscribe: (channel, handler) => baseSignals.subscribe(channel, handler),\n };\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 signals,\n });\n\n const pluginRoutes = plugins.flatMap((plugin) => plugin.routes ?? []);\n\n const events =\n config.events === false\n ? false\n : {\n heartbeatMs: config.events?.heartbeatMs ?? 25_000,\n probeIntervalMs: config.events?.probeIntervalMs ?? 30_000,\n maxDurationMs: config.events?.maxDurationMs ?? 0,\n maxStreamsPerUser: config.events?.maxStreamsPerUser ?? 10,\n maxStreams: config.events?.maxStreams ?? 5_000,\n };\n\n const sweepConfig = config.delivery?.sweepOnRequest;\n let lastRequestSweep = 0;\n const sweepOnRequest =\n sweepConfig && mode !== \"inline\"\n ? () => {\n const settings = sweepConfig === true ? {} : sweepConfig;\n const now = Date.now();\n if (now - lastRequestSweep < (settings.everyMs ?? 5_000)) return;\n lastRequestSweep = now;\n const pass = runner\n .runOnce({ limit: settings.limit ?? 5 })\n .catch((error) => logger.error(\"request-driven sweep failed\", { error }));\n config.delivery?.waitUntil?.(pass);\n }\n : undefined;\n\n const handler = createHandler({\n adapter: config.database,\n session: config.session,\n runner,\n logger,\n secret: config.secret,\n signals,\n events,\n sweepOnRequest,\n basePath: config.basePath ?? DEFAULTS.basePath,\n pluginRoutes,\n trustedOrigins: config.trustedOrigins,\n onRequest: config.onRequest,\n maxBodyBytes: config.maxBodyBytes,\n rateLimit: config.rateLimit ? createRateLimiter(config.rateLimit) : undefined,\n cronMaxSweeps: config.cron?.maxSweeps,\n ...(config.cron?.secret ? { cronSecret: config.cron.secret } : {}),\n ...((config.machineSecret ?? config.cron?.secret)\n ? { machineSecret: config.machineSecret ?? config.cron?.secret }\n : {}),\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 // Rows are committed; everything below only affects latency. RFC 0001 §8.1.\n if (result.notifications.length > 0) {\n for (const notification of result.notifications) {\n signals.publish(inboxChannel(notification.userId));\n }\n signals.publish(DELIVERIES_CHANNEL);\n\n // Scoped to this send, or an inline send 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 const purposes = new Set(\n (plugin.routes ?? []).flatMap((route) =>\n route.scope.type === \"signed\" ? [route.scope.purpose] : [],\n ),\n );\n plugin.init?.({\n store: createPluginStore(plugin.id, plugin.schema, config.database, tablePrefix),\n sign: createScopedSigner(\n config.secret,\n plugin.id,\n purposes,\n (message) => new ConfigError(message),\n ),\n logger,\n notificationTypes: Object.keys(config.notifications),\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 inboxHeaders: (userId) => ({\n [INBOX_VERSION_HEADER]: String(inboxVersions.get(userId) ?? 0),\n }),\n\n listRoutes: () => [\n ...CORE_ROUTES.filter(\n (route) =>\n (route.path !== \"/cron\" || Boolean(config.cron?.secret)) &&\n (route.path !== \"/events\" || events !== false),\n ),\n ...plugins.flatMap((plugin) =>\n (plugin.routes ?? []).map((route) => ({\n method: route.method,\n path: route.path,\n scope: route.scope,\n owner: plugin.id,\n })),\n ),\n ],\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"]}
package/dist/node.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/core/handler.ts","../src/node/index.ts"],"names":[],"mappings":";;;AA0CO,IAAM,iBAAiB,EAAA,GAAK,IAAA;AA+BnB,IAAI,WAAA;;;AC5DpB,IAAM,iBAAA,GAAN,cAAgC,KAAA,CAAM;AAAC,CAAA;AAEvC,SAAS,QAAA,CAAS,KAAsB,QAAA,EAA+C;AACrF,EAAA,IAAI,GAAA,CAAI,WAAW,KAAA,IAAS,GAAA,CAAI,WAAW,MAAA,EAAQ,OAAO,OAAA,CAAQ,OAAA,CAAQ,MAAS,CAAA;AAEnF,EAAA,MAAM,QAAA,GAAW,MAAA,CAAO,GAAA,CAAI,OAAA,CAAQ,gBAAgB,CAAC,CAAA;AACrD,EAAA,IAAI,MAAA,CAAO,QAAA,CAAS,QAAQ,CAAA,IAAK,WAAW,QAAA,EAAU;AACpD,IAAA,OAAO,OAAA,CAAQ,MAAA,CAAO,IAAI,iBAAA,EAAmB,CAAA;AAAA,EAC/C;AAEA,EAAA,OAAO,IAAI,OAAA,CAAQ,CAAC,OAAA,EAAS,MAAA,KAAW;AACtC,IAAA,MAAM,SAAmB,EAAC;AAC1B,IAAA,IAAI,KAAA,GAAQ,CAAA;AACZ,IAAA,GAAA,CAAI,EAAA,CAAG,MAAA,EAAQ,CAAC,KAAA,KAAkB;AAChC,MAAA,KAAA,IAAS,KAAA,CAAM,MAAA;AACf,MAAA,IAAI,QAAQ,QAAA,EAAU;AACpB,QAAA,GAAA,CAAI,OAAA,EAAQ;AACZ,QAAA,MAAA,CAAO,IAAI,mBAAmB,CAAA;AAC9B,QAAA;AAAA,MACF;AACA,MAAA,MAAA,CAAO,KAAK,KAAK,CAAA;AAAA,IACnB,CAAC,CAAA;AACD,IAAA,GAAA,CAAI,EAAA,CAAG,KAAA,EAAO,MAAM,OAAA,CAAQ,MAA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OAAO,IAAA,EAAK;AAC1C,UAAA,IAAI,IAAA,EAAM;AACV,UAAA,IAAI,CAAC,GAAA,CAAI,KAAA,CAAM,KAAK,GAAG,MAAM,IAAI,OAAA,CAAQ,CAAC,OAAA,KAAY,GAAA,CAAI,IAAA,CAAK,OAAA,EAAS,OAAO,CAAC,CAAA;AAAA,QAClF;AAAA,MACF,CAAA,SAAE;AACA,QAAA,UAAA,CAAW,MAAA,CAAO,mBAAA,CAAoB,OAAA,EAAS,MAAM,CAAA;AAAA,MACvD;AACA,MAAA,GAAA,CAAI,GAAA,EAAI;AAAA,IACV,SAAS,KAAA,EAAO;AAEd,MAAA,IAAI,CAAC,GAAA,CAAI,WAAA,MAAiB,UAAA,GAAa,KAAA,YAAiB,oBAAoB,GAAA,GAAM,GAAA;AAClF,MAAA,GAAA,CAAI,GAAA,EAAI;AACR,MAAA,IAAI,EAAE,KAAA,YAAiB,iBAAA,CAAA,EAAoB,OAAA,CAAQ,KAAK,CAAA;AAAA,IAC1D;AAAA,EACF,CAAA;AACF","file":"node.cjs","sourcesContent":["import type { DatabaseAdapter } from \"./adapter\";\nimport type { SessionConfig } from \"./config\";\nimport type { Logger } from \"./errors\";\nimport type { Promisable, RouteDefinition } from \"./plugin\";\nimport type { Runner } from \"./runner\";\nimport { inboxChannel, type Signals } from \"./signals\";\nimport { verifyToken } from \"./tokens\";\n\nexport type EventsSettings = {\n heartbeatMs: number;\n probeIntervalMs: number;\n maxDurationMs: number;\n};\n\nexport type HandlerDeps = {\n adapter: DatabaseAdapter;\n session: SessionConfig;\n runner: Runner;\n logger: Logger;\n basePath: string;\n secret: string;\n signals: Signals;\n /** `false` unmounts GET /events. */\n events: EventsSettings | false;\n /** Fire-and-forget delivery pass after a request. Rate-limited by the instance. */\n sweepOnRequest?: (() => void) | undefined;\n cronSecret?: string | undefined;\n /** Guards plugin machine routes. The instance defaults it to cronSecret. */\n machineSecret?: string | undefined;\n cronMaxSweeps?: number | undefined;\n pluginRoutes?: readonly RouteDefinition[] | undefined;\n /** Returns a 429 to send, or null to proceed. Runs after onRequest, before routing. */\n rateLimit?: ((request: Request) => Response | null) | undefined;\n /** Origins other than the request's own host that may POST. `*.example.com` allowed. */\n trustedOrigins?: readonly string[] | undefined;\n /** Runs before routing. Returning a Response short-circuits; use it for rate limiting. */\n // biome-ignore lint/suspicious/noConfusingVoidType: a hook that returns nothing is the common case\n onRequest?: ((request: Request) => Promisable<Response | undefined | void>) | undefined;\n maxBodyBytes?: number | undefined;\n};\n\n/** Every JSON body is capped here. Nothing legitimate the routes accept is bigger. */\nexport const MAX_BODY_BYTES = 64 * 1024;\n\nconst MAX_READ_IDS = 200;\n\n// Per-user data: no shared caching, no sniffing.\nconst PRIVATE_HEADERS: Record<string, string> = {\n \"cache-control\": \"private, no-store\",\n \"x-content-type-options\": \"nosniff\",\n};\n\nconst json = (body: unknown, status = 200) =>\n new Response(JSON.stringify(body), {\n status,\n headers: { \"content-type\": \"application/json\", ...PRIVATE_HEADERS },\n });\n\nconst empty = (status: number) => new Response(null, { status, headers: PRIVATE_HEADERS });\n\n/** Plugin responses get the same headers, without touching their body. */\nfunction harden(response: Response): Response {\n const headers = new Headers(response.headers);\n for (const [name, value] of Object.entries(PRIVATE_HEADERS)) {\n if (!headers.has(name)) headers.set(name, value);\n }\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n}\n\nconst encoder = new TextEncoder();\n\n/** Constant time over SHA-256 digests, so neither content nor length leaks. Works on edge runtimes. */\nasync function timingSafeEqual(a: string, b: string): Promise<boolean> {\n const [left, right] = await Promise.all(\n [a, b].map(\n async (value) => new Uint8Array(await crypto.subtle.digest(\"SHA-256\", encoder.encode(value))),\n ),\n );\n let diff = 0;\n for (let i = 0; i < 32; i += 1) diff |= (left?.[i] ?? 0) ^ (right?.[i] ?? 0);\n return diff === 0;\n}\n\n/** Anchored at a segment boundary: `/foo/api/notifications/cron` is not a cron request. */\nfunction routePath(url: URL, basePath: string): string {\n const { pathname } = url;\n if (pathname === basePath) return \"/\";\n if (pathname.startsWith(`${basePath}/`)) return pathname.slice(basePath.length);\n return pathname;\n}\n\nexport type JsonBody = { body: Record<string, unknown> } | { error: Response };\n\n/** Reads a JSON object body with a streaming byte cap. Malformed JSON is 400; an empty body is `{}`. */\nexport async function readJsonBody(\n request: Request,\n maxBytes: number = MAX_BODY_BYTES,\n): Promise<JsonBody> {\n const tooLarge = () => ({ error: json({ error: `body exceeds ${maxBytes} bytes` }, 413) });\n\n const declared = Number(request.headers.get(\"content-length\"));\n if (Number.isFinite(declared) && declared > maxBytes) return tooLarge();\n if (!request.body) return { body: {} };\n\n const reader = request.body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.byteLength;\n if (total > maxBytes) {\n await reader.cancel();\n return tooLarge();\n }\n chunks.push(value);\n }\n\n const bytes = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.byteLength;\n }\n\n const text = new TextDecoder().decode(bytes);\n if (text.trim() === \"\") return { body: {} };\n\n try {\n const parsed: unknown = JSON.parse(text);\n return {\n body:\n parsed && typeof parsed === \"object\" && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : {},\n };\n } catch {\n return { error: json({ error: \"body must be a JSON object\" }, 400) };\n }\n}\n\nconst isJsonContentType = (request: Request) =>\n /^application\\/json\\s*(;|$)/i.test((request.headers.get(\"content-type\") ?? \"\").trim());\n\nfunction originAllowed(origin: string, url: URL, request: Request, trusted: readonly string[]) {\n let host: string;\n try {\n host = new URL(origin).host;\n } catch {\n return false;\n }\n\n if (host === url.host) return true;\n // Behind a proxy that rewrites Host, the public host arrives here instead.\n const forwarded = request.headers.get(\"x-forwarded-host\")?.split(\",\")[0]?.trim();\n if (forwarded && host === forwarded) return true;\n\n return trusted.some((entry) =>\n entry.startsWith(\"*.\") ? host.endsWith(entry.slice(1)) : entry === origin,\n );\n}\n\n/** CSRF: a cross-site form can neither send `application/json` without a preflight nor forge `Origin`. */\nfunction csrfCheck(request: Request, url: URL, trusted: readonly string[]): Response | null {\n if (!isJsonContentType(request)) {\n return json({ error: \"content-type must be application/json\" }, 415);\n }\n\n const origin = request.headers.get(\"origin\");\n if (origin === null) return null;\n if (origin === \"null\" || !originAllowed(origin, url, request, trusted)) return empty(403);\n\n return null;\n}\n\nexport function createHandler(deps: HandlerDeps) {\n const trustedOrigins = deps.trustedOrigins ?? [];\n const maxBodyBytes = deps.maxBodyBytes ?? MAX_BODY_BYTES;\n\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. RFC 0002 §1.\n deps.logger.error(\"session.getUserId threw\", { error });\n return \"error\";\n }\n }\n\n async function bearerMatches(request: Request, secret: string | undefined): Promise<boolean> {\n if (!secret) return false;\n const header = request.headers.get(\"authorization\") ?? \"\";\n const presented = header.startsWith(\"Bearer \") ? header.slice(7) : header;\n return timingSafeEqual(presented, secret);\n }\n\n async function handleCron(request: Request): Promise<Response> {\n if (!deps.cronSecret) return empty(404);\n if (!(await bearerMatches(request, deps.cronSecret))) return empty(401);\n\n // Bounded so an overlapping scheduler does not hold a request open for the whole backlog.\n const result = await deps.runner.drain(\n deps.cronMaxSweeps === undefined ? {} : { maxSweeps: deps.cronMaxSweeps },\n );\n return json(result);\n }\n\n /** Plugin routes first; auth is enforced here so a plugin cannot forget it. */\n async function handlePluginRoute(\n route: RouteDefinition,\n request: Request,\n url: URL,\n ): Promise<Response> {\n if (route.scope.type === \"user\") {\n if (request.method === \"POST\") {\n const rejected = csrfCheck(request, url, trustedOrigins);\n if (rejected) return rejected;\n }\n\n const userId = await resolveUserId(request);\n if (userId === \"error\") return empty(500);\n if (userId === null) return empty(401);\n return harden(await route.handler({ request, userId, claims: null, params: {} }));\n }\n\n if (route.scope.type === \"machine\") {\n if (!deps.machineSecret) return empty(404);\n if (!(await bearerMatches(request, deps.machineSecret))) return empty(401);\n return harden(await 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. RFC 0002 §5.\n if (!claims) return empty(400);\n\n return harden(await route.handler({ request, userId: claims.uid, claims, params: {} }));\n }\n\n return harden(await route.handler({ request, userId: null, claims: null, params: {} }));\n }\n\n async function route(request: Request): Promise<Response> {\n const url = new URL(request.url);\n const path = routePath(url, deps.basePath);\n\n if (deps.onRequest) {\n const early = await deps.onRequest(request);\n if (early instanceof Response) return early;\n }\n\n if (deps.rateLimit) {\n const limited = deps.rateLimit(request);\n if (limited) return limited;\n }\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 (candidate) => candidate.path === path && candidate.method === request.method,\n );\n if (pluginRoute) return handlePluginRoute(pluginRoute, request, url);\n\n if (request.method === \"POST\") {\n const rejected = csrfCheck(request, url, trustedOrigins);\n if (rejected) return rejected;\n }\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 === \"/events\") {\n return deps.events ? events(request, userId, deps.events) : empty(404);\n }\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 // unseenCount rides on the first page only: a cursor request is scrollback, not a poll.\n const [page, unseenCount] = await Promise.all([\n deps.adapter.listNotifications({\n userId,\n limit,\n ...(cursor ? { cursor } : {}),\n ...(url.searchParams.get(\"unreadOnly\") === \"true\" ? { unreadOnly: true } : {}),\n }),\n cursor ? Promise.resolve(null) : deps.adapter.countUnseen(userId),\n ]);\n\n return json(unseenCount === null ? page : { ...page, unseenCount });\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 parsed = await readJsonBody(request, maxBodyBytes);\n if (\"error\" in parsed) return parsed.error;\n const before = typeof parsed.body.before === \"string\" ? new Date(parsed.body.before) : null;\n\n // +1ms: Postgres keeps microseconds, an ISO string milliseconds; without it markSeen misses the newest row.\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 deps.signals.publish(inboxChannel(userId));\n return json({ ok: true });\n }\n\n if (request.method === \"POST\" && path === \"/read\") {\n const parsed = await readJsonBody(request, maxBodyBytes);\n if (\"error\" in parsed) return parsed.error;\n const ids = Array.isArray(parsed.body.ids)\n ? parsed.body.ids.filter((id): id is string => typeof id === \"string\")\n : [];\n if (ids.length === 0) return json({ error: \"ids must be a non-empty string array\" }, 400);\n\n if (ids.length > MAX_READ_IDS) {\n return json({ error: `at most ${MAX_READ_IDS} ids per request` }, 400);\n }\n\n // 404, not 403: a 403 confirms the row exists. RFC 0002 §2.\n const updated = await deps.adapter.markRead(userId, ids);\n if (updated > 0) deps.signals.publish(inboxChannel(userId));\n return updated === 0 ? empty(404) : json({ updated });\n }\n\n if (request.method === \"POST\" && path === \"/read-all\") {\n const updated = await deps.adapter.markAllRead(userId);\n if (updated > 0) deps.signals.publish(inboxChannel(userId));\n return json({ updated });\n }\n\n return empty(404);\n }\n\n /** A change fingerprint cheap enough to take every probe interval. */\n async function fingerprint(userId: string): Promise<string> {\n const [page, unseen] = await Promise.all([\n deps.adapter.listNotifications({ userId, limit: 1 }),\n deps.adapter.countUnseen(userId),\n ]);\n const newest = page.notifications[0];\n return `${newest?.id ?? \"\"}|${newest?.readAt ? 1 : 0}|${unseen}`;\n }\n\n /**\n * Server-Sent Events: `ready` once, `changed` whenever this user's inbox\n * moves, comments as keepalive. No payload ever travels on the stream; the\n * client fetches the feed on `changed`. RFC 0006 §4D.\n */\n function events(request: Request, userId: string, settings: EventsSettings): Response {\n const encoder = new TextEncoder();\n const timers: ReturnType<typeof setInterval>[] = [];\n let unsubscribe: (() => void) | undefined;\n let closed = false;\n let cleanup = () => {};\n\n const stream = new ReadableStream<Uint8Array>({\n start(controller) {\n const write = (text: string) => {\n if (closed) return;\n try {\n controller.enqueue(encoder.encode(text));\n } catch {\n cleanup();\n }\n };\n cleanup = () => {\n if (closed) return;\n closed = true;\n unsubscribe?.();\n for (const timer of timers) clearInterval(timer);\n try {\n controller.close();\n } catch {\n // already closed by the consumer\n }\n };\n const changed = () => write(\"event: changed\\ndata: {}\\n\\n\");\n\n write(\"retry: 3000\\n\\nevent: ready\\ndata: {}\\n\\n\");\n unsubscribe = deps.signals.subscribe(inboxChannel(userId), changed);\n timers.push(setInterval(() => write(\": keepalive\\n\\n\"), settings.heartbeatMs));\n\n if (!deps.signals.crossProcess && settings.probeIntervalMs > 0) {\n let last: string | undefined;\n fingerprint(userId)\n .then((value) => {\n last = value;\n })\n .catch(() => {});\n timers.push(\n setInterval(() => {\n fingerprint(userId)\n .then((value) => {\n if (last !== undefined && value !== last) changed();\n last = value;\n })\n .catch((error) => deps.logger.error(\"events probe failed\", { error }));\n }, settings.probeIntervalMs),\n );\n }\n\n if (settings.maxDurationMs > 0) {\n timers.push(\n setTimeout(cleanup, settings.maxDurationMs) as ReturnType<typeof setInterval>,\n );\n }\n request.signal?.addEventListener(\"abort\", cleanup, { once: true });\n },\n cancel() {\n cleanup();\n },\n });\n\n return new Response(stream, {\n headers: {\n \"content-type\": \"text/event-stream; charset=utf-8\",\n \"cache-control\": \"no-cache, no-store\",\n connection: \"keep-alive\",\n \"x-accel-buffering\": \"no\",\n \"x-content-type-options\": \"nosniff\",\n },\n });\n }\n\n async function handle(request: Request): Promise<Response> {\n try {\n return await route(request);\n } catch (error) {\n // A thrown driver error must not escape: unhandled rejection on Node, stack trace elsewhere.\n deps.logger.error(\"request failed\", { url: request.url, error });\n return empty(500);\n } finally {\n deps.sweepOnRequest?.();\n }\n }\n\n return {\n handle,\n GET: handle,\n POST: handle,\n };\n}\n","import type { IncomingMessage, ServerResponse } from \"node:http\";\nimport { MAX_BODY_BYTES } from \"../core/handler\";\n\n/** Adapts the web-standard handler to Node's http/Express signature. */\nexport type NodeHandler = (req: IncomingMessage, res: ServerResponse) => Promise<void>;\n\nexport type NodeHandlerOptions = {\n /** Defaults to 64 KiB. Enforced here because this reads the raw stream, bypassing body-parser. */\n maxBodyBytes?: number;\n /** Called when the handler itself throws. Defaults to console.error; the response is already a 500. */\n onError?: (error: unknown) => void;\n};\n\nclass BodyTooLargeError extends Error {}\n\nfunction readBody(req: IncomingMessage, maxBytes: number): Promise<Buffer | undefined> {\n if (req.method === \"GET\" || req.method === \"HEAD\") return Promise.resolve(undefined);\n\n const declared = Number(req.headers[\"content-length\"]);\n if (Number.isFinite(declared) && declared > maxBytes) {\n return Promise.reject(new BodyTooLargeError());\n }\n\n return new Promise((resolve, reject) => {\n const chunks: Buffer[] = [];\n let total = 0;\n req.on(\"data\", (chunk: Buffer) => {\n total += chunk.length;\n if (total > maxBytes) {\n req.destroy();\n reject(new BodyTooLargeError());\n return;\n }\n chunks.push(chunk);\n });\n req.on(\"end\", () => resolve(chunks.length ? Buffer.concat(chunks) : undefined));\n req.on(\"error\", reject);\n });\n}\n\nexport function toWebRequest(req: IncomingMessage, body?: Buffer, signal?: AbortSignal): Request {\n // Behind a load balancer this is the only signal that the site is https.\n const protocol = (req.headers[\"x-forwarded-proto\"] as string | undefined) ?? \"http\";\n const host = req.headers.host ?? \"localhost\";\n\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (value === undefined) continue;\n if (Array.isArray(value)) for (const item of value) headers.append(key, item);\n else headers.set(key, value);\n }\n\n return new Request(`${protocol}://${host}${req.url ?? \"/\"}`, {\n method: req.method ?? \"GET\",\n headers,\n ...(body ? { body: new Uint8Array(body) } : {}),\n ...(signal ? { signal } : {}),\n });\n}\n\nexport function toNodeHandler(\n handler: (request: Request) => Promise<Response>,\n options: NodeHandlerOptions = {},\n): NodeHandler {\n const maxBodyBytes = options.maxBodyBytes ?? MAX_BODY_BYTES;\n const onError = options.onError ?? ((error: unknown) => console.error(\"[easy-ping]\", error));\n\n return async (req, res) => {\n // A client that goes away aborts the request, so an open event stream cleans up.\n const disconnect = new AbortController();\n res.on(\"close\", () => disconnect.abort());\n\n try {\n const body = await readBody(req, maxBodyBytes);\n const response = await handler(toWebRequest(req, body, disconnect.signal));\n\n res.statusCode = response.status;\n // forEach: Headers is only iterable with \"DOM.Iterable\" in lib.\n response.headers.forEach((value, key) => {\n res.setHeader(key, value);\n });\n\n if (!response.body) {\n res.end();\n return;\n }\n\n // Streamed, never buffered: GET /events stays open and every chunk must reach the client now.\n res.flushHeaders();\n const reader = response.body.getReader();\n const cancel = () => reader.cancel().catch(() => {});\n disconnect.signal.addEventListener(\"abort\", cancel, { once: true });\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n if (!res.write(value)) await new Promise((resolve) => res.once(\"drain\", resolve));\n }\n } finally {\n disconnect.signal.removeEventListener(\"abort\", cancel);\n }\n res.end();\n } catch (error) {\n // Respond and swallow: a rethrow is an unhandled rejection under Express.\n if (!res.headersSent) res.statusCode = error instanceof BodyTooLargeError ? 413 : 500;\n res.end();\n if (!(error instanceof BodyTooLargeError)) onError(error);\n }\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/core/handler.ts","../src/node/index.ts"],"names":[],"mappings":";;;AA+CO,IAAM,iBAAiB,EAAA,GAAK,IAAA;AA+BnB,IAAI,WAAA;;;ACjEpB,IAAM,iBAAA,GAAN,cAAgC,KAAA,CAAM;AAAC,CAAA;AAEvC,SAAS,QAAA,CAAS,KAAsB,QAAA,EAA+C;AACrF,EAAA,IAAI,GAAA,CAAI,WAAW,KAAA,IAAS,GAAA,C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O;AAEd,MAAA,IAAI,CAAC,GAAA,CAAI,WAAA,MAAiB,UAAA,GAAa,KAAA,YAAiB,oBAAoB,GAAA,GAAM,GAAA;AAClF,MAAA,GAAA,CAAI,GAAA,EAAI;AACR,MAAA,IAAI,EAAE,KAAA,YAAiB,iBAAA,CAAA,EAAoB,OAAA,CAAQ,KAAK,CAAA;AAAA,IAC1D;AAAA,EACF,CAAA;AACF","file":"node.cjs","sourcesContent":["import type { DatabaseAdapter } from \"./adapter\";\nimport type { SessionConfig } from \"./config\";\nimport type { Logger } from \"./errors\";\nimport type { Promisable, RouteDefinition } from \"./plugin\";\nimport type { Runner } from \"./runner\";\nimport { inboxChannel, type Signals } from \"./signals\";\nimport { verifyToken } from \"./tokens\";\n\nexport type EventsSettings = {\n heartbeatMs: number;\n probeIntervalMs: number;\n maxDurationMs: number;\n maxStreamsPerUser: number;\n maxStreams: number;\n};\n\n/** Unread chunks a stream may hold before it is closed on a consumer that stopped reading. */\nconst STREAM_HIGH_WATER_MARK = 256;\n\nexport type HandlerDeps = {\n adapter: DatabaseAdapter;\n session: SessionConfig;\n runner: Runner;\n logger: Logger;\n basePath: string;\n secret: string;\n signals: Signals;\n /** `false` unmounts GET /events. */\n events: EventsSettings | false;\n /** Fire-and-forget delivery pass after a request. Rate-limited by the instance. */\n sweepOnRequest?: (() => void) | undefined;\n cronSecret?: string | undefined;\n /** Guards plugin machine routes. The instance defaults it to cronSecret. */\n machineSecret?: string | undefined;\n cronMaxSweeps?: number | undefined;\n pluginRoutes?: readonly RouteDefinition[] | undefined;\n /** Returns a 429 to send, or null to proceed. Runs after onRequest, before routing. */\n rateLimit?: ((request: Request) => Response | null) | undefined;\n /** Origins other than the request's own host that may POST. `*.example.com` allowed. */\n trustedOrigins?: readonly string[] | undefined;\n /** Runs before routing. Returning a Response short-circuits; use it for rate limiting. */\n // biome-ignore lint/suspicious/noConfusingVoidType: a hook that returns nothing is the common case\n onRequest?: ((request: Request) => Promisable<Response | undefined | void>) | undefined;\n maxBodyBytes?: number | undefined;\n};\n\n/** Every JSON body is capped here. Nothing legitimate the routes accept is bigger. */\nexport const MAX_BODY_BYTES = 64 * 1024;\n\nconst MAX_READ_IDS = 200;\n\n// Per-user data: no shared caching, no sniffing.\nconst PRIVATE_HEADERS: Record<string, string> = {\n \"cache-control\": \"private, no-store\",\n \"x-content-type-options\": \"nosniff\",\n};\n\nconst json = (body: unknown, status = 200, headers: Record<string, string> = {}) =>\n new Response(JSON.stringify(body), {\n status,\n headers: { \"content-type\": \"application/json\", ...PRIVATE_HEADERS, ...headers },\n });\n\nconst empty = (status: number) => new Response(null, { status, headers: PRIVATE_HEADERS });\n\n/** Plugin responses get the same headers, without touching their body. */\nfunction harden(response: Response): Response {\n const headers = new Headers(response.headers);\n for (const [name, value] of Object.entries(PRIVATE_HEADERS)) {\n if (!headers.has(name)) headers.set(name, value);\n }\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n}\n\nconst encoder = new TextEncoder();\n\n/** Constant time over SHA-256 digests, so neither content nor length leaks. Works on edge runtimes. */\nasync function timingSafeEqual(a: string, b: string): Promise<boolean> {\n const [left, right] = await Promise.all(\n [a, b].map(\n async (value) => new Uint8Array(await crypto.subtle.digest(\"SHA-256\", encoder.encode(value))),\n ),\n );\n let diff = 0;\n for (let i = 0; i < 32; i += 1) diff |= (left?.[i] ?? 0) ^ (right?.[i] ?? 0);\n return diff === 0;\n}\n\n/** Anchored at a segment boundary: `/foo/api/notifications/cron` is not a cron request. */\nfunction routePath(url: URL, basePath: string): string {\n const { pathname } = url;\n if (pathname === basePath) return \"/\";\n if (pathname.startsWith(`${basePath}/`)) return pathname.slice(basePath.length);\n return pathname;\n}\n\nexport type JsonBody = { body: Record<string, unknown> } | { error: Response };\n\n/** Reads a JSON object body with a streaming byte cap. Malformed JSON is 400; an empty body is `{}`. */\nexport async function readJsonBody(\n request: Request,\n maxBytes: number = MAX_BODY_BYTES,\n): Promise<JsonBody> {\n const tooLarge = () => ({ error: json({ error: `body exceeds ${maxBytes} bytes` }, 413) });\n\n const declared = Number(request.headers.get(\"content-length\"));\n if (Number.isFinite(declared) && declared > maxBytes) return tooLarge();\n if (!request.body) return { body: {} };\n\n const reader = request.body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.byteLength;\n if (total > maxBytes) {\n await reader.cancel();\n return tooLarge();\n }\n chunks.push(value);\n }\n\n const bytes = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.byteLength;\n }\n\n const text = new TextDecoder().decode(bytes);\n if (text.trim() === \"\") return { body: {} };\n\n try {\n const parsed: unknown = JSON.parse(text);\n return {\n body:\n parsed && typeof parsed === \"object\" && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : {},\n };\n } catch {\n return { error: json({ error: \"body must be a JSON object\" }, 400) };\n }\n}\n\nconst isJsonContentType = (request: Request) =>\n /^application\\/json\\s*(;|$)/i.test((request.headers.get(\"content-type\") ?? \"\").trim());\n\nfunction originAllowed(origin: string, url: URL, request: Request, trusted: readonly string[]) {\n let host: string;\n try {\n host = new URL(origin).host;\n } catch {\n return false;\n }\n\n if (host === url.host) return true;\n // Behind a proxy that rewrites Host, the public host arrives here instead.\n const forwarded = request.headers.get(\"x-forwarded-host\")?.split(\",\")[0]?.trim();\n if (forwarded && host === forwarded) return true;\n\n return trusted.some((entry) =>\n entry.startsWith(\"*.\") ? host.endsWith(entry.slice(1)) : entry === origin,\n );\n}\n\n/** CSRF: a cross-site form can neither send `application/json` without a preflight nor forge `Origin`. */\nfunction csrfCheck(request: Request, url: URL, trusted: readonly string[]): Response | null {\n if (!isJsonContentType(request)) {\n return json({ error: \"content-type must be application/json\" }, 415);\n }\n\n const origin = request.headers.get(\"origin\");\n if (origin === null) return null;\n if (origin === \"null\" || !originAllowed(origin, url, request, trusted)) return empty(403);\n\n return null;\n}\n\nexport function createHandler(deps: HandlerDeps) {\n const trustedOrigins = deps.trustedOrigins ?? [];\n const maxBodyBytes = deps.maxBodyBytes ?? MAX_BODY_BYTES;\n\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. RFC 0002 §1.\n deps.logger.error(\"session.getUserId threw\", { error });\n return \"error\";\n }\n }\n\n async function bearerMatches(request: Request, secret: string | undefined): Promise<boolean> {\n if (!secret) return false;\n const header = request.headers.get(\"authorization\") ?? \"\";\n const presented = header.startsWith(\"Bearer \") ? header.slice(7) : header;\n return timingSafeEqual(presented, secret);\n }\n\n async function handleCron(request: Request): Promise<Response> {\n if (!deps.cronSecret) return empty(404);\n if (!(await bearerMatches(request, deps.cronSecret))) return empty(401);\n\n // Bounded so an overlapping scheduler does not hold a request open for the whole backlog.\n const result = await deps.runner.drain(\n deps.cronMaxSweeps === undefined ? {} : { maxSweeps: deps.cronMaxSweeps },\n );\n return json(result);\n }\n\n /** Plugin routes first; auth is enforced here so a plugin cannot forget it. */\n async function handlePluginRoute(\n route: RouteDefinition,\n request: Request,\n url: URL,\n ): Promise<Response> {\n if (route.scope.type === \"user\") {\n if (request.method === \"POST\") {\n const rejected = csrfCheck(request, url, trustedOrigins);\n if (rejected) return rejected;\n }\n\n const userId = await resolveUserId(request);\n if (userId === \"error\") return empty(500);\n if (userId === null) return empty(401);\n return harden(await route.handler({ request, userId, claims: null, params: {} }));\n }\n\n if (route.scope.type === \"machine\") {\n if (!deps.machineSecret) return empty(404);\n if (!(await bearerMatches(request, deps.machineSecret))) return empty(401);\n return harden(await 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. RFC 0002 §5.\n if (!claims) return empty(400);\n\n return harden(await route.handler({ request, userId: claims.uid, claims, params: {} }));\n }\n\n return harden(await route.handler({ request, userId: null, claims: null, params: {} }));\n }\n\n async function route(request: Request): Promise<Response> {\n const url = new URL(request.url);\n const path = routePath(url, deps.basePath);\n\n if (deps.onRequest) {\n const early = await deps.onRequest(request);\n if (early instanceof Response) return early;\n }\n\n if (deps.rateLimit) {\n const limited = deps.rateLimit(request);\n if (limited) return limited;\n }\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 (candidate) => candidate.path === path && candidate.method === request.method,\n );\n if (pluginRoute) return handlePluginRoute(pluginRoute, request, url);\n\n if (request.method === \"POST\") {\n const rejected = csrfCheck(request, url, trustedOrigins);\n if (rejected) return rejected;\n }\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 === \"/events\") {\n if (!deps.events) return empty(404);\n // A session can open streams for free; without a cap one account can hold every socket.\n if ((openStreams.get(userId) ?? 0) >= deps.events.maxStreamsPerUser) {\n return json({ error: \"too many open event streams\" }, 429, { \"retry-after\": \"30\" });\n }\n if (totalStreams >= deps.events.maxStreams) {\n return json({ error: \"event streams unavailable\" }, 503, { \"retry-after\": \"30\" });\n }\n return events(request, userId, deps.events);\n }\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 // unseenCount rides on the first page only: a cursor request is scrollback, not a poll.\n const [page, unseenCount] = await Promise.all([\n deps.adapter.listNotifications({\n userId,\n limit,\n ...(cursor ? { cursor } : {}),\n ...(url.searchParams.get(\"unreadOnly\") === \"true\" ? { unreadOnly: true } : {}),\n }),\n cursor ? Promise.resolve(null) : deps.adapter.countUnseen(userId),\n ]);\n\n return json(unseenCount === null ? page : { ...page, unseenCount });\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 parsed = await readJsonBody(request, maxBodyBytes);\n if (\"error\" in parsed) return parsed.error;\n const before = typeof parsed.body.before === \"string\" ? new Date(parsed.body.before) : null;\n\n // +1ms: Postgres keeps microseconds, an ISO string milliseconds; without it markSeen misses the newest row.\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 deps.signals.publish(inboxChannel(userId));\n return json({ ok: true });\n }\n\n if (request.method === \"POST\" && path === \"/read\") {\n const parsed = await readJsonBody(request, maxBodyBytes);\n if (\"error\" in parsed) return parsed.error;\n const ids = Array.isArray(parsed.body.ids)\n ? parsed.body.ids.filter((id): id is string => typeof id === \"string\")\n : [];\n if (ids.length === 0) return json({ error: \"ids must be a non-empty string array\" }, 400);\n\n if (ids.length > MAX_READ_IDS) {\n return json({ error: `at most ${MAX_READ_IDS} ids per request` }, 400);\n }\n\n // 404, not 403: a 403 confirms the row exists. RFC 0002 §2.\n const updated = await deps.adapter.markRead(userId, ids);\n if (updated > 0) deps.signals.publish(inboxChannel(userId));\n return updated === 0 ? empty(404) : json({ updated });\n }\n\n if (request.method === \"POST\" && path === \"/read-all\") {\n const updated = await deps.adapter.markAllRead(userId);\n if (updated > 0) deps.signals.publish(inboxChannel(userId));\n return json({ updated });\n }\n\n return empty(404);\n }\n\n const openStreams = new Map<string, number>();\n let totalStreams = 0;\n\n const trackStream = (userId: string) => {\n openStreams.set(userId, (openStreams.get(userId) ?? 0) + 1);\n totalStreams += 1;\n return () => {\n const remaining = (openStreams.get(userId) ?? 1) - 1;\n if (remaining > 0) openStreams.set(userId, remaining);\n else openStreams.delete(userId);\n totalStreams -= 1;\n };\n };\n\n /** A change fingerprint cheap enough to take every probe interval. */\n async function fingerprint(userId: string): Promise<string> {\n const [page, unseen] = await Promise.all([\n deps.adapter.listNotifications({ userId, limit: 1 }),\n deps.adapter.countUnseen(userId),\n ]);\n const newest = page.notifications[0];\n return `${newest?.id ?? \"\"}|${newest?.readAt ? 1 : 0}|${unseen}`;\n }\n\n // One probe per user, however many streams that user holds: N tabs must not mean N queries.\n type Probe = { listeners: Set<() => void>; timer: ReturnType<typeof setInterval>; last?: string };\n const probes = new Map<string, Probe>();\n\n function subscribeProbe(userId: string, onChanged: () => void, intervalMs: number) {\n let probe = probes.get(userId);\n if (!probe) {\n const created: Probe = {\n listeners: new Set(),\n timer: setInterval(() => {\n fingerprint(userId)\n .then((value) => {\n if (created.last !== undefined && value !== created.last) {\n for (const listener of created.listeners) listener();\n }\n created.last = value;\n })\n .catch((error) => deps.logger.error(\"events probe failed\", { error }));\n }, intervalMs),\n };\n probe = created;\n probes.set(userId, created);\n fingerprint(userId)\n .then((value) => {\n if (created.last === undefined) created.last = value;\n })\n .catch(() => {});\n }\n probe.listeners.add(onChanged);\n return () => {\n const current = probes.get(userId);\n if (!current) return;\n current.listeners.delete(onChanged);\n if (current.listeners.size === 0) {\n clearInterval(current.timer);\n probes.delete(userId);\n }\n };\n }\n\n /**\n * Server-Sent Events: `ready` once, `changed` whenever this user's inbox\n * moves, comments as keepalive. No payload ever travels on the stream; the\n * client fetches the feed on `changed`. RFC 0006 §4D.\n */\n function events(request: Request, userId: string, settings: EventsSettings): Response {\n const encoder = new TextEncoder();\n const timers: ReturnType<typeof setInterval>[] = [];\n const unsubscribes: (() => void)[] = [];\n let closed = false;\n let cleanup = () => {};\n\n const stream = new ReadableStream<Uint8Array>(\n {\n start(controller) {\n const write = (text: string) => {\n if (closed) return;\n // A consumer that stopped reading would make this queue grow without bound.\n if (controller.desiredSize !== null && controller.desiredSize <= 0) {\n cleanup();\n return;\n }\n try {\n controller.enqueue(encoder.encode(text));\n } catch {\n cleanup();\n }\n };\n cleanup = () => {\n if (closed) return;\n closed = true;\n for (const unsubscribe of unsubscribes) unsubscribe();\n for (const timer of timers) clearInterval(timer);\n try {\n controller.close();\n } catch {\n // already closed by the consumer\n }\n };\n const changed = () => write(\"event: changed\\ndata: {}\\n\\n\");\n\n unsubscribes.push(trackStream(userId));\n write(\"retry: 3000\\n\\nevent: ready\\ndata: {}\\n\\n\");\n unsubscribes.push(deps.signals.subscribe(inboxChannel(userId), changed));\n timers.push(setInterval(() => write(\": keepalive\\n\\n\"), settings.heartbeatMs));\n\n if (!deps.signals.crossProcess && settings.probeIntervalMs > 0) {\n unsubscribes.push(subscribeProbe(userId, changed, settings.probeIntervalMs));\n }\n\n if (settings.maxDurationMs > 0) {\n timers.push(\n setTimeout(cleanup, settings.maxDurationMs) as ReturnType<typeof setInterval>,\n );\n }\n request.signal?.addEventListener(\"abort\", cleanup, { once: true });\n },\n cancel() {\n cleanup();\n },\n },\n { highWaterMark: STREAM_HIGH_WATER_MARK },\n );\n\n return new Response(stream, {\n headers: {\n \"content-type\": \"text/event-stream; charset=utf-8\",\n \"cache-control\": \"no-cache, no-store\",\n connection: \"keep-alive\",\n \"x-accel-buffering\": \"no\",\n \"x-content-type-options\": \"nosniff\",\n },\n });\n }\n\n async function handle(request: Request): Promise<Response> {\n let response: Response | undefined;\n try {\n response = await route(request);\n return response;\n } catch (error) {\n // A thrown driver error must not escape: unhandled rejection on Node, stack trace elsewhere.\n deps.logger.error(\"request failed\", { url: request.url, error });\n return empty(500);\n } finally {\n // Only a served request earns a sweep; anonymous 401s must not drive database work.\n if (response && response.status < 400) deps.sweepOnRequest?.();\n }\n }\n\n return {\n handle,\n GET: handle,\n POST: handle,\n };\n}\n","import type { IncomingMessage, ServerResponse } from \"node:http\";\nimport { MAX_BODY_BYTES } from \"../core/handler\";\n\n/** Adapts the web-standard handler to Node's http/Express signature. */\nexport type NodeHandler = (req: IncomingMessage, res: ServerResponse) => Promise<void>;\n\nexport type NodeHandlerOptions = {\n /** Defaults to 64 KiB. Enforced here because this reads the raw stream, bypassing body-parser. */\n maxBodyBytes?: number;\n /** Called when the handler itself throws. Defaults to console.error; the response is already a 500. */\n onError?: (error: unknown) => void;\n};\n\nclass BodyTooLargeError extends Error {}\n\nfunction readBody(req: IncomingMessage, maxBytes: number): Promise<Buffer | undefined> {\n if (req.method === \"GET\" || req.method === \"HEAD\") return Promise.resolve(undefined);\n\n const declared = Number(req.headers[\"content-length\"]);\n if (Number.isFinite(declared) && declared > maxBytes) {\n return Promise.reject(new BodyTooLargeError());\n }\n\n return new Promise((resolve, reject) => {\n const chunks: Buffer[] = [];\n let total = 0;\n req.on(\"data\", (chunk: Buffer) => {\n total += chunk.length;\n if (total > maxBytes) {\n req.destroy();\n reject(new BodyTooLargeError());\n return;\n }\n chunks.push(chunk);\n });\n req.on(\"end\", () => resolve(chunks.length ? Buffer.concat(chunks) : undefined));\n req.on(\"error\", reject);\n });\n}\n\nexport function toWebRequest(req: IncomingMessage, body?: Buffer, signal?: AbortSignal): Request {\n // Behind a load balancer this is the only signal that the site is https.\n const protocol = (req.headers[\"x-forwarded-proto\"] as string | undefined) ?? \"http\";\n const host = req.headers.host ?? \"localhost\";\n\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (value === undefined) continue;\n if (Array.isArray(value)) for (const item of value) headers.append(key, item);\n else headers.set(key, value);\n }\n\n return new Request(`${protocol}://${host}${req.url ?? \"/\"}`, {\n method: req.method ?? \"GET\",\n headers,\n ...(body ? { body: new Uint8Array(body) } : {}),\n ...(signal ? { signal } : {}),\n });\n}\n\nexport function toNodeHandler(\n handler: (request: Request) => Promise<Response>,\n options: NodeHandlerOptions = {},\n): NodeHandler {\n const maxBodyBytes = options.maxBodyBytes ?? MAX_BODY_BYTES;\n const onError = options.onError ?? ((error: unknown) => console.error(\"[easy-ping]\", error));\n\n return async (req, res) => {\n // A client that goes away aborts the request, so an open event stream cleans up.\n const disconnect = new AbortController();\n res.on(\"close\", () => disconnect.abort());\n\n try {\n const body = await readBody(req, maxBodyBytes);\n const response = await handler(toWebRequest(req, body, disconnect.signal));\n\n res.statusCode = response.status;\n // forEach: Headers is only iterable with \"DOM.Iterable\" in lib.\n response.headers.forEach((value, key) => {\n res.setHeader(key, value);\n });\n\n if (!response.body) {\n res.end();\n return;\n }\n\n // Streamed, never buffered: GET /events stays open and every chunk must reach the client now.\n res.flushHeaders();\n const reader = response.body.getReader();\n const cancel = () => reader.cancel().catch(() => {});\n disconnect.signal.addEventListener(\"abort\", cancel, { once: true });\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n if (!res.write(value)) await new Promise((resolve) => res.once(\"drain\", resolve));\n }\n } finally {\n disconnect.signal.removeEventListener(\"abort\", cancel);\n }\n res.end();\n } catch (error) {\n // Respond and swallow: a rethrow is an unhandled rejection under Express.\n if (!res.headersSent) res.statusCode = error instanceof BodyTooLargeError ? 413 : 500;\n res.end();\n if (!(error instanceof BodyTooLargeError)) onError(error);\n }\n };\n}\n"]}
package/dist/node.js CHANGED
@@ -1,4 +1,4 @@
1
- import { MAX_BODY_BYTES } from './chunk-USQ6CQTJ.js';
1
+ import { MAX_BODY_BYTES } from './chunk-JOVIZXO6.js';
2
2
  import './chunk-ORZKH224.js';
3
3
  import './chunk-PTGHMCCG.js';
4
4
 
@@ -1,4 +1,4 @@
1
- import { R as Recipient, C as Channel, f as DeliveryOutcome, k as PluginStore } from './adapter-D3lTy-4E.js';
1
+ import { R as Recipient, C as Channel, f as DeliveryOutcome, k as PluginStore } from './adapter-BJ8Iejvs.js';
2
2
 
3
3
  declare class EasyPingError extends Error {
4
4
  constructor(message: string);
@@ -1,4 +1,4 @@
1
- import { R as Recipient, C as Channel, f as DeliveryOutcome, k as PluginStore } from './adapter-D3lTy-4E.cjs';
1
+ import { R as Recipient, C as Channel, f as DeliveryOutcome, k as PluginStore } from './adapter-BJ8Iejvs.cjs';
2
2
 
3
3
  declare class EasyPingError extends Error {
4
4
  constructor(message: string);
@@ -1,5 +1,5 @@
1
- import { h as EasyPingPlugin } from '../plugin-CHd2ZiGC.cjs';
2
- import '../adapter-D3lTy-4E.cjs';
1
+ import { h as EasyPingPlugin } from '../plugin-Wwp1nvo0.cjs';
2
+ import '../adapter-BJ8Iejvs.cjs';
3
3
 
4
4
  type DigestWindow = "daily" | "weekly";
5
5
  type LocalMoment = {
@@ -1,5 +1,5 @@
1
- import { h as EasyPingPlugin } from '../plugin-Cg9usuUi.js';
2
- import '../adapter-D3lTy-4E.js';
1
+ import { h as EasyPingPlugin } from '../plugin-CSLKKgXT.js';
2
+ import '../adapter-BJ8Iejvs.js';
3
3
 
4
4
  type DigestWindow = "daily" | "weekly";
5
5
  type LocalMoment = {
@@ -1,5 +1,5 @@
1
- import { f as ClientPlugin } from '../plugin-CHd2ZiGC.cjs';
2
- import { C as Channel, F as Frequency } from '../adapter-D3lTy-4E.cjs';
1
+ import { f as ClientPlugin } from '../plugin-Wwp1nvo0.cjs';
2
+ import { C as Channel, F as Frequency } from '../adapter-BJ8Iejvs.cjs';
3
3
 
4
4
  type PreferenceView = {
5
5
  userId: string;
@@ -1,5 +1,5 @@
1
- import { f as ClientPlugin } from '../plugin-Cg9usuUi.js';
2
- import { C as Channel, F as Frequency } from '../adapter-D3lTy-4E.js';
1
+ import { f as ClientPlugin } from '../plugin-CSLKKgXT.js';
2
+ import { C as Channel, F as Frequency } from '../adapter-BJ8Iejvs.js';
3
3
 
4
4
  type PreferenceView = {
5
5
  userId: string;
@@ -1,4 +1,4 @@
1
- type Channel = "inApp" | "email" | "push" | "sms" | "slack";
1
+ type Channel = "inApp" | "email" | "push" | "telegram" | "sms" | "slack";
2
2
  type Frequency = "instant" | "daily" | "weekly" | "off";
3
3
 
4
4
  type PreferenceView = {
@@ -1,4 +1,4 @@
1
- type Channel = "inApp" | "email" | "push" | "sms" | "slack";
1
+ type Channel = "inApp" | "email" | "push" | "telegram" | "sms" | "slack";
2
2
  type Frequency = "instant" | "daily" | "weekly" | "off";
3
3
 
4
4
  type PreferenceView = {
@@ -43,9 +43,9 @@ var PRIVATE_HEADERS = {
43
43
  "cache-control": "private, no-store",
44
44
  "x-content-type-options": "nosniff"
45
45
  };
46
- var json = (body, status = 200) => new Response(JSON.stringify(body), {
46
+ var json = (body, status = 200, headers = {}) => new Response(JSON.stringify(body), {
47
47
  status,
48
- headers: { "content-type": "application/json", ...PRIVATE_HEADERS }
48
+ headers: { "content-type": "application/json", ...PRIVATE_HEADERS, ...headers }
49
49
  });
50
50
  new TextEncoder();
51
51
  async function readJsonBody(request, maxBytes = MAX_BODY_BYTES) {
@@ -87,7 +87,7 @@ async function readJsonBody(request, maxBytes = MAX_BODY_BYTES) {
87
87
  // src/plugins/preferences/index.ts
88
88
  var UNSUBSCRIBE_PURPOSE = "unsubscribe";
89
89
  var TABLE = "notification_preference";
90
- var CHANNELS = ["inApp", "email", "push", "sms", "slack"];
90
+ var CHANNELS = ["inApp", "email", "push", "telegram", "sms", "slack"];
91
91
  var FREQUENCIES = ["instant", "daily", "weekly", "off"];
92
92
  var isChannel = (value) => CHANNELS.includes(value);
93
93
  var isFrequency = (value) => FREQUENCIES.includes(value);