@streamsy/core 0.1.0 → 0.2.1

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 (3) hide show
  1. package/dist/index.d.ts +643 -91
  2. package/dist/index.js +2228 -541
  3. package/package.json +1 -1
package/dist/index.d.ts CHANGED
@@ -2,11 +2,24 @@
2
2
  /**
3
3
  * Simplified storage boundary for Streamsy.
4
4
  *
5
- * Adapters persist facts and may provide runtime capabilities (locks,
6
- * notification, expiration scheduling). Protocol/lifecycle policy lives in core.
5
+ * Adapters persist facts and may provide runtime capabilities (notification,
6
+ * expiration scheduling). Atomic mutation is expressed through append and
7
+ * lifecycle intents on the storage adapter; protocol/lifecycle policy lives in
8
+ * core.
7
9
  */
8
10
  type StreamId = string;
11
+ /**
12
+ * Opaque, case-sensitive stream position. Within one stream incarnation,
13
+ * generated offsets are unique and strictly increasing under ordinary string
14
+ * comparison. Adapters must store, sort, and window them lexicographically;
15
+ * they must not parse or normalize generator-specific structure.
16
+ */
9
17
  type Offset = string;
18
+ /**
19
+ * One stored message. `data` is binary (`Uint8Array`) — it survives structured
20
+ * clone (the Durable Object RPC boundary) but is NOT plain JSON; a remote
21
+ * adapter transporting messages over JSON must encode it (e.g. base64).
22
+ */
10
23
  interface StoredMessage {
11
24
  data: Uint8Array;
12
25
  offset: Offset;
@@ -24,7 +37,15 @@ interface StreamLifecycleState {
24
37
  closedAt?: number;
25
38
  forkedFrom?: StreamId;
26
39
  forkOffset?: Offset;
27
- childRefCount: number;
40
+ /**
41
+ * Sub-message boundary inside the source message that follows `forkOffset`.
42
+ * Only recorded when a fork materialized a partial-message prefix (`> 0`).
43
+ * For binary/text it counts bytes within the next source message; for JSON it
44
+ * counts flattened messages/items. Kept purely for fork idempotency/config
45
+ * matching — reads use the materialized prefix stored as the child's own
46
+ * messages, not this value.
47
+ */
48
+ forkSubOffset?: number;
28
49
  softDeleted?: boolean;
29
50
  /**
30
51
  * Effective expiration deadline in epoch ms. Core updates this on create
@@ -38,20 +59,25 @@ interface StreamRecord {
38
59
  config: StreamConfig;
39
60
  lifecycle: StreamLifecycleState;
40
61
  currentOffset: Offset;
62
+ /**
63
+ * Deprecated adapter metadata retained for persisted-record compatibility.
64
+ * Core increments it for message-bearing mutations but never derives or
65
+ * orders offsets from it.
66
+ */
41
67
  counter: number;
42
68
  }
69
+ /**
70
+ * **Patches set values; they never delete them.** An absent field means "leave
71
+ * unchanged". Clearing a field is deliberately inexpressible: `undefined` is
72
+ * dropped by JSON but preserved by structured clone, so "set to undefined"
73
+ * would behave differently across transports. Core never clears fields.
74
+ */
43
75
  interface StreamRecordPatch {
44
76
  config?: Partial<StreamConfig>;
45
77
  lifecycle?: Partial<StreamLifecycleState>;
46
78
  currentOffset?: Offset;
47
79
  counter?: number;
48
80
  }
49
- type CreateStreamRecordResult = {
50
- status: "created";
51
- } | {
52
- status: "exists";
53
- record: StreamRecord;
54
- };
55
81
  interface ProducerState {
56
82
  epoch: number;
57
83
  lastSeq: number;
@@ -61,77 +87,195 @@ interface ListMessagesOptions {
61
87
  until?: Offset;
62
88
  limit?: number;
63
89
  }
64
- type StreamEventType = "message" | "closed" | "deleted" | "soft-deleted";
65
- interface WaitForEventOptions {
90
+ /**
91
+ * Observable, serializable snapshot of the change-relevant state of one stream.
92
+ * Every field is a JSON-serializable primitive so the snapshot crosses a Durable
93
+ * Object RPC (or any future remote adapter) boundary unchanged.
94
+ */
95
+ interface StreamChangeSnapshot {
96
+ /** `false` once the record has been purged. */
97
+ present: boolean;
98
+ currentOffset: Offset;
99
+ closed: boolean;
100
+ softDeleted: boolean;
101
+ }
102
+ /**
103
+ * Serializable, closure-free input to the level-triggered live-wait seam. The
104
+ * caller passes the position/lifecycle state it already observed; the adapter
105
+ * re-reads durable state and decides whether anything relevant advanced.
106
+ */
107
+ interface AwaitChangeOptions {
108
+ /** The offset the live reader is parked at. */
109
+ fromOffset: Offset;
110
+ /** Closed state the caller already observed (treated as `false` when absent). */
111
+ observedClosed?: boolean;
112
+ /** Soft-deleted state the caller already observed (treated as `false` when absent). */
113
+ observedSoftDeleted?: boolean;
66
114
  timeoutMs: number;
67
- signal?: AbortSignal;
68
115
  }
69
- type WaitForEventResult = {
70
- status: "notified";
71
- type?: StreamEventType;
116
+ /**
117
+ * Result of {@link AwaitChangeOptions}. There is no `aborted` status:
118
+ * cancellation is caller-local and the adapter never learns about it.
119
+ *
120
+ * `timeout` means "no relevant change observed yet" — it does NOT promise the
121
+ * full `timeoutMs` budget elapsed. Adapters MAY return `timeout` early (bounded
122
+ * parks are encouraged for remote backends, e.g. a Durable Object capping the
123
+ * total wait so a single RPC never strands the actor). Callers MUST re-park on
124
+ * `timeout` rather than assume the budget was consumed.
125
+ */
126
+ type AwaitChangeResult = {
127
+ status: "changed";
128
+ snapshot: StreamChangeSnapshot;
72
129
  } | {
73
130
  status: "timeout";
74
- } | {
75
- status: "aborted";
131
+ snapshot: StreamChangeSnapshot;
76
132
  };
77
133
  interface Clock {
78
134
  now(): number;
79
135
  date(value?: number | string): Date;
80
136
  } //#endregion
81
- //#region src/types/factory.d.ts
82
- /** Bound record store: every method targets the single stream this store represents. */
83
- interface StreamRecordStore {
84
- getRecord(): Promise<StreamRecord | null>;
85
- createRecord(record: StreamRecord): Promise<CreateStreamRecordResult>;
86
- updateRecord(patch: StreamRecordPatch): Promise<StreamRecord>;
87
- deleteRecord(): Promise<void>;
137
+ //#region src/types/storage-adapter.d.ts
138
+ interface StreamReader {
139
+ getRecord(streamId: StreamId): Promise<StreamRecord | null>;
140
+ listMessages(streamId: StreamId, options?: ListMessagesOptions): Promise<StoredMessage[]>;
141
+ getProducerState(streamId: StreamId, producerId: string): Promise<ProducerState | undefined>;
88
142
  }
89
- /** Bound message store for a single stream. */
90
- interface StreamMessageStore {
91
- appendMessages(messages: StoredMessage[]): Promise<void>;
92
- listMessages(options?: ListMessagesOptions): Promise<StoredMessage[]>;
93
- deleteMessages(): Promise<void>;
94
- }
95
- /** Bound producer-state store for a single stream. */
96
- interface StreamProducerStore {
97
- getProducerState(producerId: string): Promise<ProducerState | undefined>;
98
- setProducerState(producerId: string, state: ProducerState): Promise<void>;
99
- deleteProducerStates(): Promise<void>;
143
+ /**
144
+ * Streamsy's real atomic write: messages + record advance + optional producer
145
+ * compare-and-set + preconditions, in one transaction. `recordPatch` is required.
146
+ * A message-bearing append advances `currentOffset` / `counter` (a pure close folds
147
+ * into the same patch via `lifecycle.closed`); a lifecycle-only TTL renewal
148
+ * (`ExpiryPolicy.touch`) is the one append shape that patches the record without
149
+ * advancing offset/counter. Closure-free and serializable.
150
+ */
151
+ interface AppendPlan {
152
+ preconditions: {
153
+ expectedOffset?: Offset;
154
+ expectedClosed?: boolean;
155
+ /**
156
+ * Producer compare-and-set. An **absent** `expected` means "the producer
157
+ * must not exist yet" (insert-if-absent) — it does NOT mean "don't check,
158
+ * just set". Every implementation must fail the append with reason
159
+ * `"producer"` when `expected` is absent but a state already exists.
160
+ */
161
+ producer?: {
162
+ producerId: string;
163
+ expected?: ProducerState;
164
+ next: ProducerState;
165
+ };
166
+ };
167
+ messages?: StoredMessage[];
168
+ recordPatch: StreamRecordPatch;
100
169
  }
101
- /** Bound parent/child reference tracker for a single stream. */
102
- interface StreamReferenceTracker {
103
- incrementChildRefCount(): Promise<number>;
104
- decrementChildRefCount(): Promise<number>;
170
+ /**
171
+ * `reason` is required on `precondition-failed` and names the precondition that
172
+ * tripped. When multiple preconditions fail simultaneously, attribute in the
173
+ * order **offset → closed → producer**. Backends with opaque conditional writes
174
+ * may derive `reason` best-effort from a post-failure re-read under concurrency
175
+ * (report `"offset"` when the failure cannot be attributed, e.g. the record was
176
+ * concurrently purged); single-writer attribution must be exact — the contract
177
+ * kit tests exactly that case. Core's retry loop re-plans from `record` and does
178
+ * not branch on `reason`; it exists for adapter diagnostics and kit sharpness.
179
+ */
180
+ type StorageAppendResult = {
181
+ status: "appended";
182
+ record: StreamRecord;
183
+ } | {
184
+ status: "precondition-failed";
185
+ record: StreamRecord | null;
186
+ reason: "offset" | "closed" | "producer";
187
+ };
188
+ interface StreamAppender {
189
+ append(streamId: StreamId, plan: AppendPlan): Promise<StorageAppendResult>;
105
190
  }
106
- /** Per-stream mutation coordinator (lock-like). */
107
- interface StreamMutationCoordinator {
108
- withMutationLock<T>(fn: () => Promise<T>): Promise<T>;
191
+ /**
192
+ * `record` is the single source of truth for the created stream, including a
193
+ * created-closed stream (`record.lifecycle.closed` / `closedAt` are pre-folded
194
+ * by core). Adapters persist the record as given; there is no separate
195
+ * close-after step.
196
+ */
197
+ interface CreatePlan {
198
+ record: StreamRecord;
199
+ initialMessages?: StoredMessage[];
109
200
  }
110
- /** Per-stream live-read notification hub. */
111
- interface StreamEventHub {
112
- waitForEvent(options: WaitForEventOptions): Promise<WaitForEventResult>;
113
- notify(type: StreamEventType): Promise<void> | void;
201
+ type StorageCreateResult = {
202
+ status: "created";
203
+ record: StreamRecord;
204
+ } | {
205
+ status: "exists";
206
+ record: StreamRecord;
207
+ };
208
+ interface ForkPlan {
209
+ child: StreamRecord;
210
+ sourceId: StreamId;
211
+ initialMessages?: StoredMessage[];
212
+ /**
213
+ * Source liveness check: the fork proceeds only if the source exists, is not
214
+ * soft-deleted, and its `currentOffset` is `>=` `sourceLiveAtOffset`
215
+ * (lexicographic offset comparison). Its only failure is `fork-source-gone`.
216
+ */
217
+ precondition: {
218
+ sourceLiveAtOffset: Offset;
219
+ };
114
220
  }
115
- /** Per-stream active expiry scheduler. */
116
- interface StreamExpiryScheduler {
117
- scheduleExpiry(at: number, callback?: () => Promise<void>): Promise<void> | void;
118
- cancelExpiry(): Promise<void> | void;
221
+ /**
222
+ * `exists` carries the existing child record so core can run the same
223
+ * config-match idempotency it applies to `create` — a byte-identical racing
224
+ * fork resolves as idempotent success rather than a bogus conflict.
225
+ */
226
+ type StorageForkResult = {
227
+ status: "created";
228
+ record: StreamRecord;
229
+ } | {
230
+ status: "exists";
231
+ record: StreamRecord;
232
+ } | {
233
+ status: "fork-source-gone";
234
+ };
235
+ interface DeletePlan {
236
+ streamId: StreamId;
237
+ reason: "delete" | "expiry";
119
238
  }
239
+ type StorageDeleteResult = {
240
+ status: "purged";
241
+ } | {
242
+ status: "retained-soft-deleted";
243
+ } | {
244
+ status: "not-found";
245
+ } | {
246
+ status: "gone";
247
+ };
120
248
  /**
121
- * Protocol-facing stream. Represents one stream identified by `id` and exposes
122
- * all protocol storage behavior as direct methods. Adapter-private store
123
- * composition must stay behind this object.
249
+ * Per-stream level-triggered live waiter. Serializable in and out: the argument
250
+ * and result carry only plain data, so the seam crosses a Durable Object RPC (or
251
+ * any future remote adapter) boundary unchanged.
252
+ *
253
+ * Required: every adapter implements `awaitChange`. A backend that can wake
254
+ * cheaply does so directly; one that cannot implements it by polling its own
255
+ * durable reads. Core wires no polling fallback in silently, but it exports the
256
+ * contract-faithful loop — `runAwaitChangeLoop` — plus the shared
257
+ * `buildChangeSnapshot` / `changeSnapshotDiffers` primitives, so an adapter
258
+ * supplies only `readRecord` + `waitForWake` (a minimal polling adapter's
259
+ * `waitForWake` is a sleep) and stays faithful to the level-triggered contract.
124
260
  */
125
- interface Stream extends StreamRecordStore, StreamMessageStore, StreamProducerStore, StreamReferenceTracker, StreamMutationCoordinator, StreamEventHub, StreamExpiryScheduler {
126
- readonly id: StreamId;
261
+ interface StreamLiveWaiter {
262
+ awaitChange(streamId: StreamId, options: AwaitChangeOptions): Promise<AwaitChangeResult>;
263
+ }
264
+ /** Per-stream active expiry scheduler. */
265
+ interface StreamExpiryScheduler {
266
+ scheduleExpiry(streamId: StreamId, at: number): Promise<void> | void;
267
+ cancelExpiry(streamId: StreamId): Promise<void> | void;
127
268
  }
128
269
  /**
129
- * Storage factory. Maps a public stream id to a storage-bound `Stream`.
130
- * Lookup, routing, and dependency composition are factory-owned concerns
131
- * and are not exposed on the returned `Stream`.
270
+ * The storage backend an adapter author implements: one flat, fully serializable
271
+ * interface. Per-stream methods take `streamId` first; lifecycle intents carry
272
+ * the id in their plan. Adapters keep a private per-stream handle and delegate to
273
+ * it internally.
132
274
  */
133
- interface StreamFactory {
134
- getStream(streamId: StreamId): Promise<Stream>;
275
+ interface StorageAdapter extends StreamReader, StreamAppender, StreamLiveWaiter, StreamExpiryScheduler {
276
+ create(plan: CreatePlan): Promise<StorageCreateResult>;
277
+ fork?(plan: ForkPlan): Promise<StorageForkResult>;
278
+ delete(plan: DeletePlan): Promise<StorageDeleteResult>;
135
279
  }
136
280
  /**
137
281
  * Structured "feature not supported" protocol result. Protocol methods map
@@ -158,8 +302,44 @@ declare function notSupportedFromError(error: NotSupportedError): NotSupportedRe
158
302
  /** Type guard for protocol results that may be a {@link NotSupportedResult}. */
159
303
  declare function isNotSupported(value: unknown): value is NotSupportedResult;
160
304
 
305
+ //#endregion
306
+ //#region src/protocol/helpers/offset-generator.d.ts
307
+ /**
308
+ * Generates opaque offsets for one stream. `next` is called once per message,
309
+ * including every item in a JSON batch. Core verifies every returned value is
310
+ * valid and strictly greater than `previous` before a storage plan is built.
311
+ */
312
+ interface OffsetGenerator {
313
+ /** Tail value for a newly-created empty stream. */
314
+ readonly initialOffset: Offset;
315
+ /** Return the next offset after `previous`. */
316
+ next(previous: Offset): Offset;
317
+ /** Accept client-supplied lexical boundaries produced by this scheme. */
318
+ isValid(offset: string): boolean;
319
+ }
320
+ declare const ZERO_OFFSET: Offset;
321
+ /** Protocol-level constraints that apply to every generated offset scheme. */
322
+
323
+ declare function compareOffsets(a: Offset, b: Offset): number;
324
+ /** The backwards-compatible fixed-width counter generator used by default. */
325
+ declare const defaultOffsetGenerator: OffsetGenerator;
326
+ declare class InvalidGeneratedOffsetError extends Error {
327
+ constructor(message: string);
328
+ }
329
+
161
330
  //#endregion
162
331
  //#region src/types/protocol.d.ts
332
+ /** Allocate a batch without interpreting the generator's opaque offset format. */
333
+ interface CommitEvent {
334
+ streamId: StreamId;
335
+ offset: string;
336
+ closed: boolean;
337
+ softDeleted: boolean;
338
+ }
339
+ type AfterCommitHook = (commit: CommitEvent) => void;
340
+ interface CommitObservable {
341
+ onAfterCommit(hook: AfterCommitHook): () => void;
342
+ }
163
343
  interface CreateOptions {
164
344
  contentType?: string;
165
345
  ttlSeconds?: number;
@@ -168,6 +348,14 @@ interface CreateOptions {
168
348
  closed?: boolean;
169
349
  forkedFrom?: string;
170
350
  forkOffset?: string;
351
+ /**
352
+ * Optional sub-message boundary inside the source message at `forkOffset`.
353
+ * `0` is treated as equivalent to an absent header. For binary/text it is a
354
+ * byte count within the next source message; for JSON it is a flattened
355
+ * message/item count. Requires `forkedFrom`; values `> 0` require
356
+ * `forkOffset`.
357
+ */
358
+ forkSubOffset?: number;
171
359
  }
172
360
  interface ProducerOptions {
173
361
  producerId: string;
@@ -282,6 +470,8 @@ type AppendResult = {
282
470
  } | {
283
471
  status: "conflict";
284
472
  conflictReason: "content-type" | "sequence";
473
+ } | {
474
+ status: "busy";
285
475
  } | {
286
476
  status: "stale-epoch";
287
477
  currentEpoch: number;
@@ -346,24 +536,40 @@ type ProtocolGetResult = {
346
536
  } | {
347
537
  status: "gone";
348
538
  } | NotSupportedResult;
349
- interface StreamProtocolFactory {
539
+ interface StreamProtocolFactory extends CommitObservable {
540
+ readonly offsetGenerator: OffsetGenerator;
541
+ isValidOffset(offset: string): boolean;
350
542
  create(streamId: string, options: CreateOptions): Promise<CreateResult>;
351
543
  get(streamId: string): Promise<ProtocolGetResult>;
352
544
  }
353
545
 
354
546
  //#endregion
355
- //#region src/protocol/helpers/offset-generator.d.ts
356
- declare const ZERO_OFFSET: Offset;
547
+ //#region src/protocol/helpers/bind-stream.d.ts
548
+ /** The per-stream surface core call sites use (was the seam `Stream`). */
549
+ interface BoundStream {
550
+ readonly id: StreamId;
551
+ getRecord(): Promise<StreamRecord | null>;
552
+ listMessages(options?: ListMessagesOptions): Promise<StoredMessage[]>;
553
+ getProducerState(producerId: string): Promise<ProducerState | undefined>;
554
+ append(plan: AppendPlan): Promise<StorageAppendResult>;
555
+ awaitChange(options: AwaitChangeOptions): Promise<AwaitChangeResult>;
556
+ scheduleExpiry(at: number): Promise<void> | void;
557
+ cancelExpiry(): Promise<void> | void;
558
+ }
559
+ declare function bindStream(adapter: StorageAdapter, id: StreamId): BoundStream;
357
560
 
358
561
  //#endregion
359
562
  //#region src/protocol.d.ts
360
563
  interface StreamProtocolOptions {
361
564
  clock?: Clock;
565
+ /** Long-poll timeout in milliseconds. Defaults to 30 seconds. */
362
566
  longPollTimeoutMs?: number;
567
+ /** Opaque offset scheme; defaults to Streamsy's fixed-width counter format. */
568
+ offsetGenerator?: OffsetGenerator;
363
569
  }
364
570
  interface StreamProtocolDeps extends StreamProtocolOptions {
365
571
  storage: {
366
- factory: StreamFactory;
572
+ adapter: StorageAdapter;
367
573
  };
368
574
  }
369
575
  declare function createStreamProtocol(deps: StreamProtocolDeps): StreamProtocolFactory;
@@ -372,67 +578,104 @@ declare class StreamProtocol implements StreamProtocolFactory {
372
578
  private clock;
373
579
  private longPollTimeoutMs;
374
580
  private expiryPolicy;
375
- private gcService;
376
581
  private recordFactory;
582
+ readonly offsetGenerator: OffsetGenerator;
583
+ private hooks;
377
584
  constructor(deps: StreamProtocolDeps);
585
+ isValidOffset(offset: string): boolean;
378
586
  create(streamId: string, options: CreateOptions): Promise<CreateResult>;
379
587
  get(streamId: string): Promise<ProtocolGetResult>;
380
- /** Called by adapter schedulers/alarms; core decides soft-delete vs purge. */
588
+ onAfterCommit(hook: AfterCommitHook): () => void;
589
+ /** Called by adapter schedulers/alarms; core decides whether expiry applies. */
381
590
  handleScheduledExpiry(streamId: string): Promise<void>;
382
591
  private boundProtocolStream;
592
+ /** Bind the flat adapter to one id for ergonomic core-side per-stream calls. */
383
593
  private storageStream;
384
- private withStreamMutationLock;
594
+ private emitAfterCommit;
385
595
  }
386
596
 
387
597
  //#endregion
388
598
  //#region src/storage/memory/stream.d.ts
389
- declare class MemoryStream implements Stream {
599
+ /**
600
+ * Adapter-internal write engine input. Superset of {@link AppendPlan} with an
601
+ * optional `createRecord` — the `create`/`fork` intents reuse the same engine to
602
+ * insert the record, while the public `append` never carries `createRecord`.
603
+ */
604
+ interface WritePlan {
605
+ createRecord?: StreamRecord;
606
+ preconditions: AppendPlan["preconditions"];
607
+ messages?: StoredMessage[];
608
+ recordPatch?: StreamRecordPatch;
609
+ }
610
+ type WriteResult = {
611
+ status: "committed";
612
+ record: StreamRecord;
613
+ } | {
614
+ status: "precondition-failed";
615
+ record: StreamRecord | null;
616
+ reason?: "offset" | "closed" | "producer";
617
+ };
618
+ /** Adapter-private per-stream handle. Not on the seam — owned by the memory state. */
619
+ declare class MemoryStream {
390
620
  readonly id: StreamId;
391
621
  private readonly deleteFromState;
392
622
  private readonly records;
393
623
  private readonly messages;
394
624
  private readonly producers;
395
- private readonly lock;
396
625
  private readonly notifier;
397
626
  private readonly timeout;
398
- constructor(id: StreamId, deleteFromState: () => void);
399
- getRecord(): Promise<StreamRecord | null>;
400
- createRecord(record: StreamRecord): Promise<CreateStreamRecordResult>;
401
- updateRecord(patch: StreamRecordPatch): Promise<StreamRecord>;
402
- deleteRecord(): Promise<void>;
403
- appendMessages(messages: StoredMessage[]): Promise<void>;
404
- listMessages(options?: ListMessagesOptions): Promise<StoredMessage[]>;
405
- deleteMessages(): Promise<void>;
406
- getProducerState(producerId: string): Promise<ProducerState | undefined>;
407
- setProducerState(producerId: string, state: ProducerState): Promise<void>;
408
- deleteProducerStates(): Promise<void>;
409
- incrementChildRefCount(): Promise<number>;
410
- decrementChildRefCount(): Promise<number>;
411
- withMutationLock<T>(fn: () => Promise<T>): Promise<T>;
412
- waitForEvent(options: WaitForEventOptions): Promise<WaitForEventResult>;
413
- notify(type: StreamEventType): Promise<void> | void;
414
- scheduleExpiry(at: number, callback?: () => Promise<void>): Promise<void> | void;
627
+ constructor(id: StreamId, deleteFromState: () => void, onScheduledExpiry?: () => Promise<void> | void);
628
+ getRecord(): StreamRecord | null;
629
+ /** Public append intent (no `createRecord`). */
630
+ append(plan: AppendPlan): StorageAppendResult;
631
+ /**
632
+ * Adapter-internal write engine shared by `append` (no `createRecord`) and the
633
+ * `create`/`fork` intents (with `createRecord`).
634
+ */
635
+ applyMutation(plan: WritePlan): WriteResult;
636
+ listMessages(options?: ListMessagesOptions): StoredMessage[];
637
+ getProducerState(producerId: string): ProducerState | undefined;
638
+ purgeSelf(): void;
639
+ softDelete(): void;
640
+ /**
641
+ * Level-triggered live wait via the shared exported loop: re-read durable
642
+ * state first (so a mutation that landed between the caller's observation and
643
+ * this call is never missed), then park on the wake bus until the state
644
+ * advances or the budget expires. Read and park are synchronous with the wake
645
+ * bus here, so no per-park cap is needed.
646
+ */
647
+ awaitChange(options: AwaitChangeOptions): Promise<AwaitChangeResult>;
648
+ scheduleExpiry(at: number): Promise<void> | void;
415
649
  cancelExpiry(): Promise<void> | void;
416
650
  }
417
651
 
418
652
  //#endregion
419
653
  //#region src/storage/memory/state.d.ts
654
+ type MemoryExpiryHandler = (streamId: string) => Promise<void> | void;
420
655
  /** Shared in-memory stream registry. */
421
656
  declare class MemoryStreamState {
657
+ private readonly onScheduledExpiry?;
422
658
  private readonly streams;
659
+ private readonly childEdges;
660
+ constructor(onScheduledExpiry?: MemoryExpiryHandler | undefined);
423
661
  getStream(id: string): MemoryStream;
424
- stream(id: string): MemoryStream;
662
+ getExistingStream(id: string): MemoryStream | undefined;
663
+ addEdge(parent: string, child: string): void;
664
+ dropEdge(parent: string, child: string): void;
665
+ countDependents(parent: string): number;
666
+ private deleteStream;
425
667
  }
426
668
 
427
669
  //#endregion
428
- //#region src/storage/memory/factory.d.ts
429
- interface MemoryStreamFactoryOptions {
670
+ //#region src/storage/memory/adapter.d.ts
671
+ interface MemoryStorageAdapterOptions {
430
672
  /**
431
673
  * Share an existing memory state. Omit to get a fresh, isolated state.
432
674
  */
433
675
  state?: MemoryStreamState;
676
+ onScheduledExpiry?: (streamId: StreamId) => Promise<void> | void;
434
677
  }
435
- declare function createMemoryStreamFactory(options?: MemoryStreamFactoryOptions): StreamFactory;
678
+ declare function createMemoryStorageAdapter(options?: MemoryStorageAdapterOptions): StorageAdapter;
436
679
 
437
680
  //#endregion
438
681
  //#region src/http/types.d.ts
@@ -467,6 +710,256 @@ declare class ReadOnlyHttpHandler implements HttpHandlerInterface {
467
710
  fetch(request: Request): Promise<Response>;
468
711
  }
469
712
 
713
+ //#endregion
714
+ //#region src/client/types.d.ts
715
+ type StreamOffset = string;
716
+ type JsonPrimitive = null | boolean | number | string;
717
+ type JsonValue = JsonPrimitive | {
718
+ readonly [key: string]: JsonValue;
719
+ } | readonly JsonValue[];
720
+ interface ClientRequestOptions {
721
+ signal?: AbortSignal;
722
+ }
723
+ /**
724
+ * The single client-only failure member. It covers transport/auth/abort and
725
+ * other cross-cutting outcomes so per-operation unions stay small and the
726
+ * direct adapter can pass protocol results through with minimal narrowing.
727
+ */
728
+ type ClientErrorCode = "transport" | "unauthorized" | "forbidden" | "rate-limited" | "bad-request" | "busy" | "parse-error" | "not-supported" | "aborted" | "client-closed" | "unknown";
729
+ interface ClientFailure {
730
+ status: "error";
731
+ code: ClientErrorCode;
732
+ message: string;
733
+ httpStatus?: number;
734
+ retryable: boolean;
735
+ cause?: unknown;
736
+ }
737
+ interface CreateStreamOptions extends ClientRequestOptions {
738
+ contentType?: string;
739
+ ttlSeconds?: number;
740
+ expiresAt?: string;
741
+ initialData?: Uint8Array | string;
742
+ closed?: boolean;
743
+ }
744
+ interface AppendStreamOptions extends ClientRequestOptions {
745
+ /** Required where the substrate requires it (direct append). */
746
+ contentType?: string;
747
+ seq?: string;
748
+ }
749
+ interface CloseStreamOptions extends ClientRequestOptions {
750
+ contentType?: string;
751
+ finalData?: Uint8Array | string;
752
+ }
753
+ type ClientHeadResult = {
754
+ status: "ok";
755
+ contentType?: string;
756
+ /** Current tail/read-resume token when supplied by the substrate. */
757
+ offset?: StreamOffset;
758
+ closed: boolean;
759
+ etag?: string;
760
+ cacheControl?: string;
761
+ } | {
762
+ status: "not-found";
763
+ } | {
764
+ status: "gone";
765
+ } | ClientFailure;
766
+ type ClientCreateResult = {
767
+ status: "created";
768
+ contentType?: string;
769
+ } | {
770
+ status: "conflict";
771
+ } | ClientFailure;
772
+ type ClientAppendResult = {
773
+ status: "appended";
774
+ } | {
775
+ status: "not-found";
776
+ } | {
777
+ status: "gone";
778
+ } | {
779
+ status: "closed";
780
+ } | {
781
+ status: "conflict";
782
+ } | ClientFailure;
783
+ type ClientCloseResult = {
784
+ status: "closed";
785
+ finalOffset: StreamOffset;
786
+ } | {
787
+ status: "not-found";
788
+ } | {
789
+ status: "gone";
790
+ } | {
791
+ status: "conflict";
792
+ } | ClientFailure;
793
+ type ClientReadResult<T extends JsonValue = JsonValue> = {
794
+ status: "ok";
795
+ session: StreamReadSession<T>;
796
+ } | {
797
+ status: "not-found";
798
+ } | {
799
+ status: "gone";
800
+ } | ClientFailure;
801
+ type ClientLiveMode = false | "long-poll" | "sse";
802
+ interface ReadStreamOptions extends ClientRequestOptions {
803
+ /** After-exclusive token. Omission means the start of the stream. */
804
+ offset?: StreamOffset;
805
+ /** false is catch-up only. Live modes continue until EOF, cancel, or error. */
806
+ live?: ClientLiveMode;
807
+ }
808
+ interface StreamBatchMeta {
809
+ /** Pass this unchanged as the next read's offset. */
810
+ offset: StreamOffset;
811
+ cursor?: string;
812
+ upToDate: boolean;
813
+ streamClosed: boolean;
814
+ }
815
+ interface JsonStreamBatch<T extends JsonValue = JsonValue> extends StreamBatchMeta {
816
+ kind: "json";
817
+ items: readonly T[];
818
+ }
819
+ interface TextStreamBatch extends StreamBatchMeta {
820
+ kind: "text";
821
+ text: string;
822
+ }
823
+ interface ByteStreamBatch extends StreamBatchMeta {
824
+ kind: "bytes";
825
+ data: Uint8Array;
826
+ }
827
+ type StreamBatch<T extends JsonValue = JsonValue> = JsonStreamBatch<T> | TextStreamBatch | ByteStreamBatch;
828
+ /** Terminal outcome of a read session. Delivered through `done`, never thrown. */
829
+ type ReadEndResult = {
830
+ status: "done";
831
+ } | {
832
+ status: "cancelled";
833
+ } | ClientFailure;
834
+ /**
835
+ * A cancellable session of content-aware batches. Iteration yields batches and
836
+ * NEVER throws for operational failures; the terminal outcome is a result
837
+ * object resolved through {@link StreamReadSession.done}.
838
+ */
839
+ interface StreamReadSession<T extends JsonValue = JsonValue> extends AsyncIterable<StreamBatch<T>> {
840
+ readonly contentType?: string;
841
+ readonly startOffset?: StreamOffset;
842
+ /** Latest batch metadata after that batch has been delivered. */
843
+ readonly offset: StreamOffset;
844
+ readonly cursor?: string;
845
+ readonly upToDate: boolean;
846
+ readonly streamClosed: boolean;
847
+ cancel(reason?: unknown): void;
848
+ /** Always resolves, never rejects. */
849
+ readonly done: Promise<ReadEndResult>;
850
+ }
851
+ interface StreamProtocolHandle {
852
+ readonly id: string;
853
+ head(options?: ClientRequestOptions): Promise<ClientHeadResult>;
854
+ /** Create-only. An existing stream is a `conflict`, never success. */
855
+ create(options?: CreateStreamOptions): Promise<ClientCreateResult>;
856
+ /** `contentType` is required in `options` where the substrate requires it. */
857
+ append(data: Uint8Array | string, options?: AppendStreamOptions): Promise<ClientAppendResult>;
858
+ /** Permanently close the stream, optionally appending finalData atomically. */
859
+ close(options?: CloseStreamOptions): Promise<ClientCloseResult>;
860
+ read<T extends JsonValue = JsonValue>(options?: ReadStreamOptions): Promise<ClientReadResult<T>>;
861
+ }
862
+ interface StreamProtocolClient {
863
+ /** Cold handle creation: no I/O. Repeated calls need not return the same object. */
864
+ stream(streamId: string): StreamProtocolHandle;
865
+ /** Cancel all sessions created by this client and reject future operations. */
866
+ close(reason?: unknown): Promise<void>;
867
+ }
868
+ interface StreamsyProtocolClient extends StreamProtocolClient {
869
+ /** Exact local Streamsy semantics; absent from the official adapter. */
870
+ readonly streamsy: StreamProtocolFactory;
871
+ }
872
+
873
+ //#endregion
874
+ //#region src/client/direct/client.d.ts
875
+ /** Structural refinement test: is this client the exact-Streamsy direct adapter? */
876
+ declare function hasStreamsyProtocol(client: StreamProtocolClient): client is StreamsyProtocolClient;
877
+ declare function directProtocolClient(factory: StreamProtocolFactory): StreamsyProtocolClient;
878
+
879
+ //#endregion
880
+ //#region src/client/read-session.d.ts
881
+ /**
882
+ * Adapts a `StreamProtocolFactory` to the transport-neutral client seam. It
883
+ * keeps a single client-level abort controller whose signal is threaded into
884
+ * every operation and read session; `close()` aborts it and rejects new work.
885
+ * There is no session registry: sessions observe the abort through their own
886
+ * signal and end with `{ status: "cancelled" }`.
887
+ */
888
+ /**
889
+ * The single client read-session implementation, shared by every adapter.
890
+ *
891
+ * It is a one-consumer, one-batch queue whose producer is backpressured by
892
+ * iterator delivery. Iteration never throws for operational failures: the
893
+ * terminal outcome is delivered through {@link ClientReadSession.done}, which
894
+ * always resolves. Only programmer misuse (double iteration, concurrent
895
+ * `next()`) throws.
896
+ */
897
+ declare class ClientReadSession<T extends JsonValue = JsonValue> implements StreamReadSession<T>, AsyncIterator<StreamBatch<T>> {
898
+ readonly done: Promise<ReadEndResult>;
899
+ readonly contentType?: string;
900
+ readonly startOffset?: string;
901
+ offset: string;
902
+ cursor?: string;
903
+ upToDate: boolean;
904
+ streamClosed: boolean;
905
+ private doneResolve;
906
+ private pending?;
907
+ private waiting?;
908
+ private ended;
909
+ private iterated;
910
+ private cancelHook?;
911
+ constructor(options: {
912
+ contentType?: string;
913
+ startOffset: string;
914
+ offset?: string;
915
+ cursor?: string;
916
+ upToDate?: boolean;
917
+ streamClosed?: boolean;
918
+ onCancel?: (reason?: unknown) => void;
919
+ });
920
+ setCancelHook(hook: (reason?: unknown) => void): void;
921
+ [Symbol.asyncIterator](): AsyncIterator<StreamBatch<T>>;
922
+ next(): Promise<IteratorResult<StreamBatch<T>>>;
923
+ return(): Promise<IteratorResult<StreamBatch<T>>>;
924
+ cancel(reason?: unknown): void;
925
+ /** Producer side: hand a batch to the consumer, backpressured until accepted. */
926
+ deliver(batch: StreamBatch<T>): Promise<void>;
927
+ /** Producer side: terminate the session with its outcome. Always resolves `done`. */
928
+ end(result: ReadEndResult): void;
929
+ private acceptPending;
930
+ private updateState;
931
+ }
932
+
933
+ //#endregion
934
+ //#region src/protocol/helpers/change-snapshot.d.ts
935
+ /** Build the serializable, change-relevant snapshot of a (possibly absent) record. */
936
+ declare function buildChangeSnapshot(record: StreamRecord | null): StreamChangeSnapshot;
937
+ /**
938
+ * The level-triggered "differs" predicate. A snapshot differs from what the
939
+ * caller observed when the record was purged, transitioned to soft-deleted or
940
+ * closed, or its offset is not the parked position. Offset **inequality** — not
941
+ * just advance — is the trigger: within one incarnation an offset only ever
942
+ * advances, so a *lower* offset means the stream was purged and re-created
943
+ * while the waiter was parked, which is also "something happened".
944
+ */
945
+ declare function changeSnapshotDiffers(snapshot: StreamChangeSnapshot, options: Pick<AwaitChangeOptions, "fromOffset" | "observedClosed" | "observedSoftDeleted">): boolean;
946
+
947
+ //#endregion
948
+ //#region src/protocol/helpers/await-change-loop.d.ts
949
+ interface AwaitChangeLoopDeps {
950
+ /** Read the current durable record. May be sync or async. */
951
+ readRecord(): StreamRecord | null | Promise<StreamRecord | null>;
952
+ /** Park until a wake or the given timeout, whichever comes first. */
953
+ waitForWake(timeoutMs: number): Promise<void>;
954
+ /** Cap the TOTAL wait budget (early `timeout` return; callers re-park). */
955
+ totalCapMs?: number;
956
+ /** Cap each individual park so a lost wake is repaired within the cap. */
957
+ parkCapMs?: number;
958
+ /** Wall clock; overridable for deterministic tests. */
959
+ now?: () => number;
960
+ }
961
+ declare function runAwaitChangeLoop(deps: AwaitChangeLoopDeps, options: AwaitChangeOptions): Promise<AwaitChangeResult>;
962
+
470
963
  //#endregion
471
964
  //#region src/http/responses.d.ts
472
965
  declare class HttpResponseFactory {
@@ -499,4 +992,63 @@ declare function notSupportedResponse(result: NotSupportedResult, responses: Htt
499
992
  declare function maybeNotSupportedResponse<T>(result: T | NotSupportedResult, responses: HttpResponseFactory): Response | null;
500
993
 
501
994
  //#endregion
502
- export { AppendConflictReason, AppendOptions, AppendResult, Clock, CreateConflictReason, CreateOptions, CreateResult, CreateStreamRecordResult, DeleteResult, HttpHandler, HttpHandlerInterface, HttpHandlerOptions, ListMessagesOptions, MemoryStreamFactoryOptions, MetadataResult, NotSupportedError, NotSupportedResult, Offset, ProducerOptions, ProducerState, ProtocolGetResult, ProtocolStream, ReadLiveOptions, ReadLiveResult, ReadOnlyHttpHandler, ReadOnlyHttpHandlerOptions, ReadOptions, ReadResult, StoredMessage, Stream, StreamConfig, StreamEventHub, StreamEventType, StreamExpiryScheduler, StreamFactory, StreamId, StreamLifecycleState, StreamMessageStore, StreamMutationCoordinator, StreamProducerStore, StreamProtocol, StreamProtocolDeps, StreamProtocolFactory, StreamProtocolOptions, StreamRecord, StreamRecordPatch, StreamRecordStore, StreamReferenceTracker, WaitForEventOptions, WaitForEventResult, ZERO_OFFSET, createHttpHandler, createMemoryStreamFactory, createReadOnlyHttpHandler, createStreamProtocol, isNotSupported, isNotSupportedError, maybeNotSupportedResponse, notSupported, notSupportedFromError, notSupportedResponse, unsupported };
995
+ //#region src/testing/storage-adapter-contract.d.ts
996
+ /** Minimal test-runner surface. Satisfied by vitest's and `bun:test`'s `it`. */
997
+ interface StorageAdapterContractHarness {
998
+ it(name: string, fn: () => void | Promise<void>): void;
999
+ }
1000
+ /** Build a fresh, isolated adapter for one contract case. */
1001
+ type MakeStorageAdapter = () => StorageAdapter | Promise<StorageAdapter>;
1002
+ /**
1003
+ * Register the full storage-adapter contract against `makeAdapter` using the
1004
+ * provided test harness. Wrap in the caller's own `describe` for grouping:
1005
+ *
1006
+ * ```ts
1007
+ * import { it } from "vitest";
1008
+ * describe("memory adapter contract", () => {
1009
+ * runStorageAdapterContract(() => createMemoryStorageAdapter(), { it });
1010
+ * });
1011
+ * ```
1012
+ */
1013
+ declare function runStorageAdapterContract(makeAdapter: MakeStorageAdapter, harness: StorageAdapterContractHarness): void;
1014
+
1015
+ //#endregion
1016
+ //#region src/storage/strategies/lineage-store.d.ts
1017
+ interface LineageStore {
1018
+ getRecord(id: StreamId): Promise<StreamRecord | null>;
1019
+ purgeSelf(id: StreamId): Promise<void>;
1020
+ softDelete(id: StreamId): Promise<void>;
1021
+ addEdge?(parent: StreamId, child: StreamId): Promise<void>;
1022
+ dropEdge?(parent: StreamId, child: StreamId): Promise<void>;
1023
+ countDependents?(parent: StreamId): Promise<number>;
1024
+ }
1025
+ interface LineagePolicy {
1026
+ countDependents(parent: StreamId): Promise<number>;
1027
+ addEdge(parent: StreamId, child: StreamId): Promise<void>;
1028
+ dropEdge(parent: StreamId, child: StreamId): Promise<void>;
1029
+ }
1030
+ type DependentsQuery = (parent: StreamId) => Promise<number>;
1031
+
1032
+ //#endregion
1033
+ //#region src/storage/strategies/cascade-reclaim.d.ts
1034
+ declare function cascadeReclaim(store: LineageStore, plan: DeletePlan, lineage: LineagePolicy): Promise<StorageDeleteResult>;
1035
+ declare function plainPurge(store: LineageStore, plan: DeletePlan): Promise<StorageDeleteResult>;
1036
+
1037
+ //#endregion
1038
+ //#region src/storage/strategies/ref-count-lineage.d.ts
1039
+ declare function refCountLineage(store: LineageStore): LineagePolicy;
1040
+
1041
+ //#endregion
1042
+ //#region src/storage/strategies/reverse-index-lineage.d.ts
1043
+ declare function reverseIndexLineage(query: DependentsQuery): LineagePolicy;
1044
+
1045
+ //#endregion
1046
+ //#region src/storage/strategies/copy-on-fork.d.ts
1047
+ declare function copyOnForkReclaim(): LineagePolicy;
1048
+
1049
+ //#endregion
1050
+ //#region src/storage/strategies/ttl-only.d.ts
1051
+ declare function ttlOnlyReclaim(): LineagePolicy;
1052
+
1053
+ //#endregion
1054
+ export { AfterCommitHook, AppendConflictReason, AppendOptions, AppendPlan, AppendResult, AppendStreamOptions, AwaitChangeLoopDeps, AwaitChangeOptions, AwaitChangeResult, BoundStream, ByteStreamBatch, ClientAppendResult, ClientCloseResult, ClientCreateResult, ClientErrorCode, ClientFailure, ClientHeadResult, ClientLiveMode, ClientReadResult, ClientReadSession, ClientRequestOptions, Clock, CloseStreamOptions, CommitEvent, CommitObservable, CreateConflictReason, CreateOptions, CreatePlan, CreateResult, CreateStreamOptions, DeletePlan, DeleteResult, DependentsQuery, ForkPlan, HttpHandler, HttpHandlerInterface, HttpHandlerOptions, InvalidGeneratedOffsetError, JsonPrimitive, JsonStreamBatch, JsonValue, LineagePolicy, LineageStore, ListMessagesOptions, MakeStorageAdapter, MemoryStorageAdapterOptions, MetadataResult, NotSupportedError, NotSupportedResult, Offset, OffsetGenerator, ProducerOptions, ProducerState, ProtocolGetResult, ProtocolStream, ReadEndResult, ReadLiveOptions, ReadLiveResult, ReadOnlyHttpHandler, ReadOnlyHttpHandlerOptions, ReadOptions, ReadResult, ReadStreamOptions, StorageAdapter, StorageAdapterContractHarness, StorageAppendResult, StorageCreateResult, StorageDeleteResult, StorageForkResult, StoredMessage, StreamAppender, StreamBatch, StreamBatchMeta, StreamChangeSnapshot, StreamConfig, StreamExpiryScheduler, StreamId, StreamLifecycleState, StreamLiveWaiter, StreamOffset, StreamProtocol, StreamProtocolClient, StreamProtocolDeps, StreamProtocolFactory, StreamProtocolHandle, StreamProtocolOptions, StreamReadSession, StreamReader, StreamRecord, StreamRecordPatch, StreamsyProtocolClient, TextStreamBatch, ZERO_OFFSET, bindStream, buildChangeSnapshot, cascadeReclaim, changeSnapshotDiffers, compareOffsets, copyOnForkReclaim, createHttpHandler, createMemoryStorageAdapter, createReadOnlyHttpHandler, createStreamProtocol, defaultOffsetGenerator, directProtocolClient, hasStreamsyProtocol, isNotSupported, isNotSupportedError, maybeNotSupportedResponse, notSupported, notSupportedFromError, notSupportedResponse, plainPurge, refCountLineage, reverseIndexLineage, runAwaitChangeLoop, runStorageAdapterContract, ttlOnlyReclaim, unsupported };