@streamsy/core 0.4.0 → 0.6.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.
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
- import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
2
- import { $ as StreamLifecycle, B as StreamsFault, C as ProducerGap, D as StreamGone, E as StreamClosed, G as MessageWindow, H as isRetryableFault, J as ProducerState, K as Offset, L as DecodeFault, M as Storage, N as ZERO_OFFSET, O as StreamNotFound, P as compare, Q as StreamId, R as EncodeFault, S as OffsetMismatch, T as StreamBusy, U as isStreamsFault, V as TransportFault, W as ChangeSnapshot, X as StoredMessage, Y as RecordPatch, Z as StreamConfig, _ as InvalidAppendRequest, a as custom, b as InvalidReadRequest, c as state, d as address_exports, et as StreamRecord, f as AppendResult, g as ForkSourceNotFound, h as CreateConflict, k as isProtocolError, m as AppendConflict, n as bind, o as group, p as CreateResult, q as ProducerId, r as bytes, s as json, t as Wildcard, v as InvalidEpochSeq, w as StaleEpoch, x as NotSupported, y as InvalidForkRequest, z as StorageFault } from "./streamsy-OjRubIPC.js";
3
- import { n as CommitBoundary, t as layer$1 } from "./layer-D8ybaCL2.js";
4
- import { a as MutationRejected, c as OperationResult, d as ProducerPrecondition, i as MutationApplied, l as OperationResults, o as Mutations, r as Mutation, s as Operation, t as layer$2, u as Operations } from "./layer-KvknRFUT.js";
5
- import { t as http_exports } from "./http-EnNOUsIK.js";
6
- import { Data, Layer, Predicate, Schema } from "effect";
7
- //#region src/storage/capabilities.ts
1
+ import { t as __exportAll } from "./rolldown-runtime-D8jQpDG7.js";
2
+ import { $ as RecordPatch, A as StreamClosed, C as InvalidForkRequest, D as ProducerGap, E as OffsetMismatch, G as TransportFault, H as EncodeFault, I as Storage, J as ChangeSnapshot, K as isRetryableFault, L as ZERO_OFFSET, M as StreamNotFound, N as isProtocolError, O as StaleEpoch, Q as ProducerState, R as compare, S as InvalidEpochSeq, T as NotSupported, U as StorageFault, V as DecodeFault, W as StreamsFault, X as Offset, Y as MessageWindow, Z as ProducerId, _ as CreateResult, a as custom, b as ForkSourceNotFound, c as state, d as address_exports, et as StoredMessage, f as isControl, g as AppendResult, h as stateControl, it as StreamRecord, j as StreamGone, k as StreamBusy, m as stateChange, n as bind, nt as StreamId, o as group, p as isUpsert, q as isStreamsFault, r as bytes, rt as StreamLifecycle, s as json, t as Wildcard, tt as StreamConfig, v as AppendConflict, w as InvalidReadRequest, x as InvalidAppendRequest, y as CreateConflict } from "./streamsy-D9OCCdw0.js";
3
+ import { n as CommitBoundary, t as layer$1 } from "./layer-DQZj5tXr.js";
4
+ import { a as MutationRejected, c as OperationResult, d as ProducerPrecondition, i as MutationApplied, l as OperationResults, o as Mutations, r as Mutation, s as Operation, t as layer$2, u as Operations } from "./layer-8Y1cg6UL.js";
5
+ import { t as http_exports } from "./http-B10ao6xE.js";
6
+ import { Array, Data, Effect, Layer, Option, Predicate, Record, Schema, Stream } from "effect";
7
+ // src/storage/capabilities.ts
8
8
  const StorageCapabilities = Schema.Struct({
9
9
  fork: Schema.Literals([
10
10
  "none",
@@ -15,8 +15,7 @@ const StorageCapabilities = Schema.Struct({
15
15
  wake: Schema.Literals(["poll", "push"]),
16
16
  expiryIndex: Schema.Literals(["lazy", "indexed"])
17
17
  });
18
- //#endregion
19
- //#region src/storage/memory/streams.ts
18
+ // src/storage/memory/streams.ts
20
19
  var streams_exports = /* @__PURE__ */ __exportAll({
21
20
  layer: () => layer,
22
21
  layerProtocol: () => layerProtocol
@@ -28,14 +27,16 @@ function layer(group, options = {}) {
28
27
  const protocol = layer$2(options).pipe(Layer.provideMerge(storage));
29
28
  return bind(protocol, group).pipe(Layer.provideMerge(storage));
30
29
  }
31
- //#endregion
32
- //#region src/toolkit/durable-state.ts
30
+ // src/toolkit/durable-state.ts
33
31
  var durable_state_exports = /* @__PURE__ */ __exportAll({
34
32
  changes: () => changes,
33
+ materialize: () => materialize,
34
+ materialized: () => materialized,
35
35
  remove: () => remove,
36
36
  upsert: () => upsert
37
37
  });
38
38
  const operations = Data.taggedEnum();
39
+ const isOperation = (entry) => Predicate.isTagged(entry, "Upsert") || Predicate.isTagged(entry, "Delete");
39
40
  /** Describe an upsert into a collection. The key is read from the value. */
40
41
  const upsert = (type, value, options = {}) => operations.Upsert({
41
42
  type,
@@ -57,64 +58,290 @@ const checkKey = (type, source, raw) => {
57
58
  const readKey = (type, field, value) => checkKey(type, `field "${String(field)}"`, String(value[field] ?? ""));
58
59
  function changes(address, options, entries) {
59
60
  const { offset } = options;
60
- return entries.map((entry, index) => {
61
- const collection = Object.hasOwn(address.collections, entry.type) ? address.collections[entry.type] : void 0;
62
- if (collection === void 0) throw new TypeError(`Unknown state collection "${entry.type}"`);
63
- const override = entry.headers ?? {};
64
- const txid = override.txid ?? (offset === void 0 ? void 0 : `${offset}:${index}`);
65
- const headers = {};
66
- if (offset !== void 0) headers.offset = offset;
67
- if (txid !== void 0) headers.txid = txid;
68
- if (override.timestamp !== void 0) headers.timestamp = override.timestamp;
69
- if (override.from !== void 0) headers.from = override.from;
70
- if (Predicate.isTagged(entry, "Upsert")) {
71
- const key = readKey(entry.type, collection.key, entry.value);
72
- return {
73
- type: entry.type,
74
- key,
75
- value: entry.value,
76
- headers: {
77
- operation: "upsert",
78
- ...headers
79
- }
80
- };
81
- }
82
- const key = checkKey(entry.type, "key", entry.key);
83
- return entry.oldValue === void 0 ? {
84
- type: entry.type,
85
- key,
86
- headers: {
87
- operation: "delete",
88
- ...headers
89
- }
90
- } : {
61
+ return Array.map(entries, (entry, index) => isOperation(entry) ? stampChange(address.collections, entry, offset, index) : stampControl(entry, offset));
62
+ }
63
+ const stampChange = (collections, entry, offset, index) => {
64
+ const collection = Record.has(collections, entry.type) ? collections[entry.type] : void 0;
65
+ if (collection === void 0) throw new TypeError(`Unknown state collection "${entry.type}"`);
66
+ const override = entry.headers ?? {};
67
+ const txid = override.txid ?? (offset === void 0 ? void 0 : `${offset}:${index}`);
68
+ const headers = {};
69
+ if (offset !== void 0) headers.offset = offset;
70
+ if (txid !== void 0) headers.txid = txid;
71
+ if (override.timestamp !== void 0) headers.timestamp = override.timestamp;
72
+ if (override.from !== void 0) headers.from = override.from;
73
+ if (Predicate.isTagged(entry, "Upsert")) {
74
+ const key = readKey(entry.type, collection.key, entry.value);
75
+ return {
91
76
  type: entry.type,
92
77
  key,
93
- old_value: entry.oldValue,
78
+ value: entry.value,
94
79
  headers: {
95
- operation: "delete",
80
+ operation: "upsert",
96
81
  ...headers
97
82
  }
98
83
  };
99
- });
84
+ }
85
+ const key = checkKey(entry.type, "key", entry.key);
86
+ return entry.oldValue === void 0 ? {
87
+ type: entry.type,
88
+ key,
89
+ headers: {
90
+ operation: "delete",
91
+ ...headers
92
+ }
93
+ } : {
94
+ type: entry.type,
95
+ key,
96
+ old_value: entry.oldValue,
97
+ headers: {
98
+ operation: "delete",
99
+ ...headers
100
+ }
101
+ };
102
+ };
103
+ const stampControl = (entry, offset) => offset === void 0 || entry.headers.offset !== void 0 ? entry : { headers: {
104
+ control: entry.headers.control,
105
+ offset
106
+ } };
107
+ /** A row key that is unique across collections, for snapshot bookkeeping. */
108
+ const snapshotKey = (type, key) => `${type}\u0000${key}`;
109
+ /** Empty materialized state for the collections of `address`. */
110
+ function materialized(address) {
111
+ const rows = {};
112
+ for (const type of Record.keys(address.collections)) rows[type] = /* @__PURE__ */ new Map();
113
+ return {
114
+ rows,
115
+ snapshot: void 0
116
+ };
100
117
  }
101
- //#endregion
102
- //#region src/toolkit/producer.ts
118
+ /**
119
+ * Fold State events into materialized state, with the State protocol rules:
120
+ *
121
+ * - `upsert` sets the row of its key, and `delete` removes it.
122
+ * - `reset` clears every collection.
123
+ * - `snapshot-end` removes each row that no change since `snapshot-start` named.
124
+ * A snapshot may span several calls.
125
+ *
126
+ * The input state is not changed. Only the collections that `events` touch are copied.
127
+ */
128
+ function materialize(state, events) {
129
+ const rows = /* @__PURE__ */ new Map();
130
+ let cleared = false;
131
+ let snapshot = state.snapshot === void 0 ? void 0 : new Set(state.snapshot);
132
+ const source = (type) => cleared ? void 0 : Record.has(state.rows, type) ? state.rows[type] : void 0;
133
+ const writable = (type) => {
134
+ const existing = rows.get(type);
135
+ if (existing !== void 0) return existing;
136
+ const copy = new Map(source(type));
137
+ rows.set(type, copy);
138
+ return copy;
139
+ };
140
+ for (const event of events) {
141
+ if (isControl(event)) {
142
+ const control = event.headers.control;
143
+ if (control === "reset") {
144
+ cleared = true;
145
+ rows.clear();
146
+ snapshot = void 0;
147
+ } else if (control === "snapshot-start") snapshot = /* @__PURE__ */ new Set();
148
+ else if (snapshot !== void 0) {
149
+ const seen = snapshot;
150
+ for (const type of Record.keys(state.rows)) {
151
+ const table = writable(type);
152
+ for (const key of Array.fromIterable(table.keys())) if (!seen.has(snapshotKey(type, key))) table.delete(key);
153
+ }
154
+ snapshot = void 0;
155
+ }
156
+ continue;
157
+ }
158
+ const table = writable(event.type);
159
+ if (isUpsert(event)) {
160
+ table.set(event.key, event.value);
161
+ snapshot?.add(snapshotKey(event.type, event.key));
162
+ } else {
163
+ table.delete(event.key);
164
+ snapshot?.delete(snapshotKey(event.type, event.key));
165
+ }
166
+ }
167
+ const next = {};
168
+ for (const type of Record.keys(state.rows)) next[type] = rows.get(type) ?? (cleared ? /* @__PURE__ */ new Map() : state.rows[type]);
169
+ return {
170
+ rows: next,
171
+ snapshot
172
+ };
173
+ }
174
+ // src/toolkit/producer.ts
103
175
  var producer_exports = /* @__PURE__ */ __exportAll({ next: () => next });
104
176
  /** Advance only after the caller has acknowledged appended or duplicate. Persist this tuple at the owning edge. */
105
177
  const next = (position) => ({
106
178
  ...position,
107
179
  producerSeq: position.producerSeq + 1
108
180
  });
109
- //#endregion
110
- //#region src/streamsy.ts
181
+ // src/toolkit/wake.ts
182
+ /**
183
+ * Wake streams: one Durable State stream that indexes the writes of a family of
184
+ * source streams.
185
+ *
186
+ * A wake declaration is a State stream with one `stream` collection. Each row
187
+ * is the latest known state of one source stream. A projection writes the rows:
188
+ * `Projection.wake` in `@streamsy/projection` reads one source stream and
189
+ * appends its row with a producer tuple, on the same owner or another one. A
190
+ * wake stream on another owner must exist first: its owner creates it at start.
191
+ * The typed service is the normal State service.
192
+ */
193
+ /** One row of a wake stream: the latest known state of one source stream. */
194
+ const WakeRow = Schema.Struct({
195
+ /** Canonical id of the source stream. It is also the State key. */
196
+ stream: StreamId,
197
+ /** Source tail after the write. The same value as a reader's saved cursor. */
198
+ offset: Offset,
199
+ /** Present when the source stream is closed. */
200
+ closed: Schema.optionalKey(Schema.Literal(true))
201
+ });
202
+ /** The one collection of every wake stream. Its State `type` is `stream`. */
203
+ const wakeCollections = { stream: {
204
+ schema: WakeRow,
205
+ key: "stream"
206
+ } };
207
+ /**
208
+ * The codec of one wake stream message: a `stream` change or a State control.
209
+ * A client that decodes raw JSON pages uses it in place of a typed service.
210
+ */
211
+ const WakeMessage = Schema.Union([stateChange({
212
+ type: "stream",
213
+ schema: WakeRow
214
+ }), stateControl]);
215
+ /**
216
+ * Declare a wake stream: a State stream of `WakeRow`s at a template.
217
+ *
218
+ * ```ts
219
+ * class UserWake extends Streamsy.wake<UserWake>()("App/UserWake", "users/:user/wake", {
220
+ * params: { user: UserKey },
221
+ * }) {}
222
+ * ```
223
+ *
224
+ * The declaration names no sources. A `Projection.wake` binding links one
225
+ * source stream to one wake stream, with params of its own.
226
+ */
227
+ const wake = () => (name, template, options) => state()(name, template, {
228
+ params: options.params,
229
+ collections: wakeCollections
230
+ });
231
+ /** Constructors and matchers for `WakeItem`. */
232
+ const WakeItem = Data.taggedEnum();
233
+ /**
234
+ * The actions for one batch of wake messages. The function is pure: it reads
235
+ * no stream and changes none of its inputs. Rows for one stream collapse to one
236
+ * item; a delete then an upsert of one stream gives `Removed`, then `Dirty` from
237
+ * `-1`. Pass the returned `snapshot` to the call for the next batch.
238
+ *
239
+ * `followWake` uses it over a typed service. A client with its own HTTP reader
240
+ * decodes each page with `WakeMessage` and calls it directly.
241
+ */
242
+ function wakeActions(events, options) {
243
+ const { cursors } = options;
244
+ const items = [];
245
+ let pending = /* @__PURE__ */ new Map();
246
+ let reset = false;
247
+ let open = options.snapshot === void 0 ? void 0 : new Set(options.snapshot);
248
+ const flush = () => {
249
+ for (const [stream, entry] of pending) {
250
+ if (entry.removed) items.push(WakeItem.Removed({ stream }));
251
+ if (Option.isSome(entry.dirty)) items.push(WakeItem.Dirty({
252
+ stream,
253
+ ...entry.dirty.value
254
+ }));
255
+ }
256
+ pending = /* @__PURE__ */ new Map();
257
+ };
258
+ for (const event of events) {
259
+ if (isControl(event)) {
260
+ const control = event.headers.control;
261
+ if (control === "reset") {
262
+ pending = /* @__PURE__ */ new Map();
263
+ items.length = 0;
264
+ items.push(WakeItem.Reset());
265
+ reset = true;
266
+ open = void 0;
267
+ } else if (control === "snapshot-start") open = /* @__PURE__ */ new Set();
268
+ else if (open !== void 0) {
269
+ flush();
270
+ items.push(WakeItem.Snapshot({ streams: open }));
271
+ open = void 0;
272
+ }
273
+ continue;
274
+ }
275
+ const stream = StreamId.make(event.key);
276
+ const prior = pending.get(stream);
277
+ pending.delete(stream);
278
+ if (!isUpsert(event)) {
279
+ pending.set(stream, {
280
+ removed: true,
281
+ dirty: Option.none()
282
+ });
283
+ open?.delete(stream);
284
+ continue;
285
+ }
286
+ const row = event.value;
287
+ const removed = prior?.removed ?? false;
288
+ const base = removed || reset ? "-1" : cursors.get(stream) ?? "-1";
289
+ const dirty = compare(row.offset, base) > 0 || row.closed === true;
290
+ pending.set(stream, {
291
+ removed,
292
+ dirty: dirty ? Option.some({
293
+ from: base,
294
+ offset: row.offset,
295
+ closed: row.closed === true
296
+ }) : Option.none()
297
+ });
298
+ open?.add(stream);
299
+ }
300
+ flush();
301
+ return {
302
+ items,
303
+ snapshot: open
304
+ };
305
+ }
306
+ /**
307
+ * Follow one wake stream and give the actions for each batch: which source
308
+ * streams to read, from which cursor, and which to drop. The helper reads no
309
+ * source stream. Save each source cursor first and the wake cursor (`offset`)
310
+ * last; a stop between the two reads the same rows again, and the offset check
311
+ * skips the streams that were already read.
312
+ */
313
+ function followWake(declaration, params, options) {
314
+ const { from, cursors, ...follow } = options;
315
+ return Stream.unwrap(Effect.map(Effect.service(declaration), (service) => service.follow(params, {
316
+ ...follow,
317
+ offset: from
318
+ }).pipe(Stream.mapAccum(() => void 0, (snapshot, batch) => {
319
+ const next = wakeActions(batch.items, {
320
+ cursors,
321
+ snapshot
322
+ });
323
+ const out = {
324
+ items: next.items,
325
+ offset: batch.nextOffset,
326
+ upToDate: batch.upToDate
327
+ };
328
+ return [next.snapshot, [out]];
329
+ }))));
330
+ }
331
+ // src/streamsy.ts
111
332
  var streamsy_exports = /* @__PURE__ */ __exportAll({
333
+ WakeItem: () => WakeItem,
334
+ WakeMessage: () => WakeMessage,
335
+ WakeRow: () => WakeRow,
112
336
  Wildcard: () => Wildcard,
113
337
  bytes: () => bytes,
114
338
  custom: () => custom,
339
+ followWake: () => followWake,
115
340
  group: () => group,
116
341
  json: () => json,
117
- state: () => state
342
+ state: () => state,
343
+ wake: () => wake,
344
+ wakeActions: () => wakeActions,
345
+ wakeCollections: () => wakeCollections
118
346
  });
119
- //#endregion
120
347
  export { AppendConflict, AppendResult, ChangeSnapshot, CommitBoundary, CreateConflict, CreateResult, DecodeFault, durable_state_exports as DurableState, EncodeFault, ForkSourceNotFound, http_exports as Http, InvalidAppendRequest, InvalidEpochSeq, InvalidForkRequest, InvalidReadRequest, streams_exports as MemoryStorage, MessageWindow, Mutation, MutationApplied, MutationRejected, Mutations, NotSupported, Offset, OffsetMismatch, Operation, OperationResult, OperationResults, Operations, producer_exports as Producer, ProducerGap, ProducerId, ProducerPrecondition, ProducerState, RecordPatch, StaleEpoch, Storage, StorageCapabilities, StorageFault, StoredMessage, address_exports as StreamAddress, StreamBusy, StreamClosed, StreamConfig, StreamGone, StreamId, StreamLifecycle, StreamNotFound, StreamRecord, StreamsFault, streamsy_exports as Streamsy, TransportFault, ZERO_OFFSET, compare, isProtocolError, isRetryableFault, isStreamsFault };
@@ -1,6 +1,5 @@
1
- import { n as OwnerRecordsApi, t as OwnerRecords } from "../owner-records-QDlssl__.js";
1
+ import { n as OwnerRecordsApi, t as OwnerRecords } from "../owner-records-H7VEuBpy.js";
2
2
  import { Context, Effect } from "effect";
3
- //#region src/internal/owner.d.ts
4
3
  /** Private bridge: a stream guard dies with this sentinel; the atomic runner translates it. */
5
4
  declare const ForeignOwnerType: unique symbol;
6
5
  declare const ForeignOwner_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
@@ -18,5 +17,27 @@ type Owner = object;
18
17
  export declare const attachOwner: <A extends object>(value: A, owner: Owner) => A;
19
18
  export declare const ownerOf: (value: object) => Owner;
20
19
  export declare const CurrentOwner: Context.Reference<object | undefined>;
21
- //#endregion
20
+ /**
21
+ * Compile output shared by `StreamRoute` and stream validation.
22
+ *
23
+ * The public route value carries an id grammar, a typed `parse`, and an address
24
+ * constructor. Stream validation also needs the compiled grammar, so it can
25
+ * reject two templates that can both match one id. This module owns that
26
+ * compilation and the static overlap check.
27
+ */
28
+ interface LiteralSegment {
29
+ readonly kind: "literal";
30
+ readonly value: string;
31
+ }
32
+ interface ParameterSegment {
33
+ readonly kind: "parameter";
34
+ readonly name: string;
35
+ }
36
+ type Segment = LiteralSegment | ParameterSegment;
37
+ interface TemplateGrammar<Template extends string = string> {
38
+ readonly template: Template;
39
+ readonly segments: ReadonlyArray<Segment>;
40
+ readonly names: ReadonlyArray<string>;
41
+ }
42
+ export declare function compileSegments<const Template extends string>(template: Template): TemplateGrammar<Template>;
22
43
  export { OwnerRecords, type OwnerRecordsApi };
@@ -1,3 +1,3 @@
1
- import { a as isForeignOwner, n as attachOwner, o as ownerOf, t as CurrentOwner } from "../owner-BQzMpfC1.js";
2
- import { t as OwnerRecords } from "../owner-records-CX6yU28i.js";
3
- export { CurrentOwner, OwnerRecords, attachOwner, isForeignOwner, ownerOf };
1
+ import { a as attachOwner, c as isForeignOwner, i as CurrentOwner, l as ownerOf, t as compileSegments } from "../route-internal-DNL0oGTN.js";
2
+ import { t as OwnerRecords } from "../owner-records-C0p8jeC1.js";
3
+ export { CurrentOwner, OwnerRecords, attachOwner, compileSegments, isForeignOwner, ownerOf };
@@ -1,9 +1,9 @@
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, F as isValid, I as next, J as ProducerState, K as Offset, M as Storage, N as ZERO_OFFSET, O as StreamNotFound, P as compare, Q as StreamId, S as OffsetMismatch, T as StreamBusy, X as StoredMessage, Y as RecordPatch, _ as InvalidAppendRequest, b as InvalidReadRequest, et as StreamRecord, f as AppendResult, g as ForkSourceNotFound, h as CreateConflict, j as StreamsWriter, m as AppendConflict, n as bind, p as CreateResult, q as ProducerId, v as InvalidEpochSeq, w as StaleEpoch, x as NotSupported, y as InvalidForkRequest } from "./streamsy-OjRubIPC.js";
3
- import { r as attachStorage } from "./owner-BQzMpfC1.js";
4
- import { t as generateCursor } from "./cursor-generator-CGz1TO_N.js";
5
- import { Clock, Context, Data, Effect, Layer, Match, Option, Predicate, Random, Schema, Stream } from "effect";
6
- //#region src/storage/mutation.ts
1
+ import { t as __exportAll } from "./rolldown-runtime-D8jQpDG7.js";
2
+ import { $ as RecordPatch, A as StreamClosed, B as next, C as InvalidForkRequest, D as ProducerGap, E as OffsetMismatch, F as StreamsWriter, I as Storage, L as ZERO_OFFSET, M as StreamNotFound, O as StaleEpoch, P as StreamsReader, Q as ProducerState, R as compare, S as InvalidEpochSeq, T as NotSupported, X as Offset, Z as ProducerId, _ as CreateResult, b as ForkSourceNotFound, et as StoredMessage, g as AppendResult, it as StreamRecord, j as StreamGone, k as StreamBusy, n as bind, nt as StreamId, v as AppendConflict, w as InvalidReadRequest, x as InvalidAppendRequest, y as CreateConflict, z as isValid } from "./streamsy-D9OCCdw0.js";
3
+ import { o as attachStorage } from "./route-internal-DNL0oGTN.js";
4
+ import { t as generateCursor } from "./cursor-generator-DySXZ93b.js";
5
+ import { Array, Clock, Context, Data, Effect, Layer, Match, Option, Predicate, Random, Schema, Stream } from "effect";
6
+ // src/storage/mutation.ts
7
7
  const ProducerPrecondition = Schema.Struct({
8
8
  producerId: ProducerId,
9
9
  expected: Schema.Option(ProducerState),
@@ -62,8 +62,7 @@ var MutationRejected = class extends Schema.TaggedError()("MutationRejected", {
62
62
  const Operations = Data.taggedEnum();
63
63
  const OperationResults = Data.taggedEnum();
64
64
  const Mutations = Data.taggedEnum();
65
- //#endregion
66
- //#region src/policy/content-type-matcher.ts
65
+ // src/policy/content-type-matcher.ts
67
66
  /**
68
67
  * Content type normalization and matching for the durable streams protocol.
69
68
  *
@@ -84,8 +83,7 @@ function normalizeContentType(ct) {
84
83
  function contentTypeMatches(expected, actual) {
85
84
  return normalizeContentType(expected) === normalizeContentType(actual);
86
85
  }
87
- //#endregion
88
- //#region src/policy/create-config-matcher.ts
86
+ // src/policy/create-config-matcher.ts
89
87
  function configMatches(existing, options) {
90
88
  const contentType = options.contentType ?? existing.config.contentType ?? "application/octet-stream";
91
89
  if (!contentTypeMatches(existing.config.contentType, contentType)) return false;
@@ -97,8 +95,7 @@ function configMatches(existing, options) {
97
95
  if (existing.config.expiresAt !== options.expiresAt && !inheritedForkExpiry) return false;
98
96
  return existing.lifecycle.closed === (options.closed === true);
99
97
  }
100
- //#endregion
101
- //#region src/policy/expiry-policy.ts
98
+ // src/policy/expiry-policy.ts
102
99
  /** Pure rules ported from ExpiryPolicy; touch and expiry execution belong to the protocol. */
103
100
  function computeExpiresAtMs(config, now) {
104
101
  if (config.ttlSeconds !== void 0) return now + config.ttlSeconds * 1e3;
@@ -108,8 +105,7 @@ function isExpired(record, now) {
108
105
  const at = record.lifecycle.expiresAtMs;
109
106
  return at !== void 0 && at <= now;
110
107
  }
111
- //#endregion
112
- //#region src/policy/message-framer.ts
108
+ // src/policy/message-framer.ts
113
109
  /**
114
110
  * Body framing for the durable streams protocol.
115
111
  *
@@ -131,11 +127,10 @@ function isExpired(record, now) {
131
127
  function frameMessages(data, contentType) {
132
128
  if (!contentType.toLowerCase().startsWith("application/json")) return [data];
133
129
  const parsed = JSON.parse(new TextDecoder().decode(data));
134
- if (Array.isArray(parsed)) return parsed.length === 0 ? [] : parsed.map((item) => new TextEncoder().encode(JSON.stringify(item)));
130
+ if (Array.isArray(parsed)) return parsed.length === 0 ? [] : Array.map(parsed, (item) => new TextEncoder().encode(JSON.stringify(item)));
135
131
  return [new TextEncoder().encode(JSON.stringify(parsed))];
136
132
  }
137
- //#endregion
138
- //#region src/policy/fork-plan-builder.ts
133
+ // src/policy/fork-plan-builder.ts
139
134
  /** Fork-side validation and plan building. */
140
135
  const ForkBuildResult = Data.taggedEnum();
141
136
  const ForkPrefix = Data.taggedEnum();
@@ -224,7 +219,7 @@ var ForkPlanBuilder = class {
224
219
  const tail = sourceTail ?? [];
225
220
  if (contentType.toLowerCase().startsWith("application/json")) {
226
221
  if (subOffset > tail.length) return ForkPrefix.Invalid({ errorMessage: "Stream-Fork-Sub-Offset exceeds source message count" });
227
- return ForkPrefix.Prefix({ messages: tail.slice(0, subOffset).map((m) => m.data) });
222
+ return ForkPrefix.Prefix({ messages: Array.map(tail.slice(0, subOffset), (m) => m.data) });
228
223
  }
229
224
  const first = tail[0];
230
225
  if (!first) return ForkPrefix.Invalid({ errorMessage: "Stream-Fork-Sub-Offset has no source message to fork" });
@@ -235,7 +230,7 @@ var ForkPlanBuilder = class {
235
230
  const framed = [...prefix, ...initialData ? frameMessages(initialData, contentType) : []];
236
231
  let offset = previousOffset;
237
232
  const now = this.deps.clock.now();
238
- return framed.map((data) => {
233
+ return Array.map(framed, (data) => {
239
234
  offset = next(offset);
240
235
  return {
241
236
  data,
@@ -254,8 +249,7 @@ var ForkPlanBuilder = class {
254
249
  };
255
250
  }
256
251
  };
257
- //#endregion
258
- //#region src/protocol/expiry.ts
252
+ // src/protocol/expiry.ts
259
253
  const expireIfNeeded = Effect.fn("Protocol.expireIfNeeded")(function* (storage, id) {
260
254
  const record = yield* storage.record(id);
261
255
  const now = yield* Clock.currentTimeMillis;
@@ -293,8 +287,7 @@ const expireDue = Effect.fn("Protocol.expireDue")(function* () {
293
287
  })] }).pipe(Effect.uninterruptible, Effect.catchTag("MutationRejected", () => Effect.void));
294
288
  }
295
289
  });
296
- //#endregion
297
- //#region src/protocol/create.ts
290
+ // src/protocol/create.ts
298
291
  function newRecord(id, contentType, options, now, fork) {
299
292
  const at = computeExpiresAtMs(options, now);
300
293
  const config = {
@@ -365,7 +358,7 @@ const create = Effect.fn("Protocol.create")(function* (storage, id, options = {}
365
358
  const type = options.contentType ?? "application/octet-stream";
366
359
  const record = newRecord(id, type, options, now);
367
360
  let offset = record.currentOffset;
368
- const initialMessages = (options.initialData ? frameMessages(options.initialData, type) : []).map((data) => ({
361
+ const initialMessages = Array.map(options.initialData ? frameMessages(options.initialData, type) : [], (data) => ({
369
362
  data,
370
363
  offset: offset = next(offset),
371
364
  timestamp: now
@@ -396,8 +389,7 @@ const create = Effect.fn("Protocol.create")(function* (storage, id, options = {}
396
389
  return Effect.die(/* @__PURE__ */ new Error(`Unexpected create rejection: ${rejection.reason}`));
397
390
  }));
398
391
  });
399
- //#endregion
400
- //#region src/policy/producer-idempotency-service.ts
392
+ // src/policy/producer-idempotency-service.ts
401
393
  /** Pure producer idempotency decisions. */
402
394
  const ProducerValidation = Data.taggedEnum();
403
395
  function validateProducer(state, epoch, seq) {
@@ -485,7 +477,7 @@ const append = Effect.fn("Protocol.append")(function* (storage, id, options) {
485
477
  });
486
478
  const now = yield* Clock.currentTimeMillis;
487
479
  let offset = record.currentOffset;
488
- const messages = (closeOnly ? [] : frameMessages(options.data, record.config.contentType)).map((data) => ({
480
+ const messages = Array.map(closeOnly ? [] : frameMessages(options.data, record.config.contentType), (data) => ({
489
481
  data,
490
482
  offset: offset = next(offset),
491
483
  timestamp: now
@@ -529,8 +521,7 @@ const append = Effect.fn("Protocol.append")(function* (storage, id, options) {
529
521
  }
530
522
  return yield* new StreamBusy({ id });
531
523
  });
532
- //#endregion
533
- //#region src/protocol/read.ts
524
+ // src/protocol/read.ts
534
525
  const head = Effect.fn("Protocol.head")(function* (storage, id) {
535
526
  const found = yield* expireIfNeeded(storage, id);
536
527
  if (Option.isNone(found)) return yield* new StreamNotFound({ id });
@@ -561,7 +552,7 @@ const readRecord = Effect.fn("Protocol.readRecord")(function* (storage, record,
561
552
  const upToDate = nextOffset === record.currentOffset;
562
553
  return {
563
554
  contentType: record.config.contentType,
564
- messages: messages.map((message) => ({ data: message.data })),
555
+ messages: Array.map(messages, (message) => ({ data: message.data })),
565
556
  nextOffset,
566
557
  upToDate,
567
558
  closed: record.lifecycle.closed && upToDate
@@ -613,8 +604,7 @@ const readNext = Effect.fn("Protocol.readNext")(function* (storage, id, options,
613
604
  cursor: yield* cursor
614
605
  };
615
606
  });
616
- //#endregion
617
- //#region src/protocol/layer.ts
607
+ // src/protocol/layer.ts
618
608
  var layer_exports = /* @__PURE__ */ __exportAll({
619
609
  bind: () => bind,
620
610
  expireDue: () => expireDue,
@@ -652,5 +642,4 @@ const layer = (options = {}) => Layer.effectContext(Effect.gen(function* () {
652
642
  });
653
643
  return Context.make(StreamsReader, attachStorage(reader, storage)).pipe(Context.add(StreamsWriter, attachStorage(writer, storage)));
654
644
  }));
655
- //#endregion
656
645
  export { MutationRejected as a, OperationResult as c, ProducerPrecondition as d, MutationApplied as i, OperationResults as l, layer_exports as n, Mutations as o, Mutation as r, Operation as s, layer as t, Operations as u };