easy-ping 0.5.0 → 0.6.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 (62) hide show
  1. package/README.md +548 -508
  2. package/dist/adapters/mongodb.cjs +142 -0
  3. package/dist/adapters/mongodb.cjs.map +1 -1
  4. package/dist/adapters/mongodb.d.cts +39 -1
  5. package/dist/adapters/mongodb.d.ts +39 -1
  6. package/dist/adapters/mongodb.js +73 -1
  7. package/dist/adapters/mongodb.js.map +1 -1
  8. package/dist/adapters/postgres.cjs +146 -0
  9. package/dist/adapters/postgres.cjs.map +1 -1
  10. package/dist/adapters/postgres.d.cts +36 -1
  11. package/dist/adapters/postgres.d.ts +36 -1
  12. package/dist/adapters/postgres.js +78 -3
  13. package/dist/adapters/postgres.js.map +1 -1
  14. package/dist/adapters/sqlite.js +1 -1
  15. package/dist/{chunk-GJNLOQJS.js → chunk-JKTMUMQK.js} +31 -6
  16. package/dist/chunk-JKTMUMQK.js.map +1 -0
  17. package/dist/chunk-ORZKH224.js +75 -0
  18. package/dist/chunk-ORZKH224.js.map +1 -0
  19. package/dist/{chunk-BECMTNK7.js → chunk-USQ6CQTJ.js} +88 -3
  20. package/dist/chunk-USQ6CQTJ.js.map +1 -0
  21. package/dist/client.cjs +288 -17
  22. package/dist/client.cjs.map +1 -1
  23. package/dist/client.d.cts +53 -1
  24. package/dist/client.d.ts +53 -1
  25. package/dist/client.js +288 -17
  26. package/dist/client.js.map +1 -1
  27. package/dist/index.cjs +237 -7
  28. package/dist/index.cjs.map +1 -1
  29. package/dist/index.d.cts +42 -1
  30. package/dist/index.d.ts +42 -1
  31. package/dist/index.js +55 -7
  32. package/dist/index.js.map +1 -1
  33. package/dist/node.cjs +26 -5
  34. package/dist/node.cjs.map +1 -1
  35. package/dist/node.d.cts +1 -1
  36. package/dist/node.d.ts +1 -1
  37. package/dist/node.js +28 -6
  38. package/dist/node.js.map +1 -1
  39. package/dist/plugins/preferences.cjs.map +1 -1
  40. package/dist/plugins/preferences.js +2 -1
  41. package/dist/plugins/preferences.js.map +1 -1
  42. package/dist/plugins/push.cjs.map +1 -1
  43. package/dist/plugins/push.js +3 -2
  44. package/dist/plugins/push.js.map +1 -1
  45. package/dist/react.cjs +311 -19
  46. package/dist/react.cjs.map +1 -1
  47. package/dist/react.d.cts +52 -0
  48. package/dist/react.d.ts +52 -0
  49. package/dist/react.js +311 -19
  50. package/dist/react.js.map +1 -1
  51. package/dist/schema.js +1 -1
  52. package/dist/signals-kPmOlKDX.d.cts +27 -0
  53. package/dist/signals-kPmOlKDX.d.ts +27 -0
  54. package/dist/sw.cjs +39 -0
  55. package/dist/sw.cjs.map +1 -0
  56. package/dist/sw.d.cts +52 -0
  57. package/dist/sw.d.ts +52 -0
  58. package/dist/sw.js +36 -0
  59. package/dist/sw.js.map +1 -0
  60. package/package.json +6 -1
  61. package/dist/chunk-BECMTNK7.js.map +0 -1
  62. package/dist/chunk-GJNLOQJS.js.map +0 -1
package/dist/index.d.cts CHANGED
@@ -5,6 +5,8 @@ import { R as RouteScope, A as AnyPlugin, P as Promisable, L as Logger } from '.
5
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';
6
6
  import { E as EmailProvider } from './provider-CA45WVqt.cjs';
7
7
  export { a as EmailMessage, P as ProviderSendResult } from './provider-CA45WVqt.cjs';
8
+ import { S as Signals } from './signals-kPmOlKDX.cjs';
9
+ export { D as DELIVERIES_CHANNEL, c as createBridgedSignals, a as createMemorySignals, i as inboxChannel } from './signals-kPmOlKDX.cjs';
8
10
 
