@lunora/notify 0.0.0 → 1.0.0-alpha.2

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.
@@ -0,0 +1,484 @@
1
+ import { FcmConfig } from '@visulima/notification/providers/fcm';
2
+ export type { FcmConfig } from '@visulima/notification/providers/fcm';
3
+ import { PushSubscriptionLike, WebPushConfig } from '@visulima/notification/providers/web-push';
4
+ export type { PushSubscriptionLike, WebPushConfig } from '@visulima/notification/providers/web-push';
5
+ import { ChatPayload, Receipt, InAppPayload, PushPayload, NotificationMessage, WebhookPayload, Notification, Provider } from '@visulima/notification';
6
+ export type { ChatPayload, InAppPayload, NotificationMessage, PushPayload, Receipt, WebhookPayload } from '@visulima/notification';
7
+ /**
8
+ * A Worker `env` projected as a plain record (vars, secrets and bindings are
9
+ * `unknown`-valued). `defineNotify` factories receive this so a config can read
10
+ * VAPID/FCM secrets and pick bindings (D1, Queues) at request/isolate time —
11
+ * mirroring the `config.ai?.(env)` / flags `provider(env)` thunk pattern.
12
+ */
13
+ type NotifyEnv = Record<string, unknown>;
14
+ /** The delivery kind a stored device subscription targets. */
15
+ type SubscriptionKind = "fcm" | "web-push";
16
+ /** The last-known delivery outcome recorded on a subscription. */
17
+ type SubscriptionStatus = "expired" | "failed" | "ok";
18
+ /**
19
+ * A registered device/browser subscription. Web Push carries a W3C Push API
20
+ * `endpoint` + `keys`; FCM carries a device registration `token`. `id` is a
21
+ * stable, storage-safe identifier derived from the target (see `subscriptionId`).
22
+ */
23
+ interface StoredSubscription {
24
+ /** Unix-ms creation time. */
25
+ createdAt: number;
26
+ /** Web Push service endpoint URL (web-push only). */
27
+ endpoint?: string;
28
+ /** Stable identifier (endpoint/token derived) used as the store key. */
29
+ id: string;
30
+ /** Web Push client keys (web-push only). */
31
+ keys?: {
32
+ auth: string;
33
+ p256dh: string;
34
+ };
35
+ /** The delivery channel this subscription targets. */
36
+ kind: SubscriptionKind;
37
+ /** Last delivery error message, when `lastStatus` is `failed`/`expired`. */
38
+ lastError?: string;
39
+ /** Unix-ms time of the most recent register/send touch. */
40
+ lastSeenAt: number;
41
+ /** Last-known delivery outcome. */
42
+ lastStatus?: SubscriptionStatus;
43
+ /** Arbitrary app metadata (device name, locale, topics, …). */
44
+ metadata?: Record<string, unknown>;
45
+ /** FCM device registration token (fcm only). */
46
+ token?: string;
47
+ /** Owning user id, or `null` when anonymous. */
48
+ userId?: string | null;
49
+ }
50
+ /**
51
+ * The admin-facing projection of a {@link StoredSubscription} — a registered
52
+ * device as surfaced by the gated `__lunora_admin__:listPushSubscriptions` RPC
53
+ * (backing the Studio Notifications page). The delivery **secrets** are dropped:
54
+ * the Web Push `keys` (the RFC 8291 `auth`/`p256dh` encryption material) and the
55
+ * FCM `token` are never sent to the browser — only the endpoint / kind / owner /
56
+ * timestamps and the last-send status + error the page renders.
57
+ */
58
+ type PushSubscriptionDevice = Omit<StoredSubscription, "keys" | "token">;
59
+ /** Payload of a `__lunora_admin__:listPushSubscriptions` call — the registered devices, secrets redacted. */
60
+ interface PushSubscriptionsResult {
61
+ /** The registered device subscriptions matching the request filter (secrets stripped). */
62
+ subscriptions: PushSubscriptionDevice[];
63
+ }
64
+ /** Input accepted by `ctx.push.register(...)` — a web-push subscription or an FCM token. */
65
+ type RegisterInput = {
66
+ kind?: "web-push";
67
+ metadata?: Record<string, unknown>;
68
+ subscription: PushSubscriptionLike | string;
69
+ userId?: string | null;
70
+ } | {
71
+ kind: "fcm";
72
+ metadata?: Record<string, unknown>;
73
+ token: string;
74
+ userId?: string | null;
75
+ };
76
+ /** Filter narrowing which stored subscriptions a `list`/`broadcast` targets. */
77
+ interface SubscriptionFilter {
78
+ /** Restrict to a delivery kind. */
79
+ kind?: SubscriptionKind;
80
+ /** Restrict to a single owning user. */
81
+ userId?: string | null;
82
+ }
83
+ /**
84
+ * Persistence for device subscriptions. Implementations back `ctx.push`'s
85
+ * lifecycle (register, list, prune). Ships with an in-memory store (tests/dev)
86
+ * and a D1-backed store (durable, edge-safe).
87
+ */
88
+ interface SubscriptionStore {
89
+ /** Remove a subscription by id (idempotent). */
90
+ delete: (id: string) => Promise<void>;
91
+ /** Read a subscription by id, or `undefined`. */
92
+ get: (id: string) => Promise<StoredSubscription | undefined>;
93
+ /** List subscriptions, optionally filtered. */
94
+ list: (filter?: SubscriptionFilter) => Promise<StoredSubscription[]>;
95
+ /** Record the latest delivery outcome for a subscription (best-effort). */
96
+ markStatus: (id: string, status: SubscriptionStatus, error?: string) => Promise<void>;
97
+ /** Insert or update a subscription (upsert by id). */
98
+ put: (subscription: StoredSubscription) => Promise<StoredSubscription>;
99
+ }
100
+ /** Per-recipient outcome from a fan-out `broadcast`. */
101
+ interface BroadcastOutcome {
102
+ /** Delivery error message when `status` is not `ok`. */
103
+ error?: string;
104
+ /** The subscription this outcome belongs to. */
105
+ id: string;
106
+ /** `expired` subscriptions were pruned from the store. */
107
+ status: SubscriptionStatus;
108
+ }
109
+ /** Aggregate result of a `broadcast`. */
110
+ interface BroadcastResult {
111
+ /** Number of subscriptions that failed (non-gone). */
112
+ failed: number;
113
+ /** Per-subscription outcomes. */
114
+ outcomes: BroadcastOutcome[];
115
+ /** Number of pruned (gone/expired) subscriptions. */
116
+ pruned: number;
117
+ /** Number of subscriptions delivered successfully. */
118
+ sent: number;
119
+ /** Total subscriptions attempted. */
120
+ total: number;
121
+ }
122
+ /**
123
+ * The compact, stable delivery-status vocabulary emitted on notify observability
124
+ * signals — the `status` dimension on the `notify.send` metric and the failure
125
+ * log line. Modeled on Novu's execution status, but honest to edge push:
126
+ *
127
+ * - `accepted` — the provider took the message (a `Receipt.successful` send).
128
+ * - `failed` — a provider error; the log line carries the `error` text.
129
+ * - `gone` — the endpoint is unregistered (404/410, FCM `UNREGISTERED`) and pruned; push-only.
130
+ *
131
+ * Web Push and FCM give no delivery/open receipts, so the vocabulary stops at the
132
+ * send attempt: a `delivered`/`opened` status would be a lie for these channels.
133
+ * The one place a later `seen`/`read` is real is the in-app inbox, where the
134
+ * client posts a read receipt back — out of scope here.
135
+ */
136
+ type NotifyDeliveryStatus = "accepted" | "failed" | "gone";
137
+ /**
138
+ * Why a send fanned out to nobody — the "sent 0 because…" signal (mirrors Novu's
139
+ * pre-send `DetailEnum` reasons). Emitted as the `reason` dimension on a
140
+ * `notify.skipped` metric so a no-op is visible in the Studio metric/trend view
141
+ * instead of silent.
142
+ *
143
+ * - `no-subscriptions-matched` — the store held no device for the broadcast filter.
144
+ * - `channel-not-configured` — the target channel was never wired in `defineNotify`.
145
+ */
146
+ type NotifySkipReason = "channel-not-configured" | "no-subscriptions-matched";
147
+ /**
148
+ * The minimal structural slice of `ctx.log` the notify facade emits through — just
149
+ * the `warn` severity it uses for a failed delivery. Structural (rather than a
150
+ * dependency on `@lunora/server`'s `LunoraLogger`) so codegen passes the real
151
+ * `ctx.log` and a test passes a spy — the D1-store `D1Like` pattern, applied to
152
+ * observability.
153
+ */
154
+ interface NotifyLogger {
155
+ warn: (message: string, fields?: Record<string, unknown>) => void;
156
+ }
157
+ /**
158
+ * The minimal structural slice of `ctx.metrics` the notify facade emits through —
159
+ * the `count` instrument backing the `notify.send` / `notify.skipped` series.
160
+ * Structural for the same reason as {@link NotifyLogger}.
161
+ */
162
+ interface NotifyMetrics {
163
+ count: (name: string, value?: number, attributes?: Record<string, unknown>) => void;
164
+ }
165
+ /**
166
+ * The push sub-facade — spliced onto ctx as `ctx.push` (and reachable as
167
+ * `ctx.notify.push`). Owns the device-subscription lifecycle plus targeted and
168
+ * fan-out push delivery through the edge-safe Web Push / FCM providers.
169
+ */
170
+ interface LunoraPush {
171
+ /**
172
+ * Fan-out a push to every stored subscription matching `filter` (default: all).
173
+ * Reuses the engine's retry/circuit-breaker middleware; prunes subscriptions
174
+ * the push service reports as gone (HTTP 404/410, FCM `UNREGISTERED`). The `to`
175
+ * target is derived from each subscription, so it is omitted from the payload.
176
+ */
177
+ broadcast: (payload: PushContent, filter?: SubscriptionFilter) => Promise<BroadcastResult>;
178
+ /** List stored subscriptions (optionally filtered). */
179
+ list: (filter?: SubscriptionFilter) => Promise<StoredSubscription[]>;
180
+ /** Register (upsert) a device subscription and return the stored record. */
181
+ register: (input: RegisterInput) => Promise<StoredSubscription>;
182
+ /** Send a push to a single stored subscription (by id or record); `to` is derived from it. */
183
+ send: (target: StoredSubscription | string, payload: PushContent) => Promise<Receipt>;
184
+ /** Remove a subscription by id (idempotent). */
185
+ unregister: (id: string) => Promise<void>;
186
+ }
187
+ /** A push payload without its `to` target — the facade derives `to` from the stored subscription. */
188
+ type PushContent = Omit<PushPayload, "to">;
189
+ /**
190
+ * The multi-channel notification facade — spliced onto ctx as `ctx.notify`.
191
+ * `send` delivers a fully-specified multi-channel message through the engine;
192
+ * `push` is the device-push sub-facade; `chat` / `inApp` / `webhook` are
193
+ * single-channel convenience senders for the edge-safe channels.
194
+ */
195
+ interface LunoraNotify {
196
+ /** Send an outbound webhook. */
197
+ chat: (payload: ChatPayload) => Promise<Receipt>;
198
+ /** Deliver an in-app inbox notification. */
199
+ inApp: (payload: InAppPayload) => Promise<Receipt>;
200
+ /** The device-push sub-facade (identical object to `ctx.push`). */
201
+ push: LunoraPush;
202
+ /** Deliver a multi-channel message (one payload per channel). */
203
+ send: (message: NotificationMessage) => Promise<Receipt[]>;
204
+ /** Post to a chat channel (Slack/Discord/Teams/Telegram). */
205
+ webhook: (payload: WebhookPayload) => Promise<Receipt>;
206
+ }
207
+ /**
208
+ * Resolves a channel provider factory from the Worker `env`. Receiving `env`
209
+ * (rather than a constructed provider) lets a config read VAPID/FCM secrets and
210
+ * bindings at request time. Return `undefined` to leave the channel unwired.
211
+ */
212
+ type WebPushConfigFactory = (env: NotifyEnv) => WebPushConfig | undefined;
213
+ type FcmConfigFactory = (env: NotifyEnv) => FcmConfig | undefined;
214
+ /** Options accepted by `defineNotify`. */
215
+ interface NotifyConfig {
216
+ /**
217
+ * Optional chat provider factory (Slack/Discord/Teams/Telegram). Wire with a
218
+ * provider from `@visulima/notification/providers/*`. Edge-safe (fetch-based).
219
+ */
220
+ chat?: (env: NotifyEnv) => unknown;
221
+ /** FCM (Firebase Cloud Messaging HTTP v1) config. Edge-safe — supply an OAuth2 token. */
222
+ fcm?: FcmConfig | FcmConfigFactory;
223
+ /** Optional in-app inbox provider factory. Edge-safe. */
224
+ inApp?: (env: NotifyEnv) => unknown;
225
+ /**
226
+ * Builds the subscription store from `env` (usually a D1-backed store from a
227
+ * binding). Defaults to a non-durable in-memory store with a dev warning.
228
+ */
229
+ store?: (env: NotifyEnv) => SubscriptionStore;
230
+ /** Optional outbound-webhook provider factory. Edge-safe (fetch-based). */
231
+ webhook?: (env: NotifyEnv) => unknown;
232
+ /** Web Push (VAPID + RFC 8291) config. Fully edge-safe (Web Crypto only). */
233
+ webPush?: WebPushConfig | WebPushConfigFactory;
234
+ }
235
+ /**
236
+ * A branded {@link NotifyConfig} produced by `defineNotify`. This is the default
237
+ * export of `lunora/notify.ts`; codegen imports it into the generated worker and
238
+ * wires `ctx.notify` / `ctx.push` from it (mirroring `defineFlags` → `ctx.flags`).
239
+ */
240
+ interface NotifyDefinition extends NotifyConfig {
241
+ /** Runtime brand used by `isNotifyDefinition` and codegen discovery. */
242
+ readonly isLunoraNotify: true;
243
+ }
244
+ /**
245
+ * `.dev.vars` / Worker `env` keys the built-in config resolvers read. Mirrored in
246
+ * `@lunora/config`'s package-secrets registry so `lunora dev` scaffolds them into
247
+ * `.dev.vars.example`.
248
+ */
249
+ declare const WEB_PUSH_ENV_KEYS: {
250
+ readonly privateKey: "VAPID_PRIVATE_KEY";
251
+ readonly publicKey: "VAPID_PUBLIC_KEY";
252
+ readonly subject: "VAPID_SUBJECT";
253
+ };
254
+ declare const FCM_ENV_KEYS: {
255
+ readonly accessToken: "FCM_ACCESS_TOKEN";
256
+ readonly projectId: "FCM_PROJECT_ID";
257
+ };
258
+ /**
259
+ * Resolve a {@link WebPushConfig} from the Worker `env` VAPID secrets
260
+ * (`VAPID_PUBLIC_KEY`, `VAPID_PRIVATE_KEY`, `VAPID_SUBJECT`). Returns `undefined`
261
+ * when any is missing, leaving the Web Push channel unwired rather than throwing —
262
+ * so an app can ship FCM-only (or vice versa) without failing ctx construction.
263
+ *
264
+ * Generate a VAPID keypair once with `npx web-push generate-vapid-keys` (or any
265
+ * P-256 tool) and set `VAPID_SUBJECT` to a `mailto:` or `https:` contact.
266
+ */
267
+ declare const webPushFromEnv: (env: NotifyEnv, overrides?: Partial<WebPushConfig>) => WebPushConfig | undefined;
268
+ /**
269
+ * Resolve an {@link FcmConfig} from the Worker `env` (`FCM_PROJECT_ID` plus a
270
+ * static `FCM_ACCESS_TOKEN`). Returns `undefined` when the project id is missing.
271
+ *
272
+ * The static token is convenient for local dev but expires; in production prefer
273
+ * passing your own `getAccessToken` (e.g. wrapping `google-auth-library`) via
274
+ * `defineNotify({ fcm: (env) => ({ ...fcmFromEnv(env), getAccessToken }) })` —
275
+ * that keeps the provider edge-safe (no Google SDK / `node:crypto` bundled).
276
+ */
277
+ declare const fcmFromEnv: (env: NotifyEnv, overrides?: Partial<FcmConfig>) => FcmConfig | undefined;
278
+ /**
279
+ * Declare the notification channels for a Lunora app. Pure validation +
280
+ * branding — codegen discovers the default export of `lunora/notify.ts`, imports
281
+ * it into the generated worker, and wires `ctx.notify` / `ctx.push` from it
282
+ * (mirrors how `defineFlags` feeds codegen to build `ctx.flags`).
283
+ *
284
+ * ```ts
285
+ * // lunora/notify.ts
286
+ * import { defineNotify, webPushFromEnv, fcmFromEnv } from "@lunora/notify";
287
+ * import { d1SubscriptionStore } from "@lunora/notify";
288
+ *
289
+ * export default defineNotify({
290
+ * webPush: (env) => webPushFromEnv(env), // VAPID_* from .dev.vars
291
+ * fcm: (env) => fcmFromEnv(env), // FCM_PROJECT_ID / FCM_ACCESS_TOKEN
292
+ * store: (env) => d1SubscriptionStore(env.DB),
293
+ * });
294
+ * ```
295
+ *
296
+ * Only edge-safe channels are wired here — Web Push and FCM run on Web Crypto +
297
+ * `fetch` under workerd. APNs (`node:http2`) and SMS/Node-only queue adapters are
298
+ * intentionally **not** exposed on the edge facade; route heavy fan-out through
299
+ * `@lunora/queue` instead (see `broadcastViaQueue`).
300
+ */
301
+ declare const defineNotify: (config: NotifyConfig) => NotifyDefinition;
302
+ /** True when a value is a {@link defineNotify} result (the runtime brand check). */
303
+ declare const isNotifyDefinition: (value: unknown) => value is NotifyDefinition;
304
+ /** Options for {@link createNotify}. */
305
+ interface CreateNotifyOptions {
306
+ /** Max concurrent sends during a `broadcast` (default 10). */
307
+ concurrency?: number;
308
+ /**
309
+ * Override the assembled `@visulima/notification` engine. Advanced/testing
310
+ * seam — pass a `Notification` built with your own (mock) providers to bypass
311
+ * config resolution entirely.
312
+ */
313
+ engine?: Notification;
314
+ /**
315
+ * The request's `ctx.log` (structural {@link NotifyLogger}). Codegen threads
316
+ * `ctx.log` in; when present the facade emits one `warn` line per FAILED
317
+ * delivery — trace-correlated to the enclosing action and durably archived by
318
+ * the log sink. Successes and prunes stay off the log to keep the archive
319
+ * clean; they are counted on `metrics` instead. Absent ⇒ no log emits.
320
+ */
321
+ log?: NotifyLogger;
322
+ /**
323
+ * The request's `ctx.metrics` (structural {@link NotifyMetrics}). Codegen
324
+ * threads `ctx.metrics` in; when present the facade counts every send on the
325
+ * `notify.send` series (dimensions `channel` / `provider` / `status`) and every
326
+ * no-op on `notify.skipped` (`channel` / `reason`) — feeding the durable metric
327
+ * history + trend charts. Absent ⇒ no metric emits.
328
+ */
329
+ metrics?: NotifyMetrics;
330
+ /** Suppress the in-memory-store dev warning (tests set this). */
331
+ silent?: boolean;
332
+ }
333
+ /**
334
+ * Build the `ctx.notify` / `ctx.push` facades for a request from a
335
+ * {@link NotifyDefinition} (the `lunora/notify.ts` default export) and the Worker
336
+ * `env`. Codegen calls this to splice the facades onto ctx — the same shape as
337
+ * `createFlags` for `ctx.flags`. Returns both facades; `notify.push` is the very
338
+ * same object exposed as `ctx.push`.
339
+ *
340
+ * The engine and the dev fallback store are memoized per isolate (see
341
+ * {@link NotifyRuntime}), so repeat calls with the same `definition`/`env` are
342
+ * cheap — only the thin facade closures below are rebuilt each call.
343
+ */
344
+ declare const createNotify: (definition: NotifyDefinition, env: NotifyEnv, options?: CreateNotifyOptions) => {
345
+ notify: LunoraNotify;
346
+ push: LunoraPush;
347
+ };
348
+ /** Options for {@link routingPushProvider}. */
349
+ interface RoutingPushOptions {
350
+ fcm?: Provider<unknown, PushPayload>;
351
+ webPush?: Provider<unknown, PushPayload>;
352
+ }
353
+ /**
354
+ * A composite push {@link Provider} that dispatches each send to the Web Push or
355
+ * FCM provider by the shape of the payload `to` target — so a single `push`
356
+ * channel on the {@link Notification} facade transparently handles both browser
357
+ * subscriptions and mobile device tokens, and the engine's middleware wraps them
358
+ * uniformly.
359
+ */
360
+ declare const routingPushProvider: (options: RoutingPushOptions) => Provider<unknown, PushPayload>;
361
+ /** A resolved, ready-to-wire set of channel configs (edge-safe channels only). */
362
+ interface ResolvedProviders {
363
+ chat?: Provider;
364
+ fcm?: FcmConfig;
365
+ inApp?: Provider;
366
+ webhook?: Provider;
367
+ webPush?: WebPushConfig;
368
+ }
369
+ /**
370
+ * Assemble the `@visulima/notification` engine from resolved channel configs and
371
+ * attach the reused retry + circuit-breaker middleware. Only edge-safe channels
372
+ * are wired (Web Push, FCM, chat, in-app, webhook); APNs and SMS are excluded
373
+ * from the edge facade by construction.
374
+ */
375
+ declare const buildEngine: (resolved: ResolvedProviders) => Notification;
376
+ /**
377
+ * A broadcast job body — the JSON-serialisable payload enqueued for off-request
378
+ * fan-out. Shaped to travel through a `@lunora/queue` producer/consumer without
379
+ * `@lunora/notify` depending on `@lunora/queue` (the seam stays structural).
380
+ */
381
+ interface PushBroadcastJob {
382
+ /** Subscription filter (which devices/users to target). */
383
+ filter?: SubscriptionFilter;
384
+ /** The push payload to deliver (the `to` target is derived per subscription). */
385
+ payload: PushContent;
386
+ /** Discriminator so a shared queue can multiplex message kinds. */
387
+ type: "lunora.push.broadcast";
388
+ }
389
+ /** The structural slice of a `@lunora/queue` producer (`ctx.queues.&lt;name>`) used here. */
390
+ interface QueueProducerLike {
391
+ send: (body: PushBroadcastJob) => Promise<void>;
392
+ }
393
+ /**
394
+ * Enqueue a fan-out broadcast for background delivery through a `@lunora/queue`
395
+ * queue instead of blocking the request. Pair with {@link runPushBroadcastJob} in
396
+ * the queue consumer.
397
+ *
398
+ * ```ts
399
+ * // in a mutation/action:
400
+ * await enqueuePushBroadcast(ctx.queues.push, { payload: { title: "New drop", body: "…" } });
401
+ *
402
+ * // in lunora/queues.ts consumer:
403
+ * export const push = defineQueue({ async handler(batch, ctx) {
404
+ * for (const message of batch.messages) await runPushBroadcastJob(ctx.push, message.body);
405
+ * }});
406
+ * ```
407
+ */
408
+ declare const enqueuePushBroadcast: (queue: QueueProducerLike, job: Omit<PushBroadcastJob, "type">) => Promise<void>;
409
+ /**
410
+ * Run an enqueued broadcast job on the consumer side, delivering through the push
411
+ * facade (which reuses the engine's retry + circuit-breaker middleware and prunes
412
+ * gone subscriptions).
413
+ */
414
+ declare const runPushBroadcastJob: (push: LunoraPush, job: PushBroadcastJob) => Promise<unknown>;
415
+ /**
416
+ * The minimal structural slice of Cloudflare's `D1Database` this store uses. A
417
+ * structural type (rather than importing `@cloudflare/workers-types`) keeps the
418
+ * store runtime-agnostic and trivially fakeable in tests.
419
+ */
420
+ interface D1Like {
421
+ prepare: (query: string) => D1PreparedLike;
422
+ }
423
+ interface D1PreparedLike {
424
+ all: <T = Record<string, unknown>>() => Promise<{
425
+ results: T[];
426
+ }>;
427
+ bind: (...values: unknown[]) => D1PreparedLike;
428
+ first: <T = Record<string, unknown>>() => Promise<T | null>;
429
+ run: () => Promise<unknown>;
430
+ }
431
+ /** Options for {@link d1SubscriptionStore}. */
432
+ interface D1StoreOptions {
433
+ /** Table name (default `lunora_push_subscriptions`). Must be a bare identifier. */
434
+ tableName?: string;
435
+ }
436
+ /**
437
+ * A D1-backed {@link SubscriptionStore}. Edge-safe (D1 is a Worker binding). The
438
+ * backing table is created lazily on first use (`CREATE TABLE IF NOT EXISTS`), so
439
+ * no migration step is required for the subscription table itself.
440
+ *
441
+ * ```ts
442
+ * export default defineNotify({
443
+ * webPush: (env) => webPushFromEnv(env),
444
+ * store: (env) => d1SubscriptionStore(env.DB),
445
+ * });
446
+ * ```
447
+ */
448
+ declare const d1SubscriptionStore: (database: D1Like, options?: D1StoreOptions) => SubscriptionStore;
449
+ /**
450
+ * An in-memory {@link SubscriptionStore} — the zero-dependency default. Suitable
451
+ * for tests, local dev and a single-isolate app, but **not durable**: entries live
452
+ * only for the isolate's lifetime. Use {@link import("./d1-store").d1SubscriptionStore}
453
+ * (or another backing store) for production so subscriptions survive restarts.
454
+ */
455
+ declare const memorySubscriptionStore: () => SubscriptionStore;
456
+ /** Stable store id for a web-push endpoint. */
457
+ declare const webPushId: (endpoint: string) => string;
458
+ /** Stable store id for an FCM device token. */
459
+ declare const fcmId: (token: string) => string;
460
+ /**
461
+ * Normalise a `register(...)` input into a {@link StoredSubscription}. Validates
462
+ * the shape (a web-push subscription needs `endpoint` + `keys.{p256dh,auth}`; an
463
+ * FCM entry needs a non-empty `token`) and stamps `createdAt`/`lastSeenAt`.
464
+ */
465
+ declare const normalizeRegisterInput: (input: RegisterInput, now?: number) => StoredSubscription;
466
+ /**
467
+ * The provider `to` target for a stored subscription: the W3C Push subscription
468
+ * (JSON-stringified) for web-push, or the raw device token for FCM. Matches the
469
+ * shapes the `@visulima/notification` web-push / fcm providers accept.
470
+ */
471
+ declare const targetOf: (subscription: StoredSubscription) => string;
472
+ /**
473
+ * Whether a provider error message indicates the subscription is permanently gone
474
+ * (the browser/device unsubscribed) and should be pruned — as opposed to a
475
+ * transient failure worth retrying.
476
+ *
477
+ * Gates on STRUCTURED signals first: a Web Push `HTTP 404/410` status or an FCM
478
+ * `UNREGISTERED`/`NOT_REGISTERED` code, both of which the providers surface in
479
+ * their failure receipts. The free-text {@link GONE_TEXT_FALLBACK} is a tightened
480
+ * last resort only, so a transient error that happens to contain `expired`
481
+ * (a cert/session expiry) can never permanently drop a valid subscription.
482
+ */
483
+ declare const isGoneError: (message: string | undefined) => boolean;
484
+ export { type BroadcastOutcome, type BroadcastResult, type CreateNotifyOptions, type D1Like, type D1PreparedLike, type D1StoreOptions, FCM_ENV_KEYS, type FcmConfigFactory, type LunoraNotify, type LunoraPush, type NotifyConfig, type NotifyDefinition, type NotifyDeliveryStatus, type NotifyEnv, type NotifyLogger, type NotifyMetrics, type NotifySkipReason, type PushBroadcastJob, type PushSubscriptionDevice, type PushSubscriptionsResult, type QueueProducerLike, type RegisterInput, type ResolvedProviders, type RoutingPushOptions, type StoredSubscription, type SubscriptionFilter, type SubscriptionKind, type SubscriptionStatus, type SubscriptionStore, WEB_PUSH_ENV_KEYS, type WebPushConfigFactory, buildEngine, createNotify, d1SubscriptionStore, defineNotify, enqueuePushBroadcast, fcmFromEnv, fcmId, isGoneError, isNotifyDefinition, memorySubscriptionStore, normalizeRegisterInput, routingPushProvider, runPushBroadcastJob, targetOf, webPushFromEnv, webPushId };