@streamsy/core 0.15.0 → 0.17.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.
@@ -1,9 +1,15 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D8jQpDG7.js";
2
- import { l as ownerOf, n as isCanonicalIdSegment, r as templatesOverlap, s as checkWriteOwner, t as compileSegments, u as storageOf } from "./route-internal-DNL0oGTN.js";
2
+ import { I as isRetryableFault, M as InvalidStreamParams, a as compileSegments, c as templatesOverlap, f as checkWriteOwner, i as wireControlCodec, j as EncodeFault, k as StorageOwner, l as resolveParams, o as isCanonicalIdSegment, r as wireChangeCodec, s as isSingletonRoute, t as decodeMessage, u as throwInvalidStreamParams, y as newOwnerId } from "./read-message-DP1UpEFl.js";
3
3
  import { Array, Context, Data, Duration, Effect, Layer, Option, Predicate, Record, Result, Schedule, Schema, Stream } from "effect";
4
4
  // src/schema/index.ts
5
5
  const StreamId = Schema.String.pipe(Schema.brand("StreamId"));
6
- const Offset = Schema.String.pipe(Schema.check(Schema.isPattern(/^\d{16}_\d{16}$/)), Schema.brand("Offset"));
6
+ /**
7
+ * A position in a stream, as any Durable Streams server issues it. Offsets are opaque: compare
8
+ * them, but do not parse them. The read sentinels `-1` and `now` are not offsets.
9
+ */
10
+ const Offset = Schema.String.pipe(Schema.check(Schema.isNonEmpty({ expected: "a non-empty offset" }), Schema.makeFilter((value) => value !== "-1" && value !== "now", { expected: "an offset, not the sentinel -1 or now" })), Schema.brand("Offset"));
11
+ /** The offset format that Streamsy storage issues. Every `StreamsyOffset` is an `Offset`. */
12
+ const StreamsyOffset = Offset.pipe(Schema.check(Schema.isPattern(/^\d{16}_\d{16}$/)), Schema.brand("StreamsyOffset"));
7
13
  const ProducerId = Schema.String.pipe(Schema.brand("ProducerId"));