9
11
  declare function encodeBase64Url(input: string | Uint8Array): string;
10
12
  declare function decodeBase64Url(value: string): string | null;
@@ -60,6 +62,26 @@ type DeliveryConfig = {
60
62
  backoff?: "exponential" | ((attempt: number) => number);
61
63
  /** Next.js `after` or Cloudflare `ctx.waitUntil`. Injected, not detected. */
62
64
  waitUntil?: (promise: Promise<unknown>) => void;
65
+ /**
66
+ * Run one small claim-and-deliver pass after any request the handler serves,
67
+ * at most once per `everyMs` per process. Delivery then rides on your own
68
+ * traffic and the cron becomes a backstop. Ignored in `inline` mode. RFC 0006 idea 5.
69
+ */
70
+ sweepOnRequest?: true | {
71
+ everyMs?: number;
72
+ limit?: number;
73
+ };
74
+ };
75
+ type EventsConfig = {
76
+ /** Comment line keeping proxies from closing an idle stream. Default 25 s. */
77
+ heartbeatMs?: number;
78
+ /**
79
+ * Without a cross-process signal source, each stream checks the database
80
+ * for changes this often on its subscriber's behalf. Default 30 s; 0 disables.
81
+ */
82
+ probeIntervalMs?: number;
83
+ /** Close the stream after this long; the client reconnects. 0 (default) leaves it open. */
84
+ maxDurationMs?: number;
63
85
  };
