@lunora/client 1.0.0-alpha.67 → 1.0.0-alpha.69

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 (44) hide show
  1. package/dist/auth/index.d.mts +3 -2
  2. package/dist/auth/index.d.ts +3 -2
  3. package/dist/index.d.mts +80 -7
  4. package/dist/index.d.ts +80 -7
  5. package/dist/index.mjs +1 -1
  6. package/dist/packem_shared/CONFLICT_ERROR_CODE-CDDneB-G.mjs +1 -0
  7. package/dist/packem_shared/LunoraClient-NP7mgVkC.mjs +1 -0
  8. package/dist/packem_shared/OfflineQueue-DIhrKdlU.mjs +1 -0
  9. package/dist/packem_shared/{SubscriptionRegistry-CdHSrDqu.mjs → SubscriptionRegistry-D7n5ZE5F.mjs} +1 -1
  10. package/dist/packem_shared/applyDelta-DJmlwFnT.mjs +1 -0
  11. package/dist/packem_shared/{createAsyncStorageQueryCache-Di-S52wy.mjs → createAsyncStorageQueryCache-C0mJLuZK.mjs} +1 -1
  12. package/dist/packem_shared/createClientQuery-B8Nfj-7o.mjs +1 -0
  13. package/dist/packem_shared/createLocalStore-DtsP-CpS.mjs +1 -0
  14. package/dist/packem_shared/{createServerClient-BhfYV6Je.mjs → createServerClient-DwpNFoKP.mjs} +1 -1
  15. package/dist/packem_shared/{createSnapshotPrecondition-BPMQbAbk.mjs → createSnapshotPrecondition-ZyQDet2v.mjs} +1 -1
  16. package/dist/packem_shared/{delta-merge-BoVuM-rE.mjs → delta-merge-CVSN-uoC.mjs} +1 -1
  17. package/dist/packem_shared/function-reference.d-Br_hsKje.d.mts +45 -0
  18. package/dist/packem_shared/function-reference.d-Br_hsKje.d.ts +45 -0
  19. package/dist/packem_shared/{local-store-tpI9VFpO.mjs → local-store-BQuKm9n6.mjs} +1 -1
  20. package/dist/packem_shared/{lunora-client.d-DAbmOzH_.d.mts → lunora-client.d-CLwpIj61.d.ts} +1212 -47
  21. package/dist/packem_shared/{lunora-client.d-Dz6Yx4By.d.ts → lunora-client.d-DWDMVBKE.d.mts} +1212 -47
  22. package/dist/packem_shared/offline-queue-Bmeyg5fy.mjs +1 -0
  23. package/dist/packem_shared/{preload.d-CN5mOiAj.d.ts → preload.d-BAazUwhn.d.mts} +2 -2
  24. package/dist/packem_shared/{preload.d-BmPMaxYW.d.mts → preload.d-ClHaOfOQ.d.ts} +2 -2
  25. package/dist/packem_shared/{wire-codec-D4iww4NV.mjs → wire-codec-PBOTh_2d.mjs} +1 -1
  26. package/dist/packem_shared/{wire-key-BOdKmpG3.mjs → wire-key-Dl7EFWSD.mjs} +1 -1
  27. package/dist/query/index.d.mts +4 -3
  28. package/dist/query/index.d.ts +4 -3
  29. package/dist/service.d.mts +1 -1
  30. package/dist/service.d.ts +1 -1
  31. package/dist/service.mjs +1 -1
  32. package/dist/ssr/index.d.mts +4 -4
  33. package/dist/ssr/index.d.ts +4 -4
  34. package/dist/ssr/index.mjs +1 -1
  35. package/package.json +2 -2
  36. package/dist/packem_shared/CONFLICT_ERROR_CODE-LjU7z0mB.mjs +0 -1
  37. package/dist/packem_shared/LunoraClient-BKmMPd4k.mjs +0 -1
  38. package/dist/packem_shared/OfflineQueue-DG51qWl4.mjs +0 -1
  39. package/dist/packem_shared/applyDelta-DGqMpi3N.mjs +0 -1
  40. package/dist/packem_shared/createClientQuery-TKD_52cT.mjs +0 -1
  41. package/dist/packem_shared/createLocalStore-CZwiN9F4.mjs +0 -1
  42. package/dist/packem_shared/offline-queue-CzI2lYQ8.mjs +0 -1
  43. package/dist/packem_shared/types.d-BOB755CV.d.mts +0 -1015
  44. package/dist/packem_shared/types.d-BOB755CV.d.ts +0 -1015