8
14
  const StreamConfig = Schema.Struct({
9
15
  contentType: Schema.String,
@@ -16,7 +22,7 @@ const StreamLifecycle = Schema.Struct({
16
22
  closed: Schema.Boolean,
17
23
  closedAt: Schema.optionalKey(Schema.Finite),
18
24
  forkedFrom: Schema.optionalKey(StreamId),
19
- forkOffset: Schema.optionalKey(Offset),
25
+ forkOffset: Schema.optionalKey(StreamsyOffset),
20
26
  forkSubOffset: Schema.optionalKey(Schema.Finite),
21
27
  softDeleted: Schema.Boolean,
22
28
  expiresAtMs: Schema.optionalKey(Schema.Finite)
@@ -25,10 +31,10 @@ const StreamRecord = Schema.Struct({
25
31
  id: StreamId,
26
32
  config: StreamConfig,
27
33
  lifecycle: StreamLifecycle,
28
- currentOffset: Offset
34
+ currentOffset: StreamsyOffset
29
35
  });
30
36
  const StoredMessage = Schema.Struct({
31
- offset: Offset,
37
+ offset: StreamsyOffset,
32
38
  timestamp: Schema.Finite,
33
39
  data: Schema.Uint8Array
34
40
  });
@@ -37,18 +43,18 @@ const ProducerState = Schema.Struct({
37
43
  lastSeq: Schema.Finite
38
44
  });
39
45
  const MessageWindow = Schema.Struct({
40
- after: Schema.optionalKey(Offset),
41
- until: Schema.optionalKey(Offset),
46
+ after: Schema.optionalKey(StreamsyOffset),
47
+ until: Schema.optionalKey(StreamsyOffset),
42
48
  limit: Schema.optionalKey(Schema.Finite)
43
49
  });
44
50
  const ChangeSnapshot = Schema.Struct({
45
51
  present: Schema.Boolean,
46
- currentOffset: Offset,
52
+ currentOffset: StreamsyOffset,
47
53
  closed: Schema.Boolean,
48
54
  softDeleted: Schema.Boolean
49
55
  });
50
56
  const RecordPatch = Schema.Struct({
51
- currentOffset: Schema.optionalKey(Offset),
57
+ currentOffset: Schema.optionalKey(StreamsyOffset),
52
58
  config: Schema.optionalKey(Schema.Struct({
53
59
  ttlSeconds: Schema.optionalKey(Schema.Finite),
54
60
  expiresAt: Schema.optionalKey(Schema.String)
@@ -65,58 +71,21 @@ const RecordPatch = Schema.Struct({
65
71
  "lastSeq"
66
72
  ])))
67
73
  });
68
- // src/fault.ts
69
- var StorageFault = class extends Schema.TaggedError()("StorageFault", {
70
- operation: Schema.String,
71
- message: Schema.String,
72
- retryable: Schema.Boolean,
73
- cause: Schema.optionalKey(Schema.Defect())
74
- }) {};
75
- var EncodeFault = class extends Schema.TaggedError()("EncodeFault", {
76
- message: Schema.String,
77
- cause: Schema.optionalKey(Schema.Defect())
78
- }) {};
79
- var DecodeFault = class extends Schema.TaggedError()("DecodeFault", {
80
- message: Schema.String,
81
- cause: Schema.optionalKey(Schema.Defect())
82
- }) {};
83
- /** Failures of the remote boundary; protocol rejections have their own typed errors. */
84
- var TransportFault = class extends Schema.TaggedError()("TransportFault", {
85
- operation: Schema.String,
86
- reason: Schema.Literals([
87
- "request",
88
- "response",
89
- "decode",
90
- "configuration"
91
- ]),
92
- /** HTTP status of the response, when available. */
93
- status: Schema.optionalKey(Schema.Int),
94
- message: Schema.String,
95
- cause: Schema.optionalKey(Schema.Defect())
96
- }) {
97
- /** Failed requests, 429s and 5xx responses can succeed later. */
98
- get retryable() {
99
- return this.reason === "request" || this.status !== void 0 && (this.status === 429 || this.status >= 500);
100
- }
101
- };
102
- const StreamsFault = Schema.Union([StorageFault, TransportFault]);
103
- /** A storage or transport failure, as opposed to a protocol rejection. */
104
- const isStreamsFault = Schema.is(StreamsFault);
105
- /** A storage or transport failure that can succeed later. */
106
- const isRetryableFault = (error) => isStreamsFault(error) && error.retryable;
107
74
  // src/offset/index.ts
108
- const ZERO_OFFSET = Offset.make(`${"0".repeat(16)}_${"0".repeat(16)}`);
109
- const isValid = (offset) => /^\d{16}_\d{16}$/.test(offset);
75
+ const ZERO_OFFSET = StreamsyOffset.make(`${"0".repeat(16)}_${"0".repeat(16)}`);
76
+ /** Whether `offset` is an opaque `Offset`: non-empty and not the read sentinels `-1` or `now`. */
77
+ const isValid = Schema.is(Offset);
78
+ /** Whether `offset` has the format that Streamsy storage issues. Servers check this. */
79
+ const isStreamsyOffset = Schema.is(StreamsyOffset);
80
+ /** Lexicographic order. The Durable Streams protocol guarantees it for offsets of one stream. */
110
81
  const compare = (a, b) => a === b ? 0 : a < b ? -1 : 1;
111
82
  const parse = (offset) => BigInt(offset.slice(0, 16));
112
83
  /** Fixed-width successor; bigint preserves all sixteen decimal digits. */
113
84
  function next(previous) {
114
85
  const value = parse(previous) + 1n;
115
86
  if (value > 9999999999999999n) throw new RangeError("Offset exhausted");
116
- return Offset.make(`${String(value).padStart(16, "0")}_${"0".repeat(16)}`);
87
+ return StreamsyOffset.make(`${String(value).padStart(16, "0")}_${"0".repeat(16)}`);
117
88
  }
118
- // src/storage/storage.ts
119
- var Storage = class extends Context.Service()("@streamsy/core/Storage") {};
120
89
  // src/protocol/tags.ts
121
90
  var StreamsReader = class extends Context.Service()("@streamsy/core/StreamsReader") {};
122
91
  var StreamsWriter = class extends Context.Service()("@streamsy/core/StreamsWriter") {};
@@ -134,7 +103,7 @@ var StreamGone = class extends Schema.TaggedError()("StreamGone", { id: StreamId
134
103
  };
135
104
  var StreamClosed = class extends Schema.TaggedError()("StreamClosed", {
136
105
  id: StreamId,
137
- offset: Schema.String
106
+ offset: Offset
138
107
  }) {
139
108
  get message() {
140
109
  return `Stream ${this.id} is closed at ${this.offset}`;
@@ -142,8 +111,8 @@ var StreamClosed = class extends Schema.TaggedError()("StreamClosed", {
142
111
  };
143
112
  var OffsetMismatch = class extends Schema.TaggedError()("OffsetMismatch", {
144
113
  id: StreamId,
145
- expected: Schema.String,
146
- actual: Schema.String
114
+ expected: Offset,
115
+ actual: Offset
147
116
  }) {
148
117
  get message() {
149
118
  return `Stream ${this.id} is at ${this.actual}, not at the expected ${this.expected}`;
@@ -151,6 +120,12 @@ var OffsetMismatch = class extends Schema.TaggedError()("OffsetMismatch", {
151
120
  };
152
121
  var AppendConflict = class extends Schema.TaggedError()("AppendConflict", {
153
122
  id: StreamId,
123
+ /**
124
+ * `sequence` when the `Stream-Seq` does not sort after the last one, `content-type` when the
125
+ * content type differs. Absent when the cause is unknown, for example from a server that does
126
+ * not send `stream-conflict-reason`.
127
+ */
128
+ reason: Schema.optionalKey(Schema.Literals(["sequence", "content-type"])),
154
129
  message: Schema.String
155
130
  }) {};
156
131
  var StreamBusy = class extends Schema.TaggedError()("StreamBusy", { id: StreamId }) {
@@ -247,108 +222,221 @@ const isProtocolError = (error) => Record.has(protocolErrorTags, error._tag);
247
222
  /** Constructors and matchers for the protocol results above. */
248
223
  const CreateResult = Data.taggedEnum();
249
224
  const AppendResult = Data.taggedEnum();
250
- // src/toolkit/address.ts
251
- var address_exports = /* @__PURE__ */ __exportAll({
252
- bytes: () => bytes$2,
225
+ // src/toolkit/durable-state.ts
226
+ var durable_state_exports = /* @__PURE__ */ __exportAll({
227
+ changeCodec: () => changeCodec,
228
+ changes: () => changes,
229
+ controlCodec: () => controlCodec,
253
230
  isChange: () => isChange,
254
231
  isControl: () => isControl,
255
232
  isUpsert: () => isUpsert,
256
- json: () => json$2,
233
+ materialize: () => materialize,
234
+ materialized: () => materialized,
235
+ remove: () => remove$1,
257
236
  reset: () => reset,
258
237
  snapshotEnd: () => snapshotEnd,
259
238
  snapshotStart: () => snapshotStart,
260
- state: () => state$2,
261
- stateChange: () => stateChange,
262
- stateControl: () => stateControl
239
+ upsert: () => upsert
263
240
  });
264
- /** The address constructors. Each class owns the `_tag` of one address kind. */
265
- const JsonAddress = Data.TaggedClass("Json");
266
- const BytesAddress = Data.TaggedClass("Bytes");
267
- function json$2(id, options) {
268
- return new JsonAddress({
269
- id: StreamId.make(id),
270
- contentType: "application/json",
271
- codec: Schema.fromJsonString(Schema.toCodecJson(options.schema))
272
- });
273
- }
274
241
  /**
275
242
  * A codec for the upsert and delete change events of one collection.
276
- * `state` composes one of these per collection. Omit optional headers instead
277
- * of setting them to `undefined`.
243
+ * `StreamAddress.state` composes one of these per collection. Omit optional
244
+ * headers instead of setting them to `undefined`.
278
245
  */
279
- function stateChange(options) {
280
- const upsertOperation = Schema.Union([
281
- Schema.Literal("upsert"),
282
- Schema.Literal("insert").transform("upsert"),
283
- Schema.Literal("update").transform("upsert")
284
- ]);
285
- const headers = {
286
- offset: Schema.optionalKey(Schema.String),
287
- txid: Schema.optionalKey(Schema.String),
288
- timestamp: Schema.optionalKey(Schema.String),
289
- from: Schema.optionalKey(Schema.String)
290
- };
291
- return Schema.Union([Schema.Struct({
292
- type: Schema.Literal(options.type),
293
- key: Schema.String,
294
- value: options.schema,
295
- headers: Schema.Struct({
296
- operation: upsertOperation,
297
- ...headers
298
- })
299
- }), Schema.Struct({
300
- type: Schema.Literal(options.type),
301
- key: Schema.String,
302
- old_value: Schema.optionalKey(options.schema),
303
- headers: Schema.Struct({
304
- operation: Schema.Literal("delete"),
305
- ...headers
306
- })
307
- })]);
246
+ function changeCodec(options) {
247
+ return wireChangeCodec(Schema.Literal(options.type), options.schema, options.type);
308
248
  }
309
249
  /** The codec for a State control message. It needs no services. */
310
- const stateControl = Schema.Struct({ headers: Schema.Struct({
311
- control: Schema.Literals([
312
- "snapshot-start",
313
- "snapshot-end",
314
- "reset"
315
- ]),
316
- offset: Schema.optionalKey(Schema.String)
317
- }) });
250
+ const controlCodec = wireControlCodec;
318
251
  /** True for a control message. A change has `headers.operation` and no `headers.control`. */
319
252
  const isControl = (event) => Predicate.hasProperty(event.headers, "control");
320
253
  /** True for an upsert or delete change. */
321
254
  const isChange = (event) => !isControl(event);
322
255
  /** True for an upsert change, with its value available. */
323
256
  const isUpsert = (event) => isChange(event) && event.headers.operation === "upsert";
324
- const control = (name, options) => ({ headers: options.offset === void 0 ? { control: name } : {
257
+ const makeControl = (name, options) => ({ headers: options.offset === void 0 ? { control: name } : {
325
258
  control: name,
326
259
  offset: options.offset
327
260
  } });
328
261
  /** A `reset` control. A reader should clear its materialized state and apply what follows. */
329
- const reset = (options = {}) => control("reset", options);
262
+ const reset = (options = {}) => makeControl("reset", options);
330
263
  /** A `snapshot-start` control. The changes up to `snapshot-end` form a complete snapshot. */
331
- const snapshotStart = (options = {}) => control("snapshot-start", options);
264
+ const snapshotStart = (options = {}) => makeControl("snapshot-start", options);
332
265
  /** A `snapshot-end` control. It closes the snapshot that `snapshot-start` opened. */
333
- const snapshotEnd = (options = {}) => control("snapshot-end", options);
266
+ const snapshotEnd = (options = {}) => makeControl("snapshot-end", options);
267
+ const operations = Data.taggedEnum();
268
+ const isOperation = (entry) => Predicate.isTagged(entry, "Upsert") || Predicate.isTagged(entry, "Delete");
269
+ /** Describe an upsert into a collection. The key is read from the value. */
270
+ const upsert = (type, value, options = {}) => operations.Upsert({
271
+ type,
272
+ value,
273
+ ...options
274
+ });
275
+ /** Describe a delete from a collection by key. An `oldValue` is written as `old_value`. */
276
+ const remove$1 = (type, key, options = {}) => operations.Delete({
277
+ type,
278
+ key,
279
+ ...options
280
+ });
281
+ /**
282
+ * The key as a string. A null, undefined or empty key gives `""`, which the State codec rejects
283
+ * when the change is encoded, so `append` fails with `EncodeFault`.
284
+ */
285
+ const keyOf = (raw) => raw === null || raw === void 0 ? "" : String(raw);
286
+ /** Read the key field of a value. `Key` limits the field to strings and numbers. */
287
+ const readKey = (field, value) => String(value[field] ?? "");
288
+ function changes(source, entries, options = {}) {
289
+ const { offset } = options;
290
+ return Array.map(entries, (entry, index) => isOperation(entry) ? stampChange(source.collections, entry, offset, index) : stampControl(entry, offset));
291
+ }
292
+ const stampChange = (collections, entry, offset, index) => {
293
+ const collection = Record.has(collections, entry.type) ? collections[entry.type] : void 0;
294
+ if (collection === void 0) throw new TypeError(`Unknown state collection "${entry.type}"`);
295
+ const override = entry.headers ?? {};
296
+ const txid = override.txid ?? (offset === void 0 ? void 0 : `${offset}:${index}`);
297
+ const headers = {};
298
+ if (offset !== void 0) headers.offset = offset;
299
+ if (txid !== void 0) headers.txid = txid;
300
+ if (override.timestamp !== void 0) headers.timestamp = override.timestamp;
301
+ if (override.from !== void 0) headers.from = override.from;
302
+ if (Predicate.isTagged(entry, "Upsert")) {
303
+ const key = readKey(collection.key, entry.value);
304
+ return {
305
+ type: entry.type,
306
+ key,
307
+ value: entry.value,
308
+ headers: {
309
+ operation: "upsert",
310
+ ...headers
311
+ }
312
+ };
313
+ }
314
+ const key = keyOf(entry.key);
315
+ return entry.oldValue === void 0 ? {
316
+ type: entry.type,
317
+ key,
318
+ headers: {
319
+ operation: "delete",
320
+ ...headers
321
+ }
322
+ } : {
323
+ type: entry.type,
324
+ key,
325
+ old_value: entry.oldValue,
326
+ headers: {
327
+ operation: "delete",
328
+ ...headers
329
+ }
330
+ };
331
+ };
332
+ const stampControl = (entry, offset) => offset === void 0 || entry.headers.offset !== void 0 ? entry : { headers: {
333
+ control: entry.headers.control,
334
+ offset
335
+ } };
336
+ /** A row key that is unique across collections, for snapshot bookkeeping. */
337
+ const snapshotKey = (type, key) => `${type}\u0000${key}`;
338
+ /** Empty materialized state for the collections of `address`. */
339
+ function materialized(address) {
340
+ const rows = {};
341
+ for (const type of Record.keys(address.collections)) rows[type] = /* @__PURE__ */ new Map();
342
+ return {
343
+ rows,
344
+ snapshot: void 0
345
+ };
346
+ }
347
+ /**
348
+ * Fold State events into materialized state, with the State protocol rules:
349
+ *
350
+ * - `upsert` sets the row of its key, and `delete` removes it.
351
+ * - `reset` clears every collection.
352
+ * - `snapshot-end` removes each row that no change since `snapshot-start` named.
353
+ * A snapshot may span several calls.
354
+ *
355
+ * The input state is not changed. Only the collections that `events` touch are copied.
356
+ */
357
+ function materialize(state, events) {
358
+ const rows = /* @__PURE__ */ new Map();
359
+ let cleared = false;
360
+ let snapshot = state.snapshot === void 0 ? void 0 : new Set(state.snapshot);
361
+ const source = (type) => cleared ? void 0 : Record.has(state.rows, type) ? state.rows[type] : void 0;
362
+ const writable = (type) => {
363
+ const existing = rows.get(type);
364
+ if (existing !== void 0) return existing;
365
+ const copy = new Map(source(type));
366
+ rows.set(type, copy);
367
+ return copy;
368
+ };
369
+ for (const event of events) {
370
+ if (isControl(event)) {
371
+ const control = event.headers.control;
372
+ if (control === "reset") {
373
+ cleared = true;
374
+ rows.clear();
375
+ snapshot = void 0;
376
+ } else if (control === "snapshot-start") snapshot = /* @__PURE__ */ new Set();
377
+ else if (snapshot !== void 0) {
378
+ const seen = snapshot;
379
+ for (const type of Record.keys(state.rows)) {
380
+ const table = writable(type);
381
+ for (const key of Array.fromIterable(table.keys())) if (!seen.has(snapshotKey(type, key))) table.delete(key);
382
+ }
383
+ snapshot = void 0;
384
+ }
385
+ continue;
386
+ }
387
+ const table = writable(event.type);
388
+ if (isUpsert(event)) {
389
+ table.set(event.key, event.value);
390
+ snapshot?.add(snapshotKey(event.type, event.key));
391
+ } else {
392
+ table.delete(event.key);
393
+ snapshot?.delete(snapshotKey(event.type, event.key));
394
+ }
395
+ }
396
+ const next = {};
397
+ for (const type of Record.keys(state.rows)) next[type] = rows.get(type) ?? (cleared ? /* @__PURE__ */ new Map() : state.rows[type]);
398
+ return {
399
+ rows: next,
400
+ snapshot
401
+ };
402
+ }
403
+ // src/toolkit/address.ts
404
+ var address_exports = /* @__PURE__ */ __exportAll({
405
+ bytes: () => bytes$2,
406
+ json: () => json$2,
407
+ state: () => state$2
408
+ });
409
+ /** The address constructors. Each class owns the `_tag` of one address kind. */
410
+ const JsonAddress = Data.TaggedClass("Json");
411
+ const BytesAddress = Data.TaggedClass("Bytes");
412
+ function json$2(id, options) {
413
+ return new JsonAddress({
414
+ id: StreamId.make(id),
415
+ contentType: "application/json",
416
+ codec: Schema.fromJsonString(Schema.toCodecJson(options.schema))
417
+ });
418
+ }
334
419
  /**
335
420
  * A stream of Durable State events for several collections. Each record
336
421
  * key is the `type` on the wire; each entry gives the value schema and the value
337
422
  * field that becomes the event `key`. The codec also decodes and encodes the
338
423
  * State control messages `snapshot-start`, `snapshot-end` and `reset`.
424
+ * Typed reads skip changes to undeclared collections unless `strict` is true.
339
425
  */
340
426
  function state$2(id, options) {
341
- const codecs = Array.map(Record.toEntries(options.collections), ([type, collection]) => stateChange({
427
+ const codecs = Array.map(Record.toEntries(options.collections), ([type, collection]) => changeCodec({
342
428
  schema: collection.schema,
343
429
  type
344
430
  }));
345
- const address = json$2(id, { schema: Schema.Union([...codecs, stateControl]) });
346
- return new JsonAddress({
431
+ const address = json$2(id, { schema: Schema.Union([...codecs, controlCodec]) });
432
+ const stateAddress = new JsonAddress({
347
433
  id: address.id,
348
434
  contentType: address.contentType,
349
435
  codec: address.codec,
350
436
  collections: options.collections
351
437
  });
438
+ if (options.strict !== void 0) Object.assign(stateAddress, { strict: options.strict });
439
+ return stateAddress;
352
440
  }
353
441
  /** Items from one bytes append are joined into one stored message. */
354
442
  function bytes$2(id, options = {}) {
@@ -404,10 +492,15 @@ function buildId(template, segments, codecs, params) {
404
492
  if (segment.kind === "literal") return segment.value;
405
493
  const codec = codecs[segment.name];
406
494
  const value = record[segment.name];
407
- if (codec === void 0 || value === void 0) throw new RangeError(`stream route ${template} has no value for parameter: ${segment.name}`);
495
+ const invalid = (message) => throwInvalidStreamParams(new InvalidStreamParams({
496
+ stream: template,
497
+ parameter: segment.name,
498
+ message
499
+ }));
500
+ if (codec === void 0 || value === void 0) return invalid(`stream route ${template} has no value for parameter: ${segment.name}`);
408
501
  const text = Option.getOrUndefined(Schema.encodeOption(codec)(value));
409
- if (text === void 0) throw new RangeError(`stream route ${template} parameter ${segment.name} cannot encode to an id segment`);
410
- if (!isCanonicalIdSegment(text)) throw new RangeError(`stream route ${template} parameter ${segment.name} is not a canonical id segment: ${text}`);
502
+ if (text === void 0) return invalid(`stream route ${template} parameter ${segment.name} cannot encode to an id segment`);
503
+ if (!isCanonicalIdSegment(text)) return invalid(`stream route ${template} parameter ${segment.name} is not a canonical id segment: ${text}`);
411
504
  return text;
412
505
  });
413
506
  return StreamId.make(Array.join(built, "/"));
@@ -420,9 +513,16 @@ function checkTemplateParams(template, names, codecs) {
420
513
  for (const name of names) if (codecs[name] === void 0) throw new RangeError(`stream route ${template} has no codec for parameter: ${name}`);
421
514
  for (const name of Record.keys(codecs)) if (!names.includes(name)) throw new RangeError(`stream route codec is absent from the template: ${name}`);
422
515
  }
516
+ /**
517
+ * The codec record of a route. A singleton template may omit `params`, which is then the
518
+ * empty record. `checkTemplateParams` still rejects a missing codec at run time.
519
+ */
520
+ function codecsOf(params) {
521
+ return params ?? {};
522
+ }
423
523
  function json$1(template, options) {
424
524
  const { segments, names } = compileSegments(template);
425
- const codecs = options.params;
525
+ const codecs = codecsOf(options.params);
426
526
  checkTemplateParams(template, names, codecs);
427
527
  return new Route({
428
528
  template,
@@ -434,7 +534,7 @@ function json$1(template, options) {
434
534
  }
435
535
  function state$1(template, options) {
436
536
  const { segments, names } = compileSegments(template);
437
- const codecs = options.params;
537
+ const codecs = codecsOf(options.params);
438
538
  checkTemplateParams(template, names, codecs);
439
539
  return new Route({
440
540
  template,
@@ -446,16 +546,16 @@ function state$1(template, options) {
446
546
  address: (params) => state$2(buildId(template, segments, codecs, params), options)
447
547
  });
448
548
  }
449
- function bytes$1(template, options) {
549
+ function bytes$1(template, ...[options]) {
450
550
  const { segments, names } = compileSegments(template);
451
- const codecs = options.params;
551
+ const codecs = codecsOf(options?.params);
452
552
  checkTemplateParams(template, names, codecs);
453
553
  return new Route({
454
554
  template,
455
555
  paramSchema: pathSchema(codecs),
456
556
  match: (id) => Option.isSome(matchTemplate(segments, codecs, id)),
457
557
  parse: (id) => matchTemplate(segments, codecs, id),
458
- address: (params) => bytes$2(buildId(template, segments, codecs, params), { contentType: options.contentType ?? "application/octet-stream" })
558
+ address: (params) => bytes$2(buildId(template, segments, codecs, params), { contentType: options?.contentType ?? "application/octet-stream" })
459
559
  });
460
560
  }
461
561
  /** Escape hatch for a grammar a template cannot express, such as a regex stream. */
@@ -469,6 +569,7 @@ function custom$1(options) {
469
569
  }
470
570
  // src/toolkit/streams.ts
471
571
  var streams_exports = /* @__PURE__ */ __exportAll({
572
+ Batch: () => Batch,
472
573
  append: () => append,
473
574
  collect: () => collect,
474
575
  create: () => create,
@@ -476,11 +577,17 @@ var streams_exports = /* @__PURE__ */ __exportAll({
476
577
  fold: () => fold,
477
578
  follow: () => follow,
478
579
  head: () => head,
479
- items: () => items,
480
580
  read: () => read,
481
- remove: () => remove,
482
- session: () => session
581
+ readNext: () => readNext,
582
+ remove: () => remove
483
583
  });
584
+ /** Operators for streams of batches. */
585
+ const Batch = {
586
+ /**
587
+ * Flatten a stream of batches into its items. The items carry no offset, so keep the batches
588
+ * when you need to resume from where you stopped.
589
+ */
590
+ items: (batches) => batches.pipe(Stream.flatMap((batch) => Stream.fromIterable(batch.items))) };
484
591
  const create = Effect.fn("Streams.create")(function* (address, options = {}) {
485
592
  return yield* (yield* StreamsWriter).create(address.id, {
486
593
  ...options,
@@ -521,12 +628,10 @@ function concatBytes(parts) {
521
628
  return result;
522
629
  }
523
630
  const decode = Effect.fn("Streams.decode")(function* (address, result) {
631
+ const items = yield* Effect.forEach(result.messages, (message, index) => decodeMessage(address, message, index));
524
632
  return {
525
- items: yield* Effect.forEach(result.messages, (message, index) => Schema.decodeEffect(address.codec)(Predicate.isTagged(address, "Json") ? new TextDecoder().decode(message.data) : message.data).pipe(Effect.mapError((cause) => new DecodeFault({
526
- message: `Cannot decode ${address.id} at read message ${index}`,
527
- cause
528
- })))),
529
- nextOffset: result.nextOffset,
633
+ items: Array.getSomes(items),
634
+ offset: result.nextOffset,
530
635
  upToDate: result.upToDate,
531
636
  closed: result.closed
532
637
  };
@@ -539,7 +644,7 @@ function read(address, options = {}) {
539
644
  ...options,
540
645
  offset
541
646
  }));
542
- return [[batch], batch.upToDate ? Option.none() : Option.some(batch.nextOffset)];
647
+ return [[batch], batch.upToDate ? Option.none() : Option.some(batch.offset)];
543
648
  }));
544
649
  }));
545
650
  }
@@ -550,13 +655,13 @@ function read(address, options = {}) {
550
655
  const fold = Effect.fn("Streams.fold")(function* (address, initial, f, options = {}) {
551
656
  return yield* read(address, options).pipe(Stream.runFold(() => ({
552
657
  state: initial(),
553
- offset: options.offset ?? ZERO_OFFSET
658
+ offset: ZERO_OFFSET
554
659
  }), (folded, batch) => {
555
660
  let state = folded.state;
556
661
  for (const item of batch.items) state = f(state, item);
557
662
  return {
558
663
  state,
559
- offset: batch.nextOffset
664
+ offset: batch.offset
560
665
  };
561
666
  }));
562
667
  });
@@ -627,7 +732,8 @@ const capAt30Seconds = Schedule.modifyDelay(({ duration }) => Effect.succeed(Dur
627
732
  /** Same shape as `Projection.follow`'s default; kept as a copy until a third user appears. */
628
733
  const defaultFollowRetry = Schedule.exponential("200 millis").pipe(capAt30Seconds, Schedule.jittered, capAt30Seconds);
629
734
  /**
630
- * Catch up, then wait one readNext at a time, filtering empty open batches.
735
+ * Catch up, then wait one readNext at a time. A page with stored messages
736
+ * advances the reader even when all of its State changes are skipped.
631
737
  * A read that fails with a retryable transport or storage fault is retried from the same
632
738
  * offset, so a restart or network drop yields each item once.
633
739
  */
@@ -656,17 +762,25 @@ function follow(address, options = {}) {
656
762
  const [result, cursor] = yield* retrying(state.live ? live(state) : catchUp(state));
657
763
  const batch = yield* decode(address, result);
658
764
  const next = {
659
- offset: batch.nextOffset,
765
+ offset: batch.offset,
660
766
  live: batch.upToDate,
661
767
  cursor
662
768
  };
663
- return [batch.items.length > 0 || batch.closed ? [batch] : [], batch.closed ? Option.none() : Option.some(next)];
769
+ return [result.messages.length > 0 || batch.closed ? [batch] : [], batch.closed ? Option.none() : Option.some(next)];
664
770
  }));
665
771
  }));
666
772
  }
667
- const items = (batches) => batches.pipe(Stream.flatMap((batch) => Stream.fromIterable(batch.items)));
668
- const session = Effect.fn("Streams.session")(function* (address, options) {
669
- return yield* (yield* StreamsReader).readNext(address.id, options);
773
+ /**
774
+ * One live read: the items after `offset` if there are any, or else wait once for some. It
775
+ * decodes like `follow`, so a State reader skips changes to collections it does not declare.
776
+ */
777
+ const readNext = Effect.fn("Streams.readNext")(function* (address, options) {
778
+ const result = yield* (yield* StreamsReader).readNext(address.id, options);
779
+ return {
780
+ ...yield* decode(address, result),
781
+ cursor: result.cursor,
782
+ timedOut: result.timedOut
783
+ };
670
784
  });
671
785
  const head = Effect.fn("Streams.head")(function* (address) {
672
786
  return yield* (yield* StreamsReader).head(address.id);
@@ -689,11 +803,10 @@ function checkNoOverlap(routes) {
689
803
  });
690
804
  for (const [index, template] of templates.entries()) for (const other of templates.slice(index + 1)) if (templatesOverlap(template, other)) throw new RangeError(`stream route templates overlap: ${template} and ${other}`);
691
805
  }
692
- /** Build a stream service over one protocol graph's wires, with the ownership guard on writes. */
693
- function wireApi(route, services) {
694
- const storage = storageOf(services.writer);
695
- const owner = storage === void 0 ? services.writer : ownerOf(storage);
696
- const write = (id, run) => checkWriteOwner(owner, id, storage !== void 0).pipe(Effect.andThen(Effect.suspend(run)));
806
+ /** Guard a protocol graph's wires for one route, with the ownership guard on writes. */
807
+ function wireRoute(route, services) {
808
+ const { owner, knownOwner } = services;
809
+ const write = (id, run) => checkWriteOwner(owner, id, knownOwner).pipe(Effect.andThen(Effect.suspend(run)));
697
810
  const own = (id, run) => Effect.suspend(() => route.match(id) ? run() : Effect.die(/* @__PURE__ */ new RangeError(`${id} is outside stream ${route.template}`)));
698
811
  const wire = {
699
812
  head: (id) => own(id, () => services.reader.head(id)),
@@ -710,25 +823,49 @@ function wireApi(route, services) {
710
823
  append: (id, options) => write(id, () => own(id, () => services.writer.append(id, options))),
711
824
  remove: (id) => write(id, () => own(id, () => services.writer.remove(id)))
712
825
  };
713
- const context = Context.make(StreamsReader, wire).pipe(Context.add(StreamsWriter, wire));
714
826
  return {
715
827
  owner,
716
- route,
717
828
  wire,
718
- create: (params, options) => create(route.address(params), options).pipe(Effect.provide(context)),
719
- append: (params, items, options) => append(route.address(params), items, options).pipe(Effect.provide(context)),
720
- read: (params, options) => read(route.address(params), options).pipe(Stream.provideContext(context)),
721
- fold: (params, initial, f, options) => fold(route.address(params), initial, f, options).pipe(Effect.provide(context)),
722
- collect: (params, options) => collect(route.address(params), options).pipe(Effect.provide(context)),
723
- decide: (params, spec) => decide(route.address(params), spec).pipe(Effect.provide(context)),
724
- follow: (params, options) => follow(route.address(params), options).pipe(Stream.provideContext(context)),
725
- session: (params, options) => wire.readNext(route.address(params).id, options),
726
- head: (params) => wire.head(route.address(params).id),
727
- remove: (params) => wire.remove(route.address(params).id),
728
- fork: (params, source, options) => wire.fork(route.address(params).id, route.address(source).id, {
729
- ...options,
730
- contentType: route.address(params).contentType
731
- })
829
+ context: Context.make(StreamsReader, wire).pipe(Context.add(StreamsWriter, wire))
830
+ };
831
+ }
832
+ /** Build the handle of one stream. `address` fails with `E` when its params cannot form an id. */
833
+ function wireHandle(wired, address) {
834
+ const { owner, wire, context } = wired;
835
+ const run = (f) => address.pipe(Effect.flatMap(f), Effect.provide(context));
836
+ const stream = (f) => Stream.unwrap(address.pipe(Effect.map(f))).pipe(Stream.provideContext(context));
837
+ return {
838
+ owner,
839
+ wire,
840
+ address,
841
+ create: (options) => run((bound) => create(bound, options)),
842
+ append: (items, options) => run((bound) => append(bound, items, options)),
843
+ read: (options) => stream((bound) => read(bound, options)),
844
+ fold: (initial, f, options) => run((bound) => fold(bound, initial, f, options)),
845
+ collect: (options) => run((bound) => collect(bound, options)),
846
+ decide: (spec) => run((bound) => decide(bound, spec)),
847
+ follow: (options) => stream((bound) => follow(bound, options)),
848
+ readNext: (options) => run((bound) => readNext(bound, options)),
849
+ head: () => address.pipe(Effect.flatMap(({ id }) => wire.head(id))),
850
+ remove: () => address.pipe(Effect.flatMap(({ id }) => wire.remove(id)))
851
+ };
852
+ }
853
+ /** Build the service of a stream with params: `at(params)` gives the handle of one stream. */
854
+ function wireFamily(route, wired, bindAddress) {
855
+ const { owner, wire } = wired;
856
+ return {
857
+ owner,
858
+ wire,
859
+ at: (params) => {
860
+ const address = resolveParams(() => bindAddress(params));
861
+ return {
862
+ ...wireHandle(wired, address),
863
+ fork: (source, options) => Effect.all([address, resolveParams(() => route.address(source))]).pipe(Effect.flatMap(([target, from]) => wire.fork(target.id, from.id, {
864
+ ...options,
865
+ contentType: target.contentType
866
+ })))
867
+ };
868
+ }
732
869
  };
733
870
  }
734
871
  /**
@@ -741,13 +878,29 @@ function define() {
741
878
  return (name, route) => {
742
879
  const key = `@streamsy/core/Stream/${name}`;
743
880
  const service = Context.Service()(key);
881
+ const at = (params) => {
882
+ return Object.assign(route.address(params), { stream: service });
883
+ };
884
+ const singleton = isSingletonRoute(route) ? Option.some(at({})) : Option.none();
885
+ const make = (services) => {
886
+ const wired = wireRoute(route, services);
887
+ return Option.match(singleton, {
888
+ onNone: () => wireFamily(route, wired, at),
889
+ onSome: (address) => wireHandle(wired, Effect.succeed(address))
890
+ });
891
+ };
744
892
  const declared = Object.defineProperty(service, metadataKey, { value: {
745
893
  route,
746
- make: (services) => wireApi(route, services)
747
- } });
748
- return Object.assign(declared, route, { at: (params) => {
749
- return Object.assign(route.address(params), { stream: service });
894
+ make
750
895
  } });
896
+ const statics = Option.match(singleton, {
897
+ onNone: () => ({
898
+ at,
899
+ resolve: (params) => resolveParams(() => at(params))
900
+ }),
901
+ onSome: (address) => ({ singleton: address })
902
+ });
903
+ return Object.assign(declared, route, statics);
751
904
  };
752
905
  }
753
906
  const json = () => (name, ...args) => define()(name, json$1(...args));
@@ -779,19 +932,28 @@ function checkStreams(keys) {
779
932
  function bind(source, streams) {
780
933
  const keys = streams.streams;
781
934
  checkStreams(keys);
782
- const bindContext = (wires, storage) => {
783
- if (storage !== void 0 && (storageOf(wires.reader) !== storage || storageOf(wires.writer) !== storage)) throw new RangeError("The exposed Storage does not own the protocol wires");
935
+ const bindContext = (wires) => {
784
936
  let context = Context.empty();
785
937
  for (const key of keys) context = Context.add(context, key, declaration(key).make(wires));
786
938
  return context;
787
939
  };
788
940
  return source.pipe(Layer.flatMap((context) => Layer.syncContext(() => bindContext({
789
941
  reader: Context.get(context, StreamsReader),
790
- writer: Context.get(context, StreamsWriter)
791
- }, Option.getOrUndefined(Context.getOption(context, Storage))))));
942
+ writer: Context.get(context, StreamsWriter),
943
+ ...Option.match(Context.getOption(context, StorageOwner), {
944
+ onNone: () => ({
945
+ owner: newOwnerId("remote"),
946
+ knownOwner: false
947
+ }),
948
+ onSome: (owner) => ({
949
+ owner: owner.id,
950
+ knownOwner: true
951
+ })
952
+ })
953
+ }))));
792
954
  }
793
955
  function group(...keys) {
794
956
  checkStreams(keys);
795
957
  return Object.freeze({ streams: Object.freeze(keys) });
796
958
  }
797
- export { ProducerState as $, StreamBusy as A, isValid as B, InvalidEpochSeq as C, OffsetMismatch as D, NotSupported as E, StreamsReader as F, StreamsFault as G, DecodeFault as H, StreamsWriter as I, isStreamsFault as J, TransportFault as K, Storage as L, StreamGone as M, StreamNotFound as N, ProducerGap as O, isProtocolError as P, ProducerId as Q, ZERO_OFFSET as R, InvalidCreateRequest as S, InvalidReadRequest as T, EncodeFault as U, next as V, StorageFault as W, MessageWindow as X, ChangeSnapshot as Y, Offset as Z, CreateResult as _, custom as a, StreamRecord as at, ForkSourceNotFound as b, state as c, address_exports as d, RecordPatch as et, isControl as f, AppendResult as g, stateControl as h, checkStreams as i, StreamLifecycle as it, StreamClosed as j, StaleEpoch as k, streams_exports as l, stateChange as m, bind as n, StreamConfig as nt, group as o, isUpsert as p, isRetryableFault as q, bytes as r, StreamId as rt, json as s, Wildcard as t, StoredMessage as tt, route_exports as u, AppendConflict as v, InvalidForkRequest as w, InvalidAppendRequest as x, CreateConflict as y, compare as z };
959
+ export { StreamLifecycle as $, ProducerGap as A, compare as B, InvalidAppendRequest as C, InvalidReadRequest as D, InvalidForkRequest as E, StreamNotFound as F, MessageWindow as G, isValid as H, isProtocolError as I, ProducerState as J, Offset as K, StreamsReader as L, StreamBusy as M, StreamClosed as N, NotSupported as O, StreamGone as P, StreamId as Q, StreamsWriter as R, ForkSourceNotFound as S, InvalidEpochSeq as T, next as U, isStreamsyOffset as V, ChangeSnapshot as W, StoredMessage as X, RecordPatch as Y, StreamConfig as Z, isUpsert as _, custom as a, AppendConflict as b, state as c, route_exports as d, StreamRecord as et, address_exports as f, isControl as g, durable_state_exports as h, checkStreams as i, StaleEpoch as j, OffsetMismatch as k, Batch as l, controlCodec as m, bind as n, group as o, changeCodec as p, ProducerId as q, bytes as r, json as s, Wildcard as t, StreamsyOffset as tt, streams_exports as u, AppendResult as v, InvalidCreateRequest as w, CreateConflict as x, CreateResult as y, ZERO_OFFSET as z };