@lunora/notify 1.0.0-alpha.7 → 1.0.0-alpha.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -75,14 +75,45 @@ type RegisterInput = {
75
75
  };
76
76
  /** Filter narrowing which stored subscriptions a `list`/`broadcast` targets. */
77
77
  interface SubscriptionFilter {
78
+ /**
79
+ * Keyset pagination cursor: return only rows with `id` strictly GREATER
80
+ * than this value, ordered ascending by `id`. `id` is a stable,
81
+ * content-derived hash (see `webPushId`/`fcmId`), so ordering by it is
82
+ * immune to concurrent inserts/deletes elsewhere in the table — a page
83
+ * already walked never re-delivers or skips a row when another device
84
+ * registers mid-broadcast (the reviewer-flagged "stable under concurrent
85
+ * registers" property). `broadcastPage`/`broadcast` set this internally to
86
+ * walk pages; a direct `list()` caller may also page through results with
87
+ * it.
88
+ *
89
+ * OPTIONAL for a reason: `SubscriptionStore` is implementable outside this
90
+ * package. An external store that does not support cursoring may ignore
91
+ * `after` entirely and keep returning its (from-the-top) unpaged result —
92
+ * `broadcastPage` defensively re-filters whatever the store returns down
93
+ * to `id > after` itself, so a non-cursoring store can never cause a
94
+ * double-send or an infinite page-walk (each page's result only ever
95
+ * contains ids the previous page didn't already deliver), but it also
96
+ * cannot deliver the FULL matched audience beyond whatever the store's own
97
+ * (unpaged) response window happens to contain — implement `after`
98
+ * (ordered ascending by `id`, exclusive) to get real, complete pagination
99
+ * over a large audience.
100
+ */
101
+ after?: string;
78
102
  /** Restrict to a delivery kind. */
79
103
  kind?: SubscriptionKind;
80
104
  /**
81
105
  * Cap the number of rows returned (a `LIMIT`). Applied server-side by the
82
106
  * store, so a large audience never materializes wholesale in the isolate.
83
107
  * A non-positive/absent value means "no cap"; a fractional value is truncated.
84
- * `broadcast` deliberately leaves this unset (it must reach every matched
85
- * device); admin/list reads set it to bound the page.
108
+ *
109
+ * For `list`/admin reads this bounds the returned page as before. For
110
+ * `broadcast`, this is now an OVERALL cap on the total number of
111
+ * subscriptions reached across every internally-walked page (still
112
+ * deliberately left unset by default — it must reach every matched
113
+ * device); the PER-PAGE batch size is a separate, independent knob (see
114
+ * `CreateNotifyOptions`'s `broadcastPageSize`, default 250) so a caller
115
+ * that sets `limit` to bound the audience doesn't also have to reason
116
+ * about page sizing.
86
117
  */
87
118
  limit?: number;
88
119
  /** Restrict to a single owning user. */
@@ -98,7 +129,13 @@ interface SubscriptionStore {
98
129
  delete: (id: string) => Promise<void>;
99
130
  /** Read a subscription by id, or `undefined`. */
100
131
  get: (id: string) => Promise<StoredSubscription | undefined>;
101
- /** List subscriptions, optionally filtered. */
132
+ /**
133
+ * List subscriptions, optionally filtered. When `filter.after` is set,
134
+ * results are keyset-paginated: only rows with `id` strictly greater than
135
+ * `filter.after` are returned, ordered ascending by `id`. Implementing
136
+ * `after` is OPTIONAL (see {@link SubscriptionFilter.after}) — a store
137
+ * that ignores it may keep returning its unpaged result.
138
+ */
102
139
  list: (filter?: SubscriptionFilter) => Promise<StoredSubscription[]>;
103
140
  /** Record the latest delivery outcome for a subscription (best-effort). */
104
141
  markStatus: (id: string, status: SubscriptionStatus, error?: string) => Promise<void>;
@@ -127,6 +164,18 @@ interface BroadcastResult {
127
164
  /** Total subscriptions attempted. */
128
165
  total: number;
129
166
  }
167
+ /**
168
+ * Result of `broadcastPage` — one bounded page of a fan-out, plus the cursor
169
+ * to fetch the next page. `nextCursor` is `undefined` when this was the last
170
+ * page (or the store doesn't support cursoring — see
171
+ * {@link SubscriptionFilter.after}'s documented unpaged fallback).
172
+ */
173
+ interface BroadcastPageResult {
174
+ /** Cursor for the next page (pass as `filter.after`), or `undefined` when done. */
175
+ nextCursor?: string;
176
+ /** The delivery outcome for just this page. */
177
+ result: BroadcastResult;
178
+ }
130
179
  /**
131
180
  * The compact, stable delivery-status vocabulary emitted on notify observability
132
181
  * signals — the `status` dimension on the `notify.send` metric and the failure
@@ -181,8 +230,28 @@ interface LunoraPush {
181
230
  * Reuses the engine's retry/circuit-breaker middleware; prunes subscriptions
182
231
  * the push service reports as gone (HTTP 404/410, FCM `UNREGISTERED`). The `to`
183
232
  * target is derived from each subscription, so it is omitted from the payload.
233
+ *
234
+ * Internally walks the audience in bounded pages (via {@link LunoraPush.broadcastPage},
235
+ * keyset-paginated on the subscription `id`) so a huge audience is never
236
+ * materialized wholesale in the isolate — see `CreateNotifyOptions`'s
237
+ * `broadcastPageSize`. This call still processes the WHOLE matched
238
+ * audience in one request/queue message; use {@link LunoraPush.broadcastPage}
239
+ * directly (as `runPushBroadcastJob` does) to bound a single queue message
240
+ * to one page.
184
241
  */
185
242
  broadcast: (payload: PushContent, filter?: SubscriptionFilter) => Promise<BroadcastResult>;
243
+ /**
244
+ * Fan-out a push to ONE bounded page of stored subscriptions matching
245
+ * `filter` (page size: `CreateNotifyOptions`'s `broadcastPageSize`, default
246
+ * 250, capped by `filter.limit` when set). Same delivery semantics as
247
+ * {@link LunoraPush.broadcast} (retry/circuit-breaker, gone-pruning) but
248
+ * scoped to a single page; returns the page's own {@link BroadcastResult}
249
+ * plus a `nextCursor` to fetch the next page (`undefined` when done).
250
+ * Backs `runPushBroadcastJob` so one queue message does bounded work
251
+ * regardless of audience size — most app code should call
252
+ * {@link LunoraPush.broadcast} instead.
253
+ */
254
+ broadcastPage: (payload: PushContent, filter?: SubscriptionFilter) => Promise<BroadcastPageResult>;
186
255
  /**
187
256
  * List stored subscriptions (optionally filtered), with the delivery
188
257
  * **secrets** stripped — the Web Push `keys` (RFC 8291 `auth`/`p256dh`) and the
@@ -333,6 +402,16 @@ declare const defineNotify: (config: NotifyConfig) => NotifyDefinition;
333
402
  declare const isNotifyDefinition: (value: unknown) => value is NotifyDefinition;
334
403
  /** Options for {@link createNotify}. */
335
404
  interface CreateNotifyOptions {
405
+ /**
406
+ * Page size for `push.broadcast`'s internal keyset pagination over the
407
+ * subscription store (default {@link DEFAULT_BROADCAST_PAGE_SIZE}, 250).
408
+ * Each page is fetched, delivered, and counted independently before the
409
+ * next page's store round trip, so a huge audience is never materialized
410
+ * wholesale in the isolate. Also the per-message bound `push.broadcastPage`
411
+ * (and so `runPushBroadcastJob`) uses. A test/tuning seam — most apps never
412
+ * need to set this.
413
+ */
414
+ broadcastPageSize?: number;
336
415
  /** Max concurrent sends during a `broadcast` (default 10). */
337
416
  concurrency?: number;
338
417
  /**
@@ -407,9 +486,11 @@ declare const buildEngine: (resolved: ResolvedProviders) => Notification;
407
486
  * A broadcast job body — the JSON-serialisable payload enqueued for off-request
408
487
  * fan-out. Shaped to travel through a `@lunora/queue` producer/consumer without
409
488
  * `@lunora/notify` depending on `@lunora/queue` (the seam stays structural).
489
+ * `filter.after`, when set, resumes a broadcast partway through (see
490
+ * {@link runPushBroadcastJob}'s continuation semantics).
410
491
  */
411
492
  interface PushBroadcastJob {
412
- /** Subscription filter (which devices/users to target). */
493
+ /** Subscription filter (which devices/users to target; `filter.after` resumes a paged broadcast). */
413
494
  filter?: SubscriptionFilter;
414
495
  /** The push payload to deliver (the `to` target is derived per subscription). */
415
496
  payload: PushContent;
@@ -423,7 +504,8 @@ interface QueueProducerLike {
423
504
  /**
424
505
  * Enqueue a fan-out broadcast for background delivery through a `@lunora/queue`
425
506
  * queue instead of blocking the request. Pair with {@link runPushBroadcastJob} in
426
- * the queue consumer.
507
+ * the queue consumer — see its doc comment for how a large audience continues
508
+ * across MULTIPLE messages (one bounded page per message), not one.
427
509
  *
428
510
  * ```ts
429
511
  * // in a mutation/action:
@@ -431,29 +513,59 @@ interface QueueProducerLike {
431
513
  *
432
514
  * // in lunora/queues.ts consumer:
433
515
  * export const push = defineQueue({ async handler(batch, ctx) {
434
- * for (const message of batch.messages) await runPushBroadcastJob(ctx.push, message.body);
516
+ * for (const message of batch.messages) {
517
+ * const { nextCursor } = await runPushBroadcastJob(ctx.push, message.body);
518
+ *
519
+ * if (nextCursor !== undefined) {
520
+ * // More pages remain — enqueue the continuation. Each message still
521
+ * // does only ONE bounded page of work.
522
+ * await enqueuePushBroadcast(ctx.queues.push, {
523
+ * payload: message.body.payload,
524
+ * filter: { ...message.body.filter, after: nextCursor },
525
+ * });
526
+ * }
527
+ * }
435
528
  * }});
436
529
  * ```
437
530
  */
438
531
  declare const enqueuePushBroadcast: (queue: QueueProducerLike, job: Omit<PushBroadcastJob, "type">) => Promise<void>;
439
532
  /**
440
- * Run an enqueued broadcast job on the consumer side, delivering through the push
441
- * facade (which reuses the engine's retry + circuit-breaker middleware and prunes
442
- * gone subscriptions).
533
+ * Run ONE bounded page of an enqueued broadcast job on the consumer side,
534
+ * delivering through the push facade's {@link LunoraPush.broadcastPage} (which
535
+ * reuses the engine's retry + circuit-breaker middleware and prunes gone
536
+ * subscriptions).
537
+ *
538
+ * RETRY / CONTINUATION SEMANTICS (rewritten for plan 222 / NOTIFY-01 — a
539
+ * broadcast job used to process the WHOLE audience in one message, which could
540
+ * exceed Worker CPU/wall limits for a large audience and made a retry re-run
541
+ * everything):
443
542
  *
444
- * RETRY SEMANTICS: retry is gated on `failed` the count of TRANSIENT delivery
445
- * errors (a provider 5xx / network fault worth another attempt). When at least one
446
- * recipient `failed`, the job is RE-THROWN so the queue does NOT ack it and its
447
- * normal retry/backoff (and, on exhaustion, dead-letter) applies. A broadcast with
448
- * zero `failed` resolves and is ackedthis includes the all-`pruned` case (every
449
- * device had unsubscribed: `sent:0`, `failed:0`, `pruned:N`), which is a SUCCESSFUL
450
- * prune, not a failure, so throwing on it would spuriously retry and pressure the
451
- * DLQ; and the empty audience (zero `total`), which has nothing to retry. Note a
452
- * retry re-runs the WHOLE broadcast, re-sending to the already-delivered recipients
453
- * (broadcast is not idempotent) the accepted cost of getting the transiently
454
- * failed ones redelivered.
543
+ * - A job now processes exactly ONE bounded page (see `CreateNotifyOptions`'s
544
+ * page-size option, default 250, or `job.filter.limit` when smaller),
545
+ * keyset-paginated on the subscription `id` (see `SubscriptionFilter.after`)
546
+ * so per-message work is bounded regardless of total audience size.
547
+ * - Retry is still gated on `result.failed` the count of TRANSIENT delivery
548
+ * errors (a provider 5xx / network fault worth another attempt). When at
549
+ * least one recipient in THIS PAGE `failed`, the job is RE-THROWN so the
550
+ * queue does NOT ack it and its normal retry/backoff (and, on exhaustion,
551
+ * dead-letter) applies to just this page, not the whole broadcast.
552
+ * - A page with zero `failed` resolves and is acked — this includes the
553
+ * all-`pruned` case (every device on the page had unsubscribed:
554
+ * `sent:0`, `failed:0`, `pruned:N`), which is a SUCCESSFUL prune, not a
555
+ * failure, so throwing on it would spuriously retry and pressure the DLQ;
556
+ * and the empty-page case (zero `total`), which has nothing to retry.
557
+ * - The returned `nextCursor` is set when more pages remain. `@lunora/notify`
558
+ * does NOT enqueue the continuation itself — it has no `@lunora/queue`
559
+ * dependency (the seam stays structural) and no reference to the producer
560
+ * that enqueued this message — so the CALLER (the `lunora/queues.ts`
561
+ * consumer) is responsible for re-enqueueing with `filter.after: nextCursor`
562
+ * when present. See the consumer example on {@link enqueuePushBroadcast}.
563
+ * - A retry of a page redelivers only that page's already-delivered recipients
564
+ * on a transient partial failure (a page is not individually idempotent) —
565
+ * the accepted cost of getting the transiently failed ones redelivered, now
566
+ * scoped to one page instead of the whole broadcast.
455
567
  */
456
- declare const runPushBroadcastJob: (push: LunoraPush, job: PushBroadcastJob) => Promise<BroadcastResult>;
568
+ declare const runPushBroadcastJob: (push: LunoraPush, job: PushBroadcastJob) => Promise<BroadcastPageResult>;
457
569
  /**
458
570
  * The minimal structural slice of Cloudflare's `D1Database` this store uses. A
459
571
  * structural type (rather than importing `@cloudflare/workers-types`) keeps the
@@ -536,7 +648,8 @@ interface NormalizeOptions {
536
648
  * Normalise a `register(...)` input into a {@link StoredSubscription}. Validates
537
649
  * the shape (a web-push subscription needs `endpoint` + `keys.{p256dh,auth}`; an
538
650
  * FCM entry needs a non-empty `token`), enforces the anti-SSRF endpoint boundary
539
- * (see {@link assertPushEndpoint}), and stamps `createdAt`/`lastSeenAt`.
651
+ * (see {@link assertPushEndpoint}), validates `metadata` (see
652
+ * {@link validateMetadata}), and stamps `createdAt`/`lastSeenAt`.
540
653
  */
541
654
  declare const normalizeRegisterInput: (input: RegisterInput, now?: number, options?: NormalizeOptions) => StoredSubscription;
542
655
  /**
package/dist/index.d.ts CHANGED
@@ -75,14 +75,45 @@ type RegisterInput = {
75
75
  };
76
76
  /** Filter narrowing which stored subscriptions a `list`/`broadcast` targets. */
77
77
  interface SubscriptionFilter {
78
+ /**
79
+ * Keyset pagination cursor: return only rows with `id` strictly GREATER
80
+ * than this value, ordered ascending by `id`. `id` is a stable,
81
+ * content-derived hash (see `webPushId`/`fcmId`), so ordering by it is
82
+ * immune to concurrent inserts/deletes elsewhere in the table — a page
83
+ * already walked never re-delivers or skips a row when another device
84
+ * registers mid-broadcast (the reviewer-flagged "stable under concurrent
85
+ * registers" property). `broadcastPage`/`broadcast` set this internally to
86
+ * walk pages; a direct `list()` caller may also page through results with
87
+ * it.
88
+ *
89
+ * OPTIONAL for a reason: `SubscriptionStore` is implementable outside this
90
+ * package. An external store that does not support cursoring may ignore
91
+ * `after` entirely and keep returning its (from-the-top) unpaged result —
92
+ * `broadcastPage` defensively re-filters whatever the store returns down
93
+ * to `id > after` itself, so a non-cursoring store can never cause a
94
+ * double-send or an infinite page-walk (each page's result only ever
95
+ * contains ids the previous page didn't already deliver), but it also
96
+ * cannot deliver the FULL matched audience beyond whatever the store's own
97
+ * (unpaged) response window happens to contain — implement `after`
98
+ * (ordered ascending by `id`, exclusive) to get real, complete pagination
99
+ * over a large audience.
100
+ */
101
+ after?: string;
78
102
  /** Restrict to a delivery kind. */
79
103
  kind?: SubscriptionKind;
80
104
  /**
81
105
  * Cap the number of rows returned (a `LIMIT`). Applied server-side by the
82
106
  * store, so a large audience never materializes wholesale in the isolate.
83
107
  * A non-positive/absent value means "no cap"; a fractional value is truncated.
84
- * `broadcast` deliberately leaves this unset (it must reach every matched
85
- * device); admin/list reads set it to bound the page.
108
+ *
109
+ * For `list`/admin reads this bounds the returned page as before. For
110
+ * `broadcast`, this is now an OVERALL cap on the total number of
111
+ * subscriptions reached across every internally-walked page (still
112
+ * deliberately left unset by default — it must reach every matched
113
+ * device); the PER-PAGE batch size is a separate, independent knob (see
114
+ * `CreateNotifyOptions`'s `broadcastPageSize`, default 250) so a caller
115
+ * that sets `limit` to bound the audience doesn't also have to reason
116
+ * about page sizing.
86
117
  */
87
118
  limit?: number;
88
119
  /** Restrict to a single owning user. */
@@ -98,7 +129,13 @@ interface SubscriptionStore {
98
129
  delete: (id: string) => Promise<void>;
99
130
  /** Read a subscription by id, or `undefined`. */
100
131
  get: (id: string) => Promise<StoredSubscription | undefined>;
101
- /** List subscriptions, optionally filtered. */
132
+ /**
133
+ * List subscriptions, optionally filtered. When `filter.after` is set,
134
+ * results are keyset-paginated: only rows with `id` strictly greater than
135
+ * `filter.after` are returned, ordered ascending by `id`. Implementing
136
+ * `after` is OPTIONAL (see {@link SubscriptionFilter.after}) — a store
137
+ * that ignores it may keep returning its unpaged result.
138
+ */
102
139
  list: (filter?: SubscriptionFilter) => Promise<StoredSubscription[]>;
103
140
  /** Record the latest delivery outcome for a subscription (best-effort). */
104
141
  markStatus: (id: string, status: SubscriptionStatus, error?: string) => Promise<void>;
@@ -127,6 +164,18 @@ interface BroadcastResult {
127
164
  /** Total subscriptions attempted. */
128
165
  total: number;
129
166
  }
167
+ /**
168
+ * Result of `broadcastPage` — one bounded page of a fan-out, plus the cursor
169
+ * to fetch the next page. `nextCursor` is `undefined` when this was the last
170
+ * page (or the store doesn't support cursoring — see
171
+ * {@link SubscriptionFilter.after}'s documented unpaged fallback).
172
+ */
173
+ interface BroadcastPageResult {
174
+ /** Cursor for the next page (pass as `filter.after`), or `undefined` when done. */
175
+ nextCursor?: string;
176
+ /** The delivery outcome for just this page. */
177
+ result: BroadcastResult;
178
+ }
130
179
  /**
131
180
  * The compact, stable delivery-status vocabulary emitted on notify observability
132
181
  * signals — the `status` dimension on the `notify.send` metric and the failure
@@ -181,8 +230,28 @@ interface LunoraPush {
181
230
  * Reuses the engine's retry/circuit-breaker middleware; prunes subscriptions
182
231
  * the push service reports as gone (HTTP 404/410, FCM `UNREGISTERED`). The `to`
183
232
  * target is derived from each subscription, so it is omitted from the payload.
233
+ *
234
+ * Internally walks the audience in bounded pages (via {@link LunoraPush.broadcastPage},
235
+ * keyset-paginated on the subscription `id`) so a huge audience is never
236
+ * materialized wholesale in the isolate — see `CreateNotifyOptions`'s
237
+ * `broadcastPageSize`. This call still processes the WHOLE matched
238
+ * audience in one request/queue message; use {@link LunoraPush.broadcastPage}
239
+ * directly (as `runPushBroadcastJob` does) to bound a single queue message
240
+ * to one page.
184
241
  */
185
242
  broadcast: (payload: PushContent, filter?: SubscriptionFilter) => Promise<BroadcastResult>;
243
+ /**
244
+ * Fan-out a push to ONE bounded page of stored subscriptions matching
245
+ * `filter` (page size: `CreateNotifyOptions`'s `broadcastPageSize`, default
246
+ * 250, capped by `filter.limit` when set). Same delivery semantics as
247
+ * {@link LunoraPush.broadcast} (retry/circuit-breaker, gone-pruning) but
248
+ * scoped to a single page; returns the page's own {@link BroadcastResult}
249
+ * plus a `nextCursor` to fetch the next page (`undefined` when done).
250
+ * Backs `runPushBroadcastJob` so one queue message does bounded work
251
+ * regardless of audience size — most app code should call
252
+ * {@link LunoraPush.broadcast} instead.
253
+ */
254
+ broadcastPage: (payload: PushContent, filter?: SubscriptionFilter) => Promise<BroadcastPageResult>;
186
255
  /**
187
256
  * List stored subscriptions (optionally filtered), with the delivery
188
257
  * **secrets** stripped — the Web Push `keys` (RFC 8291 `auth`/`p256dh`) and the
@@ -333,6 +402,16 @@ declare const defineNotify: (config: NotifyConfig) => NotifyDefinition;
333
402
  declare const isNotifyDefinition: (value: unknown) => value is NotifyDefinition;
334
403
  /** Options for {@link createNotify}. */
335
404
  interface CreateNotifyOptions {
405
+ /**
406
+ * Page size for `push.broadcast`'s internal keyset pagination over the
407
+ * subscription store (default {@link DEFAULT_BROADCAST_PAGE_SIZE}, 250).
408
+ * Each page is fetched, delivered, and counted independently before the
409
+ * next page's store round trip, so a huge audience is never materialized
410
+ * wholesale in the isolate. Also the per-message bound `push.broadcastPage`
411
+ * (and so `runPushBroadcastJob`) uses. A test/tuning seam — most apps never
412
+ * need to set this.
413
+ */
414
+ broadcastPageSize?: number;
336
415
  /** Max concurrent sends during a `broadcast` (default 10). */
337
416
  concurrency?: number;
338
417
  /**
@@ -407,9 +486,11 @@ declare const buildEngine: (resolved: ResolvedProviders) => Notification;
407
486
  * A broadcast job body — the JSON-serialisable payload enqueued for off-request
408
487
  * fan-out. Shaped to travel through a `@lunora/queue` producer/consumer without
409
488
  * `@lunora/notify` depending on `@lunora/queue` (the seam stays structural).
489
+ * `filter.after`, when set, resumes a broadcast partway through (see
490
+ * {@link runPushBroadcastJob}'s continuation semantics).
410
491
  */
411
492
  interface PushBroadcastJob {
412
- /** Subscription filter (which devices/users to target). */
493
+ /** Subscription filter (which devices/users to target; `filter.after` resumes a paged broadcast). */
413
494
  filter?: SubscriptionFilter;
414
495
  /** The push payload to deliver (the `to` target is derived per subscription). */
415
496
  payload: PushContent;
@@ -423,7 +504,8 @@ interface QueueProducerLike {
423
504
  /**
424
505
  * Enqueue a fan-out broadcast for background delivery through a `@lunora/queue`
425
506
  * queue instead of blocking the request. Pair with {@link runPushBroadcastJob} in
426
- * the queue consumer.
507
+ * the queue consumer — see its doc comment for how a large audience continues
508
+ * across MULTIPLE messages (one bounded page per message), not one.
427
509
  *
428
510
  * ```ts
429
511
  * // in a mutation/action:
@@ -431,29 +513,59 @@ interface QueueProducerLike {
431
513
  *
432
514
  * // in lunora/queues.ts consumer:
433
515
  * export const push = defineQueue({ async handler(batch, ctx) {
434
- * for (const message of batch.messages) await runPushBroadcastJob(ctx.push, message.body);
516
+ * for (const message of batch.messages) {
517
+ * const { nextCursor } = await runPushBroadcastJob(ctx.push, message.body);
518
+ *
519
+ * if (nextCursor !== undefined) {
520
+ * // More pages remain — enqueue the continuation. Each message still
521
+ * // does only ONE bounded page of work.
522
+ * await enqueuePushBroadcast(ctx.queues.push, {
523
+ * payload: message.body.payload,
524
+ * filter: { ...message.body.filter, after: nextCursor },
525
+ * });
526
+ * }
527
+ * }
435
528
  * }});
436
529
  * ```
437
530
  */
438
531
  declare const enqueuePushBroadcast: (queue: QueueProducerLike, job: Omit<PushBroadcastJob, "type">) => Promise<void>;
439
532
  /**
440
- * Run an enqueued broadcast job on the consumer side, delivering through the push
441
- * facade (which reuses the engine's retry + circuit-breaker middleware and prunes
442
- * gone subscriptions).
533
+ * Run ONE bounded page of an enqueued broadcast job on the consumer side,
534
+ * delivering through the push facade's {@link LunoraPush.broadcastPage} (which
535
+ * reuses the engine's retry + circuit-breaker middleware and prunes gone
536
+ * subscriptions).
537
+ *
538
+ * RETRY / CONTINUATION SEMANTICS (rewritten for plan 222 / NOTIFY-01 — a
539
+ * broadcast job used to process the WHOLE audience in one message, which could
540
+ * exceed Worker CPU/wall limits for a large audience and made a retry re-run
541
+ * everything):
443
542
  *
444
- * RETRY SEMANTICS: retry is gated on `failed` the count of TRANSIENT delivery
445
- * errors (a provider 5xx / network fault worth another attempt). When at least one
446
- * recipient `failed`, the job is RE-THROWN so the queue does NOT ack it and its
447
- * normal retry/backoff (and, on exhaustion, dead-letter) applies. A broadcast with
448
- * zero `failed` resolves and is ackedthis includes the all-`pruned` case (every
449
- * device had unsubscribed: `sent:0`, `failed:0`, `pruned:N`), which is a SUCCESSFUL
450
- * prune, not a failure, so throwing on it would spuriously retry and pressure the
451
- * DLQ; and the empty audience (zero `total`), which has nothing to retry. Note a
452
- * retry re-runs the WHOLE broadcast, re-sending to the already-delivered recipients
453
- * (broadcast is not idempotent) the accepted cost of getting the transiently
454
- * failed ones redelivered.
543
+ * - A job now processes exactly ONE bounded page (see `CreateNotifyOptions`'s
544
+ * page-size option, default 250, or `job.filter.limit` when smaller),
545
+ * keyset-paginated on the subscription `id` (see `SubscriptionFilter.after`)
546
+ * so per-message work is bounded regardless of total audience size.
547
+ * - Retry is still gated on `result.failed` the count of TRANSIENT delivery
548
+ * errors (a provider 5xx / network fault worth another attempt). When at
549
+ * least one recipient in THIS PAGE `failed`, the job is RE-THROWN so the
550
+ * queue does NOT ack it and its normal retry/backoff (and, on exhaustion,
551
+ * dead-letter) applies to just this page, not the whole broadcast.
552
+ * - A page with zero `failed` resolves and is acked — this includes the
553
+ * all-`pruned` case (every device on the page had unsubscribed:
554
+ * `sent:0`, `failed:0`, `pruned:N`), which is a SUCCESSFUL prune, not a
555
+ * failure, so throwing on it would spuriously retry and pressure the DLQ;
556
+ * and the empty-page case (zero `total`), which has nothing to retry.
557
+ * - The returned `nextCursor` is set when more pages remain. `@lunora/notify`
558
+ * does NOT enqueue the continuation itself — it has no `@lunora/queue`
559
+ * dependency (the seam stays structural) and no reference to the producer
560
+ * that enqueued this message — so the CALLER (the `lunora/queues.ts`
561
+ * consumer) is responsible for re-enqueueing with `filter.after: nextCursor`
562
+ * when present. See the consumer example on {@link enqueuePushBroadcast}.
563
+ * - A retry of a page redelivers only that page's already-delivered recipients
564
+ * on a transient partial failure (a page is not individually idempotent) —
565
+ * the accepted cost of getting the transiently failed ones redelivered, now
566
+ * scoped to one page instead of the whole broadcast.
455
567
  */
456
- declare const runPushBroadcastJob: (push: LunoraPush, job: PushBroadcastJob) => Promise<BroadcastResult>;
568
+ declare const runPushBroadcastJob: (push: LunoraPush, job: PushBroadcastJob) => Promise<BroadcastPageResult>;
457
569
  /**
458
570
  * The minimal structural slice of Cloudflare's `D1Database` this store uses. A
459
571
  * structural type (rather than importing `@cloudflare/workers-types`) keeps the
@@ -536,7 +648,8 @@ interface NormalizeOptions {
536
648
  * Normalise a `register(...)` input into a {@link StoredSubscription}. Validates
537
649
  * the shape (a web-push subscription needs `endpoint` + `keys.{p256dh,auth}`; an
538
650
  * FCM entry needs a non-empty `token`), enforces the anti-SSRF endpoint boundary
539
- * (see {@link assertPushEndpoint}), and stamps `createdAt`/`lastSeenAt`.
651
+ * (see {@link assertPushEndpoint}), validates `metadata` (see
652
+ * {@link validateMetadata}), and stamps `createdAt`/`lastSeenAt`.
540
653
  */
541
654
  declare const normalizeRegisterInput: (input: RegisterInput, now?: number, options?: NormalizeOptions) => StoredSubscription;
542
655
  /**
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{FCM_ENV_KEYS as e,WEB_PUSH_ENV_KEYS as t,fcmFromEnv as i,webPushFromEnv as f}from"./packem_shared/FCM_ENV_KEYS-D0tvRTLQ.mjs";import{defineNotify as n,isNotifyDefinition as u}from"./packem_shared/defineNotify-DLEy53HJ.mjs";import{createNotify as p}from"./packem_shared/createNotify-iBbs9Bew.mjs";import{buildEngine as d,routingPushProvider as x}from"./packem_shared/buildEngine-Jlzf2Jzn.mjs";import{enqueuePushBroadcast as c,runPushBroadcastJob as P}from"./packem_shared/enqueuePushBroadcast-DMwYIM0o.mjs";import{d1SubscriptionStore as b}from"./packem_shared/d1SubscriptionStore-BwssRgeI.mjs";import{memorySubscriptionStore as N}from"./packem_shared/memorySubscriptionStore-BxKdyxjC.mjs";import{fcmId as g,isGoneError as y,normalizeRegisterInput as v,targetOf as B,webPushId as F}from"./packem_shared/fcmId-CLRyQJVw.mjs";export{e as FCM_ENV_KEYS,t as WEB_PUSH_ENV_KEYS,d as buildEngine,p as createNotify,b as d1SubscriptionStore,n as defineNotify,c as enqueuePushBroadcast,i as fcmFromEnv,g as fcmId,y as isGoneError,u as isNotifyDefinition,N as memorySubscriptionStore,v as normalizeRegisterInput,x as routingPushProvider,P as runPushBroadcastJob,B as targetOf,f as webPushFromEnv,F as webPushId};
1
+ import{FCM_ENV_KEYS as e,WEB_PUSH_ENV_KEYS as t,fcmFromEnv as i,webPushFromEnv as f}from"./packem_shared/FCM_ENV_KEYS-D0tvRTLQ.mjs";import{defineNotify as n,isNotifyDefinition as u}from"./packem_shared/defineNotify-DLEy53HJ.mjs";import{createNotify as p}from"./packem_shared/createNotify-ClocmjsQ.mjs";import{buildEngine as d,routingPushProvider as x}from"./packem_shared/buildEngine-Jlzf2Jzn.mjs";import{enqueuePushBroadcast as c,runPushBroadcastJob as P}from"./packem_shared/enqueuePushBroadcast-tf1LqgzA.mjs";import{d1SubscriptionStore as b}from"./packem_shared/d1SubscriptionStore-67jpK0Vx.mjs";import{memorySubscriptionStore as N}from"./packem_shared/memorySubscriptionStore-FKZR4-fB.mjs";import{fcmId as g,isGoneError as y,normalizeRegisterInput as v,targetOf as B,webPushId as F}from"./packem_shared/fcmId-CFZ8IquF.mjs";export{e as FCM_ENV_KEYS,t as WEB_PUSH_ENV_KEYS,d as buildEngine,p as createNotify,b as d1SubscriptionStore,n as defineNotify,c as enqueuePushBroadcast,i as fcmFromEnv,g as fcmId,y as isGoneError,u as isNotifyDefinition,N as memorySubscriptionStore,v as normalizeRegisterInput,x as routingPushProvider,P as runPushBroadcastJob,B as targetOf,f as webPushFromEnv,F as webPushId};
@@ -0,0 +1 @@
1
+ import{LunoraError as k}from"@lunora/errors";import{buildEngine as R}from"./buildEngine-Jlzf2Jzn.mjs";import{memorySubscriptionStore as W}from"./memorySubscriptionStore-FKZR4-fB.mjs";import{normalizeRegisterInput as L,targetOf as Q,isGoneError as U}from"./fcmId-CFZ8IquF.mjs";const j=250,g=(s,u)=>typeof s=="function"?s(u):s,b=s=>s.successful?void 0:s.errorMessages.join("; "),z=(s,u)=>s.successful?"accepted":U(u)?"gone":"failed",G=async(s,u,d)=>{const c=Array.from({length:s.length});let h=0;const p=async()=>{for(;h<s.length;){const f=h;h+=1,c[f]=await d(s[f])}};return await Promise.all(Array.from({length:Math.min(u,s.length)},()=>p())),c},_=(s,u)=>({chat:g(s.chat,u),fcm:g(s.fcm,u),inApp:g(s.inApp,u),webhook:g(s.webhook,u),webPush:g(s.webPush,u)}),M=new WeakMap,q=(s,u)=>{let d=M.get(s);d===void 0&&(d=new WeakMap,M.set(s,d));let c=d.get(u);return c===void 0&&(c={warnedNoPushOriginAllowlist:!1,warnedNoStore:!1},d.set(u,c)),c},V=(s,u,d={})=>{const c=q(s,u);let h;d.engine===void 0?(c.engine??=R(_(s,u)),h=c.engine):h=d.engine,c.store??=s.store?.(u);let{store:p}=c;p===void 0&&(c.fallbackStore??=W(),!d.silent&&!c.warnedNoStore&&(c.warnedNoStore=!0,console.warn("@lunora/notify: no `store` configured — using a non-durable in-memory subscription store. Configure `store: (env) => d1SubscriptionStore(env.DB)` for production.")),p=c.fallbackStore);const f=p,T=Math.max(1,d.concurrency??10),S=Math.max(1,d.broadcastPageSize??j),{log:$,metrics:P}=d,w=(t,e,n,i=1)=>{P?.count("notify.send",i,{channel:t,provider:e??t,status:n})},v=(t,e,n)=>{$?.warn(`notify ${t} delivery failed`,{channel:t,provider:e??t,status:"failed",...n})},N=(t,e)=>{P?.count("notify.skipped",1,{channel:t,reason:e})},x=()=>{const t=s.allowedPushOrigins!==void 0&&s.allowedPushOrigins.length>0;d.silent||t||c.warnedNoPushOriginAllowlist||(c.warnedNoPushOriginAllowlist=!0,console.warn("@lunora/notify: Web Push registered without `allowedPushOrigins` — the endpoint host is validated by a string classifier that does NOT resolve DNS, so a public hostname resolving to a private/internal IP (e.g. `https://127.0.0.1.nip.io/…`) is NOT blocked. Set `allowedPushOrigins` to the exact push-service origins to close DNS rebinding."))},I=async t=>(await f.list(t)).map(({keys:e,token:n,...i})=>i),D=async t=>{if(typeof t!="string")return t;const e=await f.get(t);if(e===void 0)throw new k("BAD_REQUEST",`@lunora/notify: no registered subscription with id "${t}"`);return e},O=async(t,e,n)=>{let i,o,r;try{i=await h.sendToChannel("push",{...e,to:Q(t)}),o=b(i),r=z(i,o)}catch(l){r="failed",o=l instanceof Error?l.message:String(l)}try{r==="accepted"?await f.markStatus(t.id,"ok"):r==="gone"?await f.delete(t.id):await f.markStatus(t.id,"failed",o)}catch{}return r==="failed"&&v("push",t.kind,{error:o,subscriptionId:t.id,userId:t.userId??null}),n&&w("push",t.kind,r),{error:o,receipt:i,status:r}},C=async(t,e)=>{const n=await G(e,T,async r=>{const{error:l,status:a}=await O(r,t,!1);return{error:l,kind:r.kind,status:a,subscription:r}}),i=new Map;for(const{kind:r,status:l}of n){const a=`${r} ${l}`,m=i.get(a);m===void 0?i.set(a,{count:1,kind:r,status:l}):m.count+=1}for(const{count:r,kind:l,status:a}of i.values())w("push",l,a,r);const o=n.map(({error:r,status:l,subscription:a})=>l==="accepted"?{id:a.id,status:"ok"}:l==="gone"?{error:r,id:a.id,status:"expired"}:{error:r,id:a.id,status:"failed"});return{failed:o.filter(r=>r.status==="failed").length,outcomes:o,pruned:o.filter(r=>r.status==="expired").length,sent:o.filter(r=>r.status==="ok").length,total:o.length}},A=async(t,e)=>{const n=e?.limit!==void 0&&e.limit>0?Math.trunc(e.limit):void 0,i=n===void 0?S:Math.min(n,S),o=await f.list({after:e?.after,kind:e?.kind,limit:i+1,userId:e?.userId}),r=e?.after===void 0?o:o.filter(B=>B.id>e.after),l=r.length>i,a=l?r.slice(0,i):r;a.length===0&&e?.after===void 0&&N("push","no-subscriptions-matched");const m=await C(t,a);return{nextCursor:l?a[a.length-1]?.id:void 0,result:m}},E={broadcast:async(t,e)=>{const n={failed:0,outcomes:[],pruned:0,sent:0,total:0};let i=e?.after;const o=e?.limit;for(;;){const r=o===void 0?{...e,after:i}:{...e,after:i,limit:o-n.total},{nextCursor:l,result:a}=await A(t,r);if(n.failed+=a.failed,n.pruned+=a.pruned,n.sent+=a.sent,n.total+=a.total,n.outcomes.push(...a.outcomes),o!==void 0&&n.total>=o||l===void 0||l===i)break;i=l}return n},broadcastPage:A,list:t=>I(t),register:t=>("token"in t||x(),f.put(L(t,void 0,{allowedPushOrigins:s.allowedPushOrigins}))),send:async(t,e)=>{const{error:n,receipt:i}=await O(await D(t),e,!0);if(i===void 0)throw new k("INTERNAL",`@lunora/notify: push send failed: ${n??"unknown error"}`);return i},unregister:t=>f.delete(t)},y=async(t,e)=>{if(h.getProvider(t)===void 0)throw N(t,"channel-not-configured"),new k("BAD_REQUEST",`@lunora/notify: the "${t}" channel is not configured in defineNotify(...)`);const n=await h.sendToChannel(t,e),i=n.successful?"accepted":"failed";return w(t,n.provider,i),i==="failed"&&v(t,n.provider,{error:b(n)}),n};return{notify:{chat:t=>y("chat",t),inApp:t=>y("inapp",t),push:E,send:async t=>{const e=await h.send(t);for(const n of e){const i=n.channel??"unknown",o=n.successful?"accepted":"failed";w(i,n.provider,o),o==="failed"&&v(i,n.provider,{error:b(n)})}return e},webhook:t=>y("webhook",t)},push:E}};export{V as createNotify};
@@ -0,0 +1 @@
1
+ import{LunoraError as h}from"@lunora/errors";import{legacyIdFor as S}from"./fcmId-CFZ8IquF.mjs";const o=a=>{const e={createdAt:a.created_at,id:a.id,kind:a.kind,lastSeenAt:a.last_seen_at,userId:a.user_id};if(a.endpoint!==null&&(e.endpoint=a.endpoint),a.p256dh!==null&&a.auth!==null&&(e.keys={auth:a.auth,p256dh:a.p256dh}),a.token!==null&&(e.token=a.token),a.last_status!==null&&(e.lastStatus=a.last_status),a.last_error!==null&&(e.lastError=a.last_error),a.metadata!==null)try{e.metadata=JSON.parse(a.metadata)}catch{}return e},c=/^[A-Za-z_]\w*$/u,k=(a,e={})=>{const r=e.tableName??"lunora_push_subscriptions";if(!c.test(r))throw new h("BAD_REQUEST",`@lunora/notify: d1SubscriptionStore tableName "${r}" is not a bare SQL identifier`);let s;const d=()=>(s===void 0&&(s=a.prepare(`CREATE TABLE IF NOT EXISTS ${r} (id TEXT PRIMARY KEY, kind TEXT NOT NULL, endpoint TEXT, p256dh TEXT, auth TEXT, token TEXT, user_id TEXT, metadata TEXT, created_at INTEGER NOT NULL, last_seen_at INTEGER NOT NULL, last_status TEXT, last_error TEXT)`).run().then(()=>a.prepare(`CREATE INDEX IF NOT EXISTS ${r}_user_id_idx ON ${r} (user_id)`).run()).then(()=>a.prepare(`CREATE INDEX IF NOT EXISTS ${r}_kind_idx ON ${r} (kind)`).run()).then(()=>{}),s.catch(()=>{s=void 0})),s),l=async t=>{await d();const n=await a.prepare(`SELECT * FROM ${r} WHERE id = ?1`).bind(t).first();return n===null?void 0:o(n)};return{delete:async t=>{await d(),await a.prepare(`DELETE FROM ${r} WHERE id = ?1`).bind(t).run()},get:l,list:async t=>{await d();const n=[],i=[];t?.kind!==void 0&&(i.push(t.kind),n.push(`kind = ?${i.length.toString()}`)),t?.userId!==void 0&&(t.userId===null?n.push("user_id IS NULL"):(i.push(t.userId),n.push(`user_id = ?${i.length.toString()}`))),t?.after!==void 0&&(i.push(t.after),n.push(`id > ?${i.length.toString()}`));const E=n.length===0?"":` WHERE ${n.join(" AND ")}`,p=" ORDER BY id ASC";let u="";t?.limit!==void 0&&t.limit>0&&(i.push(Math.trunc(t.limit)),u=` LIMIT ?${i.length.toString()}`);const{results:T}=await a.prepare(`SELECT * FROM ${r}${E}${p}${u}`).bind(...i).all();return T.map(_=>o(_))},markStatus:async(t,n,i)=>{await d(),await a.prepare(`UPDATE ${r} SET last_status = ?2, last_error = ?3, last_seen_at = ?4 WHERE id = ?1`).bind(t,n,i??null,Date.now()).run()},put:async t=>{await d(),await a.prepare(`INSERT INTO ${r} (id, kind, endpoint, p256dh, auth, token, user_id, metadata, created_at, last_seen_at, last_status, last_error) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12) ON CONFLICT(id) DO UPDATE SET kind = ?2, endpoint = ?3, p256dh = ?4, auth = ?5, token = ?6, user_id = ?7, metadata = ?8, last_seen_at = ?10`).bind(t.id,t.kind,t.endpoint??null,t.keys?.p256dh??null,t.keys?.auth??null,t.token??null,t.userId??null,t.metadata===void 0?null:JSON.stringify(t.metadata),t.createdAt,t.lastSeenAt,t.lastStatus??null,t.lastError??null).run();const n=S(t);return n!==void 0&&n!==t.id&&await a.prepare(`DELETE FROM ${r} WHERE id = ?1`).bind(n).run(),await l(t.id)??t}}};export{k as d1SubscriptionStore};
@@ -0,0 +1 @@
1
+ import{LunoraError as s}from"@lunora/errors";const o=(e,r)=>e.send({...r,type:"lunora.push.broadcast"}),n=async(e,r)=>{const t=await e.broadcastPage(r.payload,r.filter);if(t.result.failed>0)throw new s("INTERNAL",`@lunora/notify: push broadcast page had ${t.result.failed.toString()} transient failure(s) of ${t.result.total.toString()} subscription(s) (${t.result.sent.toString()} sent, ${t.result.pruned.toString()} pruned) — throwing so the queue retries this page`);return t};export{o as enqueuePushBroadcast,n as runPushBroadcastJob};
@@ -0,0 +1 @@
1
+ import{LunoraError as a}from"@lunora/errors";const k=/^\d{1,3}$/u,A=/^::ffff:([\da-f]{1,4}):([\da-f]{1,4})$/u,I=/^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/u,v=/^::(\d{1,3}(?:\.\d{1,3}){3})$/u,O=/^::([\da-f]{1,4}):([\da-f]{1,4})$/u,D=/^64:ff9b::[\da-f]{1,4}:[\da-f]{1,4}$/u,R=/^\[|\]$/gu,_=/\.$/u,c=t=>{const e=t.split(".");if(e.length!==4)return;const n=e.map(r=>k.test(r)?Number(r):-1);if(!n.some(r=>r<0||r>255))return[n[0],n[1],n[2],n[3]]},f=([t,e])=>t===0||t===10||t===127||t===100&&e>=64&&e<=127||t===169&&e===254||t===172&&e>=16&&e<=31||t===192&&e===168||t>=224,h=(t,e)=>{const n=Number.parseInt(t??"",16),r=Number.parseInt(e??"",16);return!Number.isFinite(n)||!Number.isFinite(r)?!0:f([Math.floor(n/256),n%256,Math.floor(r/256),r%256])},N=t=>{const e=t.toLowerCase(),n=A.exec(e);if(n)return h(n[1],n[2]);const r=I.exec(e);if(r){const i=c(r[1]??"");return i===void 0||f(i)}const o=v.exec(e);if(o){const i=c(o[1]??"");return i===void 0||f(i)}const s=O.exec(e);return s?h(s[1],s[2]):D.test(e)||e.startsWith("2002:")||e.startsWith("2001:0:")?!0:e==="::"||e==="::1"||e.startsWith("fc")||e.startsWith("fd")||e.startsWith("fe8")||e.startsWith("fe9")||e.startsWith("fea")||e.startsWith("feb")},W=t=>t==="localhost"||t.endsWith(".localhost")||t.endsWith(".local")||t.endsWith(".internal")||t.endsWith(".home.arpa"),B=t=>t.replaceAll(R,"").replace(_,"").toLowerCase(),P=t=>{const e=B(t);if(e.includes(":"))return N(e);const n=c(e);return n===void 0?W(e):f(n)},g=4096,w=t=>{if(t===void 0)return;const e=typeof t=="object"&&t!==null?Object.getPrototypeOf(t):void 0;if(!(typeof t=="object"&&t!==null&&!Array.isArray(t)&&(e===Object.prototype||e===null)))throw new a("BAD_REQUEST","@lunora/notify: register() `metadata` must be a plain object");let n;try{n=JSON.stringify(t)}catch(o){throw new a("BAD_REQUEST",`@lunora/notify: register() \`metadata\` is not JSON-serialisable: ${o instanceof Error?o.message:String(o)}`)}const r=new TextEncoder().encode(n).length;if(r>g)throw new a("BAD_REQUEST",`@lunora/notify: register() \`metadata\` is ${r.toString()} bytes, exceeding the ${g.toString()}-byte cap`);return t},d=t=>t.toString(16).padStart(4,"0"),b=t=>{let e=8997,n=33826,r=40164,o=52210;for(let s=0;s<t.length;s+=1){const i=t.codePointAt(s)??0;e^=i&65535,n^=i>>>16&65535;const u=e*435,m=n*435,$=r*435+e*256,E=o*435+n*256,l=m+(u>>>16),p=$+(l>>>16),S=E+(p>>>16);e=u&65535,n=l&65535,r=p&65535,o=S&65535}return d(o)+d(r)+d(n)+d(e)},T=t=>`wp2_${b(t)}`,U=t=>`fcm2_${b(t)}`,y=t=>{let e=2166136261;for(let n=0;n<t.length;n+=1)e^=t.codePointAt(n)??0,e=Math.imul(e,16777619);return(e>>>0).toString(16).padStart(8,"0")},x=t=>`wp_${y(t)}`,Q=t=>`fcm_${y(t)}`,C=t=>t.kind==="fcm"?t.token===void 0?void 0:Q(t.token):t.endpoint===void 0?void 0:x(t.endpoint),F=t=>{if(typeof t!="string")return t??{};try{return JSON.parse(t)}catch(e){throw new a("BAD_REQUEST",`@lunora/notify: register() web-push subscription is not valid JSON: ${e instanceof Error?e.message:String(e)}`)}},j=(t,e)=>{let n;try{n=new URL(t)}catch{throw new a("BAD_REQUEST",`@lunora/notify: register() web-push \`endpoint\` must be an absolute https URL (got "${t}")`)}if(n.protocol!=="https:")throw new a("BAD_REQUEST",`@lunora/notify: register() web-push \`endpoint\` must use https (got "${n.protocol}")`);if(e!==void 0&&e.length>0){if(!e.includes(n.origin))throw new a("FORBIDDEN",`@lunora/notify: register() web-push endpoint origin "${n.origin}" is not in the configured allowedPushOrigins allowlist`);return}if(P(n.hostname))throw new a("FORBIDDEN",`@lunora/notify: register() web-push endpoint host "${n.hostname}" is a private/internal address; configure allowedPushOrigins to permit a specific origin`)},z=(t,e=Date.now(),n={})=>{if("token"in t){const{token:u}=t;if(typeof u!="string"||u==="")throw new a("BAD_REQUEST","@lunora/notify: register() fcm input requires a non-empty `token`");return{createdAt:e,id:U(u),kind:"fcm",lastSeenAt:e,metadata:w(t.metadata),token:u,userId:t.userId??null}}const r=F(t.subscription),{endpoint:o}=r,s=r.keys?.p256dh,i=r.keys?.auth;if(typeof o!="string"||o===""||typeof s!="string"||typeof i!="string")throw new a("BAD_REQUEST","@lunora/notify: register() web-push subscription requires `endpoint` and `keys.{p256dh, auth}`");return j(o,n.allowedPushOrigins),{createdAt:e,endpoint:o,id:T(o),keys:{auth:i,p256dh:s},kind:"web-push",lastSeenAt:e,metadata:w(t.metadata),userId:t.userId??null}},G=t=>t.kind==="fcm"?t.token??"":JSON.stringify({endpoint:t.endpoint,keys:t.keys}),J=/\bhttp\s*4(?:04|10)\b/iu,L=/\b(?:unregistered|not[\s-]?registered|registration-token-not-registered)\b/iu,M=/\bsubscription (?:is )?(?:gone|expired|no longer valid)\b/iu,H=t=>t===void 0?!1:J.test(t)||L.test(t)||M.test(t);export{U as fcmId,H as isGoneError,Q as legacyFcmId,C as legacyIdFor,x as legacyWebPushId,z as normalizeRegisterInput,G as targetOf,T as webPushId};
@@ -0,0 +1 @@
1
+ import{legacyIdFor as d}from"./fcmId-CFZ8IquF.mjs";const n=(r,t)=>r.id<t.id?-1:r.id>t.id?1:0,l=(r,t)=>t===void 0?!0:!(t.kind!==void 0&&r.kind!==t.kind||t.userId!==void 0&&(r.userId??null)!==t.userId),u=()=>{const r=new Map;return{delete:t=>(r.delete(t),Promise.resolve()),get:t=>Promise.resolve(r.get(t)),list:t=>{const e=[];for(const s of r.values())l(s,t)&&e.push(s);e.sort(n);const o=t?.after===void 0?e:e.filter(s=>s.id>t.after),i=t?.limit!==void 0&&t.limit>0?o.slice(0,Math.trunc(t.limit)):o;return Promise.resolve(i)},markStatus:(t,e,o)=>{const i=r.get(t);return i!==void 0&&r.set(t,{...i,lastError:o,lastSeenAt:Date.now(),lastStatus:e}),Promise.resolve()},put:t=>{const e=d(t);e!==void 0&&e!==t.id&&r.delete(e);const o=r.get(t.id),i=o===void 0?t:{...o,...t,createdAt:o.createdAt};return r.set(i.id,i),Promise.resolve(i)}}};export{u as memorySubscriptionStore};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/notify",
3
- "version": "1.0.0-alpha.7",
3
+ "version": "1.0.0-alpha.8",
4
4
  "description": "Multi-channel notifications for Lunora — ctx.notify / ctx.push over @visulima/notification: edge-safe Web Push + FCM, plus chat, in-app inbox and webhook channels, with subscription storage and queue-backed fan-out",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -49,7 +49,7 @@
49
49
  "access": "public"
50
50
  },
51
51
  "dependencies": {
52
- "@lunora/errors": "1.0.0-alpha.10",
52
+ "@lunora/errors": "1.0.0-alpha.11",
53
53
  "@visulima/notification": "1.0.5"
54
54
  },
55
55
  "engines": {
@@ -1 +0,0 @@
1
- import{LunoraError as v}from"@lunora/errors";import{buildEngine as R}from"./buildEngine-Jlzf2Jzn.mjs";import{memorySubscriptionStore as x}from"./memorySubscriptionStore-BxKdyxjC.mjs";import{normalizeRegisterInput as C,targetOf as W,isGoneError as B}from"./fcmId-CLRyQJVw.mjs";const w=(t,s)=>typeof t=="function"?t(s):t,b=t=>t.successful?void 0:t.errorMessages.join("; "),L=(t,s)=>t.successful?"accepted":B(s)?"gone":"failed",_=async(t,s,l)=>{const a=Array.from({length:t.length});let f=0;const g=async()=>{for(;f<t.length;){const c=f;f+=1,a[c]=await l(t[c])}};return await Promise.all(Array.from({length:Math.min(s,t.length)},()=>g())),a},j=(t,s)=>({chat:w(t.chat,s),fcm:w(t.fcm,s),inApp:w(t.inApp,s),webhook:w(t.webhook,s),webPush:w(t.webPush,s)}),E=new WeakMap,Q=(t,s)=>{let l=E.get(t);l===void 0&&(l=new WeakMap,E.set(t,l));let a=l.get(s);return a===void 0&&(a={warnedNoPushOriginAllowlist:!1,warnedNoStore:!1},l.set(s,a)),a},F=(t,s,l={})=>{const a=Q(t,s);let f;l.engine===void 0?(a.engine??=R(j(t,s)),f=a.engine):f=l.engine,a.store??=t.store?.(s);let{store:g}=a;g===void 0&&(a.fallbackStore??=x(),!l.silent&&!a.warnedNoStore&&(a.warnedNoStore=!0,console.warn("@lunora/notify: no `store` configured — using a non-durable in-memory subscription store. Configure `store: (env) => d1SubscriptionStore(env.DB)` for production.")),g=a.fallbackStore);const c=g,T=Math.max(1,l.concurrency??10),{log:$,metrics:S}=l,y=(e,o,n,i=1)=>{S?.count("notify.send",i,{channel:e,provider:o??e,status:n})},m=(e,o,n)=>{$?.warn(`notify ${e} delivery failed`,{channel:e,provider:o??e,status:"failed",...n})},P=(e,o)=>{S?.count("notify.skipped",1,{channel:e,reason:o})},I=()=>{const e=t.allowedPushOrigins!==void 0&&t.allowedPushOrigins.length>0;l.silent||e||a.warnedNoPushOriginAllowlist||(a.warnedNoPushOriginAllowlist=!0,console.warn("@lunora/notify: Web Push registered without `allowedPushOrigins` — the endpoint host is validated by a string classifier that does NOT resolve DNS, so a public hostname resolving to a private/internal IP (e.g. `https://127.0.0.1.nip.io/…`) is NOT blocked. Set `allowedPushOrigins` to the exact push-service origins to close DNS rebinding."))},D=async e=>(await c.list(e)).map(({keys:o,token:n,...i})=>i),M=async e=>{if(typeof e!="string")return e;const o=await c.get(e);if(o===void 0)throw new v("BAD_REQUEST",`@lunora/notify: no registered subscription with id "${e}"`);return o},N=async(e,o,n)=>{let i,u,d;try{i=await f.sendToChannel("push",{...o,to:W(e)}),u=b(i),d=L(i,u)}catch(r){d="failed",u=r instanceof Error?r.message:String(r)}try{d==="accepted"?await c.markStatus(e.id,"ok"):d==="gone"?await c.delete(e.id):await c.markStatus(e.id,"failed",u)}catch{}return d==="failed"&&m("push",e.kind,{error:u,subscriptionId:e.id,userId:e.userId??null}),n&&y("push",e.kind,d),{error:u,receipt:i,status:d}},O={broadcast:async(e,o)=>{const n=await c.list(o);n.length===0&&P("push","no-subscriptions-matched");const i=await _(n,T,async r=>{const{error:p,status:h}=await N(r,e,!1);return{error:p,kind:r.kind,status:h,subscription:r}}),u=new Map;for(const{kind:r,status:p}of i){const h=`${r}\0${p}`,A=u.get(h);A===void 0?u.set(h,{count:1,kind:r,status:p}):A.count+=1}for(const{count:r,kind:p,status:h}of u.values())y("push",p,h,r);const d=i.map(({error:r,status:p,subscription:h})=>p==="accepted"?{id:h.id,status:"ok"}:p==="gone"?{error:r,id:h.id,status:"expired"}:{error:r,id:h.id,status:"failed"});return{failed:d.filter(r=>r.status==="failed").length,outcomes:d,pruned:d.filter(r=>r.status==="expired").length,sent:d.filter(r=>r.status==="ok").length,total:d.length}},list:e=>D(e),register:e=>("token"in e||I(),c.put(C(e,void 0,{allowedPushOrigins:t.allowedPushOrigins}))),send:async(e,o)=>{const{error:n,receipt:i}=await N(await M(e),o,!0);if(i===void 0)throw new v("INTERNAL",`@lunora/notify: push send failed: ${n??"unknown error"}`);return i},unregister:e=>c.delete(e)},k=async(e,o)=>{if(f.getProvider(e)===void 0)throw P(e,"channel-not-configured"),new v("BAD_REQUEST",`@lunora/notify: the "${e}" channel is not configured in defineNotify(...)`);const n=await f.sendToChannel(e,o),i=n.successful?"accepted":"failed";return y(e,n.provider,i),i==="failed"&&m(e,n.provider,{error:b(n)}),n};return{notify:{chat:e=>k("chat",e),inApp:e=>k("inapp",e),push:O,send:async e=>{const o=await f.send(e);for(const n of o){const i=n.channel??"unknown",u=n.successful?"accepted":"failed";y(i,n.provider,u),u==="failed"&&m(i,n.provider,{error:b(n)})}return o},webhook:e=>k("webhook",e)},push:O}};export{F as createNotify};
@@ -1 +0,0 @@
1
- import{LunoraError as _}from"@lunora/errors";import{legacyIdFor as h}from"./fcmId-CLRyQJVw.mjs";const o=a=>{const i={createdAt:a.created_at,id:a.id,kind:a.kind,lastSeenAt:a.last_seen_at,userId:a.user_id};if(a.endpoint!==null&&(i.endpoint=a.endpoint),a.p256dh!==null&&a.auth!==null&&(i.keys={auth:a.auth,p256dh:a.p256dh}),a.token!==null&&(i.token=a.token),a.last_status!==null&&(i.lastStatus=a.last_status),a.last_error!==null&&(i.lastError=a.last_error),a.metadata!==null)try{i.metadata=JSON.parse(a.metadata)}catch{}return i},S=/^[A-Za-z_]\w*$/u,I=(a,i={})=>{const r=i.tableName??"lunora_push_subscriptions";if(!S.test(r))throw new _("BAD_REQUEST",`@lunora/notify: d1SubscriptionStore tableName "${r}" is not a bare SQL identifier`);let s;const d=()=>(s===void 0&&(s=a.prepare(`CREATE TABLE IF NOT EXISTS ${r} (id TEXT PRIMARY KEY, kind TEXT NOT NULL, endpoint TEXT, p256dh TEXT, auth TEXT, token TEXT, user_id TEXT, metadata TEXT, created_at INTEGER NOT NULL, last_seen_at INTEGER NOT NULL, last_status TEXT, last_error TEXT)`).run().then(()=>a.prepare(`CREATE INDEX IF NOT EXISTS ${r}_user_id_idx ON ${r} (user_id)`).run()).then(()=>a.prepare(`CREATE INDEX IF NOT EXISTS ${r}_kind_idx ON ${r} (kind)`).run()).then(()=>{}),s.catch(()=>{s=void 0})),s),l=async t=>{await d();const n=await a.prepare(`SELECT * FROM ${r} WHERE id = ?1`).bind(t).first();return n===null?void 0:o(n)};return{delete:async t=>{await d(),await a.prepare(`DELETE FROM ${r} WHERE id = ?1`).bind(t).run()},get:l,list:async t=>{await d();const n=[],e=[];t?.kind!==void 0&&(e.push(t.kind),n.push(`kind = ?${e.length.toString()}`)),t?.userId!==void 0&&(t.userId===null?n.push("user_id IS NULL"):(e.push(t.userId),n.push(`user_id = ?${e.length.toString()}`)));const E=n.length===0?"":` WHERE ${n.join(" AND ")}`;let u="";t?.limit!==void 0&&t.limit>0&&(e.push(Math.trunc(t.limit)),u=` LIMIT ?${e.length.toString()}`);const{results:p}=await a.prepare(`SELECT * FROM ${r}${E}${u}`).bind(...e).all();return p.map(T=>o(T))},markStatus:async(t,n,e)=>{await d(),await a.prepare(`UPDATE ${r} SET last_status = ?2, last_error = ?3, last_seen_at = ?4 WHERE id = ?1`).bind(t,n,e??null,Date.now()).run()},put:async t=>{await d(),await a.prepare(`INSERT INTO ${r} (id, kind, endpoint, p256dh, auth, token, user_id, metadata, created_at, last_seen_at, last_status, last_error) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12) ON CONFLICT(id) DO UPDATE SET kind = ?2, endpoint = ?3, p256dh = ?4, auth = ?5, token = ?6, user_id = ?7, metadata = ?8, last_seen_at = ?10`).bind(t.id,t.kind,t.endpoint??null,t.keys?.p256dh??null,t.keys?.auth??null,t.token??null,t.userId??null,t.metadata===void 0?null:JSON.stringify(t.metadata),t.createdAt,t.lastSeenAt,t.lastStatus??null,t.lastError??null).run();const n=h(t);return n!==void 0&&n!==t.id&&await a.prepare(`DELETE FROM ${r} WHERE id = ?1`).bind(n).run(),await l(t.id)??t}}};export{I as d1SubscriptionStore};
@@ -1 +0,0 @@
1
- import{LunoraError as a}from"@lunora/errors";const e=(o,r)=>o.send({...r,type:"lunora.push.broadcast"}),s=async(o,r)=>{const t=await o.broadcast(r.payload,r.filter);if(t.failed>0)throw new a("INTERNAL",`@lunora/notify: push broadcast had ${t.failed.toString()} transient failure(s) of ${t.total.toString()} subscription(s) (${t.sent.toString()} sent, ${t.pruned.toString()} pruned) — throwing so the queue retries`);return t};export{e as enqueuePushBroadcast,s as runPushBroadcastJob};
@@ -1 +0,0 @@
1
- import{LunoraError as u}from"@lunora/errors";const k=/^\d{1,3}$/u,E=/^::ffff:([\da-f]{1,4}):([\da-f]{1,4})$/u,I=/^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/u,S=/^::(\d{1,3}(?:\.\d{1,3}){3})$/u,v=/^::([\da-f]{1,4}):([\da-f]{1,4})$/u,A=/^64:ff9b::[\da-f]{1,4}:[\da-f]{1,4}$/u,W=/^\[|\]$/gu,N=/\.$/u,l=t=>{const e=t.split(".");if(e.length!==4)return;const n=e.map(r=>k.test(r)?Number(r):-1);if(!n.some(r=>r<0||r>255))return[n[0],n[1],n[2],n[3]]},f=([t,e])=>t===0||t===10||t===127||t===100&&e>=64&&e<=127||t===169&&e===254||t===172&&e>=16&&e<=31||t===192&&e===168||t>=224,p=(t,e)=>{const n=Number.parseInt(t??"",16),r=Number.parseInt(e??"",16);return!Number.isFinite(n)||!Number.isFinite(r)?!0:f([Math.floor(n/256),n%256,Math.floor(r/256),r%256])},R=t=>{const e=t.toLowerCase(),n=E.exec(e);if(n)return p(n[1],n[2]);const r=I.exec(e);if(r){const o=l(r[1]??"");return o===void 0||f(o)}const i=S.exec(e);if(i){const o=l(i[1]??"");return o===void 0||f(o)}const s=v.exec(e);return s?p(s[1],s[2]):A.test(e)||e.startsWith("2002:")||e.startsWith("2001:0:")?!0:e==="::"||e==="::1"||e.startsWith("fc")||e.startsWith("fd")||e.startsWith("fe8")||e.startsWith("fe9")||e.startsWith("fea")||e.startsWith("feb")},_=t=>t==="localhost"||t.endsWith(".localhost")||t.endsWith(".local")||t.endsWith(".internal")||t.endsWith(".home.arpa"),D=t=>t.replaceAll(W,"").replace(N,"").toLowerCase(),O=t=>{const e=D(t);if(e.includes(":"))return R(e);const n=l(e);return n===void 0?_(e):f(n)},d=t=>t.toString(16).padStart(4,"0"),g=t=>{let e=8997,n=33826,r=40164,i=52210;for(let s=0;s<t.length;s+=1){const o=t.codePointAt(s)??0;e^=o&65535,n^=o>>>16&65535;const a=e*435,w=n*435,b=r*435+e*256,y=i*435+n*256,c=w+(a>>>16),h=b+(c>>>16),$=y+(h>>>16);e=a&65535,n=c&65535,r=h&65535,i=$&65535}return d(i)+d(r)+d(n)+d(e)},P=t=>`wp2_${g(t)}`,B=t=>`fcm2_${g(t)}`,m=t=>{let e=2166136261;for(let n=0;n<t.length;n+=1)e^=t.codePointAt(n)??0,e=Math.imul(e,16777619);return(e>>>0).toString(16).padStart(8,"0")},U=t=>`wp_${m(t)}`,x=t=>`fcm_${m(t)}`,q=t=>t.kind==="fcm"?t.token===void 0?void 0:x(t.token):t.endpoint===void 0?void 0:U(t.endpoint),F=t=>{if(typeof t!="string")return t??{};try{return JSON.parse(t)}catch(e){throw new u("BAD_REQUEST",`@lunora/notify: register() web-push subscription is not valid JSON: ${e instanceof Error?e.message:String(e)}`)}},T=(t,e)=>{let n;try{n=new URL(t)}catch{throw new u("BAD_REQUEST",`@lunora/notify: register() web-push \`endpoint\` must be an absolute https URL (got "${t}")`)}if(n.protocol!=="https:")throw new u("BAD_REQUEST",`@lunora/notify: register() web-push \`endpoint\` must use https (got "${n.protocol}")`);if(e!==void 0&&e.length>0){if(!e.includes(n.origin))throw new u("FORBIDDEN",`@lunora/notify: register() web-push endpoint origin "${n.origin}" is not in the configured allowedPushOrigins allowlist`);return}if(O(n.hostname))throw new u("FORBIDDEN",`@lunora/notify: register() web-push endpoint host "${n.hostname}" is a private/internal address; configure allowedPushOrigins to permit a specific origin`)},C=(t,e=Date.now(),n={})=>{if("token"in t){const{token:a}=t;if(typeof a!="string"||a==="")throw new u("BAD_REQUEST","@lunora/notify: register() fcm input requires a non-empty `token`");return{createdAt:e,id:B(a),kind:"fcm",lastSeenAt:e,metadata:t.metadata,token:a,userId:t.userId??null}}const r=F(t.subscription),{endpoint:i}=r,s=r.keys?.p256dh,o=r.keys?.auth;if(typeof i!="string"||i===""||typeof s!="string"||typeof o!="string")throw new u("BAD_REQUEST","@lunora/notify: register() web-push subscription requires `endpoint` and `keys.{p256dh, auth}`");return T(i,n.allowedPushOrigins),{createdAt:e,endpoint:i,id:P(i),keys:{auth:o,p256dh:s},kind:"web-push",lastSeenAt:e,metadata:t.metadata,userId:t.userId??null}},z=t=>t.kind==="fcm"?t.token??"":JSON.stringify({endpoint:t.endpoint,keys:t.keys}),L=/\bhttp\s*4(?:04|10)\b/iu,Q=/\b(?:unregistered|not[\s-]?registered|registration-token-not-registered)\b/iu,J=/\bsubscription (?:is )?(?:gone|expired|no longer valid)\b/iu,G=t=>t===void 0?!1:L.test(t)||Q.test(t)||J.test(t);export{B as fcmId,G as isGoneError,x as legacyFcmId,q as legacyIdFor,U as legacyWebPushId,C as normalizeRegisterInput,z as targetOf,P as webPushId};
@@ -1 +0,0 @@
1
- import{legacyIdFor as i}from"./fcmId-CLRyQJVw.mjs";const d=(e,t)=>t===void 0?!0:!(t.kind!==void 0&&e.kind!==t.kind||t.userId!==void 0&&(e.userId??null)!==t.userId),l=()=>{const e=new Map;return{delete:t=>(e.delete(t),Promise.resolve()),get:t=>Promise.resolve(e.get(t)),list:t=>{const r=[];for(const o of e.values())d(o,t)&&r.push(o);const s=t?.limit!==void 0&&t.limit>0?r.slice(0,Math.trunc(t.limit)):r;return Promise.resolve(s)},markStatus:(t,r,s)=>{const o=e.get(t);return o!==void 0&&e.set(t,{...o,lastError:s,lastSeenAt:Date.now(),lastStatus:r}),Promise.resolve()},put:t=>{const r=i(t);r!==void 0&&r!==t.id&&e.delete(r);const s=e.get(t.id),o=s===void 0?t:{...s,...t,createdAt:s.createdAt};return e.set(o.id,o),Promise.resolve(o)}}};export{l as memorySubscriptionStore};