@@ -1,1015 +0,0 @@
1
- /** The registered function kinds a {@link FunctionReference} can describe. `stream` is a query that yields multiple frames over the WS. */
2
- type FunctionKind = "action" | "mutation" | "query" | "stream";
3
- /**
4
- * Opaque reference to a registered function emitted by `@lunora/codegen`.
5
- *
6
- * At runtime it carries the `<file>:<function>` identifier in `__lunoraRef`.
7
- * Generated declarations decorate this with phantom type parameters so the
8
- * client can infer args / return values per call site.
9
- */
10
- interface FunctionReference<Kind extends FunctionKind = FunctionKind, Args = unknown, Return = unknown> {
11
- /**
12
- * Phantom marker carrying the `Kind`/`Args`/`Return` type parameters for
13
- * inference. Never present at runtime; declared as a covariant (output)
14
- * position so a concrete reference stays assignable to a widened one.
15
- */
16
- readonly __lunoraPhantom?: {
17
- args: Args;
18
- kind: Kind;
19
- returns: Return;
20
- };
21
- readonly __lunoraRef: string;
22
- }
23
- /** Extract the args type from a {@link FunctionReference}. */
24
- type ArgsOf<F> = F extends FunctionReference<infer _K, infer A, infer _R> ? A : never;
25
- /** Extract the return type from a {@link FunctionReference}. */
26
- type ReturnOf<F> = F extends FunctionReference<infer _K, infer _A, infer R> ? R : never;
27
- /**
28
- * Typed reference to an HTTP-SSE stream route (`httpRoute.<verb>(path).stream()`)
29
- * emitted by `@lunora/codegen` as `httpStreams.<namespace>.<name>`.
30
- *
31
- * Distinct from {@link FunctionReference}: this is the **HTTP-SSE route stream**
32
- * (opened with `fetch` + `ReadableStream` against the route's own URL), not the
33
- * WS procedure stream (`kind: "stream"`). At runtime it carries the HTTP verb
34
- * and the route path; the phantom marker carries the chunk / searchParams /
35
- * params types so `httpStream` (and the framework hooks over it) infer the
36
- * chunk type end-to-end.
37
- * @experimental Reconnect/POST-body/wire-fidelity design questions are still open, so the shape may change.
38
- */
39
- interface HttpStreamRef<Chunk = unknown, SearchParams = unknown, Params = unknown> {
40
- /**
41
- * Phantom marker carrying the `Chunk`/`SearchParams`/`Params` type
42
- * parameters for inference. Never present at runtime; declared in a
43
- * covariant (output) position so a concrete reference stays assignable to
44
- * a widened one.
45
- */
46
- readonly __lunoraHttpStream?: {
47
- chunk: Chunk;
48
- params: Params;
49
- searchParams: SearchParams;
50
- };
51
- /** HTTP verb the route binds to (uppercased), e.g. `"GET"`. */
52
- readonly method: string;
53
- /** The route path as declared, e.g. `/api/tokens/:id` — `:name` segments are filled from `params`. */
54
- readonly path: string;
55
- }
56
- /**
57
- * The call-side args of an HTTP-SSE stream route: `:name` path params plus URL query params.
58
- * @experimental Part of the HTTP-SSE stream surface.
59
- */
60
- interface HttpStreamCallArgs<SearchParams = unknown, Params = unknown> {
61
- /** Values for the route path's `:name` segments. */
62
- params?: Params;
63
- /** URL query params, appended to the request URL (undefined entries are skipped). */
64
- searchParams?: SearchParams;
65
- }
66
- /**
67
- * Extract the chunk type from a {@link HttpStreamRef}.
68
- * @experimental Part of the HTTP-SSE stream surface.
69
- */
70
- type HttpStreamChunkOf<R> = R extends HttpStreamRef<infer Chunk, infer _S, infer _P> ? Chunk : never;
71
- /**
72
- * Extract the call-side args type from a {@link HttpStreamRef}.
73
- * @experimental Part of the HTTP-SSE stream surface.
74
- */
75
- type HttpStreamArgsOf<R> = R extends HttpStreamRef<infer _C, infer S, infer P> ? HttpStreamCallArgs<S, P> : never;
76
- type Unsubscribe = () => void;
77
- /**
78
- * Serializable result of `preloadQuery`. Produced on the server during SSR,
79
- * embedded in the rendered HTML, then handed to `usePreloadedQuery` on the
80
- * client so the first render shows the server value with no loading flash
81
- * before a live subscription attaches. Every field survives `JSON.stringify`.
82
- */
83
- interface Preloaded<T = unknown> {
84
- readonly __lunoraPreloaded: true;
85
- readonly args: Record<string, unknown>;
86
- readonly functionPath: string;
87
- readonly shardKey?: string;
88
- readonly value: T;
89
- }
90
- /**
91
- * Pluggable storage for the `x-d1-bookmark` value used to provide
92
- * read-your-writes between a mutation and subsequent queries.
93
- */
94
- interface BookmarkStorage {
95
- get: () => string | null;
96
- set: (value: string | null) => void;
97
- }
98
- interface ReconnectOptions {
99
- initialDelayMs?: number;
100
- jitter?: boolean;
101
- maxDelayMs?: number;
102
- }
103
- /** Which durable-storage operation failed, passed to {@link OfflineQueueOptions.onPersistenceError}. */
104
- type PersistenceOperation = "append" | "clear" | "load" | "remove";
105
- /** Context handed to a persistence-error handler. */
106
- interface PersistenceErrorContext {
107
- readonly error: unknown;
108
- /** The mutation id involved, when the failing op was scoped to one (`append`/`remove`). */
109
- readonly mutationId?: string;
110
- readonly operation: PersistenceOperation;
111
- }
112
- interface OfflineQueueOptions {
113
- maxItems?: number;
114
- /**
115
- * Invoked when a {@link PersistenceAdapter} call rejects (e.g. IndexedDB quota
116
- * exceeded). Without a handler, failures are logged via `console.warn` so they
117
- * are never fully silent. Note: a failed `append` means the write is queued in
118
- * memory but NOT durable — it will not survive a reload.
119
- */
120
- onPersistenceError?: (context: PersistenceErrorContext) => void;
121
- /**
122
- * Queue mutations issued before a shard's first successful WebSocket
123
- * connect (defaults to `false`). The standard behaviour (`LunoraClient`'s
124
- * `mutation()`) queues only when the targeted shard has been connected at
125
- * least once (`wasEverConnected`), so the registry / resubscribe handshake
126
- * has run. Set this to `true` for offline-first apps that want to enqueue
127
- * writes on the very first session before the WS is up.
128
- */
129
- queueBeforeFirstConnect?: boolean;
130
- }
131
- /**
132
- * Serializable shape of an offline mutation, durably stored by a
133
- * {@link PersistenceAdapter} so queued writes survive a reload/crash. The live
134
- * `resolve`/`reject` callbacks of an in-flight `QueuedMutation` are *not*
135
- * persisted — a restored mutation is replayed with no original awaiter.
136
- */
137
- interface PersistedMutation {
138
- args: Record<string, unknown>;
139
- /**
140
- * The client id that queued this write, persisted so a replay after a reload
141
- * lands in the SAME server-side dedup namespace it was issued under. The
142
- * standalone client's own `clientId` is minted per session, so replaying under
143
- * the live one would miss the `__idempotency` row for an anonymous caller and
144
- * re-run a write the server already committed. Absent on records written by
145
- * older client versions, which replay under the live id.
146
- */
147
- clientId?: string;
148
- functionPath: string;
149
- id: string;
150
- /**
151
- * Issuing identity fingerprint, persisted so a hydrated write replays only
152
- * under the identity that queued it (`null` = queued while signed out).
153
- * Absent on records written by older client versions, which replay under
154
- * the ambient identity for back-compat.
155
- */
156
- identity?: string | null;
157
- shardKey?: string;
158
- /**
159
- * App/schema version stamped at enqueue (from `LunoraClientOptions.persistenceVersion`).
160
- * On hydrate, a record whose `version` doesn't match the current one is dropped
161
- * and purged rather than replayed — so a write persisted by an older deploy
162
- * (with a now-changed function signature) can't replay against the new schema.
163
- * Absent when no `persistenceVersion` is configured (no version gating).
164
- */
165
- version?: string;
166
- }
167
- /**
168
- * Durable store for the offline mutation queue. The default client keeps the
169
- * queue in memory; supplying an adapter (e.g. `createIndexedDbPersistence`)
170
- * makes queued writes survive a page reload. Implementations must preserve FIFO
171
- * (enqueue) order in `PersistenceAdapter.load`.
172
- *
173
- * Replay semantics are at-least-once: a mutation is removed only after the
174
- * server confirms (or rejects) it, so a crash between commit and `remove` can
175
- * replay it again on the next load.
176
- */
177
- interface PersistenceAdapter {
178
- /** Append a mutation to durable storage (called on enqueue). */
179
- append: (mutation: PersistedMutation) => Promise<void>;
180
- /** Drop every persisted mutation (e.g. on logout). */
181
- clear: () => Promise<void>;
182
- /** Load all persisted mutations in FIFO order — called once at startup. */
183
- load: () => Promise<PersistedMutation[]>;
184
- /** Remove a mutation by id once it has been replayed (resolved or rejected). */
185
- remove: (id: string) => Promise<void>;
186
- }
187
- /**
188
- * One write handed to an {@link OutboxSink}. Mirrors {@link PersistedMutation}
189
- * plus the custom-mutator identity (`clientId`/`mutationId`/`idempotencyKey`)
190
- * the durable outbox needs to dedupe and watermark replays.
191
- */
192
- interface OutboxMutation {
193
- args: Record<string, unknown>;
194
- /** Stable per-client id; pairs with {@link OutboxMutation.mutationId} as `idempotencyKey`. */
195
- clientId: string;
196
- functionPath: string;
197
- /** `${clientId}:${mutationId}` — sent as `x-lunora-mutation-id` so a replay is server-idempotent. */
198
- idempotencyKey: string;
199
- /** Issuing identity fingerprint (`null` = signed out); drives the sink's identity guard. */
200
- identity: string | null;
201
- /** Monotonic per-client mutation id, backing the server `__client_watermark`. */
202
- mutationId: number;
203
- shardKey?: string;
204
- }
205
- /**
206
- * Pluggable durable outbox seam. When set on {@link LunoraClientOptions.outbox},
207
- * the client delegates offline write durability + at-least-once replay to this
208
- * sink instead of its built-in {@link PersistenceAdapter}-backed `OfflineQueue`.
209
- * `@lunora/db` supplies the blessed implementation (`createExecutorOutboxSink`,
210
- * backed by the TanStack `OfflineExecutor`); the interface itself is
211
- * dependency-free so `@lunora/client` stays TanStack-free.
212
- */
213
- interface OutboxSink {
214
- /**
215
- * Persist and schedule a write for replay. Rejects with an
216
- * `OFFLINE_QUEUE_OVERFLOW`-coded error when the sink's cap is exceeded, so
217
- * the caller can surface back-pressure to the issuing mutation.
218
- */
219
- enqueue: (mutation: OutboxMutation) => Promise<void>;
220
- }
221
- /**
222
- * One persisted query result in the durable read cache (Pillar 2). Keyed in the
223
- * store by `shardKey + functionPath + argsKey`; the record carries everything
224
- * needed to render offline on reload and to resume the live subscription.
225
- */
226
- interface CachedQuery {
227
- /**
228
- * Issuing identity fingerprint (same shape the offline queue stamps). A
229
- * cached value only hydrates when it matches the current identity, so a
230
- * signed-out cache never leaks into a new session. `null` = cached while
231
- * signed out.
232
- */
233
- identity: string | null;
234
- /**
235
- * The `cursor` high-watermark this value reflects, replayed as `sinceSeq`
236
- * on reconnect so the server can resume instead of re-snapshotting. Absent
237
- * when the value predates CDC / no cursor was advertised.
238
- */
239
- serverCursor?: number;
240
- /**
241
- * The CDC `epoch` the `serverCursor` belongs to, replayed as `sinceEpoch`
242
- * on reconnect so the server only resumes when the client is still on the
243
- * same changelog timeline. Absent when no epoch was advertised.
244
- */
245
- serverEpoch?: string;
246
- /** Wall-clock millis the value was written — drives LRU eviction. */
247
- ts: number;
248
- /** The full query result last seen from the server. */
249
- value: unknown;
250
- /**
251
- * App/schema version stamped when persisted (from `LunoraClientOptions.persistenceVersion`).
252
- * A cached value whose `version` doesn't match the current one is not hydrated —
253
- * so a result of a now-changed shape from an older deploy can't render. Absent
254
- * when no `persistenceVersion` is configured (no version gating).
255
- */
256
- version?: string;
257
- }
258
- /** A stored read-cache row: the {@link CachedQuery} plus the key it is stored under. */
259
- interface StoredQuery extends CachedQuery {
260
- key: string;
261
- }
262
- /**
263
- * Durable store for the client read cache (Pillar 2): query results survive a
264
- * reload so reads hydrate from disk and render immediately while the socket
265
- * reconnects. Opt-in via {@link LunoraClientOptions.queryCache}; omit to keep
266
- * reads in memory only (today's behaviour). Mirrors {@link PersistenceAdapter}'s
267
- * shape over the same IndexedDB plumbing.
268
- */
269
- interface QueryCacheAdapter {
270
- /** Drop every cached query (e.g. on logout / identity change). */
271
- clear: () => Promise<void>;
272
- /** Load every cached query — called once at startup to hydrate reads. */
273
- load: () => Promise<StoredQuery[]>;
274
- /** Upsert one cached query by key (called when a subscription value advances). */
275
- put: (key: string, entry: CachedQuery) => Promise<void>;
276
- /** Remove one cached query by key. */
277
- remove: (key: string) => Promise<void>;
278
- }
279
- /**
280
- * Resolves the WS `?token=` credential fresh at every (re)connect — the channel
281
- * for short-lived tokens (e.g. the ephemeral admin sub-token the worker mints
282
- * at `POST /_lunora/admin/ws-token`) instead of a static secret in the URL.
283
- * May return the token synchronously or as a Promise; returning `undefined`
284
- * connects without a token. A thrown error / rejected Promise fails that
285
- * connect attempt, and the client retries with its normal reconnect backoff.
286
- */
287
- type WsTokenProvider = () => Promise<string | undefined> | string | undefined;
288
- interface LunoraClientOptions {
289
- /**
290
- * Base path the worker mounts better-auth at, used by the client's
291
- * `getCurrentUser()` to reach the `get-session` route. Defaults to
292
- * `/api/auth` (matching `@lunora/auth`'s `DEFAULT_AUTH_BASE_PATH`).
293
- */
294
- authBasePath?: string;
295
- bookmarkStorage?: BookmarkStorage;
296
- /**
297
- * Stable per-client id backing the custom-mutator watermark. Sent on the
298
- * `connect` envelope (so the server can scope this client's
299
- * `__client_watermark`) and stamped onto every {@link OutboxMutation} the
300
- * {@link LunoraClientOptions.outbox} sink persists, where it pairs with the
301
- * monotonic mutation id to form the idempotency key. The `@lunora/db` path
302
- * persists a stable id alongside the outbox and passes it here; omit for the
303
- * standalone client, which generates an ephemeral per-session id.
304
- */
305
- clientId?: string;
306
- /**
307
- * Default app context sent in the `connect` envelope right after each socket
308
- * opens, forwarded to the server's `onConnect`/`onDisconnect` lifecycle hooks
309
- * as `event.context`. A per-shard context registered via
310
- * `setConnectionContext` overrides this for that shard. Omit when no lifecycle
311
- * hook needs connection context.
312
- */
313
- connectionContext?: Record<string, unknown>;
314
- /**
315
- * Fail-fast timeout (ms) for opening a subscription WebSocket. If the
316
- * handshake doesn't complete within this window — a hung dev proxy or a cold
317
- * worker that never upgrades — the client force-closes the socket and routes
318
- * through its normal reconnect/backoff (surfacing `offline` status) instead
319
- * of leaving the live channel silently stuck on the browser's much longer
320
- * default. Does not affect HTTP queries/mutations (those never ride the WS).
321
- * Defaults to 10000 (10s); set to `0` (or negative) to disable.
322
- */
323
- connectTimeoutMs?: number;
324
- /**
325
- * When `true`, tabs sharing the same origin coordinate via BroadcastChannel
326
- * so only one tab (the "leader") opens WebSocket connections to the server.
327
- * Follower tabs receive subscription data through the channel instead.
328
- *
329
- * Reduces simultaneous WS connections, bandwidth, and cross-tab state drift.
330
- * Requires `BroadcastChannel` (browser-only); silently ignored otherwise.
331
- * Defaults to `false`.
332
- */
333
- crossTabSync?: boolean;
334
- fetch?: typeof fetch;
335
- /**
336
- * Interval (ms) between keepalive pings sent on each open subscription
337
- * socket. The server answers them via the Durable Object's hibernation
338
- * auto-response WITHOUT waking the DO, so an idle socket stays alive across
339
- * hibernation without a billable wakeup. Defaults to 30000 (30s); set to
340
- * `0` (or a negative value) to disable the heartbeat entirely.
341
- */
342
- heartbeatIntervalMs?: number;
343
- /**
344
- * When `true` and a `queryCache` is active, framework hooks (React, Vue, …)
345
- * wait for the durable cache to finish hydrating before their first render
346
- * with an enabled subscription, so users see cached data instead of an
347
- * undefined flash before the socket round-trip. Defaults to `false`.
348
- *
349
- * Requires `queryCache` to be set (not `false`); silently ignored otherwise.
350
- */
351
- hydrateOnStart?: boolean;
352
- offlineQueue?: OfflineQueueOptions;
353
- /**
354
- * Durable outbox seam for offline writes. When supplied (the `@lunora/db`
355
- * path wires `createExecutorOutboxSink`), offline mutations are delegated to
356
- * the sink and the built-in {@link PersistenceAdapter}-backed `OfflineQueue`
357
- * is bypassed, so a db app has exactly one durable write path. Omit for the
358
- * standalone client, which keeps using {@link LunoraClientOptions.persistence}.
359
- */
360
- outbox?: OutboxSink;
361
- /**
362
- * Durable store for the offline mutation queue. Tri-state — an explicit
363
- * {@link PersistenceAdapter} is used as-is; `false` opts out (the queue stays
364
- * in memory, lost on reload); omitted (the default) auto-probes a durable
365
- * IndexedDB store when the `indexedDB` global is present (browsers), otherwise
366
- * in-memory, so SSR/Node/React-Native keep the in-memory behaviour and only
367
- * environments that can persist do. Pass `createAsyncStoragePersistence()` on
368
- * React Native.
369
- */
370
- persistence?: false | PersistenceAdapter;
371
- /**
372
- * App/schema version stamped onto every persisted queued write and cached
373
- * read. Bump it on a breaking change to a function signature or query shape:
374
- * on the next boot, persisted writes / cached reads stamped with a different
375
- * version are dropped (and purged) rather than replayed / hydrated against the
376
- * new schema. Omit to disable version gating (records are never invalidated by
377
- * version).
378
- *
379
- * **Adoption is itself an invalidation event:** records written before you set
380
- * `persistenceVersion` carry no version, so the first boot after enabling it
381
- * purges all currently-queued offline writes (and cached reads) as stale. Adopt
382
- * it on a build where that clean slate is acceptable — typically the same
383
- * breaking deploy you're protecting against — not purely speculatively.
384
- */
385
- persistenceVersion?: string;
386
- /**
387
- * Durable store for the read cache (Pillar 2). When active, query results
388
- * are persisted as their subscriptions advance and hydrated on construction
389
- * so a reload renders cached data before the socket reconnects, then resumes
390
- * the live subscription from the persisted cursor. Tri-state — an explicit
391
- * {@link QueryCacheAdapter} is used as-is; `false` opts out (reads stay in
392
- * memory only); omitted (the default) auto-probes IndexedDB exactly like
393
- * {@link LunoraClientOptions.persistence}.
394
- */
395
- queryCache?: QueryCacheAdapter | false;
396
- reconnect?: ReconnectOptions;
397
- url: string;
398
- WebSocket?: typeof WebSocket;
399
- /**
400
- * Credential appended to the WebSocket URL as `?token=…`. The server matches
401
- * it against `LUNORA_WS_BEARER` (to clear the upgrade gate) and/or
402
- * `LUNORA_ADMIN_TOKEN` (to authorize `__lunora_admin__:*` subscriptions —
403
- * what the studio supplies). Browsers can't set headers on the `WebSocket`
404
- * constructor, so the query parameter is the only channel; it ends up in
405
- * server logs and history, so prefer a short-lived rotating token in
406
- * production over a static secret.
407
- *
408
- * Pass a {@link WsTokenProvider} function to resolve the token fresh at
409
- * every (re)connect — the channel for short-lived credentials such as the
410
- * ephemeral admin sub-token minted by `POST /_lunora/admin/ws-token`: the
411
- * provider re-mints on each reconnect, including the one following a `4001`
412
- * token-expired drop, so a static master token never has to ride the URL.
413
- */
414
- wsToken?: string | WsTokenProvider;
415
- wsUrl?: string;
416
- }
417
- /** Wire envelope sent on `POST /_lunora/rpc`. */
418
- interface RpcEnvelope {
419
- args?: Record<string, unknown>;
420
- /**
421
- * Stable per-client identifier (custom-mutator push path). Pairs with
422
- * {@link RpcEnvelope.mutationId} to form `idempotencyKey` and scope the
423
- * server `__client_watermark`. Absent on plain `client.mutation` calls.
424
- */
425
- clientId?: string;
426
- functionPath: string;
427
- /**
428
- * Idempotency key (`${clientId}:${mutationId}`) for the custom-mutator push
429
- * path, mirrored into the `x-lunora-mutation-id` header. Absent on plain
430
- * `client.mutation` calls.
431
- */
432
- idempotencyKey?: string;
433
- /**
434
- * Monotonic per-client mutation id (custom-mutator push path), backing the
435
- * server-side per-client watermark: `id <= watermark` is a replay (skipped),
436
- * `id == watermark + 1` runs authoritatively, `id > watermark + 1` halts the
437
- * batch so the client resends from `watermark + 1`. Absent on plain
438
- * `client.mutation` calls.
439
- */
440
- mutationId?: number;
441
- shardKey?: string;
442
- }
443
- /**
444
- * Wire response from the shard's `/rpc` endpoint (forwarded by the runtime). A
445
- * watermarked custom-mutator push additionally carries `lastMutationId` — the
446
- * highest per-client sequence the DO has applied — which the client uses to keep
447
- * its `clientSeq` generator monotonic across reloads (see `LunoraClient.callMutator`).
448
- * A plain mutation on a CDC shard carries `commitCursor` — the cursor the write
449
- * committed at — which gates the drop of a per-call optimistic layer.
450
- */
451
- type RpcResponseBody = {
452
- error: {
453
- code: string;
454
- data?: unknown;
455
- message: string;
456
- };
457
- } | {
458
- commitCursor?: number;
459
- lastMutationId?: number;
460
- result: unknown;
461
- };
462
- /** Subscription protocol — client → server. */
463
- interface ClientSubscribeMessage {
464
- id: string;
465
- /**
466
- * `sinceSeq` is the persisted `cursor` high-watermark the client last saw
467
- * for this shard (Pillar 1b resume). Present only when a durable
468
- * {@link QueryCacheAdapter} restored a cached value with a cursor; the
469
- * server replies with a lightweight `resume` frame instead of a full
470
- * snapshot when nothing the query reads changed since it. Absent on a
471
- * first-time subscribe.
472
- */
473
- query: {
474
- args?: Record<string, unknown>;
475
- functionPath?: string;
476
- sinceEpoch?: string;
477
- sinceSeq?: number;
478
- table?: string;
479
- };
480
- type: "subscribe";
481
- }
482
- interface ClientUnsubscribeMessage {
483
- id: string;
484
- type: "unsubscribe";
485
- }
486
- /**
487
- * One-shot control frame sent right after the socket opens. Registers the
488
- * connection's app `context` (e.g. `{ roomId, sessionId }`) with the server and
489
- * fires the `onConnect` lifecycle hooks; the same context is replayed to
490
- * `onDisconnect` when the socket drops.
491
- */
492
- interface ClientConnectMessage {
493
- /**
494
- * Wire behaviours this client can handle that an older one cannot, so the
495
- * server can use them without breaking clients that can't. Currently just
496
- * `"pageDelta"`; see `shared/page-result.ts` for what it promises and why it
497
- * must be announced rather than assumed. Omitting it is always safe.
498
- */
499
- caps?: ReadonlyArray<string>;
500
- /**
501
- * Stable per-client id (persisted alongside the outbox). Lets the server
502
- * scope this connection's `__client_watermark` so custom-mutator pokes can
503
- * echo the right per-client `lastMutationId`. Omitted by clients that don't
504
- * use custom mutators.
505
- */
506
- clientId?: string;
507
- context?: Record<string, unknown>;
508
- id: string;
509
- type: "connect";
510
- }
511
- /**
512
- * Subscribe to a declarative **shape** — server-side partial replication scoped
513
- * by `shardBy` + the shape's predicate + RLS. The client sends the shape *name*
514
- * + validated `args`; the server resolves the trusted `where` (identity/RLS
515
- * `baseWhere` the client can't forge) and streams the matching rowset, then live
516
- * {@link ServerPokePartMessage} diffs. `id` namespaces the subscription and is
517
- * echoed as `shapeId` on every poke part.
518
- */
519
- interface ClientShapeSubscribeMessage {
520
- id: string;
521
- shape: {
522
- args?: Record<string, unknown>;
523
- name: string;
524
- };
525
- /**
526
- * Resume from this checkpoint (the `__cdc_log` cursor the client last
527
- * applied for this shape). When absent or below the server's retained floor
528
- * (`minCdcSeq`), the server re-seeds with a full insert-poke instead of a
529
- * delta.
530
- */
531
- sinceCheckpoint?: number;
532
- /**
533
- * The CDC epoch {@link ClientShapeSubscribeMessage.sinceCheckpoint} belongs
534
- * to. A mismatch (forked changelog timeline) forces a full re-seed even when
535
- * the cursor is numerically in range.
536
- */
537
- sinceEpoch?: string;
538
- type: "shape_subscribe";
539
- }
540
- /** Cancel a shape subscription started with the same `id`. */
541
- interface ClientShapeUnsubscribeMessage {
542
- id: string;
543
- type: "shape_unsubscribe";
544
- }
545
- interface ClientAckMessage {
546
- id: string;
547
- type: "ack";
548
- }
549
- /**
550
- * Start a streaming query. The id namespaces a fresh stream and is echoed on
551
- * every {@link ServerChunkMessage} the server pushes back. Cancel a running
552
- * stream by sending a {@link ClientUnsubscribeMessage} with the same id —
553
- * subscription and stream id-spaces share the cancel channel; the prefix
554
- * (`sub_*` vs `stream_*`) keeps the local registries searchable.
555
- */
556
- interface ClientStreamMessage {
557
- /**
558
- * Run generation the {@link ClientStreamMessage.sinceChunk} watermark
559
- * belongs to: the `generation` stamp carried by the chunk frames this
560
- * client already received, echoed back on a resume. The server refuses to
561
- * splice a different run's tail onto the held prefix — a mismatch fails
562
- * with `STREAM_INTERRUPTED` instead. Omitted on a first attach.
563
- */
564
- generation?: number;
565
- id: string;
566
- query: {
567
- args?: Record<string, unknown>;
568
- functionPath: string;
569
- shardKey?: string;
570
- };
571
- /**
572
- * Resume watermark: the highest chunk `seq` this client already received.
573
- * Only meaningful for a stream the server declared `durable` — the run
574
- * replays everything after it and then continues live, which is what turns
575
- * a reconnect into a resume instead of a lost generation. Omitted on a
576
- * first attach.
577
- *
578
- * Named `sinceChunk`, not `sinceSeq`, because a subscribe envelope already
579
- * carries a `query.sinceSeq` meaning the CDC cursor.
580
- */
581
- sinceChunk?: number;
582
- type: "stream";
583
- }
584
- /**
585
- * Join or leave a whisper `topic` — an app-chosen ephemeral channel scoped to a
586
- * shard. While joined, the client receives every {@link ServerWhisperMessage}
587
- * other members broadcast to the topic.
588
- */
589
- interface ClientWhisperSubscribeMessage {
590
- topic: string;
591
- type: "whisper_subscribe" | "whisper_unsubscribe";
592
- }
593
- /**
594
- * Broadcast ephemeral `data` to the topic's other members on the shard. The
595
- * payload is relayed verbatim with no server-side persistence (no SQLite/CDC
596
- * write) — for typing indicators, live cursors, presence pings. The sender does
597
- * not receive its own whisper.
598
- */
599
- interface ClientWhisperMessage {
600
- data?: unknown;
601
- topic: string;
602
- type: "whisper";
603
- }
604
- type ClientMessage = ClientAckMessage | ClientConnectMessage | ClientShapeSubscribeMessage | ClientShapeUnsubscribeMessage | ClientStreamMessage | ClientSubscribeMessage | ClientUnsubscribeMessage | ClientWhisperMessage | ClientWhisperSubscribeMessage;
605
- /** Subscription protocol — server → client. */
606
- interface ServerDataMessage {
607
- /**
608
- * The `__cdc_log` high-watermark covered by this frame (Pillar 1b). The
609
- * client persists it as the query's `serverCursor` and replays it as
610
- * `sinceSeq` on the next reconnect. Absent on shards that never enabled CDC.
611
- */
612
- cursor?: number;
613
- data?: unknown;
614
- delta?: unknown;
615
- /** The CDC epoch this frame's cursor belongs to (see {@link CachedQuery.serverEpoch}). */
616
- epoch?: string;
617
- id: string;
618
- /**
619
- * The highest custom-mutator `mutationId` from this client the server has
620
- * now applied (the per-client `__client_watermark`). Echoed so the client's
621
- * outbox can drop confirmed pending mutations and let TanStack DB collapse
622
- * the matching optimistic overlay. Absent on shards without custom mutators.
623
- */
624
- lastMutationId?: number;
625
- type: "data" | "delta";
626
- }
627
- /**
628
- * Lightweight resume acknowledgement (Pillar 1b): the server determined that
629
- * nothing the subscription reads changed since the client's `sinceSeq`, so it
630
- * skips re-sending the snapshot. The client keeps its cached value and only
631
- * advances `serverCursor` to `cursor`.
632
- */
633
- interface ServerResumeMessage {
634
- cursor?: number;
635
- /** The CDC epoch this resume's cursor belongs to (see {@link CachedQuery.serverEpoch}). */
636
- epoch?: string;
637
- id: string;
638
- /** Per-client custom-mutator watermark (see {@link ServerDataMessage.lastMutationId}). */
639
- lastMutationId?: number;
640
- type: "resume";
641
- }
642
- /**
643
- * Settled acknowledgement for a **list** subscription: a write touched one of
644
- * the subscription's read tables but produced a byte-identical result, so the
645
- * server suppressed the data frame. Sent ONLY to a `@lunora/db` custom-mutator
646
- * client (one that announced a `clientId`, hence has a server-side
647
- * `__client_watermark`) so its optimistic list overlay drops even when no data
648
- * frame arrives. Plain `useQuery` subscribers never receive it, and an older
649
- * client safely ignores the unknown frame.
650
- */
651
- interface ServerSettledMessage {
652
- cursor?: number;
653
- /** The CDC epoch this settled frame's cursor belongs to (see {@link CachedQuery.serverEpoch}). */
654
- epoch?: string;
655
- id: string;
656
- /**
657
- * The highest custom-mutator `mutationId` from this client the server has
658
- * now applied (the per-client `__client_watermark`). Forwarded to a
659
- * collection's `onCheckpoint` so it can drop the overlay for the confirmed
660
- * write whose result didn't change this list.
661
- */
662
- lastMutationId?: number;
663
- type: "settled";
664
- }
665
- interface ServerErrorMessage {
666
- error?: unknown;
667
- id?: string;
668
- message?: string;
669
- type: "error";
670
- }
671
- interface ServerAckMessage {
672
- id: string;
673
- type: "ack";
674
- }
675
- interface ServerCompleteMessage {
676
- id: string;
677
- type: "complete";
678
- }
679
- /** One frame of a streaming query — `data` carries the user-yielded chunk. */
680
- interface ServerChunkMessage {
681
- data: unknown;
682
- /**
683
- * Generation stamp of the **durable** run this chunk belongs to. The client
684
- * stores it beside {@link ServerChunkMessage.seq} and echoes it as
685
- * {@link ClientStreamMessage.generation} on a resume, so the server can
686
- * tell a genuine resume from an attempt to splice onto a different run
687
- * under the same key. Absent on an ephemeral stream.
688
- */
689
- generation?: number;
690
- id: string;
691
- /**
692
- * Monotonic position of this chunk within a **durable** run, starting at 1.
693
- * The client stores the last one it saw and replays it as
694
- * {@link ClientStreamMessage.sinceChunk} when the socket comes back. Absent
695
- * on an ephemeral stream, which has nothing to resume from.
696
- */
697
- seq?: number;
698
- type: "chunk";
699
- }
700
- /**
701
- * An ephemeral whisper relayed from another member of `topic` on the same shard
702
- * (AnyCable-style whispering). `data` is the sender's payload verbatim; `from`
703
- * is the sender's verified user id when known (absent for an anonymous sender).
704
- * Never persisted server-side.
705
- */
706
- interface ServerWhisperMessage {
707
- data: unknown;
708
- from?: string;
709
- topic: string;
710
- type: "whisper";
711
- }
712
- /**
713
- * One row-level change in a shape's replication stream — the wire form of the
714
- * DO's `__cdc_log` `CdcChange`. `insert`/`update` carry the post-image in
715
- * `value` (projected to the shape's `columns`); `delete` omits it, identifying
716
- * the removed row by `key` alone. The client applies these to its local
717
- * collection; an unknown `key` on a `delete` is a safe no-op (a row the client
718
- * never had in this shape).
719
- */
720
- interface RowOp {
721
- /** Row primary key (`_id`). */
722
- key: string;
723
- op: "delete" | "insert" | "update";
724
- /** Logical table the row belongs to. */
725
- table: string;
726
- /** Post-image document for insert/update; absent on delete. */
727
- value?: Record<string, unknown>;
728
- }
729
- /**
730
- * Opens a **poke** — an atomically-applied batch of shape diffs (Zero's poke
731
- * protocol). A `pokeStart` is followed by zero or more {@link ServerPokePartMessage}
732
- * frames and closed by exactly one {@link ServerPokeEndMessage}; the client
733
- * buffers every part and applies them in a single transaction at `pokeEnd`, so a
734
- * socket that drops mid-poke simply re-seeds on reconnect (no torn view).
735
- */
736
- interface ServerPokeStartMessage {
737
- /**
738
- * Poke-level fallback base, stamped by single-part senders. Per-shape
739
- * {@link ServerPokePartMessage.baseCheckpoint} takes precedence; this is what
740
- * a part without its own base falls back to.
741
- */
742
- baseCheckpoint?: number;
743
- /** CDC epoch this poke belongs to; a mismatch forces the client to re-seed rather than apply. */
744
- epoch?: string;
745
- /** Correlates this poke's `pokeStart`/`pokePart`/`pokeEnd` frames. */
746
- pokeId: string;
747
- type: "pokeStart";
748
- }
749
- /** One shape's slice of an in-flight poke: the row-ops to apply for `shapeId`. */
750
- interface ServerPokePartMessage {
751
- /**
752
- * The checkpoint this shape's view must be at for `rowsPatch` to splice on
753
- * cleanly. Per shape, because every shape on a socket has its own
754
- * delivered-through cursor. Absent when the server cannot name a base — the
755
- * gap check is then disarmed for this part, never guessed at.
756
- */
757
- baseCheckpoint?: number;
758
- /** Per-client custom-mutator watermark carried with this slice (see {@link ServerSettledMessage.lastMutationId}). */
759
- lastMutationId?: number;
760
- pokeId: string;
761
- /**
762
- * `true` when `rowsPatch` is the shape's COMPLETE membership, not a diff (a
763
- * full seed or re-seed). The client MUST drop its current view for this shape
764
- * before applying: a seed is inserts-only, so merging it leaves any row that
765
- * left the shape while the client was disconnected on screen forever.
766
- *
767
- * Never inferred from an absent {@link ServerPokePartMessage.baseCheckpoint} —
768
- * most live poke paths legitimately carry no base.
769
- */
770
- reset?: boolean;
771
- /** Ordered row-level changes for this shape, applied in sequence at `pokeEnd`. */
772
- rowsPatch: RowOp[];
773
- /** The {@link ClientShapeSubscribeMessage.id} these row-ops belong to. */
774
- shapeId: string;
775
- type: "pokePart";
776
- }
777
- /**
778
- * Closes a poke: the client commits the buffered parts atomically and advances
779
- * its checkpoint to {@link ServerPokeEndMessage.checkpoint} (the `__cdc_log`
780
- * cursor high-watermark the view now reflects), replayed as `sinceCheckpoint` on
781
- * the next reconnect.
782
- */
783
- interface ServerPokeEndMessage {
784
- /** The `__cdc_log` cursor the view is at after applying this poke. */
785
- checkpoint?: number;
786
- /** CDC epoch the {@link ServerPokeEndMessage.checkpoint} belongs to. */
787
- epoch?: string;
788
- pokeId: string;
789
- type: "pokeEnd";
790
- }
791
- type ServerMessage = ServerAckMessage | ServerChunkMessage | ServerCompleteMessage | ServerDataMessage | ServerErrorMessage | ServerPokeEndMessage | ServerPokePartMessage | ServerPokeStartMessage | ServerResumeMessage | ServerSettledMessage | ServerWhisperMessage;
792
- /**
793
- * The authenticated user as exposed client-side, mirroring better-auth's
794
- * `user` row (the `user` field of the `get-session` response). Kept minimal
795
- * and structural — only `id` is guaranteed; the rest are the common better-auth
796
- * fields, and the index signature carries any plugin-contributed extras.
797
- */
798
- interface User {
799
- readonly createdAt?: NullableTimestamp;
800
- readonly email?: null | string;
801
- readonly emailVerified?: boolean | null;
802
- readonly id: string;
803
- readonly image?: null | string;
804
- readonly name?: null | string;
805
- readonly [key: string]: unknown;
806
- readonly updatedAt?: NullableTimestamp;
807
- }
808
- /**
809
- * One pending scheduled function, as returned by the worker's
810
- * `GET /_lunora/admin/scheduled` endpoint. Mirrors `@lunora/scheduler`'s
811
- * `ScheduleRecord` structurally so the client carries no dependency on it.
812
- */
813
- interface ScheduleRecord {
814
- args: Record<string, unknown>;
815
- /**
816
- * Dispatch attempts already made. Absent (treated as 0) until the first
817
- * failure; on a dead-letter record it is the exhausted count (> the retry
818
- * budget). Surfaced so the studio can show how hard a job tried before it
819
- * was parked.
820
- */
821
- attempts?: number;
822
- enqueuedAt: number;
823
- functionPath: string;
824
- id: string;
825
- /** Logical workpool the job is routed to (concurrency-gated), when any. */
826
- pool?: string;
827
- scheduledFor: number;
828
- shardKey?: string;
829
- }
830
- /**
831
- * One workpool's live backlog, as returned by the worker's
832
- * `GET /_lunora/admin/scheduled/status` endpoint. Mirrors `@lunora/scheduler`'s
833
- * `SchedulerPoolStatus` structurally so the client carries no dependency on it.
834
- */
835
- interface SchedulerPoolStatus {
836
- /** Jobs currently dispatched-but-not-yet-completed (the held concurrency slots). */
837
- inFlight: number;
838
- /** The pool's concurrency cap. */
839
- maxConcurrency: number;
840
- /** The logical workpool name. */
841
- name: string;
842
- /** Pending jobs routed to this pool but not yet dispatched. */
843
- queued: number;
844
- }
845
- /**
846
- * The app-level scheduler backlog, as returned by the worker's
847
- * `GET /_lunora/admin/scheduled/status` endpoint. `pools` is the per-pool
848
- * breakdown; `backlog` and `inFlight` are the app-wide sums of `queued` and
849
- * `inFlight` across every pool — the headline numbers for the studio SLO
850
- * view. Mirrors `@lunora/scheduler`'s `SchedulerStatus` structurally.
851
- */
852
- interface SchedulerStatus {
853
- /** Sum of every pool's `queued` count — the total pending backlog. */
854
- backlog: number;
855
- /** Sum of every pool's `inFlight` count — the total held concurrency slots. */
856
- inFlight: number;
857
- /** Per-pool backlog breakdown. */
858
- pools: SchedulerPoolStatus[];
859
- }
860
- /**
861
- * One shard's request volume, as returned by the worker's
862
- * `POST /_lunora/admin/shard-traffic` endpoint. The cross-shard traffic feed
863
- * the studio's `hot_shard` advisor lint consumes: `requests` is the shard's
864
- * lifetime dispatch total, `shardKey` the DO id name (`""` for the root shard).
865
- */
866
- interface ShardTrafficEntry {
867
- requests: number;
868
- shardKey: string;
869
- }
870
- /**
871
- * The whole-shard-set traffic distribution returned by the worker's
872
- * `POST /_lunora/admin/shard-traffic` endpoint. `shards` is one entry per live
873
- * shard (a failed shard surfaces with `requests: 0`); `ok`/`failed` count the
874
- * shards that returned vs. errored. Shaped to feed the advisor's `hot_shard`
875
- * lint after the studio tags each entry with its sharded function `group`.
876
- */
877
- interface ShardTrafficResult {
878
- failed: number;
879
- ok: number;
880
- shards: ShardTrafficEntry[];
881
- }
882
- /**
883
- * One object in the storage bucket, as returned by the worker's
884
- * `GET /_lunora/admin/storage` endpoint. Mirrors `@lunora/storage`'s
885
- * `R2ObjectLike` structurally.
886
- */
887
- interface StorageObject {
888
- customMetadata?: Record<string, string>;
889
- etag: string;
890
- httpMetadata?: {
891
- contentType?: string;
892
- };
893
- key: string;
894
- size: number;
895
- /**
896
- * When the object was stored. R2 emits a `Date`, which JSON-serializes to an
897
- * ISO string over the wire; a mock may supply epoch ms — so consumers should
898
- * normalise via `new Date(uploaded)`. Absent if the backend didn't report it.
899
- */
900
- uploaded?: number | string;
901
- }
902
- /** One page of {@link StorageObject}s plus the cursor to fetch the next, if any. */
903
- interface StorageListPage {
904
- cursor?: string;
905
- objects: StorageObject[];
906
- }
907
- /**
908
- * One argument of a registered function, derived from its `v.*` validator by the
909
- * worker. A compact signature shape — enough to render a function's API without
910
- * the build-time codegen types.
911
- */
912
- interface FunctionArgumentDescriptor {
913
- /** Element validator kind for an `array` arg (one level), e.g. `string`. */
914
- element?: string;
915
- /** The (optional-unwrapped) validator kind, e.g. `string`, `id`, `object`. */
916
- kind: string;
917
- /** The argument name. */
918
- name: string;
919
- /** True when the arg is wrapped in `v.optional(...)`. */
920
- optional: boolean;
921
- /** Target table for an `id` arg (`v.id("table")`). */
922
- table?: string;
923
- }
924
- /**
925
- * One registered function, as returned by the worker's
926
- * `GET /_lunora/admin/functions` endpoint: its `<file>:<function>` path, which
927
- * client method (`query` / `mutation` / `action`) invokes it, and its argument
928
- * signature. `args` is absent on responses from an older worker.
929
- */
930
- interface FunctionDescriptor {
931
- args?: FunctionArgumentDescriptor[];
932
- kind: "action" | "mutation" | "query";
933
- path: string;
934
- }
935
- /** A `.global()` (D1-backed) table plus its row count, from `/_lunora/admin/global/tables`. */
936
- interface GlobalTableInfo {
937
- name: string;
938
- rowCount: number;
939
- }
940
- /** A window of rows from one global table, from `/_lunora/admin/global/table`. */
941
- interface GlobalTablePage {
942
- columns: string[];
943
- /** FK columns (local column → referenced table) for external tables with real `REFERENCES` constraints, from `PRAGMA foreign_key_list`. */
944
- refs?: Record<string, string>;
945
- rows: Record<string, unknown>[];
946
- total: number;
947
- }
948
- /**
949
- * One equality constraint a facet-value click adds to the global browser's view
950
- * (`column = value`). `value` is the raw stored scalar the facet returned, sent
951
- * as-is and bound server-side, so it never injects SQL.
952
- */
953
- interface GlobalFilterClause {
954
- column: string;
955
- value: unknown;
956
- }
957
- /** One distinct value of a faceted global column with its row count, from `/_lunora/admin/global/facet`. */
958
- interface GlobalFacetValue {
959
- count: number;
960
- value: unknown;
961
- }
962
- /** Per-column distinct-value summary for the global browser, from `/_lunora/admin/global/facet`. */
963
- interface GlobalFacetResult {
964
- truncated: boolean;
965
- values: GlobalFacetValue[];
966
- }
967
- /** A nullable timestamp field as better-auth serializes it: epoch-ms, ISO string, or null. */
968
- type NullableTimestamp = null | number | string;
969
- /** A workflow instance's lifecycle status. Mirrors Cloudflare's `InstanceStatus`. */
970
- type WorkflowInstanceStatus = "complete" | "errored" | "paused" | "queued" | "running" | "terminated" | "unknown" | "waiting" | "waitingForPause";
971
- /** The lifecycle mutations the status endpoint accepts. */
972
- type WorkflowInstanceAction = "pause" | "resume" | "terminate";
973
- /** One row of the workflow-instances list. */
974
- interface WorkflowInstanceSummary {
975
- createdOn?: string;
976
- endedOn?: string;
977
- id: string;
978
- startedOn?: string;
979
- status: WorkflowInstanceStatus;
980
- }
981
- /** One durable step of an instance's execution timeline. */
982
- interface WorkflowStepDetail {
983
- /** 1-based attempt count (`> 1` means the step retried). */
984
- attempts?: number;
985
- end?: string;
986
- error?: unknown;
987
- name: string;
988
- output?: unknown;
989
- start?: string;
990
- success?: boolean;
991
- /** `step` / `sleep` / `waitForEvent` / … (Cloudflare's step `type`). */
992
- type?: string;
993
- }
994
- /** A workflow instance's full detail: summary plus params/output/error and the step timeline. */
995
- interface WorkflowInstanceDetail extends WorkflowInstanceSummary {
996
- error?: unknown;
997
- output?: unknown;
998
- params?: unknown;
999
- steps: WorkflowStepDetail[];
1000
- }
1001
- /** A page of workflow instances. */
1002
- interface WorkflowInstancePage {
1003
- /**
1004
- * Whether workflow inspection is configured on the worker (a Cloudflare
1005
- * account id + API token). `false` when the admin proxy reports it can't
1006
- * inspect instances; omitted (treated as configured) otherwise. Lets a
1007
- * caller render a "set credentials" state without a failed request.
1008
- */
1009
- configured?: boolean;
1010
- instances: WorkflowInstanceSummary[];
1011
- page: number;
1012
- perPage: number;
1013
- totalCount?: number;
1014
- }
1015
- export { ArgsOf as A, BookmarkStorage as B, CachedQuery as C, RpcEnvelope as D, RpcResponseBody as E, FunctionReference as F, GlobalTableInfo as G, HttpStreamRef as H, SchedulerPoolStatus as I, ServerMessage as J, ServerPokeEndMessage as K, LunoraClientOptions as L, ServerPokePartMessage as M, ServerPokeStartMessage as N, OfflineQueueOptions as O, Preloaded as P, QueryCacheAdapter as Q, ReturnOf as R, ShardTrafficResult as S, ShardTrafficEntry as T, User as U, StorageObject as V, WsTokenProvider as W, StoredQuery as X, WorkflowInstanceSummary as Y, WorkflowStepDetail as Z, Unsubscribe as a, ScheduleRecord as b, SchedulerStatus as c, WorkflowInstanceStatus as d, WorkflowInstancePage as e, WorkflowInstanceDetail as f, WorkflowInstanceAction as g, FunctionDescriptor as h, StorageListPage as i, GlobalFilterClause as j, GlobalTablePage as k, GlobalFacetResult as l, HttpStreamArgsOf as m, HttpStreamChunkOf as n, PersistenceAdapter as o, ReconnectOptions as p, ClientMessage as q, ClientShapeSubscribeMessage as r, ClientShapeUnsubscribeMessage as s, FunctionArgumentDescriptor as t, GlobalFacetValue as u, HttpStreamCallArgs as v, OutboxMutation as w, OutboxSink as x, PersistedMutation as y, RowOp as z };