@streamsy/core 0.2.0 → 0.4.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.
@@ -0,0 +1,829 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
2
+ import { i as checkWriteOwner, o as ownerOf, s as storageOf } from "./owner-BQzMpfC1.js";
3
+ import { Context, Data, Duration, Effect, Layer, Option, Predicate, Result, Schedule, Schema, Stream } from "effect";
4
+ import { isReadonlyArrayNonEmpty } from "effect/Array";
5
+ //#region src/schema/index.ts
6
+ const StreamId = Schema.String.pipe(Schema.brand("StreamId"));
7
+ const Offset = Schema.String.pipe(Schema.check(Schema.isPattern(/^\d{16}_\d{16}$/)), Schema.brand("Offset"));
8
+ const ProducerId = Schema.String.pipe(Schema.brand("ProducerId"));
9
+ const StreamConfig = Schema.Struct({
10
+ contentType: Schema.String,
11
+ ttlSeconds: Schema.optionalKey(Schema.Finite),
12
+ expiresAt: Schema.optionalKey(Schema.String),
13
+ createdAt: Schema.Finite
14
+ });
15
+ const StreamLifecycle = Schema.Struct({
16
+ lastSeq: Schema.optionalKey(Schema.String),
17
+ closed: Schema.Boolean,
18
+ closedAt: Schema.optionalKey(Schema.Finite),
19
+ forkedFrom: Schema.optionalKey(StreamId),
20
+ forkOffset: Schema.optionalKey(Offset),
21
+ forkSubOffset: Schema.optionalKey(Schema.Finite),
22
+ softDeleted: Schema.Boolean,
23
+ expiresAtMs: Schema.optionalKey(Schema.Finite)
24
+ });
25
+ const StreamRecord = Schema.Struct({
26
+ id: StreamId,
27
+ config: StreamConfig,
28
+ lifecycle: StreamLifecycle,
29
+ currentOffset: Offset
30
+ });
31
+ const StoredMessage = Schema.Struct({
32
+ offset: Offset,
33
+ timestamp: Schema.Finite,
34
+ data: Schema.Uint8Array
35
+ });
36
+ const ProducerState = Schema.Struct({
37
+ epoch: Schema.Finite,
38
+ lastSeq: Schema.Finite
39
+ });
40
+ const MessageWindow = Schema.Struct({
41
+ after: Schema.optionalKey(Offset),
42
+ until: Schema.optionalKey(Offset),
43
+ limit: Schema.optionalKey(Schema.Finite)
44
+ });
45
+ const ChangeSnapshot = Schema.Struct({
46
+ present: Schema.Boolean,
47
+ currentOffset: Offset,
48
+ closed: Schema.Boolean,
49
+ softDeleted: Schema.Boolean
50
+ });
51
+ const RecordPatch = Schema.Struct({
52
+ currentOffset: Schema.optionalKey(Offset),
53
+ config: Schema.optionalKey(Schema.Struct({
54
+ ttlSeconds: Schema.optionalKey(Schema.Finite),
55
+ expiresAt: Schema.optionalKey(Schema.String)
56
+ })),
57
+ lifecycle: Schema.optionalKey(Schema.Struct({
58
+ ...StreamLifecycle.fields,
59
+ closed: Schema.optionalKey(Schema.Boolean),
60
+ softDeleted: Schema.optionalKey(Schema.Boolean)
61
+ })),
62
+ clear: Schema.optionalKey(Schema.Array(Schema.Literals([
63
+ "ttlSeconds",
64
+ "expiresAt",
65
+ "expiresAtMs",
66
+ "lastSeq"
67
+ ])))
68
+ });
69
+ //#endregion
70
+ //#region src/fault.ts
71
+ var StorageFault = class extends Schema.TaggedError()("StorageFault", {
72
+ operation: Schema.String,
73
+ message: Schema.String,
74
+ retryable: Schema.Boolean,
75
+ cause: Schema.optionalKey(Schema.Defect())
76
+ }) {};
77
+ var EncodeFault = class extends Schema.TaggedError()("EncodeFault", {
78
+ message: Schema.String,
79
+ cause: Schema.optionalKey(Schema.Defect())
80
+ }) {};
81
+ var DecodeFault = class extends Schema.TaggedError()("DecodeFault", {
82
+ message: Schema.String,
83
+ cause: Schema.optionalKey(Schema.Defect())
84
+ }) {};
85
+ /** Failures of the remote boundary; protocol rejections have their own typed errors. */
86
+ var TransportFault = class extends Schema.TaggedError()("TransportFault", {
87
+ operation: Schema.String,
88
+ reason: Schema.Literals([
89
+ "request",
90
+ "response",
91
+ "decode",
92
+ "configuration"
93
+ ]),
94
+ /** HTTP status of the response, when available. */
95
+ status: Schema.optionalKey(Schema.Int),
96
+ message: Schema.String,
97
+ cause: Schema.optionalKey(Schema.Defect())
98
+ }) {
99
+ /** Failed requests, 429s and 5xx responses can succeed later. */
100
+ get retryable() {
101
+ return this.reason === "request" || this.status !== void 0 && (this.status === 429 || this.status >= 500);
102
+ }
103
+ };
104
+ const StreamsFault = Schema.Union([StorageFault, TransportFault]);
105
+ /** A storage or transport failure, as opposed to a protocol rejection. */
106
+ const isStreamsFault = Schema.is(StreamsFault);
107
+ /** A storage or transport failure that can succeed later. */
108
+ const isRetryableFault = (error) => isStreamsFault(error) && error.retryable;
109
+ //#endregion
110
+ //#region src/offset/index.ts
111
+ const ZERO_OFFSET = Offset.make(`${"0".repeat(16)}_${"0".repeat(16)}`);
112
+ const isValid = (offset) => /^\d{16}_\d{16}$/.test(offset);
113
+ const compare = (a, b) => a === b ? 0 : a < b ? -1 : 1;
114
+ const parse = (offset) => BigInt(offset.slice(0, 16));
115
+ /** Fixed-width successor; bigint preserves all sixteen decimal digits. */
116
+ function next(previous) {
117
+ const value = parse(previous) + 1n;
118
+ if (value > 9999999999999999n) throw new RangeError("Offset exhausted");
119
+ return Offset.make(`${String(value).padStart(16, "0")}_${"0".repeat(16)}`);
120
+ }
121
+ //#endregion
122
+ //#region src/storage/storage.ts
123
+ var Storage = class extends Context.Service()("@streamsy/core/Storage") {};
124
+ //#endregion
125
+ //#region src/protocol/tags.ts
126
+ var StreamsReader = class extends Context.Service()("@streamsy/core/StreamsReader") {};
127
+ var StreamsWriter = class extends Context.Service()("@streamsy/core/StreamsWriter") {};
128
+ //#endregion
129
+ //#region src/protocol/errors.ts
130
+ /** Protocol rejections. Optional create reasons reflect the public HTTP wire's loss of detail. */
131
+ var StreamNotFound = class extends Schema.TaggedError()("StreamNotFound", { id: StreamId }) {
132
+ get message() {
133
+ return `Stream ${this.id} was not found`;
134
+ }
135
+ };
136
+ var StreamGone = class extends Schema.TaggedError()("StreamGone", { id: StreamId }) {
137
+ get message() {
138
+ return `Stream ${this.id} was deleted`;
139
+ }
140
+ };
141
+ var StreamClosed = class extends Schema.TaggedError()("StreamClosed", {
142
+ id: StreamId,
143
+ offset: Schema.String
144
+ }) {
145
+ get message() {
146
+ return `Stream ${this.id} is closed at ${this.offset}`;
147
+ }
148
+ };
149
+ var OffsetMismatch = class extends Schema.TaggedError()("OffsetMismatch", {
150
+ id: StreamId,
151
+ expected: Schema.String,
152
+ actual: Schema.String
153
+ }) {
154
+ get message() {
155
+ return `Stream ${this.id} is at ${this.actual}, not at the expected ${this.expected}`;
156
+ }
157
+ };
158
+ var AppendConflict = class extends Schema.TaggedError()("AppendConflict", {
159
+ id: StreamId,
160
+ message: Schema.String
161
+ }) {};
162
+ var StreamBusy = class extends Schema.TaggedError()("StreamBusy", { id: StreamId }) {
163
+ get message() {
164
+ return `Stream ${this.id} is busy; try again`;
165
+ }
166
+ };
167
+ var StaleEpoch = class extends Schema.TaggedError()("StaleEpoch", {
168
+ id: StreamId,
169
+ currentEpoch: Schema.Finite
170
+ }) {
171
+ get message() {
172
+ return `Producer epoch is stale on ${this.id}; the current epoch is ${this.currentEpoch}`;
173
+ }
174
+ };
175
+ var ProducerGap = class extends Schema.TaggedError()("ProducerGap", {
176
+ id: StreamId,
177
+ expectedSeq: Schema.Finite,
178
+ receivedSeq: Schema.Finite
179
+ }) {
180
+ get message() {
181
+ return `Producer sequence gap on ${this.id}: expected ${this.expectedSeq}, received ${this.receivedSeq}`;
182
+ }
183
+ };
184
+ var InvalidEpochSeq = class extends Schema.TaggedError()("InvalidEpochSeq", { id: StreamId }) {
185
+ get message() {
186
+ return `Invalid producer epoch or sequence on ${this.id}`;
187
+ }
188
+ };
189
+ var InvalidAppendRequest = class extends Schema.TaggedError()("InvalidAppendRequest", {
190
+ id: StreamId,
191
+ message: Schema.String
192
+ }) {};
193
+ var CreateConflict = class extends Schema.TaggedError()("CreateConflict", {
194
+ id: StreamId,
195
+ reason: Schema.optionalKey(Schema.Literals([
196
+ "config-mismatch",
197
+ "soft-deleted",
198
+ "fork-content-type",
199
+ "fork-source-soft-deleted"
200
+ ])),
201
+ message: Schema.String
202
+ }) {};
203
+ var ForkSourceNotFound = class extends Schema.TaggedError()("ForkSourceNotFound", {
204
+ id: StreamId,
205
+ source: StreamId
206
+ }) {
207
+ get message() {
208
+ return `Fork source ${this.source} of ${this.id} was not found`;
209
+ }
210
+ };
211
+ var InvalidForkRequest = class extends Schema.TaggedError()("InvalidForkRequest", {
212
+ id: StreamId,
213
+ message: Schema.String
214
+ }) {};
215
+ var NotSupported = class extends Schema.TaggedError()("NotSupported", {
216
+ id: StreamId,
217
+ feature: Schema.String
218
+ }) {
219
+ get message() {
220
+ return `Stream ${this.id} does not support ${this.feature}`;
221
+ }
222
+ };
223
+ var InvalidReadRequest = class extends Schema.TaggedError()("InvalidReadRequest", {
224
+ id: StreamId,
225
+ message: Schema.String
226
+ }) {};
227
+ /** Exhaustive record of every protocol tag, checked against the union it must cover. */
228
+ const protocolErrorTags = {
229
+ InvalidReadRequest: true,
230
+ StreamNotFound: true,
231
+ StreamGone: true,
232
+ StreamClosed: true,
233
+ OffsetMismatch: true,
234
+ AppendConflict: true,
235
+ StreamBusy: true,
236
+ StaleEpoch: true,
237
+ ProducerGap: true,
238
+ InvalidEpochSeq: true,
239
+ InvalidAppendRequest: true,
240
+ CreateConflict: true,
241
+ ForkSourceNotFound: true,
242
+ InvalidForkRequest: true,
243
+ NotSupported: true
244
+ };
245
+ /** The HTTP edge answers every protocol rejection through one mapper, so it needs one guard. */
246
+ const isProtocolError = (error) => Object.hasOwn(protocolErrorTags, error._tag);
247
+ //#endregion
248
+ //#region src/protocol/results.ts
249
+ /** Constructors and matchers for the protocol results above. */
250
+ const CreateResult = Data.taggedEnum();
251
+ const AppendResult = Data.taggedEnum();
252
+ //#endregion
253
+ //#region src/toolkit/route-internal.ts
254
+ /** Ids are canonical relative paths, the same rule the remote Layer enforces. */
255
+ function isCanonicalIdSegment(value) {
256
+ if (value.length === 0 || value === "." || value === "..") return false;
257
+ return !/[%?#/\\]/.test(value);
258
+ }
259
+ function compileSegments(template) {
260
+ if (template.length === 0) throw new RangeError("a stream route template must name at least one segment");
261
+ if (template.startsWith("/")) throw new RangeError("a stream route template is relative and cannot start with a slash");
262
+ if (/[?#*]/.test(template)) throw new RangeError("a stream route template cannot contain a query, fragment, or wildcard");
263
+ const names = [];
264
+ const segments = [];
265
+ for (const part of template.split("/")) {
266
+ if (part.length === 0) throw new RangeError("a stream route template cannot contain an empty segment");
267
+ if (!part.startsWith(":")) {
268
+ if (!isCanonicalIdSegment(part)) throw new RangeError(`a stream route literal segment is not a canonical id segment: ${part}`);
269
+ segments.push({
270
+ kind: "literal",
271
+ value: part
272
+ });
273
+ continue;
274
+ }
275
+ const name = part.slice(1);
276
+ if (name.length === 0) throw new RangeError("a stream route parameter needs a name");
277
+ if (names.includes(name)) throw new RangeError(`duplicate stream route parameter: ${name}`);
278
+ names.push(name);
279
+ segments.push({
280
+ kind: "parameter",
281
+ name
282
+ });
283
+ }
284
+ return {
285
+ template,
286
+ segments: Object.freeze(segments),
287
+ names: Object.freeze(names)
288
+ };
289
+ }
290
+ /**
291
+ * True when two template routes can both match one id.
292
+ *
293
+ * Lengths must agree, and every position must be either an equal literal pair
294
+ * or a parameter on at least one side. A parameter is treated as matching any
295
+ * segment, so a codec-constrained parameter can report an overlap it would
296
+ * never actually match. A custom route carries no template and is never
297
+ * checked; HTTP dispatch uses declaration order and the first match wins.
298
+ */
299
+ function templatesOverlap(left, right) {
300
+ if (left.length === 0 || right.length === 0) return false;
301
+ const a = compileSegments(left).segments;
302
+ const b = compileSegments(right).segments;
303
+ if (a.length !== b.length) return false;
304
+ for (const [index, segment] of a.entries()) {
305
+ const other = b[index];
306
+ if (!other || segment.kind === "parameter" || other.kind === "parameter") continue;
307
+ if (segment.value !== other.value) return false;
308
+ }
309
+ return true;
310
+ }
311
+ //#endregion
312
+ //#region src/toolkit/address.ts
313
+ var address_exports = /* @__PURE__ */ __exportAll({
314
+ bytes: () => bytes$2,
315
+ json: () => json$2,
316
+ state: () => state$2,
317
+ stateChange: () => stateChange
318
+ });
319
+ /** The address constructors. Each class owns the `_tag` of one address kind. */
320
+ const JsonAddress = Data.TaggedClass("Json");
321
+ const BytesAddress = Data.TaggedClass("Bytes");
322
+ function json$2(id, options) {
323
+ return new JsonAddress({
324
+ id: StreamId.make(id),
325
+ contentType: "application/json",
326
+ codec: Schema.fromJsonString(Schema.toCodecJson(options.schema))
327
+ });
328
+ }
329
+ /**
330
+ * A codec for the upsert and delete change events of one collection.
331
+ * `state` composes one of these per collection. Omit optional headers instead
332
+ * of setting them to `undefined`.
333
+ */
334
+ function stateChange(options) {
335
+ const upsertOperation = Schema.Union([
336
+ Schema.Literal("upsert"),
337
+ Schema.Literal("insert").transform("upsert"),
338
+ Schema.Literal("update").transform("upsert")
339
+ ]);
340
+ const headers = {
341
+ offset: Schema.optionalKey(Schema.String),
342
+ txid: Schema.optionalKey(Schema.String),
343
+ timestamp: Schema.optionalKey(Schema.String),
344
+ from: Schema.optionalKey(Schema.String)
345
+ };
346
+ return Schema.Union([Schema.Struct({
347
+ type: Schema.Literal(options.type),
348
+ key: Schema.String,
349
+ value: options.schema,
350
+ headers: Schema.Struct({
351
+ operation: upsertOperation,
352
+ ...headers
353
+ })
354
+ }), Schema.Struct({
355
+ type: Schema.Literal(options.type),
356
+ key: Schema.String,
357
+ old_value: Schema.optionalKey(options.schema),
358
+ headers: Schema.Struct({
359
+ operation: Schema.Literal("delete"),
360
+ ...headers
361
+ })
362
+ })]);
363
+ }
364
+ /**
365
+ * A stream of Durable State change events for several collections. Each record
366
+ * key is the `type` on the wire; each entry gives the value schema and the value
367
+ * field that becomes the event `key`.
368
+ */
369
+ function state$2(id, options) {
370
+ const codecs = Object.entries(options.collections).map(([type, collection]) => stateChange({
371
+ schema: collection.schema,
372
+ type
373
+ }));
374
+ const address = json$2(id, { schema: Schema.Union(codecs) });
375
+ return new JsonAddress({
376
+ id: address.id,
377
+ contentType: address.contentType,
378
+ codec: address.codec,
379
+ collections: options.collections
380
+ });
381
+ }
382
+ /** Items from one bytes append are joined into one stored message. */
383
+ function bytes$2(id, options = {}) {
384
+ return new BytesAddress({
385
+ id: StreamId.make(id),
386
+ contentType: options.contentType ?? "application/octet-stream",
387
+ codec: Schema.Uint8Array
388
+ });
389
+ }
390
+ //#endregion
391
+ //#region src/toolkit/route.ts
392
+ var route_exports = /* @__PURE__ */ __exportAll({
393
+ bytes: () => bytes$1,
394
+ custom: () => custom$1,
395
+ json: () => json$1,
396
+ state: () => state$1
397
+ });
398
+ /** The route constructor. It owns the `StreamRoute` tag of every route. */
399
+ const Route = Data.TaggedClass("StreamRoute");
400
+ function pathSchema(codecs) {
401
+ return Schema.Struct(codecs);
402
+ }
403
+ function decodeParams(codecs, raw) {
404
+ const decoded = {};
405
+ for (const name of Object.keys(codecs)) {
406
+ const value = raw[name];
407
+ const codec = codecs[name];
408
+ if (value === void 0 || codec === void 0) return Option.none();
409
+ const result = Schema.decodeOption(codec)(value);
410
+ if (Option.isNone(result)) return Option.none();
411
+ decoded[name] = result.value;
412
+ }
413
+ return Option.some(decoded);
414
+ }
415
+ function matchTemplate(segments, codecs, id) {
416
+ const actual = id.split("/");
417
+ if (actual.length !== segments.length) return Option.none();
418
+ const raw = {};
419
+ for (const [index, segment] of segments.entries()) {
420
+ const value = actual[index];
421
+ if (value === void 0) return Option.none();
422
+ if (segment.kind === "literal") {
423
+ if (value !== segment.value) return Option.none();
424
+ continue;
425
+ }
426
+ if (!isCanonicalIdSegment(value)) return Option.none();
427
+ raw[segment.name] = value;
428
+ }
429
+ return decodeParams(codecs, raw);
430
+ }
431
+ function buildId(template, segments, codecs, params) {
432
+ const record = params;
433
+ const built = segments.map((segment) => {
434
+ if (segment.kind === "literal") return segment.value;
435
+ const codec = codecs[segment.name];
436
+ const value = record[segment.name];
437
+ if (codec === void 0 || value === void 0) throw new RangeError(`stream route ${template} has no value for parameter: ${segment.name}`);
438
+ const text = Option.getOrUndefined(Schema.encodeOption(codec)(value));
439
+ if (text === void 0) throw new RangeError(`stream route ${template} parameter ${segment.name} cannot encode to an id segment`);
440
+ if (!isCanonicalIdSegment(text)) throw new RangeError(`stream route ${template} parameter ${segment.name} is not a canonical id segment: ${text}`);
441
+ return text;
442
+ });
443
+ return StreamId.make(built.join("/"));
444
+ }
445
+ /**
446
+ * The codec record and the template must name the same parameters. The type
447
+ * check covers the common case; this backstop covers a widened template.
448
+ */
449
+ function checkTemplateParams(template, names, codecs) {
450
+ for (const name of names) if (codecs[name] === void 0) throw new RangeError(`stream route ${template} has no codec for parameter: ${name}`);
451
+ for (const name of Object.keys(codecs)) if (!names.includes(name)) throw new RangeError(`stream route codec is absent from the template: ${name}`);
452
+ }
453
+ function json$1(template, options) {
454
+ const { segments, names } = compileSegments(template);
455
+ const codecs = options.params;
456
+ checkTemplateParams(template, names, codecs);
457
+ return new Route({
458
+ template,
459
+ paramSchema: pathSchema(codecs),
460
+ match: (id) => Option.isSome(matchTemplate(segments, codecs, id)),
461
+ parse: (id) => matchTemplate(segments, codecs, id),
462
+ address: (params) => json$2(buildId(template, segments, codecs, params), options)
463
+ });
464
+ }
465
+ function state$1(template, options) {
466
+ const { segments, names } = compileSegments(template);
467
+ const codecs = options.params;
468
+ checkTemplateParams(template, names, codecs);
469
+ return new Route({
470
+ template,
471
+ paramSchema: pathSchema(codecs),
472
+ match: (id) => Option.isSome(matchTemplate(segments, codecs, id)),
473
+ parse: (id) => matchTemplate(segments, codecs, id),
474
+ collections: options.collections,
475
+ address: (params) => state$2(buildId(template, segments, codecs, params), options)
476
+ });
477
+ }
478
+ function bytes$1(template, options) {
479
+ const { segments, names } = compileSegments(template);
480
+ const codecs = options.params;
481
+ checkTemplateParams(template, names, codecs);
482
+ return new Route({
483
+ template,
484
+ paramSchema: pathSchema(codecs),
485
+ match: (id) => Option.isSome(matchTemplate(segments, codecs, id)),
486
+ parse: (id) => matchTemplate(segments, codecs, id),
487
+ address: (params) => bytes$2(buildId(template, segments, codecs, params), { contentType: options.contentType ?? "application/octet-stream" })
488
+ });
489
+ }
490
+ /** Escape hatch for a grammar a template cannot express, such as a regex stream. */
491
+ function custom$1(options) {
492
+ return new Route({
493
+ template: "",
494
+ match: (id) => Option.isSome(options.parse(id)),
495
+ parse: options.parse,
496
+ address: options.address
497
+ });
498
+ }
499
+ //#endregion
500
+ //#region src/toolkit/streams.ts
501
+ var streams_exports = /* @__PURE__ */ __exportAll({
502
+ append: () => append,
503
+ collect: () => collect,
504
+ create: () => create,
505
+ decide: () => decide,
506
+ fold: () => fold,
507
+ follow: () => follow,
508
+ head: () => head,
509
+ items: () => items,
510
+ read: () => read,
511
+ remove: () => remove,
512
+ session: () => session
513
+ });
514
+ const create = Effect.fn("Streams.create")(function* (address, options = {}) {
515
+ return yield* (yield* StreamsWriter).create(address.id, {
516
+ ...options,
517
+ contentType: address.contentType
518
+ });
519
+ });
520
+ /** Whether these options can lead to this rejection. Any other rejection is a host bug. */
521
+ const possibleFor = (options, error) => Predicate.isTagged(error, "InvalidAppendRequest") || Predicate.isTagged(error, "InvalidEpochSeq") ? false : Predicate.isTagged(error, "OffsetMismatch") ? options.expectedOffset !== void 0 : Predicate.isTagged(error, "StaleEpoch") || Predicate.isTagged(error, "ProducerGap") ? options.producer !== void 0 : true;
522
+ /**
523
+ * Append items to one stream. The error type lists only the rejections that the
524
+ * options make possible; a host that answers another one dies.
525
+ */
526
+ const append = Effect.fn("Streams.append")(function* (address, items, options) {
527
+ const callOptions = options ?? {};
528
+ const list = items;
529
+ const encoded = yield* Effect.forEach(list, (item) => Schema.encodeEffect(address.codec)(item).pipe(Effect.mapError((cause) => new EncodeFault({
530
+ message: `Cannot encode ${address.id}`,
531
+ cause
532
+ }))));
533
+ for (const item of encoded) if (Predicate.isUint8Array(item) && item.byteLength === 0) return yield* Effect.die(/* @__PURE__ */ new RangeError(`Cannot append an empty bytes item to ${address.id}`));
534
+ const data = list.length === 0 && callOptions.close ? /* @__PURE__ */ new Uint8Array() : Predicate.isTagged(address, "Json") ? new TextEncoder().encode(`[${encoded.join(",")}]`) : concatBytes(encoded);
535
+ const possible = (error) => possibleFor(callOptions, error);
536
+ const appended = (yield* StreamsWriter).append(address.id, {
537
+ ...callOptions,
538
+ data,
539
+ contentType: address.contentType
540
+ });
541
+ return yield* Effect.catchIf(appended, possible, Effect.fail, Effect.die);
542
+ });
543
+ function concatBytes(parts) {
544
+ const arrays = parts.map((part) => Predicate.isString(part) ? new TextEncoder().encode(part) : part);
545
+ const result = new Uint8Array(arrays.reduce((size, part) => size + part.byteLength, 0));
546
+ let offset = 0;
547
+ for (const part of arrays) {
548
+ result.set(part, offset);
549
+ offset += part.byteLength;
550
+ }
551
+ return result;
552
+ }
553
+ const decode = Effect.fn("Streams.decode")(function* (address, result) {
554
+ return {
555
+ 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({
556
+ message: `Cannot decode ${address.id} at read message ${index}`,
557
+ cause
558
+ })))),
559
+ nextOffset: result.nextOffset,
560
+ upToDate: result.upToDate,
561
+ closed: result.closed
562
+ };
563
+ });
564
+ function read(address, options = {}) {
565
+ return Stream.unwrap(Effect.gen(function* () {
566
+ const reader = yield* StreamsReader;
567
+ return Stream.paginate(options.offset, (offset) => Effect.gen(function* () {
568
+ const batch = yield* decode(address, yield* reader.read(address.id, {
569
+ ...options,
570
+ offset
571
+ }));
572
+ return [[batch], batch.upToDate ? Option.none() : Option.some(batch.nextOffset)];
573
+ }));
574
+ }));
575
+ }
576
+ /**
577
+ * Read the stream up to its tail and fold every item into one value. Pass
578
+ * `options.offset` to fold on from a tail that an earlier fold returned.
579
+ */
580
+ const fold = Effect.fn("Streams.fold")(function* (address, initial, f, options = {}) {
581
+ return yield* read(address, options).pipe(Stream.runFold(() => ({
582
+ state: initial(),
583
+ offset: options.offset ?? ZERO_OFFSET
584
+ }), (folded, batch) => {
585
+ let state = folded.state;
586
+ for (const item of batch.items) state = f(state, item);
587
+ return {
588
+ state,
589
+ offset: batch.nextOffset
590
+ };
591
+ }));
592
+ });
593
+ /** Read the stream up to its tail and return its items. */
594
+ const collect = Effect.fn("Streams.collect")(function* (address, options = {}) {
595
+ const { state, offset } = yield* fold(address, () => [], (items, item) => {
596
+ items.push(item);
597
+ return items;
598
+ }, options);
599
+ return {
600
+ items: state,
601
+ offset
602
+ };
603
+ });
604
+ /** Up to three retries after a lost race, so at most four appends per call. */
605
+ const defaultDecideRetry = Schedule.recurs(3);
606
+ /**
607
+ * Read, decide, append. Fold the stream to its tail, decide from the state, and
608
+ * append with `expectedOffset` set to the tail that was read. After an
609
+ * `OffsetMismatch`, fold on from that tail and decide again while `retry` allows;
610
+ * then fail with the last `OffsetMismatch`. Transport faults are not retried: a
611
+ * lost reply may hide an append that landed.
612
+ */
613
+ const decide = Effect.fn("Streams.decide")(function* (address, spec) {
614
+ let folded;
615
+ const attempt = Effect.gen(function* () {
616
+ const last = folded;
617
+ folded = last === void 0 ? yield* fold(address, spec.initial, spec.fold) : yield* fold(address, () => last.state, spec.fold, { offset: last.offset });
618
+ const { state, offset } = folded;
619
+ const { value, items } = yield* spec.decide(state, { offset });
620
+ if (!isReadonlyArrayNonEmpty(items)) return {
621
+ value,
622
+ offset,
623
+ appended: false
624
+ };
625
+ return {
626
+ value,
627
+ offset: (yield* append(address, items, { expectedOffset: offset }).pipe(Effect.catchTag("OffsetMismatch", (mismatch) => Effect.fail(new LostRace(mismatch))))).offset,
628
+ appended: true
629
+ };
630
+ });
631
+ return yield* retryLostRace(attempt, spec.retry ?? defaultDecideRetry);
632
+ });
633
+ /**
634
+ * Marks the `OffsetMismatch` of a decide loop's own append. Only this error is
635
+ * retried: an `OffsetMismatch` that the caller's `decide` raises is its own
636
+ * failure and passes through.
637
+ */
638
+ var LostRace = class {
639
+ mismatch;
640
+ constructor(mismatch) {
641
+ this.mismatch = mismatch;
642
+ }
643
+ };
644
+ /**
645
+ * Retry `attempt` after a `LostRace` while `schedule` allows, then fail with the
646
+ * last `OffsetMismatch`. `retry` steps its schedule with every error it sees, so
647
+ * every other outcome passes the retry as a `Result` and is raised after.
648
+ */
649
+ const retryLostRace = Effect.fnUntraced(function* (attempt, schedule) {
650
+ const outcome = yield* attempt.pipe(Effect.matchEffect({
651
+ onFailure: (error) => error instanceof LostRace ? Effect.fail(error.mismatch) : Effect.succeed(Result.fail(error)),
652
+ onSuccess: (value) => Effect.succeed(Result.succeed(value))
653
+ }), Effect.retry(schedule));
654
+ return yield* Effect.fromResult(outcome);
655
+ });
656
+ const capAt30Seconds = Schedule.modifyDelay(({ duration }) => Effect.succeed(Duration.millis(Math.min(3e4, Duration.toMillis(duration)))));
657
+ /** Same shape as `Projection.follow`'s default; kept as a copy until a third user appears. */
658
+ const defaultFollowRetry = Schedule.exponential("200 millis").pipe(capAt30Seconds, Schedule.jittered, capAt30Seconds);
659
+ /**
660
+ * Catch up, then wait one readNext at a time, filtering empty open batches.
661
+ * A read that fails with a retryable transport or storage fault is retried from the same
662
+ * offset, so a restart or network drop yields each item once.
663
+ */
664
+ function follow(address, options = {}) {
665
+ const { retry = defaultFollowRetry, ...readOptions } = options;
666
+ const retrying = (reading) => reading.pipe(Effect.tapError((error) => isRetryableFault(error) ? Effect.logWarning("Streams.follow retry", error) : Effect.void), Effect.retry({
667
+ while: isRetryableFault,
668
+ schedule: retry
669
+ }));
670
+ return Stream.unwrap(Effect.gen(function* () {
671
+ const reader = yield* StreamsReader;
672
+ const initial = {
673
+ offset: readOptions.offset,
674
+ live: false,
675
+ cursor: void 0
676
+ };
677
+ const live = (state) => reader.readNext(address.id, {
678
+ offset: state.offset ?? "-1",
679
+ cursor: state.cursor
680
+ }).pipe(Effect.map((result) => [result, result.cursor]));
681
+ const catchUp = (state) => reader.read(address.id, {
682
+ ...readOptions,
683
+ offset: state.offset
684
+ }).pipe(Effect.map((result) => [result, state.cursor]));
685
+ return Stream.paginate(initial, (state) => Effect.gen(function* () {
686
+ const [result, cursor] = yield* retrying(state.live ? live(state) : catchUp(state));
687
+ const batch = yield* decode(address, result);
688
+ const next = {
689
+ offset: batch.nextOffset,
690
+ live: batch.upToDate,
691
+ cursor
692
+ };
693
+ return [batch.items.length > 0 || batch.closed ? [batch] : [], batch.closed ? Option.none() : Option.some(next)];
694
+ }));
695
+ }));
696
+ }
697
+ const items = (batches) => batches.pipe(Stream.flatMap((batch) => Stream.fromIterable(batch.items)));
698
+ const session = Effect.fn("Streams.session")(function* (address, options) {
699
+ return yield* (yield* StreamsReader).readNext(address.id, options);
700
+ });
701
+ const head = Effect.fn("Streams.head")(function* (address) {
702
+ return yield* (yield* StreamsReader).head(address.id);
703
+ });
704
+ const remove = Effect.fn("Streams.remove")(function* (address) {
705
+ return yield* (yield* StreamsWriter).remove(address.id);
706
+ });
707
+ //#endregion
708
+ //#region src/toolkit/streamsy.ts
709
+ const templateOf = (route) => {
710
+ if (!("template" in route)) return void 0;
711
+ const template = route.template;
712
+ if (!Predicate.isString(template)) return void 0;
713
+ return template.length > 0 ? template : void 0;
714
+ };
715
+ /** Template streams must have disjoint id grammars. Custom routes use declaration order. */
716
+ function checkNoOverlap(routes) {
717
+ const templates = routes.flatMap((route) => {
718
+ const template = templateOf(route);
719
+ return template === void 0 ? [] : [template];
720
+ });
721
+ 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}`);
722
+ }
723
+ /** Build a stream service over one protocol graph's wires, with the ownership guard on writes. */
724
+ function wireApi(route, services) {
725
+ const storage = storageOf(services.writer);
726
+ const owner = storage === void 0 ? services.writer : ownerOf(storage);
727
+ const write = (id, run) => checkWriteOwner(owner, id, storage !== void 0).pipe(Effect.andThen(Effect.suspend(run)));
728
+ const own = (id, run) => Effect.suspend(() => route.match(id) ? run() : Effect.die(/* @__PURE__ */ new RangeError(`${id} is outside stream ${route.template}`)));
729
+ const wire = {
730
+ head: (id) => own(id, () => services.reader.head(id)),
731
+ read: (id, options) => own(id, () => services.reader.read(id, options)),
732
+ readNext: (id, options) => own(id, () => services.reader.readNext(id, options)),
733
+ create: (id, options) => write(id, () => own(id, () => options?.forkedFrom === void 0 ? services.writer.create(id, options) : route.match(options.forkedFrom) ? services.writer.create(id, options) : Effect.fail(new ForkSourceNotFound({
734
+ id,
735
+ source: StreamId.make(options.forkedFrom)
736
+ })))),
737
+ fork: (id, source, options) => write(id, () => own(id, () => route.match(source) ? services.writer.fork(id, source, options) : Effect.fail(new ForkSourceNotFound({
738
+ id,
739
+ source
740
+ })))),
741
+ append: (id, options) => write(id, () => own(id, () => services.writer.append(id, options))),
742
+ remove: (id) => write(id, () => own(id, () => services.writer.remove(id)))
743
+ };
744
+ const context = Context.make(StreamsReader, wire).pipe(Context.add(StreamsWriter, wire));
745
+ return {
746
+ owner,
747
+ route,
748
+ wire,
749
+ create: (params, options) => create(route.address(params), options).pipe(Effect.provide(context)),
750
+ append: (params, items, options) => append(route.address(params), items, options).pipe(Effect.provide(context)),
751
+ read: (params, options) => read(route.address(params), options).pipe(Stream.provideContext(context)),
752
+ fold: (params, initial, f, options) => fold(route.address(params), initial, f, options).pipe(Effect.provide(context)),
753
+ collect: (params, options) => collect(route.address(params), options).pipe(Effect.provide(context)),
754
+ decide: (params, spec) => decide(route.address(params), spec).pipe(Effect.provide(context)),
755
+ follow: (params, options) => follow(route.address(params), options).pipe(Stream.provideContext(context)),
756
+ session: (params, options) => wire.readNext(route.address(params).id, options),
757
+ head: (params) => wire.head(route.address(params).id),
758
+ remove: (params) => wire.remove(route.address(params).id),
759
+ fork: (params, source, options) => wire.fork(route.address(params).id, route.address(source).id, {
760
+ ...options,
761
+ contentType: route.address(params).contentType
762
+ })
763
+ };
764
+ }
765
+ /**
766
+ * Names are global Context identities, including across separate providers.
767
+ * Use an application namespace for distinct streams. Reusing a name intentionally
768
+ * aliases the service; providers cannot detect collisions in other Layer graphs.
769
+ * Wildcard is reserved for the built-in catch-all and its intentional aliases.
770
+ */
771
+ function define() {
772
+ return (name, route) => {
773
+ const key = `@streamsy/core/Stream/${name}`;
774
+ const service = Context.Service()(key);
775
+ const declared = Object.defineProperty(service, metadataKey, { value: {
776
+ route,
777
+ make: (services) => wireApi(route, services)
778
+ } });
779
+ return Object.assign(declared, route, { at: (params) => {
780
+ return Object.assign(route.address(params), { stream: service });
781
+ } });
782
+ };
783
+ }
784
+ const json = () => (name, ...args) => define()(name, json$1(...args));
785
+ const state = () => (name, ...args) => define()(name, state$1(...args));
786
+ const bytes = () => (name, ...args) => define()(name, bytes$1(...args));
787
+ const custom = () => (name, options) => define()(name, custom$1(options));
788
+ const metadataKey = Symbol.for("@streamsy/core/Stream/metadata");
789
+ function declaration(key) {
790
+ const value = key[metadataKey];
791
+ if (value === void 0) throw new TypeError(`Unknown stream declaration: ${key.key}`);
792
+ return value;
793
+ }
794
+ var Wildcard = class extends define()("Wildcard", custom$1({
795
+ parse: (id) => Option.some({ id }),
796
+ address: ({ id }) => bytes$2(id)
797
+ })) {};
798
+ function checkStreams(keys) {
799
+ const templates = /* @__PURE__ */ new Set();
800
+ const names = /* @__PURE__ */ new Set();
801
+ for (const [index, key] of keys.entries()) {
802
+ if (names.has(key.key)) throw new RangeError(`duplicate stream name: ${key.key}`);
803
+ names.add(key.key);
804
+ if (key.template !== "" && templates.has(key.template)) throw new RangeError(`duplicate stream template: ${key.template}`);
805
+ templates.add(key.template);
806
+ if (key.key === Wildcard.key && index !== keys.length - 1) throw new RangeError("Wildcard must be last");
807
+ }
808
+ checkNoOverlap(keys.map((key) => declaration(key).route));
809
+ }
810
+ function bind(source, streams) {
811
+ const keys = streams.streams;
812
+ checkStreams(keys);
813
+ const bindContext = (wires, storage) => {
814
+ if (storage !== void 0 && (storageOf(wires.reader) !== storage || storageOf(wires.writer) !== storage)) throw new RangeError("The exposed Storage does not own the protocol wires");
815
+ let context = Context.empty();
816
+ for (const key of keys) context = Context.add(context, key, declaration(key).make(wires));
817
+ return context;
818
+ };
819
+ return source.pipe(Layer.flatMap((context) => Layer.syncContext(() => bindContext({
820
+ reader: Context.get(context, StreamsReader),
821
+ writer: Context.get(context, StreamsWriter)
822
+ }, Option.getOrUndefined(Context.getOption(context, Storage))))));
823
+ }
824
+ function group(...keys) {
825
+ checkStreams(keys);
826
+ return Object.freeze({ streams: Object.freeze(keys) });
827
+ }
828
+ //#endregion
829
+ export { StreamLifecycle as $, StreamsReader as A, StreamsFault as B, ProducerGap as C, StreamGone as D, StreamClosed as E, isValid as F, MessageWindow as G, isRetryableFault as H, next as I, ProducerState as J, Offset as K, DecodeFault as L, Storage as M, ZERO_OFFSET as N, StreamNotFound as O, compare as P, StreamId as Q, EncodeFault as R, OffsetMismatch as S, StreamBusy as T, isStreamsFault as U, TransportFault as V, ChangeSnapshot as W, StoredMessage as X, RecordPatch as Y, StreamConfig as Z, InvalidAppendRequest as _, custom as a, InvalidReadRequest as b, state as c, address_exports as d, StreamRecord as et, AppendResult as f, ForkSourceNotFound as g, CreateConflict as h, checkStreams as i, StreamsWriter as j, isProtocolError as k, streams_exports as l, AppendConflict as m, bind as n, group as o, CreateResult as p, ProducerId as q, bytes as r, json as s, Wildcard as t, route_exports as u, InvalidEpochSeq as v, StaleEpoch as w, NotSupported as x, InvalidForkRequest as y, StorageFault as z };