@streamsy/core 0.4.0 → 0.5.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,9 @@
1
- import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
2
- import { A as StreamsReader, F as isValid, Q as StreamId, f as AppendResult, j as StreamsWriter, k as isProtocolError, p as CreateResult } from "./streamsy-OjRubIPC.js";
3
- import { t as generateCursor } from "./cursor-generator-CGz1TO_N.js";
4
- import { Clock, Context, DateTime, Deferred, Effect, Layer, Match, Option, Random, Ref, Schedule, Stream } from "effect";
1
+ import { t as __exportAll } from "./rolldown-runtime-D8jQpDG7.js";
2
+ import { A as StreamsReader, F as isValid, Q as StreamId, f as AppendResult, j as StreamsWriter, k as isProtocolError, p as CreateResult } from "./streamsy-DJMArv09.js";
3
+ import { t as generateCursor } from "./cursor-generator-DySXZ93b.js";
4
+ import { Array, Clock, Context, DateTime, Deferred, Effect, Layer, Match, Option, Random, Record, Ref, Schedule, Stream } from "effect";
5
5
  import { HttpServerRequest, HttpServerResponse } from "effect/http";
6
- //#region src/http/responses.ts
6
+ // src/http/responses.ts
7
7
  var responses_exports = /* @__PURE__ */ __exportAll({
8
8
  badRequest: () => badRequest$1,
9
9
  cacheControlForVisibility: () => cacheControlForVisibility,
@@ -86,18 +86,16 @@ function fromWeb(response) {
86
86
  return HttpServerResponse.raw(response, {
87
87
  status: response.status,
88
88
  statusText: response.statusText,
89
- headers: Object.fromEntries(response.headers)
89
+ headers: Record.fromEntries(response.headers)
90
90
  });
91
91
  }
92
- //#endregion
93
- //#region src/http/security-headers.ts
92
+ // src/http/security-headers.ts
94
93
  /** Shared protocol and host security headers. */
95
94
  const securityHeaders = Object.freeze({
96
95
  "x-content-type-options": "nosniff",
97
96
  "cross-origin-resource-policy": "cross-origin"
98
97
  });
99
- //#endregion
100
- //#region src/http/stream-path-service.ts
98
+ // src/http/stream-path-service.ts
101
99
  /** Prefix helpers shared by protocol and host routers. */
102
100
  const streamPath = (pathPrefix = "/") => {
103
101
  const prefix = pathPrefix.endsWith("/") ? pathPrefix : `${pathPrefix}/`;
@@ -109,8 +107,7 @@ const streamPath = (pathPrefix = "/") => {
109
107
  canonicalizeForkSource: (source) => regex.test(source) ? strip(source) : source.replace(/^\//, "")
110
108
  };
111
109
  };
112
- //#endregion
113
- //#region src/http/request-body-reader.ts
110
+ // src/http/request-body-reader.ts
114
111
  const requestBodyReader = (maxMessageSize) => ({ read: Effect.fn("Http.readBody")(function* (request) {
115
112
  return yield* request.arrayBuffer.pipe(Effect.map((data) => data.byteLength > maxMessageSize ? {
116
113
  ok: false,
@@ -124,8 +121,7 @@ const requestBodyReader = (maxMessageSize) => ({ read: Effect.fn("Http.readBody"
124
121
  response: payloadTooLarge()
125
122
  })));
126
123
  }) });
127
- //#endregion
128
- //#region src/http/request-body-discard.ts
124
+ // src/http/request-body-discard.ts
129
125
  /**
130
126
  * Consumes an unread request body before an early rejection.
131
127
  *
@@ -141,8 +137,7 @@ const requestBodyReader = (maxMessageSize) => ({ read: Effect.fn("Http.readBody"
141
137
  * the outcome that matters.
142
138
  */
143
139
  const discardRequestBody = (request) => Stream.runDrain(request.stream).pipe(Effect.ignoreCause);
144
- //#endregion
145
- //#region src/http/create.ts
140
+ // src/http/create.ts
146
141
  const responses$4 = responses_exports;
147
142
  function parseHeaders$1(request, path) {
148
143
  const rawContentType = request.headers.get("content-type");
@@ -219,8 +214,7 @@ function toResponse$1(result, location) {
219
214
  if (result.closed) headers.set("stream-closed", "true");
220
215
  return responses$4.empty(created ? 201 : 200, headers);
221
216
  }
222
- //#endregion
223
- //#region src/http/producer-header-parser.ts
217
+ // src/http/producer-header-parser.ts
224
218
  var producer_header_parser_exports = /* @__PURE__ */ __exportAll({ parse: () => parse });
225
219
  const MAX_SAFE_PRODUCER_INT = Number.MAX_SAFE_INTEGER;
226
220
  const NON_NEGATIVE_INT_RE = /^(0|[1-9]\d*)$/;
@@ -228,11 +222,11 @@ function parse(request) {
228
222
  const id = request.headers.get("producer-id");
229
223
  const epoch = request.headers.get("producer-epoch");
230
224
  const seq = request.headers.get("producer-seq");
231
- const present = [
225
+ const present = Array.filter([
232
226
  id,
233
227
  epoch,
234
228
  seq
235
- ].filter((v) => v !== null).length;
229
+ ], (v) => v !== null).length;
236
230
  if (present === 0) return { kind: "absent" };
237
231
  if (present !== 3 || id === null || epoch === null || seq === null) return { kind: "invalid" };
238
232
  if (id.length === 0) return { kind: "invalid" };
@@ -254,8 +248,7 @@ function parseInt$1(raw) {
254
248
  if (!Number.isFinite(n) || n > MAX_SAFE_PRODUCER_INT) return null;
255
249
  return n;
256
250
  }
257
- //#endregion
258
- //#region src/http/append.ts
251
+ // src/http/append.ts
259
252
  const producerParser = producer_header_parser_exports;
260
253
  const responses$3 = responses_exports;
261
254
  function parseHeaders(request) {
@@ -298,15 +291,13 @@ function toResponse(result, producerHeaders, isEmpty) {
298
291
  }
299
292
  });
300
293
  }
301
- //#endregion
302
- //#region src/http/etag-builder.ts
294
+ // src/http/etag-builder.ts
303
295
  var etag_builder_exports = /* @__PURE__ */ __exportAll({ forCatchUp: () => forCatchUp });
304
296
  function forCatchUp(pathname, startOffset, nextOffset, closed) {
305
297
  const closedSuffix = closed ? ":c" : "";
306
298
  return `"${btoa(pathname)}:${startOffset}:${nextOffset}${closedSuffix}"`;
307
299
  }
308
- //#endregion
309
- //#region src/http/bytes.ts
300
+ // src/http/bytes.ts
310
301
  /**
311
302
  * Cross-runtime byte normalization for HTTP bodies.
312
303
  *
@@ -369,8 +360,7 @@ function nodeBufferBase64(bytes) {
369
360
  if (encoded === null || encoded === void 0 || isReferenceValue(encoded) || Object.getPrototypeOf(Object(encoded)) !== String.prototype) return;
370
361
  return String.prototype.valueOf.call(encoded);
371
362
  }
372
- //#endregion
373
- //#region src/http/message-body-codec.ts
363
+ // src/http/message-body-codec.ts
374
364
  var message_body_codec_exports = /* @__PURE__ */ __exportAll({
375
365
  bytesToBase64: () => bytesToBase64,
376
366
  concatBytes: () => concatBytes,
@@ -380,15 +370,18 @@ var message_body_codec_exports = /* @__PURE__ */ __exportAll({
380
370
  const decoder$1 = new TextDecoder();
381
371
  function encodeHttpBody(messages, contentType) {
382
372
  const lower = contentType.toLowerCase();
383
- if (lower.startsWith("application/json")) return `[${messages.map((msg) => decoder$1.decode(msg.data)).join(",")}]`;
384
- if (lower.startsWith("text/")) return messages.map((msg) => decoder$1.decode(msg.data)).join("");
373
+ if (lower.startsWith("application/json")) {
374
+ const items = Array.map(messages, (msg) => decoder$1.decode(msg.data));
375
+ return `[${Array.join(items, ",")}]`;
376
+ }
377
+ if (lower.startsWith("text/")) return Array.join(Array.map(messages, (msg) => decoder$1.decode(msg.data)), "");
385
378
  return toArrayBuffer(concatBytes(messages));
386
379
  }
387
380
  function emptyBodyForContentType(contentType) {
388
381
  return contentType.toLowerCase().startsWith("application/json") ? "[]" : "";
389
382
  }
390
383
  function concatBytes(messages) {
391
- const totalLength = messages.reduce((acc, msg) => acc + msg.data.length, 0);
384
+ const totalLength = Array.reduce(messages, 0, (acc, msg) => acc + msg.data.length);
392
385
  const combined = new Uint8Array(totalLength);
393
386
  let pos = 0;
394
387
  for (const msg of messages) {
@@ -405,8 +398,7 @@ function bytesToBase64(bytes) {
405
398
  for (let i = 0; i < bytes.length; i += chunk) binary += String.fromCharCode(...bytes.subarray(i, i + chunk));
406
399
  return btoa(binary);
407
400
  }
408
- //#endregion
409
- //#region src/http/read-query-parser.ts
401
+ // src/http/read-query-parser.ts
410
402
  const readQueryParser = (isValidOffset) => ({ parse(url) {
411
403
  const offset = url.searchParams.get("offset") ?? void 0;
412
404
  const liveParam = url.searchParams.get("live");
@@ -427,8 +419,7 @@ const readQueryParser = (isValidOffset) => ({ parse(url) {
427
419
  cursor
428
420
  };
429
421
  } });
430
- //#endregion
431
- //#region src/http/sse-event-encoder.ts
422
+ // src/http/sse-event-encoder.ts
432
423
  var sse_event_encoder_exports = /* @__PURE__ */ __exportAll({
433
424
  controlEvent: () => controlEvent,
434
425
  dataEvent: () => dataEvent
@@ -441,7 +432,7 @@ function dataEvent(messages, options) {
441
432
  const combined = concatBytes(messages);
442
433
  chunks.push(encode(`data:${bytesToBase64(combined)}\n`));
443
434
  } else if (options.isJson) {
444
- const items = messages.map((msg) => decoder.decode(msg.data));
435
+ const items = Array.map(messages, (msg) => decoder.decode(msg.data));
445
436
  chunks.push(encode("data:[\n"));
446
437
  for (let i = 0; i < items.length; i++) {
447
438
  const suffix = i < items.length - 1 ? "," : "";
@@ -449,7 +440,7 @@ function dataEvent(messages, options) {
449
440
  }
450
441
  chunks.push(encode("data:]\n"));
451
442
  } else {
452
- const text = messages.map((msg) => decoder.decode(msg.data)).join("");
443
+ const text = Array.join(Array.map(messages, (msg) => decoder.decode(msg.data)), "");
453
444
  for (const line of text.split(/\r\n|\r|\n/)) chunks.push(encode(`data:${line}\n`));
454
445
  }
455
446
  chunks.push(encode("\n"));
@@ -461,8 +452,7 @@ function controlEvent(data) {
461
452
  function encode(value) {
462
453
  return encoder.encode(value);
463
454
  }
464
- //#endregion
465
- //#region src/http/sse.ts
455
+ // src/http/sse.ts
466
456
  const events = sse_event_encoder_exports;
467
457
  /** Each connection's deadline is `deadlineMs` scaled by a factor from 0.9 to 1.1. */
468
458
  const DEADLINE_JITTER = .1;
@@ -511,7 +501,7 @@ function sse(reader, id, contentType, offset, cursor, deadlineMs = 6e4, signal)
511
501
  if (!result.closed && result.upToDate) control.upToDate = true;
512
502
  chunks.push(events.controlEvent(control));
513
503
  return {
514
- frames: [concatBytes(chunks.map((data) => ({ data })))],
504
+ frames: [concatBytes(Array.map(chunks, (data) => ({ data })))],
515
505
  done: result.closed
516
506
  };
517
507
  }).pipe(Effect.catchTags({
@@ -536,10 +526,9 @@ function sse(reader, id, contentType, offset, cursor, deadlineMs = 6e4, signal)
536
526
  });
537
527
  if (encoding.useBase64) headers.set("stream-sse-data-encoding", "base64");
538
528
  const body = signal === void 0 ? frames : signal.trackStream(frames);
539
- return HttpServerResponse.stream(body, { headers: Object.fromEntries(headers) });
529
+ return HttpServerResponse.stream(body, { headers: Record.fromEntries(headers) });
540
530
  }
541
- //#endregion
542
- //#region src/http/shutdown-signal.ts
531
+ // src/http/shutdown-signal.ts
543
532
  var ShutdownSignal = class extends Context.Service()("@streamsy/core/ShutdownSignal") {};
544
533
  /** How often `drain` checks the live-read count. */
545
534
  const POLL = Schedule.spaced("5 millis");
@@ -561,8 +550,7 @@ const makeShutdownSignal = Effect.gen(function* () {
561
550
  });
562
551
  /** A fresh signal. Provide it to the routes and call `drain` before they close. */
563
552
  const layerShutdownSignal = Layer.effect(ShutdownSignal, makeShutdownSignal);
564
- //#endregion
565
- //#region src/http/read.ts
553
+ // src/http/read.ts
566
554
  const responses$2 = responses_exports;
567
555
  const bodyCodec = message_body_codec_exports;
568
556
  const etags = etag_builder_exports;
@@ -644,14 +632,12 @@ const read$1 = Effect.fn("Http.read")(function* (reader, id, url, requestHeaders
644
632
  headers.set("content-type", result.contentType);
645
633
  return new Response(bodyCodec.encodeHttpBody(result.messages, result.contentType), { headers });
646
634
  });
647
- //#endregion
648
- //#region src/http/route.ts
635
+ // src/http/route.ts
649
636
  /** Preserve the Web request origin; Effect 4.0.1 toURL otherwise reconstructs it from Host. */
650
637
  function requestUrl(request) {
651
638
  return URL.parse(request.originalUrl) ?? Option.getOrUndefined(HttpServerRequest.toURL(request));
652
639
  }
653
- //#endregion
654
- //#region src/http/read-program.ts
640
+ // src/http/read-program.ts
655
641
  /** @internal Shared construction-time validation for HTTP read routes. */
656
642
  function checkReadOptions(options) {
657
643
  if (options.sseDeadlineMs !== void 0 && (!Number.isFinite(options.sseDeadlineMs) || options.sseDeadlineMs <= 0)) throw new RangeError("sseDeadlineMs must be positive");
@@ -676,15 +662,14 @@ function read(id, options = {}) {
676
662
  if (meta.expiresAt) headers.set("stream-expires-at", meta.expiresAt);
677
663
  return HttpServerResponse.empty({
678
664
  status: 200,
679
- headers: Object.fromEntries(headers)
665
+ headers: Record.fromEntries(headers)
680
666
  });
681
667
  }
682
668
  const response = yield* read$1(reader, id, url, new Headers(request.headers), cacheControlForVisibility(options.cacheVisibility ?? "private"), options.sseDeadlineMs);
683
669
  return response instanceof Response ? fromWeb(response) : response;
684
670
  }).pipe(Effect.map(HttpServerResponse.setHeaders(securityHeaders)));
685
671
  }
686
- //#endregion
687
- //#region src/http/protocol-error-response.ts
672
+ // src/http/protocol-error-response.ts
688
673
  const responses$1 = responses_exports;
689
674
  const conflict = ({ message }) => responses$1.conflict(message);
690
675
  const badRequest = ({ message }) => responses$1.badRequest(message);
@@ -717,8 +702,7 @@ function protocolErrorResponse(error, context) {
717
702
  })
718
703
  });
719
704
  }
720
- //#endregion
721
- //#region src/http/program.ts
705
+ // src/http/program.ts
722
706
  const responses = responses_exports;
723
707
  const failure = (error) => Effect.map(HttpServerRequest.HttpServerRequest, (request) => protocolErrorResponse(error, { method: request.method }));
724
708
  /**
@@ -810,5 +794,4 @@ function app(options = {}) {
810
794
  return HttpServerResponse.setHeaders(result, securityHeaders);
811
795
  }));
812
796
  }
813
- //#endregion
814
797
  export { ShutdownSignal as a, streamPath as c, requestUrl as i, securityHeaders as l, checkReadOptions as n, layerShutdownSignal as o, read as r, discardRequestBody as s, app as t };
@@ -1,8 +1,6 @@
1
- import { _ as StreamsWriter, g as StreamsReader, h as Reader, v as Writer } from "../owner-records-QDlssl__.js";
2
- import { D as streams_d_exports, P as layer_d_exports, u as RoutesOptions, z as route_d_exports } from "../index-CFv8vZvy.js";
1
+ import { _ as StreamsWriter, g as StreamsReader, h as Reader, v as Writer } from "../owner-records-BV5Un5R0.js";
2
+ import { D as streams_d_exports, P as layer_d_exports, u as RoutesOptions, z as route_d_exports } from "../index-C26ncp7Y.js";
3
3
  import { HttpRouter } from "effect/http";
4
- //#region src/protocol/routes.d.ts
5
4
  /** Raw protocol route for adapters and wire conformance tests. */
6
5
  export declare const routes: (options?: Omit<RoutesOptions, "access">) => import("effect/Layer").Layer<never, never, HttpRouter.HttpRouter | HttpRouter.Request<"Requires", StreamsReader> | HttpRouter.Request<"Requires", StreamsWriter>>;
7
- //#endregion
8
6
  export { layer_d_exports as Protocol, type Reader, route_d_exports as StreamRoute, streams_d_exports as Streams, StreamsReader, StreamsWriter, type Writer };
@@ -1,8 +1,8 @@
1
- import { A as StreamsReader, j as StreamsWriter, l as streams_exports, u as route_exports } from "../streamsy-OjRubIPC.js";
2
- import { n as layer_exports } from "../layer-KvknRFUT.js";
3
- import { t as app } from "../program-DJ8NpHIf.js";
1
+ import { A as StreamsReader, j as StreamsWriter, l as streams_exports, u as route_exports } from "../streamsy-DJMArv09.js";
2
+ import { n as layer_exports } from "../layer-DyezIxJT.js";
3
+ import { t as app } from "../program-DXUjw5B2.js";
4
4
  import { HttpRouter } from "effect/http";
5
- //#region src/protocol/routes.ts
5
+ // src/protocol/routes.ts
6
6
  /** Raw protocol route for adapters and wire conformance tests. */
7
7
  const routes = (options = {}) => {
8
8
  const prefix = options.prefix?.replace(/\/$/, "") || "/";
@@ -12,5 +12,4 @@ const routes = (options = {}) => {
12
12
  pathPrefix: prefix
13
13
  }));
14
14
  };
15
- //#endregion
16
15
  export { layer_exports as Protocol, route_exports as StreamRoute, streams_exports as Streams, StreamsReader, StreamsWriter, routes };
@@ -1,8 +1,7 @@
1
- import { _ as StreamsWriter, g as StreamsReader, vt as TransportFault } from "../owner-records-QDlssl__.js";
2
- import { f as Any, m as Identifiers, p as Group } from "../index-CFv8vZvy.js";
1
+ import { _ as StreamsWriter, g as StreamsReader, vt as TransportFault } from "../owner-records-BV5Un5R0.js";
2
+ import { f as Any, m as Identifiers, p as Group } from "../index-C26ncp7Y.js";
3
3
  import { Layer } from "effect";
4
4
  import { HttpClient, HttpClientRequest } from "effect/http";
5
- //#region src/remote/request.d.ts
6
5
  interface Options {
7
6
  readonly baseUrl: string;
8
7
  readonly headers?: Readonly<Record<string, string>>;
@@ -19,5 +18,4 @@ declare namespace streams_d_exports {
19
18
  declare const layerProtocol: (options: Options) => Layer.Layer<StreamsReader | StreamsWriter, TransportFault, HttpClient.HttpClient>;
20
19
  /** Remote streams have no local change feed. */
21
20
  declare function layer<const Keys extends ReadonlyArray<Any>>(group: Group<Keys>, options: Options): Layer.Layer<Identifiers<Keys>, TransportFault, HttpClient.HttpClient>;
22
- //#endregion
23
21
  export { streams_d_exports as RemoteStreams };
@@ -1,14 +1,14 @@
1
- import { t as __exportAll } from "../rolldown-runtime-D7D4PA-g.js";
2
- import { A as StreamsReader, C as ProducerGap, D as StreamGone, E as StreamClosed, O as StreamNotFound, Q as StreamId, S as OffsetMismatch, T as StreamBusy, V as TransportFault, _ as InvalidAppendRequest, b as InvalidReadRequest, f as AppendResult, g as ForkSourceNotFound, h as CreateConflict, j as StreamsWriter, m as AppendConflict, n as bind, p as CreateResult, w as StaleEpoch, x as NotSupported, y as InvalidForkRequest } from "../streamsy-OjRubIPC.js";
3
- import { Context, DateTime, Effect, Fiber, Layer, Option, Schema, Scope, Stream } from "effect";
1
+ import { t as __exportAll } from "../rolldown-runtime-D8jQpDG7.js";
2
+ import { A as StreamsReader, C as ProducerGap, D as StreamGone, E as StreamClosed, O as StreamNotFound, Q as StreamId, S as OffsetMismatch, T as StreamBusy, V as TransportFault, _ as InvalidAppendRequest, b as InvalidReadRequest, f as AppendResult, g as ForkSourceNotFound, h as CreateConflict, j as StreamsWriter, m as AppendConflict, n as bind, p as CreateResult, w as StaleEpoch, x as NotSupported, y as InvalidForkRequest } from "../streamsy-DJMArv09.js";
3
+ import { Array, Context, DateTime, Effect, Fiber, Layer, Option, Schema, Scope, Stream } from "effect";
4
4
  import { HttpClient, HttpClientRequest } from "effect/http";
5
- //#region src/remote/request.ts
5
+ // src/remote/request.ts
6
6
  function requests(options) {
7
7
  const base = new URL(options.baseUrl);
8
8
  if (!/^https?:$/.test(base.protocol) || base.search || base.hash || base.username || base.password) throw new TypeError("baseUrl must be an HTTP(S) URL without credentials, query or fragment");
9
9
  const prefix = base.pathname.replace(/\/$/, "") + "/";
10
10
  const url = (id) => {
11
- if (!id || id.split("/").some((part) => !part || part === "." || part === "..") || /[%?#\\]/.test(id)) throw new TypeError("Stream ID must be a canonical relative path");
11
+ if (!id || Array.some(id.split("/"), (part) => !part || part === "." || part === "..") || /[%?#\\]/.test(id)) throw new TypeError("Stream ID must be a canonical relative path");
12
12
  const target = new URL(base);
13
13
  target.pathname = prefix + id;
14
14
  if (target.pathname !== prefix + id) throw new TypeError("Stream ID must be URL-safe");
@@ -60,8 +60,7 @@ function requests(options) {
60
60
  }
61
61
  };
62
62
  }
63
- //#endregion
64
- //#region src/remote/wire.ts
63
+ // src/remote/wire.ts
65
64
  /**
66
65
  * Standard Durable Streams HTTP response primitives.
67
66
  *
@@ -114,7 +113,7 @@ const integer = (operation, name, value) => {
114
113
  return Effect.succeed(Number(value));
115
114
  };
116
115
  const body = (operation, response) => response.stream.pipe(Stream.runCollect, Effect.map((chunks) => {
117
- const bytes = new Uint8Array(chunks.reduce((size, chunk) => size + chunk.length, 0));
116
+ const bytes = new Uint8Array(Array.reduce(chunks, 0, (size, chunk) => size + chunk.length));
118
117
  let position = 0;
119
118
  for (const chunk of chunks) {
120
119
  bytes.set(chunk, position);
@@ -147,9 +146,8 @@ const readMessages = (operation, response, bytes) => {
147
146
  }));
148
147
  };
149
148
  const jsonArray = Schema.fromJsonString(Schema.Array(Schema.Unknown));
150
- const jsonMessages = (operation, decoded) => Schema.decodeEffect(jsonArray)(decoded).pipe(Effect.mapError((cause) => failure(operation, "decode", "Read body is not a JSON array", cause)), Effect.map((items) => items.map((item) => ({ data: new TextEncoder().encode(JSON.stringify(item)) }))));
151
- //#endregion
152
- //#region src/remote/response.ts
149
+ const jsonMessages = (operation, decoded) => Schema.decodeEffect(jsonArray)(decoded).pipe(Effect.mapError((cause) => failure(operation, "decode", "Read body is not a JSON array", cause)), Effect.map((items) => Array.map(items, (item) => ({ data: new TextEncoder().encode(JSON.stringify(item)) }))));
150
+ // src/remote/response.ts
153
151
  /** Decode standard HTTP successes and fail with the protocol details carried by the wire. */
154
152
  const emptyToUndefined = (value) => {
155
153
  const trimmed = value.trim();
@@ -342,8 +340,7 @@ const remove = (operation, response, context) => Effect.gen(function* () {
342
340
  if (response.status === 503) return yield* new StreamBusy({ id: context.id });
343
341
  return yield* unexpected(operation, response);
344
342
  });
345
- //#endregion
346
- //#region src/remote/streams.ts
343
+ // src/remote/streams.ts
347
344
  var streams_exports = /* @__PURE__ */ __exportAll({
348
345
  TransportFault: () => TransportFault,
349
346
  layer: () => layer,
@@ -424,5 +421,4 @@ function layer(group, options) {
424
421
  const protocol = layerProtocol(options);
425
422
  return bind(protocol, group);
426
423
  }
427
- //#endregion
428
424
  export { streams_exports as RemoteStreams };
@@ -1,4 +1,4 @@
1
- //#region \0rolldown/runtime.js
1
+ // \0rolldown/runtime.js
2
2
  var __defProp = Object.defineProperty;
3
3
  var __exportAll = (all, no_symbols) => {
4
4
  let target = {};
@@ -9,5 +9,4 @@ var __exportAll = (all, no_symbols) => {
9
9
  if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
10
10
  return target;
11
11
  };
12
- //#endregion
13
12
  export { __exportAll as t };
@@ -1,8 +1,7 @@
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
1
+ import { t as __exportAll } from "./rolldown-runtime-D8jQpDG7.js";
2
+ import { i as checkWriteOwner, o as ownerOf, s as storageOf } from "./owner-BWQ2KvC_.js";
3
+ import { Array, Context, Data, Duration, Effect, Layer, Option, Predicate, Record, Result, Schedule, Schema, Stream } from "effect";
4
+ // src/schema/index.ts
6
5
  const StreamId = Schema.String.pipe(Schema.brand("StreamId"));
7
6
  const Offset = Schema.String.pipe(Schema.check(Schema.isPattern(/^\d{16}_\d{16}$/)), Schema.brand("Offset"));
8
7
  const ProducerId = Schema.String.pipe(Schema.brand("ProducerId"));
@@ -66,8 +65,7 @@ const RecordPatch = Schema.Struct({
66
65
  "lastSeq"
67
66
  ])))
68
67
  });
69
- //#endregion
70
- //#region src/fault.ts
68
+ // src/fault.ts
71
69
  var StorageFault = class extends Schema.TaggedError()("StorageFault", {
72
70
  operation: Schema.String,
73
71
  message: Schema.String,
@@ -106,8 +104,7 @@ const StreamsFault = Schema.Union([StorageFault, TransportFault]);
106
104
  const isStreamsFault = Schema.is(StreamsFault);
107
105
  /** A storage or transport failure that can succeed later. */
108
106
  const isRetryableFault = (error) => isStreamsFault(error) && error.retryable;
109
- //#endregion
110
- //#region src/offset/index.ts
107
+ // src/offset/index.ts
111
108
  const ZERO_OFFSET = Offset.make(`${"0".repeat(16)}_${"0".repeat(16)}`);
112
109
  const isValid = (offset) => /^\d{16}_\d{16}$/.test(offset);
113
110
  const compare = (a, b) => a === b ? 0 : a < b ? -1 : 1;
@@ -118,15 +115,12 @@ function next(previous) {
118
115
  if (value > 9999999999999999n) throw new RangeError("Offset exhausted");
119
116
  return Offset.make(`${String(value).padStart(16, "0")}_${"0".repeat(16)}`);
120
117
  }
121
- //#endregion
122
- //#region src/storage/storage.ts
118
+ // src/storage/storage.ts
123
119
  var Storage = class extends Context.Service()("@streamsy/core/Storage") {};
124
- //#endregion
125
- //#region src/protocol/tags.ts
120
+ // src/protocol/tags.ts
126
121
  var StreamsReader = class extends Context.Service()("@streamsy/core/StreamsReader") {};
127
122
  var StreamsWriter = class extends Context.Service()("@streamsy/core/StreamsWriter") {};
128
- //#endregion
129
- //#region src/protocol/errors.ts
123
+ // src/protocol/errors.ts
130
124
  /** Protocol rejections. Optional create reasons reflect the public HTTP wire's loss of detail. */
131
125
  var StreamNotFound = class extends Schema.TaggedError()("StreamNotFound", { id: StreamId }) {
132
126
  get message() {
@@ -243,14 +237,12 @@ const protocolErrorTags = {
243
237
  NotSupported: true
244
238
  };
245
239
  /** 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
240
+ const isProtocolError = (error) => Record.has(protocolErrorTags, error._tag);
241
+ // src/protocol/results.ts
249
242
  /** Constructors and matchers for the protocol results above. */
250
243
  const CreateResult = Data.taggedEnum();
251
244
  const AppendResult = Data.taggedEnum();
252
- //#endregion
253
- //#region src/toolkit/route-internal.ts
245
+ // src/toolkit/route-internal.ts
254
246
  /** Ids are canonical relative paths, the same rule the remote Layer enforces. */
255
247
  function isCanonicalIdSegment(value) {
256
248
  if (value.length === 0 || value === "." || value === "..") return false;
@@ -308,13 +300,18 @@ function templatesOverlap(left, right) {
308
300
  }
309
301
  return true;
310
302
  }
311
- //#endregion
312
- //#region src/toolkit/address.ts
303
+ // src/toolkit/address.ts
313
304
  var address_exports = /* @__PURE__ */ __exportAll({
314
305
  bytes: () => bytes$2,
306
+ isChange: () => isChange,
307
+ isControl: () => isControl,
315
308
  json: () => json$2,
309
+ reset: () => reset,
310
+ snapshotEnd: () => snapshotEnd,
311
+ snapshotStart: () => snapshotStart,
316
312
  state: () => state$2,
317
- stateChange: () => stateChange
313
+ stateChange: () => stateChange,
314
+ stateControl: () => stateControl
318
315
  });
319
316
  /** The address constructors. Each class owns the `_tag` of one address kind. */
320
317
  const JsonAddress = Data.TaggedClass("Json");
@@ -361,17 +358,41 @@ function stateChange(options) {
361
358
  })
362
359
  })]);
363
360
  }
361
+ /** The codec for a State control message. It needs no services. */
362
+ const stateControl = Schema.Struct({ headers: Schema.Struct({
363
+ control: Schema.Literals([
364
+ "snapshot-start",
365
+ "snapshot-end",
366
+ "reset"
367
+ ]),
368
+ offset: Schema.optionalKey(Schema.String)
369
+ }) });
370
+ /** True for a control message. A change has `headers.operation` and no `headers.control`. */
371
+ const isControl = (event) => Predicate.hasProperty(event.headers, "control");
372
+ /** True for an upsert or delete change. */
373
+ const isChange = (event) => !isControl(event);
374
+ const control = (name, options) => ({ headers: options.offset === void 0 ? { control: name } : {
375
+ control: name,
376
+ offset: options.offset
377
+ } });
378
+ /** A `reset` control. A reader should clear its materialized state and apply what follows. */
379
+ const reset = (options = {}) => control("reset", options);
380
+ /** A `snapshot-start` control. The changes up to `snapshot-end` form a complete snapshot. */
381
+ const snapshotStart = (options = {}) => control("snapshot-start", options);
382
+ /** A `snapshot-end` control. It closes the snapshot that `snapshot-start` opened. */
383
+ const snapshotEnd = (options = {}) => control("snapshot-end", options);
364
384
  /**
365
- * A stream of Durable State change events for several collections. Each record
385
+ * A stream of Durable State events for several collections. Each record
366
386
  * key is the `type` on the wire; each entry gives the value schema and the value
367
- * field that becomes the event `key`.
387
+ * field that becomes the event `key`. The codec also decodes and encodes the
388
+ * State control messages `snapshot-start`, `snapshot-end` and `reset`.
368
389
  */
369
390
  function state$2(id, options) {
370
- const codecs = Object.entries(options.collections).map(([type, collection]) => stateChange({
391
+ const codecs = Array.map(Record.toEntries(options.collections), ([type, collection]) => stateChange({
371
392
  schema: collection.schema,
372
393
  type
373
394
  }));
374
- const address = json$2(id, { schema: Schema.Union(codecs) });
395
+ const address = json$2(id, { schema: Schema.Union([...codecs, stateControl]) });
375
396
  return new JsonAddress({
376
397
  id: address.id,
377
398
  contentType: address.contentType,
@@ -387,8 +408,7 @@ function bytes$2(id, options = {}) {
387
408
  codec: Schema.Uint8Array
388
409
  });
389
410
  }
390
- //#endregion
391
- //#region src/toolkit/route.ts
411
+ // src/toolkit/route.ts
392
412
  var route_exports = /* @__PURE__ */ __exportAll({
393
413
  bytes: () => bytes$1,
394
414
  custom: () => custom$1,
@@ -402,7 +422,7 @@ function pathSchema(codecs) {
402
422
  }
403
423
  function decodeParams(codecs, raw) {
404
424
  const decoded = {};
405
- for (const name of Object.keys(codecs)) {
425
+ for (const name of Record.keys(codecs)) {
406
426
  const value = raw[name];
407
427
  const codec = codecs[name];
408
428
  if (value === void 0 || codec === void 0) return Option.none();
@@ -430,7 +450,7 @@ function matchTemplate(segments, codecs, id) {
430
450
  }
431
451
  function buildId(template, segments, codecs, params) {
432
452
  const record = params;
433
- const built = segments.map((segment) => {
453
+ const built = Array.map(segments, (segment) => {
434
454
  if (segment.kind === "literal") return segment.value;
435
455
  const codec = codecs[segment.name];
436
456
  const value = record[segment.name];
@@ -440,7 +460,7 @@ function buildId(template, segments, codecs, params) {
440
460
  if (!isCanonicalIdSegment(text)) throw new RangeError(`stream route ${template} parameter ${segment.name} is not a canonical id segment: ${text}`);
441
461
  return text;
442
462
  });
443
- return StreamId.make(built.join("/"));
463
+ return StreamId.make(Array.join(built, "/"));
444
464
  }
445
465
  /**
446
466
  * The codec record and the template must name the same parameters. The type
@@ -448,7 +468,7 @@ function buildId(template, segments, codecs, params) {
448
468
  */
449
469
  function checkTemplateParams(template, names, codecs) {
450
470
  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}`);
471
+ for (const name of Record.keys(codecs)) if (!names.includes(name)) throw new RangeError(`stream route codec is absent from the template: ${name}`);
452
472
  }
453
473
  function json$1(template, options) {
454
474
  const { segments, names } = compileSegments(template);
@@ -496,8 +516,7 @@ function custom$1(options) {
496
516
  address: options.address
497
517
  });
498
518
  }
499
- //#endregion
500
- //#region src/toolkit/streams.ts
519
+ // src/toolkit/streams.ts
501
520
  var streams_exports = /* @__PURE__ */ __exportAll({
502
521
  append: () => append,
503
522
  collect: () => collect,
@@ -531,7 +550,7 @@ const append = Effect.fn("Streams.append")(function* (address, items, options) {
531
550
  cause
532
551
  }))));
533
552
  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);
553
+ const data = list.length === 0 && callOptions.close ? /* @__PURE__ */ new Uint8Array() : Predicate.isTagged(address, "Json") ? new TextEncoder().encode(`[${Array.join(Array.map(encoded, String), ",")}]`) : concatBytes(encoded);
535
554
  const possible = (error) => possibleFor(callOptions, error);
536
555
  const appended = (yield* StreamsWriter).append(address.id, {
537
556
  ...callOptions,
@@ -541,8 +560,8 @@ const append = Effect.fn("Streams.append")(function* (address, items, options) {
541
560
  return yield* Effect.catchIf(appended, possible, Effect.fail, Effect.die);
542
561
  });
543
562
  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));
563
+ const arrays = Array.map(parts, (part) => Predicate.isString(part) ? new TextEncoder().encode(part) : part);
564
+ const result = new Uint8Array(Array.reduce(arrays, 0, (size, part) => size + part.byteLength));
546
565
  let offset = 0;
547
566
  for (const part of arrays) {
548
567
  result.set(part, offset);
@@ -617,7 +636,7 @@ const decide = Effect.fn("Streams.decide")(function* (address, spec) {
617
636
  folded = last === void 0 ? yield* fold(address, spec.initial, spec.fold) : yield* fold(address, () => last.state, spec.fold, { offset: last.offset });
618
637
  const { state, offset } = folded;
619
638
  const { value, items } = yield* spec.decide(state, { offset });
620
- if (!isReadonlyArrayNonEmpty(items)) return {
639
+ if (!Array.isReadonlyArrayNonEmpty(items)) return {
621
640
  value,
622
641
  offset,
623
642
  appended: false
@@ -704,8 +723,7 @@ const head = Effect.fn("Streams.head")(function* (address) {
704
723
  const remove = Effect.fn("Streams.remove")(function* (address) {
705
724
  return yield* (yield* StreamsWriter).remove(address.id);
706
725
  });
707
- //#endregion
708
- //#region src/toolkit/streamsy.ts
726
+ // src/toolkit/streamsy.ts
709
727
  const templateOf = (route) => {
710
728
  if (!("template" in route)) return void 0;
711
729
  const template = route.template;
@@ -714,7 +732,7 @@ const templateOf = (route) => {
714
732
  };
715
733
  /** Template streams must have disjoint id grammars. Custom routes use declaration order. */
716
734
  function checkNoOverlap(routes) {
717
- const templates = routes.flatMap((route) => {
735
+ const templates = Array.flatMap(routes, (route) => {
718
736
  const template = templateOf(route);
719
737
  return template === void 0 ? [] : [template];
720
738
  });
@@ -805,7 +823,7 @@ function checkStreams(keys) {
805
823
  templates.add(key.template);
806
824
  if (key.key === Wildcard.key && index !== keys.length - 1) throw new RangeError("Wildcard must be last");
807
825
  }
808
- checkNoOverlap(keys.map((key) => declaration(key).route));
826
+ checkNoOverlap(Array.map(keys, (key) => declaration(key).route));
809
827
  }
810
828
  function bind(source, streams) {
811
829
  const keys = streams.streams;
@@ -825,5 +843,4 @@ function group(...keys) {
825
843
  checkStreams(keys);
826
844
  return Object.freeze({ streams: Object.freeze(keys) });
827
845
  }
828
- //#endregion
829
846
  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 };