@streamsy/core 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/index.d.ts +378 -88
  2. package/dist/index.js +1692 -536
  3. package/package.json +1 -1
package/dist/index.d.ts CHANGED
@@ -2,11 +2,28 @@
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
+ * Public stream offset. **Seam guarantee**: offsets are fixed-width,
13
+ * lexicographically ordered strings of the form `<counter:16>_<sub:16>` where
14
+ * both parts are zero-padded decimals, so **lexicographic order = offset
15
+ * order**. Adapters rely on this to compare and window offsets inside their own
16
+ * storage engines (SQL `WHERE offset > ?`, key-range scans, line filtering).
17
+ * `compareOffsets` and `ZERO_OFFSET` are exported from the package root.
18
+ * Within one stream incarnation an offset only ever advances; a purge followed
19
+ * by a re-create restarts the offset sequence.
20
+ */
9
21
  type Offset = string;
22
+ /**
23
+ * One stored message. `data` is binary (`Uint8Array`) — it survives structured
24
+ * clone (the Durable Object RPC boundary) but is NOT plain JSON; a remote
25
+ * adapter transporting messages over JSON must encode it (e.g. base64).
26
+ */
10
27
  interface StoredMessage {
11
28
  data: Uint8Array;
12
29
  offset: Offset;
@@ -24,7 +41,15 @@ interface StreamLifecycleState {
24
41
  closedAt?: number;
25
42
  forkedFrom?: StreamId;
26
43
  forkOffset?: Offset;
27
- childRefCount: number;
44
+ /**
45
+ * Sub-message boundary inside the source message that follows `forkOffset`.
46
+ * Only recorded when a fork materialized a partial-message prefix (`> 0`).
47
+ * For binary/text it counts bytes within the next source message; for JSON it
48
+ * counts flattened messages/items. Kept purely for fork idempotency/config
49
+ * matching — reads use the materialized prefix stored as the child's own
50
+ * messages, not this value.
51
+ */
52
+ forkSubOffset?: number;
28
53
  softDeleted?: boolean;
29
54
  /**
30
55
  * Effective expiration deadline in epoch ms. Core updates this on create
@@ -40,18 +65,18 @@ interface StreamRecord {
40
65
  currentOffset: Offset;
41
66
  counter: number;
42
67
  }
68
+ /**
69
+ * **Patches set values; they never delete them.** An absent field means "leave
70
+ * unchanged". Clearing a field is deliberately inexpressible: `undefined` is
71
+ * dropped by JSON but preserved by structured clone, so "set to undefined"
72
+ * would behave differently across transports. Core never clears fields.
73
+ */
43
74
  interface StreamRecordPatch {
44
75
  config?: Partial<StreamConfig>;
45
76
  lifecycle?: Partial<StreamLifecycleState>;
46
77
  currentOffset?: Offset;
47
78
  counter?: number;
48
79
  }
49
- type CreateStreamRecordResult = {
50
- status: "created";
51
- } | {
52
- status: "exists";
53
- record: StreamRecord;
54
- };
55
80
  interface ProducerState {
56
81
  epoch: number;
57
82
  lastSeq: number;
@@ -61,77 +86,195 @@ interface ListMessagesOptions {
61
86
  until?: Offset;
62
87
  limit?: number;
63
88
  }
64
- type StreamEventType = "message" | "closed" | "deleted" | "soft-deleted";
65
- interface WaitForEventOptions {
89
+ /**
90
+ * Observable, serializable snapshot of the change-relevant state of one stream.
91
+ * Every field is a JSON-serializable primitive so the snapshot crosses a Durable
92
+ * Object RPC (or any future remote adapter) boundary unchanged.
93
+ */
94
+ interface StreamChangeSnapshot {
95
+ /** `false` once the record has been purged. */
96
+ present: boolean;
97
+ currentOffset: Offset;
98
+ closed: boolean;
99
+ softDeleted: boolean;
100
+ }
101
+ /**
102
+ * Serializable, closure-free input to the level-triggered live-wait seam. The
103
+ * caller passes the position/lifecycle state it already observed; the adapter
104
+ * re-reads durable state and decides whether anything relevant advanced.
105
+ */
106
+ interface AwaitChangeOptions {
107
+ /** The offset the live reader is parked at. */
108
+ fromOffset: Offset;
109
+ /** Closed state the caller already observed (treated as `false` when absent). */
110
+ observedClosed?: boolean;
111
+ /** Soft-deleted state the caller already observed (treated as `false` when absent). */
112
+ observedSoftDeleted?: boolean;
66
113
  timeoutMs: number;
67
- signal?: AbortSignal;
68
114
  }
69
- type WaitForEventResult = {
70
- status: "notified";
71
- type?: StreamEventType;
115
+ /**
116
+ * Result of {@link AwaitChangeOptions}. There is no `aborted` status:
117
+ * cancellation is caller-local and the adapter never learns about it.
118
+ *
119
+ * `timeout` means "no relevant change observed yet" — it does NOT promise the
120
+ * full `timeoutMs` budget elapsed. Adapters MAY return `timeout` early (bounded
121
+ * parks are encouraged for remote backends, e.g. a Durable Object capping the
122
+ * total wait so a single RPC never strands the actor). Callers MUST re-park on
123
+ * `timeout` rather than assume the budget was consumed.
124
+ */
125
+ type AwaitChangeResult = {
126
+ status: "changed";
127
+ snapshot: StreamChangeSnapshot;
72
128
  } | {
73
129
  status: "timeout";
74
- } | {
75
- status: "aborted";
130
+ snapshot: StreamChangeSnapshot;
76
131
  };
77
132
  interface Clock {
78
133
  now(): number;
79
134
  date(value?: number | string): Date;
80
135
  } //#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>;
88
- }
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>;
136
+ //#region src/types/storage-adapter.d.ts
137
+ interface StreamReader {
138
+ getRecord(streamId: StreamId): Promise<StreamRecord | null>;
139
+ listMessages(streamId: StreamId, options?: ListMessagesOptions): Promise<StoredMessage[]>;
140
+ getProducerState(streamId: StreamId, producerId: string): Promise<ProducerState | undefined>;
94
141
  }
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>;
142
+ /**
143
+ * Streamsy's real atomic write: messages + record advance + optional producer
144
+ * compare-and-set + preconditions, in one transaction. `recordPatch` is required.
145
+ * A message-bearing append advances `currentOffset` / `counter` (a pure close folds
146
+ * into the same patch via `lifecycle.closed`); a lifecycle-only TTL renewal
147
+ * (`ExpiryPolicy.touch`) is the one append shape that patches the record without
148
+ * advancing offset/counter. Closure-free and serializable.
149
+ */
150
+ interface AppendPlan {
151
+ preconditions: {
152
+ expectedOffset?: Offset;
153
+ expectedClosed?: boolean;
154
+ /**
155
+ * Producer compare-and-set. An **absent** `expected` means "the producer
156
+ * must not exist yet" (insert-if-absent) — it does NOT mean "don't check,
157
+ * just set". Every implementation must fail the append with reason
158
+ * `"producer"` when `expected` is absent but a state already exists.
159
+ */
160
+ producer?: {
161
+ producerId: string;
162
+ expected?: ProducerState;
163
+ next: ProducerState;
164
+ };
165
+ };
166
+ messages?: StoredMessage[];
167
+ recordPatch: StreamRecordPatch;
100
168
  }
101
- /** Bound parent/child reference tracker for a single stream. */
102
- interface StreamReferenceTracker {
103
- incrementChildRefCount(): Promise<number>;
104
- decrementChildRefCount(): Promise<number>;
169
+ /**
170
+ * `reason` is required on `precondition-failed` and names the precondition that
171
+ * tripped. When multiple preconditions fail simultaneously, attribute in the
172
+ * order **offset → closed → producer**. Backends with opaque conditional writes
173
+ * may derive `reason` best-effort from a post-failure re-read under concurrency
174
+ * (report `"offset"` when the failure cannot be attributed, e.g. the record was
175
+ * concurrently purged); single-writer attribution must be exact — the contract
176
+ * kit tests exactly that case. Core's retry loop re-plans from `record` and does
177
+ * not branch on `reason`; it exists for adapter diagnostics and kit sharpness.
178
+ */
179
+ type StorageAppendResult = {
180
+ status: "appended";
181
+ record: StreamRecord;
182
+ } | {
183
+ status: "precondition-failed";
184
+ record: StreamRecord | null;
185
+ reason: "offset" | "closed" | "producer";
186
+ };
187
+ interface StreamAppender {
188
+ append(streamId: StreamId, plan: AppendPlan): Promise<StorageAppendResult>;
105
189
  }
106
- /** Per-stream mutation coordinator (lock-like). */
107
- interface StreamMutationCoordinator {
108
- withMutationLock<T>(fn: () => Promise<T>): Promise<T>;
190
+ /**
191
+ * `record` is the single source of truth for the created stream, including a
192
+ * created-closed stream (`record.lifecycle.closed` / `closedAt` are pre-folded
193
+ * by core). Adapters persist the record as given; there is no separate
194
+ * close-after step.
195
+ */
196
+ interface CreatePlan {
197
+ record: StreamRecord;
198
+ initialMessages?: StoredMessage[];
109
199
  }
110
- /** Per-stream live-read notification hub. */
111
- interface StreamEventHub {
112
- waitForEvent(options: WaitForEventOptions): Promise<WaitForEventResult>;
113
- notify(type: StreamEventType): Promise<void> | void;
200
+ type StorageCreateResult = {
201
+ status: "created";
202
+ record: StreamRecord;
203
+ } | {
204
+ status: "exists";
205
+ record: StreamRecord;
206
+ };
207
+ interface ForkPlan {
208
+ child: StreamRecord;
209
+ sourceId: StreamId;
210
+ initialMessages?: StoredMessage[];
211
+ /**
212
+ * Source liveness check: the fork proceeds only if the source exists, is not
213
+ * soft-deleted, and its `currentOffset` is `>=` `sourceLiveAtOffset`
214
+ * (lexicographic offset comparison). Its only failure is `fork-source-gone`.
215
+ */
216
+ precondition: {
217
+ sourceLiveAtOffset: Offset;
218
+ };
114
219
  }
115
- /** Per-stream active expiry scheduler. */
116
- interface StreamExpiryScheduler {
117
- scheduleExpiry(at: number, callback?: () => Promise<void>): Promise<void> | void;
118
- cancelExpiry(): Promise<void> | void;
220
+ /**
221
+ * `exists` carries the existing child record so core can run the same
222
+ * config-match idempotency it applies to `create` — a byte-identical racing
223
+ * fork resolves as idempotent success rather than a bogus conflict.
224
+ */
225
+ type StorageForkResult = {
226
+ status: "created";
227
+ record: StreamRecord;
228
+ } | {
229
+ status: "exists";
230
+ record: StreamRecord;
231
+ } | {
232
+ status: "fork-source-gone";
233
+ };
234
+ interface DeletePlan {
235
+ streamId: StreamId;
236
+ reason: "delete" | "expiry";
119
237
  }
238
+ type StorageDeleteResult = {
239
+ status: "purged";
240
+ } | {
241
+ status: "retained-soft-deleted";
242
+ } | {
243
+ status: "not-found";
244
+ } | {
245
+ status: "gone";
246
+ };
120
247
  /**
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.
248
+ * Per-stream level-triggered live waiter. Serializable in and out: the argument
249
+ * and result carry only plain data, so the seam crosses a Durable Object RPC (or
250
+ * any future remote adapter) boundary unchanged.
251
+ *
252
+ * Required: every adapter implements `awaitChange`. A backend that can wake
253
+ * cheaply does so directly; one that cannot implements it by polling its own
254
+ * durable reads. Core wires no polling fallback in silently, but it exports the
255
+ * contract-faithful loop — `runAwaitChangeLoop` — plus the shared
256
+ * `buildChangeSnapshot` / `changeSnapshotDiffers` primitives, so an adapter
257
+ * supplies only `readRecord` + `waitForWake` (a minimal polling adapter's
258
+ * `waitForWake` is a sleep) and stays faithful to the level-triggered contract.
124
259
  */
125
- interface Stream extends StreamRecordStore, StreamMessageStore, StreamProducerStore, StreamReferenceTracker, StreamMutationCoordinator, StreamEventHub, StreamExpiryScheduler {
126
- readonly id: StreamId;
260
+ interface StreamLiveWaiter {
261
+ awaitChange(streamId: StreamId, options: AwaitChangeOptions): Promise<AwaitChangeResult>;
262
+ }
263
+ /** Per-stream active expiry scheduler. */
264
+ interface StreamExpiryScheduler {
265
+ scheduleExpiry(streamId: StreamId, at: number): Promise<void> | void;
266
+ cancelExpiry(streamId: StreamId): Promise<void> | void;
127
267
  }
128
268
  /**
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`.
269
+ * The storage backend an adapter author implements: one flat, fully serializable
270
+ * interface. Per-stream methods take `streamId` first; lifecycle intents carry
271
+ * the id in their plan. Adapters keep a private per-stream handle and delegate to
272
+ * it internally.
132
273
  */
133
- interface StreamFactory {
134
- getStream(streamId: StreamId): Promise<Stream>;
274
+ interface StorageAdapter extends StreamReader, StreamAppender, StreamLiveWaiter, StreamExpiryScheduler {
275
+ create(plan: CreatePlan): Promise<StorageCreateResult>;
276
+ fork?(plan: ForkPlan): Promise<StorageForkResult>;
277
+ delete(plan: DeletePlan): Promise<StorageDeleteResult>;
135
278
  }
136
279
  /**
137
280
  * Structured "feature not supported" protocol result. Protocol methods map
@@ -168,6 +311,14 @@ interface CreateOptions {
168
311
  closed?: boolean;
169
312
  forkedFrom?: string;
170
313
  forkOffset?: string;
314
+ /**
315
+ * Optional sub-message boundary inside the source message at `forkOffset`.
316
+ * `0` is treated as equivalent to an absent header. For binary/text it is a
317
+ * byte count within the next source message; for JSON it is a flattened
318
+ * message/item count. Requires `forkedFrom`; values `> 0` require
319
+ * `forkOffset`.
320
+ */
321
+ forkSubOffset?: number;
171
322
  }
172
323
  interface ProducerOptions {
173
324
  producerId: string;
@@ -282,6 +433,8 @@ type AppendResult = {
282
433
  } | {
283
434
  status: "conflict";
284
435
  conflictReason: "content-type" | "sequence";
436
+ } | {
437
+ status: "busy";
285
438
  } | {
286
439
  status: "stale-epoch";
287
440
  currentEpoch: number;
@@ -351,9 +504,25 @@ interface StreamProtocolFactory {
351
504
  get(streamId: string): Promise<ProtocolGetResult>;
352
505
  }
353
506
 
507
+ //#endregion
508
+ //#region src/protocol/helpers/bind-stream.d.ts
509
+ /** The per-stream surface core call sites use (was the seam `Stream`). */
510
+ interface BoundStream {
511
+ readonly id: StreamId;
512
+ getRecord(): Promise<StreamRecord | null>;
513
+ listMessages(options?: ListMessagesOptions): Promise<StoredMessage[]>;
514
+ getProducerState(producerId: string): Promise<ProducerState | undefined>;
515
+ append(plan: AppendPlan): Promise<StorageAppendResult>;
516
+ awaitChange(options: AwaitChangeOptions): Promise<AwaitChangeResult>;
517
+ scheduleExpiry(at: number): Promise<void> | void;
518
+ cancelExpiry(): Promise<void> | void;
519
+ }
520
+ declare function bindStream(adapter: StorageAdapter, id: StreamId): BoundStream;
521
+
354
522
  //#endregion
355
523
  //#region src/protocol/helpers/offset-generator.d.ts
356
524
  declare const ZERO_OFFSET: Offset;
525
+ declare function compareOffsets(a: Offset, b: Offset): number;
357
526
 
358
527
  //#endregion
359
528
  //#region src/protocol.d.ts
@@ -363,7 +532,7 @@ interface StreamProtocolOptions {
363
532
  }
364
533
  interface StreamProtocolDeps extends StreamProtocolOptions {
365
534
  storage: {
366
- factory: StreamFactory;
535
+ adapter: StorageAdapter;
367
536
  };
368
537
  }
369
538
  declare function createStreamProtocol(deps: StreamProtocolDeps): StreamProtocolFactory;
@@ -372,67 +541,99 @@ declare class StreamProtocol implements StreamProtocolFactory {
372
541
  private clock;
373
542
  private longPollTimeoutMs;
374
543
  private expiryPolicy;
375
- private gcService;
376
544
  private recordFactory;
377
545
  constructor(deps: StreamProtocolDeps);
378
546
  create(streamId: string, options: CreateOptions): Promise<CreateResult>;
379
547
  get(streamId: string): Promise<ProtocolGetResult>;
380
- /** Called by adapter schedulers/alarms; core decides soft-delete vs purge. */
548
+ /** Called by adapter schedulers/alarms; core decides whether expiry applies. */
381
549
  handleScheduledExpiry(streamId: string): Promise<void>;
382
550
  private boundProtocolStream;
551
+ /** Bind the flat adapter to one id for ergonomic core-side per-stream calls. */
383
552
  private storageStream;
384
- private withStreamMutationLock;
385
553
  }
386
554
 
387
555
  //#endregion
388
556
  //#region src/storage/memory/stream.d.ts
389
- declare class MemoryStream implements Stream {
557
+ /**
558
+ * Adapter-internal write engine input. Superset of {@link AppendPlan} with an
559
+ * optional `createRecord` — the `create`/`fork` intents reuse the same engine to
560
+ * insert the record, while the public `append` never carries `createRecord`.
561
+ */
562
+ interface WritePlan {
563
+ createRecord?: StreamRecord;
564
+ preconditions: AppendPlan["preconditions"];
565
+ messages?: StoredMessage[];
566
+ recordPatch?: StreamRecordPatch;
567
+ }
568
+ type WriteResult = {
569
+ status: "committed";
570
+ record: StreamRecord;
571
+ } | {
572
+ status: "precondition-failed";
573
+ record: StreamRecord | null;
574
+ reason?: "offset" | "closed" | "producer";
575
+ };
576
+ /** Adapter-private per-stream handle. Not on the seam — owned by the memory state. */
577
+ declare class MemoryStream {
390
578
  readonly id: StreamId;
391
579
  private readonly deleteFromState;
392
580
  private readonly records;
393
581
  private readonly messages;
394
582
  private readonly producers;
395
- private readonly lock;
396
583
  private readonly notifier;
397
584
  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;
585
+ constructor(id: StreamId, deleteFromState: () => void, onScheduledExpiry?: () => Promise<void> | void);
586
+ getRecord(): StreamRecord | null;
587
+ /** Public append intent (no `createRecord`). */
588
+ append(plan: AppendPlan): StorageAppendResult;
589
+ /**
590
+ * Adapter-internal write engine shared by `append` (no `createRecord`) and the
591
+ * `create`/`fork` intents (with `createRecord`).
592
+ */
593
+ applyMutation(plan: WritePlan): WriteResult;
594
+ listMessages(options?: ListMessagesOptions): StoredMessage[];
595
+ getProducerState(producerId: string): ProducerState | undefined;
596
+ purgeSelf(): void;
597
+ softDelete(): void;
598
+ /**
599
+ * Level-triggered live wait via the shared exported loop: re-read durable
600
+ * state first (so a mutation that landed between the caller's observation and
601
+ * this call is never missed), then park on the wake bus until the state
602
+ * advances or the budget expires. Read and park are synchronous with the wake
603
+ * bus here, so no per-park cap is needed.
604
+ */
605
+ awaitChange(options: AwaitChangeOptions): Promise<AwaitChangeResult>;
606
+ scheduleExpiry(at: number): Promise<void> | void;
415
607
  cancelExpiry(): Promise<void> | void;
416
608
  }
417
609
 
418
610
  //#endregion
419
611
  //#region src/storage/memory/state.d.ts
612
+ type MemoryExpiryHandler = (streamId: string) => Promise<void> | void;
420
613
  /** Shared in-memory stream registry. */
421
614
  declare class MemoryStreamState {
615
+ private readonly onScheduledExpiry?;
422
616
  private readonly streams;
617
+ private readonly childEdges;
618
+ constructor(onScheduledExpiry?: MemoryExpiryHandler | undefined);
423
619
  getStream(id: string): MemoryStream;
424
- stream(id: string): MemoryStream;
620
+ getExistingStream(id: string): MemoryStream | undefined;
621
+ addEdge(parent: string, child: string): void;
622
+ dropEdge(parent: string, child: string): void;
623
+ countDependents(parent: string): number;
624
+ private deleteStream;
425
625
  }
426
626
 
427
627
  //#endregion
428
- //#region src/storage/memory/factory.d.ts
429
- interface MemoryStreamFactoryOptions {
628
+ //#region src/storage/memory/adapter.d.ts
629
+ interface MemoryStorageAdapterOptions {
430
630
  /**
431
631
  * Share an existing memory state. Omit to get a fresh, isolated state.
432
632
  */
433
633
  state?: MemoryStreamState;
634
+ onScheduledExpiry?: (streamId: StreamId) => Promise<void> | void;
434
635
  }
435
- declare function createMemoryStreamFactory(options?: MemoryStreamFactoryOptions): StreamFactory;
636
+ declare function createMemoryStorageAdapter(options?: MemoryStorageAdapterOptions): StorageAdapter;
436
637
 
437
638
  //#endregion
438
639
  //#region src/http/types.d.ts
@@ -467,6 +668,36 @@ declare class ReadOnlyHttpHandler implements HttpHandlerInterface {
467
668
  fetch(request: Request): Promise<Response>;
468
669
  }
469
670
 
671
+ //#endregion
672
+ //#region src/protocol/helpers/change-snapshot.d.ts
673
+ /** Build the serializable, change-relevant snapshot of a (possibly absent) record. */
674
+ declare function buildChangeSnapshot(record: StreamRecord | null): StreamChangeSnapshot;
675
+ /**
676
+ * The level-triggered "differs" predicate. A snapshot differs from what the
677
+ * caller observed when the record was purged, transitioned to soft-deleted or
678
+ * closed, or its offset is not the parked position. Offset **inequality** — not
679
+ * just advance — is the trigger: within one incarnation an offset only ever
680
+ * advances, so a *lower* offset means the stream was purged and re-created
681
+ * while the waiter was parked, which is also "something happened".
682
+ */
683
+ declare function changeSnapshotDiffers(snapshot: StreamChangeSnapshot, options: Pick<AwaitChangeOptions, "fromOffset" | "observedClosed" | "observedSoftDeleted">): boolean;
684
+
685
+ //#endregion
686
+ //#region src/protocol/helpers/await-change-loop.d.ts
687
+ interface AwaitChangeLoopDeps {
688
+ /** Read the current durable record. May be sync or async. */
689
+ readRecord(): StreamRecord | null | Promise<StreamRecord | null>;
690
+ /** Park until a wake or the given timeout, whichever comes first. */
691
+ waitForWake(timeoutMs: number): Promise<void>;
692
+ /** Cap the TOTAL wait budget (early `timeout` return; callers re-park). */
693
+ totalCapMs?: number;
694
+ /** Cap each individual park so a lost wake is repaired within the cap. */
695
+ parkCapMs?: number;
696
+ /** Wall clock; overridable for deterministic tests. */
697
+ now?: () => number;
698
+ }
699
+ declare function runAwaitChangeLoop(deps: AwaitChangeLoopDeps, options: AwaitChangeOptions): Promise<AwaitChangeResult>;
700
+
470
701
  //#endregion
471
702
  //#region src/http/responses.d.ts
472
703
  declare class HttpResponseFactory {
@@ -499,4 +730,63 @@ declare function notSupportedResponse(result: NotSupportedResult, responses: Htt
499
730
  declare function maybeNotSupportedResponse<T>(result: T | NotSupportedResult, responses: HttpResponseFactory): Response | null;
500
731
 
501
732
  //#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 };
733
+ //#region src/testing/storage-adapter-contract.d.ts
734
+ /** Minimal test-runner surface. Satisfied by vitest's and `bun:test`'s `it`. */
735
+ interface StorageAdapterContractHarness {
736
+ it(name: string, fn: () => void | Promise<void>): void;
737
+ }
738
+ /** Build a fresh, isolated adapter for one contract case. */
739
+ type MakeStorageAdapter = () => StorageAdapter | Promise<StorageAdapter>;
740
+ /**
741
+ * Register the full storage-adapter contract against `makeAdapter` using the
742
+ * provided test harness. Wrap in the caller's own `describe` for grouping:
743
+ *
744
+ * ```ts
745
+ * import { it } from "vitest";
746
+ * describe("memory adapter contract", () => {
747
+ * runStorageAdapterContract(() => createMemoryStorageAdapter(), { it });
748
+ * });
749
+ * ```
750
+ */
751
+ declare function runStorageAdapterContract(makeAdapter: MakeStorageAdapter, harness: StorageAdapterContractHarness): void;
752
+
753
+ //#endregion
754
+ //#region src/storage/strategies/lineage-store.d.ts
755
+ interface LineageStore {
756
+ getRecord(id: StreamId): Promise<StreamRecord | null>;
757
+ purgeSelf(id: StreamId): Promise<void>;
758
+ softDelete(id: StreamId): Promise<void>;
759
+ addEdge?(parent: StreamId, child: StreamId): Promise<void>;
760
+ dropEdge?(parent: StreamId, child: StreamId): Promise<void>;
761
+ countDependents?(parent: StreamId): Promise<number>;
762
+ }
763
+ interface LineagePolicy {
764
+ countDependents(parent: StreamId): Promise<number>;
765
+ addEdge(parent: StreamId, child: StreamId): Promise<void>;
766
+ dropEdge(parent: StreamId, child: StreamId): Promise<void>;
767
+ }
768
+ type DependentsQuery = (parent: StreamId) => Promise<number>;
769
+
770
+ //#endregion
771
+ //#region src/storage/strategies/cascade-reclaim.d.ts
772
+ declare function cascadeReclaim(store: LineageStore, plan: DeletePlan, lineage: LineagePolicy): Promise<StorageDeleteResult>;
773
+ declare function plainPurge(store: LineageStore, plan: DeletePlan): Promise<StorageDeleteResult>;
774
+
775
+ //#endregion
776
+ //#region src/storage/strategies/ref-count-lineage.d.ts
777
+ declare function refCountLineage(store: LineageStore): LineagePolicy;
778
+
779
+ //#endregion
780
+ //#region src/storage/strategies/reverse-index-lineage.d.ts
781
+ declare function reverseIndexLineage(query: DependentsQuery): LineagePolicy;
782
+
783
+ //#endregion
784
+ //#region src/storage/strategies/copy-on-fork.d.ts
785
+ declare function copyOnForkReclaim(): LineagePolicy;
786
+
787
+ //#endregion
788
+ //#region src/storage/strategies/ttl-only.d.ts
789
+ declare function ttlOnlyReclaim(): LineagePolicy;
790
+
791
+ //#endregion
792
+ export { AppendConflictReason, AppendOptions, AppendPlan, AppendResult, AwaitChangeLoopDeps, AwaitChangeOptions, AwaitChangeResult, BoundStream, Clock, CreateConflictReason, CreateOptions, CreatePlan, CreateResult, DeletePlan, DeleteResult, DependentsQuery, ForkPlan, HttpHandler, HttpHandlerInterface, HttpHandlerOptions, LineagePolicy, LineageStore, ListMessagesOptions, MakeStorageAdapter, MemoryStorageAdapterOptions, MetadataResult, NotSupportedError, NotSupportedResult, Offset, ProducerOptions, ProducerState, ProtocolGetResult, ProtocolStream, ReadLiveOptions, ReadLiveResult, ReadOnlyHttpHandler, ReadOnlyHttpHandlerOptions, ReadOptions, ReadResult, StorageAdapter, StorageAdapterContractHarness, StorageAppendResult, StorageCreateResult, StorageDeleteResult, StorageForkResult, StoredMessage, StreamAppender, StreamChangeSnapshot, StreamConfig, StreamExpiryScheduler, StreamId, StreamLifecycleState, StreamLiveWaiter, StreamProtocol, StreamProtocolDeps, StreamProtocolFactory, StreamProtocolOptions, StreamReader, StreamRecord, StreamRecordPatch, ZERO_OFFSET, bindStream, buildChangeSnapshot, cascadeReclaim, changeSnapshotDiffers, compareOffsets, copyOnForkReclaim, createHttpHandler, createMemoryStorageAdapter, createReadOnlyHttpHandler, createStreamProtocol, isNotSupported, isNotSupportedError, maybeNotSupportedResponse, notSupported, notSupportedFromError, notSupportedResponse, plainPurge, refCountLineage, reverseIndexLineage, runAwaitChangeLoop, runStorageAdapterContract, ttlOnlyReclaim, unsupported };