64
86
  type ChannelsConfig = {
65
87
  inApp?: {
@@ -88,6 +110,14 @@ type EasyPingConfig<TDefs extends NotificationDefinitions> = {
88
110
  machineSecret?: string;
89
111
  /** In-process fixed-window limiter, applied before routing. */
90
112
  rateLimit?: RateLimitConfig;
113
+ /**
114
+ * How "something changed" travels between the sender, the worker and open
115
+ * event streams. Defaults to in-process. Supply a LISTEN/NOTIFY or change
116
+ * stream implementation to cross replicas. RFC 0006 §4C.
117
+ */
118
+ signals?: Signals;
119
+ /** `GET /events`, a Server-Sent Events stream per user. `false` unmounts it. */
120
+ events?: EventsConfig | false;
91
121
  plugins?: readonly AnyPlugin[];
92
122
  /** Where the handler is mounted, used to strip the prefix off incoming URLs. */
93
123
  basePath?: string;
@@ -141,6 +171,8 @@ type HealthReport = {
141
171
  cronRequiredButMissing: boolean;
142
172
  warnings: readonly string[];
143
173
  };
174
+ /** Response header carrying a per-user inbox version, so app traffic can replace polling. */
175
+ declare const INBOX_VERSION_HEADER = "x-easy-ping-inbox";
144
176
  type EasyPing<TDefs extends NotificationDefinitions> = {
145
177
  send<TKey extends keyof TDefs & string>(type: TKey, args: SendArgs<TDefs, TKey>): Promise<SendResult>;
146
178
  handler: {
@@ -149,6 +181,7 @@ type EasyPing<TDefs extends NotificationDefinitions> = {
149
181
  GET: (request: Request) => Promise<Response>;
150
182
  POST: (request: Request) => Promise<Response>;
151
183
  };
184
+ /** Idle interval defaults to 10 s; a send in this process wakes the loop at once. */
152
185
  startWorker(options?: {
153
186
  intervalMs?: number;
154
187
  batchSize?: number;
@@ -156,6 +189,12 @@ type EasyPing<TDefs extends NotificationDefinitions> = {
156
189
  healthCheck(): Promise<HealthReport>;
157
190
  /** Every mounted route with its auth scope, so `custom`-scoped ones stay visible. RFC 0002 §3. */
158
191
  listRoutes(): readonly MountedRoute[];
192
+ /**
193
+ * Headers to attach to any response your app sends this user. The client's
194
+ * `instrument(fetch)` reads them and refreshes only when the version moved,
195
+ * so an active user never needs a dedicated poll. RFC 0006 idea 1.
196
+ */
197
+ inboxHeaders(userId: string): Record<string, string>;
159
198
  /** Deliveries that exhausted their attempts, newest first. Wire it to an admin page or an alert. */
160
199
  getFailedDeliveries(options?: {
161
200
  /** Defaults to the last 24 hours. */
@@ -177,6 +216,8 @@ type RunnerDeps = {
177
216
  leaseMs: number;
178
217
  batchSize: number;
179
218
  backoff: Backoff;
219
+ /** Wakes an idle worker the moment a send commits, so the idle interval can be long. */
220
+ signals?: Signals | undefined;
180
221
  };
181
222
  type SweepResult = {
182
223
  claimed: number;
@@ -221,4 +262,4 @@ declare const escapeHtml: (value: unknown) => string;
221
262
  declare const MIN_SECRET_LENGTH = 16;
222
263
  declare function easyPing<TDefs extends NotificationDefinitions>(config: EasyPingConfig<TDefs>): EasyPing<TDefs>;
223
264
 
224
- export { type AnyNotificationDefinition, AnyPlugin, Channel, type ChannelsConfig, DatabaseAdapter, type DeliveryConfig, DeliveryMode, DeliveryRecord, type EasyPing, type EasyPingConfig, EmailProvider, type EmailTemplate, type HealthReport, type JsonBody, Logger, MAX_BODY_BYTES, MIN_SECRET_LENGTH, type MountedRoute, type NotificationDefinition, type NotificationDefinitions, type PayloadFromSchema, type PayloadOf, Promisable, type RateLimitConfig, Recipient, RouteScope, type Runner, type RunnerDeps, type SendArgs, type SendResult, type SessionConfig, SkipReason, type SweepResult, type Worker, createRateLimiter, createRunner, decodeBase64Url, defineNotification, easyPing, encodeBase64Url, escapeHtml, readJsonBody, redactErrorMessage };
265
+ export { type AnyNotificationDefinition, AnyPlugin, Channel, type ChannelsConfig, DatabaseAdapter, type DeliveryConfig, DeliveryMode, DeliveryRecord, type EasyPing, type EasyPingConfig, EmailProvider, type EmailTemplate, type EventsConfig, type HealthReport, INBOX_VERSION_HEADER, type JsonBody, Logger, MAX_BODY_BYTES, MIN_SECRET_LENGTH, type MountedRoute, type NotificationDefinition, type NotificationDefinitions, type PayloadFromSchema, type PayloadOf, Promisable, type RateLimitConfig, Recipient, RouteScope, type Runner, type RunnerDeps, type SendArgs, type SendResult, type SessionConfig, Signals, SkipReason, type SweepResult, type Worker, createRateLimiter, createRunner, decodeBase64Url, defineNotification, easyPing, encodeBase64Url, escapeHtml, readJsonBody, redactErrorMessage };
package/dist/index.d.ts CHANGED
@@ -5,6 +5,8 @@ import { R as RouteScope, A as AnyPlugin, P as Promisable, L as Logger } from '.
5
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';
6
6
  import { E as EmailProvider } from './provider-CA45WVqt.js';
7
7
  export { a as EmailMessage, P as ProviderSendResult } from './provider-CA45WVqt.js';
8
+ import { S as Signals } from './signals-kPmOlKDX.js';
9
+ export { D as DELIVERIES_CHANNEL, c as createBridgedSignals, a as createMemorySignals, i as inboxChannel } from './signals-kPmOlKDX.js';
8
10
 
9
11
  declare function encodeBase64Url(input: string | Uint8Array): string;
10
12
  declare function decodeBase64Url(value: string): string | null;
@@ -60,6 +62,26 @@ type DeliveryConfig = {
60
62
  backoff?: "exponential" | ((attempt: number) => number);
61
63
  /** Next.js `after` or Cloudflare `ctx.waitUntil`. Injected, not detected. */
62
64
  waitUntil?: (promise: Promise<unknown>) => void;
65
+ /**
66
+ * Run one small claim-and-deliver pass after any request the handler serves,
67
+ * at most once per `everyMs` per process. Delivery then rides on your own
68
+ * traffic and the cron becomes a backstop. Ignored in `inline` mode. RFC 0006 idea 5.
69
+ */
70
+ sweepOnRequest?: true | {
71
+ everyMs?: number;
72
+ limit?: number;
73
+ };
74
+ };
75
+ type EventsConfig = {
76
+ /** Comment line keeping proxies from closing an idle stream. Default 25 s. */
77
+ heartbeatMs?: number;
78
+ /**
79
+ * Without a cross-process signal source, each stream checks the database
80
+ * for changes this often on its subscriber's behalf. Default 30 s; 0 disables.
81
+ */
82
+ probeIntervalMs?: number;
83
+ /** Close the stream after this long; the client reconnects. 0 (default) leaves it open. */
84
+ maxDurationMs?: number;
63
85
  };
64
86
  type ChannelsConfig = {
65
87
  inApp?: {
@@ -88,6 +110,14 @@ type EasyPingConfig<TDefs extends NotificationDefinitions> = {
88
110
  machineSecret?: string;
89
111
  /** In-process fixed-window limiter, applied before routing. */
90
112
  rateLimit?: RateLimitConfig;
113
+ /**
114
+ * How "something changed" travels between the sender, the worker and open
115
+ * event streams. Defaults to in-process. Supply a LISTEN/NOTIFY or change
116
+ * stream implementation to cross replicas. RFC 0006 §4C.
117
+ */
118
+ signals?: Signals;
119
+ /** `GET /events`, a Server-Sent Events stream per user. `false` unmounts it. */
120
+ events?: EventsConfig | false;
91
121
  plugins?: readonly AnyPlugin[];
92
122
  /** Where the handler is mounted, used to strip the prefix off incoming URLs. */
93
123
  basePath?: string;
@@ -141,6 +171,8 @@ type HealthReport = {
141
171
  cronRequiredButMissing: boolean;
142
172
  warnings: readonly string[];
143
173
  };
174
+ /** Response header carrying a per-user inbox version, so app traffic can replace polling. */
175
+ declare const INBOX_VERSION_HEADER = "x-easy-ping-inbox";
144
176
  type EasyPing<TDefs extends NotificationDefinitions> = {
145
177
  send<TKey extends keyof TDefs & string>(type: TKey, args: SendArgs<TDefs, TKey>): Promise<SendResult>;
146
178
  handler: {
@@ -149,6 +181,7 @@ type EasyPing<TDefs extends NotificationDefinitions> = {
149
181
  GET: (request: Request) => Promise<Response>;
150
182
  POST: (request: Request) => Promise<Response>;
151
183
  };
184
+ /** Idle interval defaults to 10 s; a send in this process wakes the loop at once. */
152
185
  startWorker(options?: {
153
186
  intervalMs?: number;
154
187
  batchSize?: number;
@@ -156,6 +189,12 @@ type EasyPing<TDefs extends NotificationDefinitions> = {
156
189
  healthCheck(): Promise<HealthReport>;
157
190
  /** Every mounted route with its auth scope, so `custom`-scoped ones stay visible. RFC 0002 §3. */
158
191
  listRoutes(): readonly MountedRoute[];
192
+ /**
193
+ * Headers to attach to any response your app sends this user. The client's
194
+ * `instrument(fetch)` reads them and refreshes only when the version moved,
195
+ * so an active user never needs a dedicated poll. RFC 0006 idea 1.
196
+ */
197
+ inboxHeaders(userId: string): Record<string, string>;
159
198
  /** Deliveries that exhausted their attempts, newest first. Wire it to an admin page or an alert. */
160
199
  getFailedDeliveries(options?: {
161
200
  /** Defaults to the last 24 hours. */
@@ -177,6 +216,8 @@ type RunnerDeps = {
177
216
  leaseMs: number;
178
217
  batchSize: number;
179
218
  backoff: Backoff;
219
+ /** Wakes an idle worker the moment a send commits, so the idle interval can be long. */
220
+ signals?: Signals | undefined;
180
221
  };
181
222
  type SweepResult = {
182
223
  claimed: number;
@@ -221,4 +262,4 @@ declare const escapeHtml: (value: unknown) => string;
221
262
  declare const MIN_SECRET_LENGTH = 16;
222
263
  declare function easyPing<TDefs extends NotificationDefinitions>(config: EasyPingConfig<TDefs>): EasyPing<TDefs>;
223
264
 
224
- export { type AnyNotificationDefinition, AnyPlugin, Channel, type ChannelsConfig, DatabaseAdapter, type DeliveryConfig, DeliveryMode, DeliveryRecord, type EasyPing, type EasyPingConfig, EmailProvider, type EmailTemplate, type HealthReport, type JsonBody, Logger, MAX_BODY_BYTES, MIN_SECRET_LENGTH, type MountedRoute, type NotificationDefinition, type NotificationDefinitions, type PayloadFromSchema, type PayloadOf, Promisable, type RateLimitConfig, Recipient, RouteScope, type Runner, type RunnerDeps, type SendArgs, type SendResult, type SessionConfig, SkipReason, type SweepResult, type Worker, createRateLimiter, createRunner, decodeBase64Url, defineNotification, easyPing, encodeBase64Url, escapeHtml, readJsonBody, redactErrorMessage };
265
+ export { type AnyNotificationDefinition, AnyPlugin, Channel, type ChannelsConfig, DatabaseAdapter, type DeliveryConfig, DeliveryMode, DeliveryRecord, type EasyPing, type EasyPingConfig, EmailProvider, type EmailTemplate, type EventsConfig, type HealthReport, INBOX_VERSION_HEADER, type JsonBody, Logger, MAX_BODY_BYTES, MIN_SECRET_LENGTH, type MountedRoute, type NotificationDefinition, type NotificationDefinitions, type PayloadFromSchema, type PayloadOf, Promisable, type RateLimitConfig, Recipient, RouteScope, type Runner, type RunnerDeps, type SendArgs, type SendResult, type SessionConfig, Signals, SkipReason, type SweepResult, type Worker, createRateLimiter, createRunner, decodeBase64Url, defineNotification, easyPing, encodeBase64Url, escapeHtml, readJsonBody, redactErrorMessage };
package/dist/index.js CHANGED
@@ -1,13 +1,18 @@
1
+ import { createRunner } from './chunk-JKTMUMQK.js';
2
+ export { createRunner, redactErrorMessage } from './chunk-JKTMUMQK.js';
1
3
  export { defineClientPlugin, definePlugin } from './chunk-E4IZ2CQC.js';
2
- import { createRunner } from './chunk-GJNLOQJS.js';
3
- export { createRunner, redactErrorMessage } from './chunk-GJNLOQJS.js';
4
- import { createHandler, createScopedSigner } from './chunk-BECMTNK7.js';
5
- export { DEFAULT_TOKEN_TTL_SECONDS, MAX_BODY_BYTES, MAX_TOKEN_TTL_SECONDS, expiresIn, readJsonBody, signToken, verifyToken } from './chunk-BECMTNK7.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';
6
+ import { createMemorySignals, inboxChannel, DELIVERIES_CHANNEL } from './chunk-ORZKH224.js';
7
+ export { DELIVERIES_CHANNEL, createBridgedSignals, createMemorySignals, inboxChannel } from './chunk-ORZKH224.js';
6
8
  import { consoleLogger, ConfigError, createPluginStore, ValidationError } from './chunk-3VOQOGDR.js';
7
9
  export { ConfigError, EasyPingError, ValidationError, consoleLogger } from './chunk-3VOQOGDR.js';
8
10
  import './chunk-AEYYTE5I.js';
9
11
  export { decodeBase64Url, encodeBase64Url } from './chunk-PTGHMCCG.js';
10
12
 
13
+ // src/core/config.ts
14
+ var INBOX_VERSION_HEADER = "x-easy-ping-inbox";
15
+
11
16
  // src/core/definition.ts
12
17
  function defineNotification(definition) {
13
18
  return definition;
@@ -253,6 +258,7 @@ var CORE_ROUTES = [
253
258
  { method: "POST", path: "/seen", scope: { type: "user" }, owner: "core" },
254
259
  { method: "POST", path: "/read", scope: { type: "user" }, owner: "core" },
255
260
  { method: "POST", path: "/read-all", scope: { type: "user" }, owner: "core" },
261
+ { method: "GET", path: "/events", scope: { type: "user" }, owner: "core" },
256
262
  { method: "POST", path: "/cron", scope: { type: "machine" }, owner: "core" }
257
263
  ];
258
264
  var DEFAULTS = {
@@ -377,6 +383,20 @@ function easyPing(config) {
377
383
  }
378
384
  }
379
385
  for (const warning of warnings) logger.warn(warning);
386
+ const baseSignals = config.signals ?? createMemorySignals();
387
+ const inboxVersions = /* @__PURE__ */ new Map();
388
+ const signals = {
389
+ crossProcess: baseSignals.crossProcess,
390
+ publish(channel) {
391
+ if (channel.startsWith("inbox:")) {
392
+ if (inboxVersions.size > 5e4) inboxVersions.clear();
393
+ const userId = channel.slice("inbox:".length);
394
+ inboxVersions.set(userId, (inboxVersions.get(userId) ?? 0) + 1);
395
+ }
396
+ baseSignals.publish(channel);
397
+ },
398
+ subscribe: (channel, handler2) => baseSignals.subscribe(channel, handler2)
399
+ };
380
400
  const runner = createRunner({
381
401
  adapter: config.database,
382
402
  definitions: config.notifications,
@@ -386,15 +406,34 @@ function easyPing(config) {
386
406
  logger,
387
407
  leaseMs,
388
408
  batchSize: config.delivery?.batchSize ?? DEFAULTS.batchSize,
389
- backoff: config.delivery?.backoff ?? "exponential"
409
+ backoff: config.delivery?.backoff ?? "exponential",
410
+ signals
390
411
  });
391
412
  const pluginRoutes = plugins.flatMap((plugin) => plugin.routes ?? []);
413
+ const events = config.events === false ? false : {
414
+ heartbeatMs: config.events?.heartbeatMs ?? 25e3,
415
+ probeIntervalMs: config.events?.probeIntervalMs ?? 3e4,
416
+ maxDurationMs: config.events?.maxDurationMs ?? 0
417
+ };
418
+ const sweepConfig = config.delivery?.sweepOnRequest;
419
+ let lastRequestSweep = 0;
420
+ const sweepOnRequest = sweepConfig && mode !== "inline" ? () => {
421
+ const settings = sweepConfig === true ? {} : sweepConfig;
422
+ const now = Date.now();
423
+ if (now - lastRequestSweep < (settings.everyMs ?? 5e3)) return;
424
+ lastRequestSweep = now;
425
+ const pass = runner.runOnce({ limit: settings.limit ?? 5 }).catch((error) => logger.error("request-driven sweep failed", { error }));
426
+ config.delivery?.waitUntil?.(pass);
427
+ } : void 0;
392
428
  const handler = createHandler({
393
429
  adapter: config.database,
394
430
  session: config.session,
395
431
  runner,
396
432
  logger,
397
433
  secret: config.secret,
434
+ signals,
435
+ events,
436
+ sweepOnRequest,
398
437
  basePath: config.basePath ?? DEFAULTS.basePath,
399
438
  pluginRoutes,
400
439
  trustedOrigins: config.trustedOrigins,
@@ -426,6 +465,10 @@ function easyPing(config) {
426
465
  }
427
466
  );
428
467
  if (result.notifications.length > 0) {
468
+ for (const notification of result.notifications) {
469
+ signals.publish(inboxChannel(notification.userId));
470
+ }
471
+ signals.publish(DELIVERIES_CHANNEL);
429
472
  const ids = result.notifications.flatMap(
430
473
  (notification) => notification.deliveries.map((delivery) => delivery.id)
431
474
  );
@@ -458,8 +501,13 @@ function easyPing(config) {
458
501
  send,
459
502
  handler,
460
503
  startWorker: (options) => runner.startWorker(options ?? {}),
504
+ inboxHeaders: (userId) => ({
505
+ [INBOX_VERSION_HEADER]: String(inboxVersions.get(userId) ?? 0)
506
+ }),
461
507
  listRoutes: () => [
462
- ...CORE_ROUTES.filter((route) => route.path !== "/cron" || Boolean(config.cron?.secret)),
508
+ ...CORE_ROUTES.filter(
509
+ (route) => (route.path !== "/cron" || Boolean(config.cron?.secret)) && (route.path !== "/events" || events !== false)
510
+ ),
463
511
  ...plugins.flatMap(
464
512
  (plugin) => (plugin.routes ?? []).map((route) => ({
465
513
  method: route.method,
@@ -485,6 +533,6 @@ function easyPing(config) {
485
533
  };
486
534
  }
487
535
 
488
- export { MIN_SECRET_LENGTH, createRateLimiter, defineNotification, easyPing, escapeHtml };
536
+ export { INBOX_VERSION_HEADER, MIN_SECRET_LENGTH, createRateLimiter, defineNotification, easyPing, escapeHtml };
489
537
  //# sourceMappingURL=index.js.map
490
538
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/core/definition.ts","../src/core/html.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,CAAC,KAAA,MAAW;AAAA,UACpC,QAAQ,KAAA,CAAM,MAAA;AAAA,UACd,MAAM,KAAA,CAAM,IAAA;AAAA,UACZ,OAAO,KAAA,CAAM,KAAA;AAAA,UACb,OAAO,MAAA,CAAO;AAAA,SAChB,CAAE;AAAA;AACJ,KACF;AAAA,IAEA,qBAAqB,CAAC,OAAA,GAAU,EAAC,KAC/B,MAAA,CAAO,SAAS,mBAAA,CAAoB;AAAA,MAClC,KAAA,EAAO,QAAQ,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 { 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 type {\n EasyPing,\n EasyPingConfig,\n HealthReport,\n MountedRoute,\n SendArgs,\n 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 { 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: \"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 runner = createRunner({\n adapter: config.database,\n definitions: config.notifications,\n channels: config.channels,\n plugins,\n getRecipients: config.getRecipients,\n logger,\n leaseMs,\n batchSize: config.delivery?.batchSize ?? DEFAULTS.batchSize,\n backoff: (config.delivery?.backoff ?? \"exponential\") as Backoff,\n });\n\n const pluginRoutes = plugins.flatMap((plugin) => plugin.routes ?? []);\n\n const handler = createHandler({\n adapter: config.database,\n session: config.session,\n runner,\n logger,\n secret: config.secret,\n basePath: config.basePath ?? DEFAULTS.basePath,\n pluginRoutes,\n 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 // 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 listRoutes: () => [\n ...CORE_ROUTES.filter((route) => route.path !== \"/cron\" || Boolean(config.cron?.secret)),\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/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,GAAA,EAAK,QAAA;AAAA,EACL,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,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"]}
package/dist/node.cjs CHANGED
@@ -29,7 +29,7 @@ function readBody(req, maxBytes) {
29
29
  req.on("error", reject);
30
30
  });
31
31
  }
32
- function toWebRequest(req, body) {
32
+ function toWebRequest(req, body, signal) {
33
33
  const protocol = req.headers["x-forwarded-proto"] ?? "http";
34
34
  const host = req.headers.host ?? "localhost";
35
35
  const headers = new Headers();
@@ -41,21 +41,42 @@ function toWebRequest(req, body) {
41
41
  return new Request(`${protocol}://${host}${req.url ?? "/"}`, {
42
42
  method: req.method ?? "GET",
43
43
  headers,
44
- ...body ? { body: new Uint8Array(body) } : {}
44
+ ...body ? { body: new Uint8Array(body) } : {},
45
+ ...signal ? { signal } : {}
45
46
  });
46
47
  }
47
48
  function toNodeHandler(handler, options = {}) {
48
49
  const maxBodyBytes = options.maxBodyBytes ?? MAX_BODY_BYTES;
49
50
  const onError = options.onError ?? ((error) => console.error("[easy-ping]", error));
50
51
  return async (req, res) => {
52
+ const disconnect = new AbortController();
53
+ res.on("close", () => disconnect.abort());
51
54
  try {
52
- const response = await handler(toWebRequest(req, await readBody(req, maxBodyBytes)));
55
+ const body = await readBody(req, maxBodyBytes);
56
+ const response = await handler(toWebRequest(req, body, disconnect.signal));
53
57
  res.statusCode = response.status;
54
58
  response.headers.forEach((value, key) => {
55
59
  res.setHeader(key, value);
56
60
  });
57
- const buffer = response.body ? Buffer.from(await response.arrayBuffer()) : null;
58
- res.end(buffer ?? void 0);
61
+ if (!response.body) {
62
+ res.end();
63
+ return;
64
+ }
65
+ res.flushHeaders();
66
+ const reader = response.body.getReader();
67
+ const cancel = () => reader.cancel().catch(() => {
68
+ });
69
+ disconnect.signal.addEventListener("abort", cancel, { once: true });
70
+ try {
71
+ for (; ; ) {
72
+ const { done, value } = await reader.read();
73
+ if (done) break;
74
+ if (!res.write(value)) await new Promise((resolve) => res.once("drain", resolve));
75
+ }
76
+ } finally {
77
+ disconnect.signal.removeEventListener("abort", cancel);
78
+ }
79
+ res.end();
59
80
  } catch (error) {
60
81
  if (!res.headersSent) res.statusCode = error instanceof BodyTooLargeError ? 413 : 500;
61
82
  res.end();