@streamsy/core 0.15.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- import { $ as ProducerGap, At as StreamsFault, B as AppendErrorFor, C as OperationResults, Ct as StreamConfig, Dt as DecodeFault, E as StorageCapabilities, Et as StreamRecord, F as ReadNextResult, G as HeadError, H as CreateConflictReason, I as ReadResult, J as InvalidEpochSeq, K as InvalidAppendRequest, L as AppendBaseError, M as CreateResult, Mt as isRetryableFault, N as HeadResult, Nt as isStreamsFault, Ot as EncodeFault, P as ReadMessage, Q as OffsetMismatch, R as AppendConflict, S as OperationResult, St as StoredMessage, T as ProducerPrecondition, Tt as StreamLifecycle, U as CreateError, V as CreateConflict, W as ForkSourceNotFound, X as InvalidReadRequest, Y as InvalidForkRequest, Z as NotSupported, _ as Mutation, _t as MessageWindow, at as StreamBusy, b as Mutations, bt as ProducerState, ct as StreamNotFound, dt as AppendOptions, et as ProtocolError, ft as ProducerOptions, g as StorageShape, gt as ChangeSnapshot, h as Storage, ht as CreateOptions, it as StaleEpoch, j as AppendResult, jt as TransportFault, kt as StorageFault, lt as isProtocolError, m as CommitBoundaryApi, mt as ReadOptions, nt as ReadNextError, ot as StreamClosed, p as CommitBoundary, pt as ReadNextOptions, q as InvalidCreateRequest, rt as RemoveError, st as StreamGone, tt as ReadError, ut as AppendCallOptions, v as MutationApplied, vt as Offset, w as Operations, wt as StreamId, x as Operation, xt as RecordPatch, y as MutationRejected, yt as ProducerId, z as AppendError } from "./projection-marks-BEZv8qDJ.js";
2
- import { A as Batch, B as RemoveFailure, F as Decision, G as streams_d_exports, H as streamsy_d_exports, I as Folded, L as FollowFailure, M as CreateFailure, N as DecideSpec, P as Decided, Q as address_d_exports, R as HeadFailure, U as producer_d_exports, W as durable_state_d_exports, X as compare, Y as ZERO_OFFSET, j as Collected, k as AppendFailure, t as index_d_exports, z as ReadFailure } from "./index-BtVxu6VJ.js";
3
- export { AppendBaseError, type AppendCallOptions, AppendConflict, AppendError, AppendErrorFor, type AppendFailure, type AppendOptions, AppendResult, type Batch, ChangeSnapshot, type Collected, CommitBoundary, type CommitBoundaryApi, CreateConflict, CreateConflictReason, CreateError, type CreateFailure, type CreateOptions, CreateResult, type DecideSpec, type Decided, type Decision, DecodeFault, durable_state_d_exports as DurableState, EncodeFault, type Folded, type FollowFailure, ForkSourceNotFound, HeadError, type HeadFailure, type HeadResult, index_d_exports as Http, InvalidAppendRequest, InvalidCreateRequest, InvalidEpochSeq, InvalidForkRequest, InvalidReadRequest, streams_d_exports as MemoryStorage, MessageWindow, Mutation, MutationApplied, MutationRejected, Mutations, NotSupported, Offset, OffsetMismatch, Operation, OperationResult, OperationResults, Operations, producer_d_exports as Producer, ProducerGap, ProducerId, type ProducerOptions, ProducerPrecondition, ProducerState, ProtocolError, ReadError, type ReadFailure, type ReadMessage, ReadNextError, type ReadNextOptions, type ReadNextResult, type ReadOptions, type ReadResult, RecordPatch, RemoveError, type RemoveFailure, StaleEpoch, Storage, StorageCapabilities, StorageFault, type StorageShape, StoredMessage, address_d_exports as StreamAddress, StreamBusy, StreamClosed, StreamConfig, StreamGone, StreamId, StreamLifecycle, StreamNotFound, StreamRecord, StreamsFault, streamsy_d_exports as Streamsy, TransportFault, ZERO_OFFSET, compare, isProtocolError, isRetryableFault, isStreamsFault };
1
+ import { $ as StreamsFault, A as ReadResult, B as ProducerId, C as StorageOwnerApi, D as HeadResult, E as CreateResult, F as ReadOptions, G as StreamId, H as RecordPatch, I as StartOffset, J as StreamsyOffset, K as StreamLifecycle, L as ChangeSnapshot, M as AppendOptions, N as ProducerOptions, O as ReadMessage, P as ReadNextOptions, Q as StorageFault, R as MessageWindow, S as StorageOwner, T as AppendResult, U as StoredMessage, V as ProducerState, W as StreamConfig, X as EncodeFault, Y as DecodeFault, Z as InvalidStreamParams, a as Mutations, b as durable_state_d_exports, c as OperationResults, et as TransportFault, i as MutationRejected, j as AppendCallOptions, k as ReadNextResult, l as Operations, n as Mutation, nt as isStreamsFault, o as Operation, p as address_d_exports, q as StreamRecord, r as MutationApplied, s as OperationResult, t as StorageShape, tt as isRetryableFault, u as ProducerPrecondition, w as StorageCapabilities, x as OwnerId, z as Offset } from "./storage-xTb82JxJ.js";
2
+ import { A as Batch, At as StreamNotFound, B as ReadFailure, Ct as ReadError, Dt as StreamBusy, Et as StaleEpoch, F as Decision, G as streams_d_exports, I as Folded, L as FollowFailure, M as CreateFailure, Mt as CreateOptions, N as DecideSpec, Ot as StreamClosed, P as Decided, R as HeadFailure, St as ProtocolError, Tt as RemoveError, U as streamsy_d_exports, V as RemoveFailure, W as producer_d_exports, X as compare, Y as ZERO_OFFSET, _t as InvalidForkRequest, at as AppendBaseError, bt as OffsetMismatch, ct as AppendErrorFor, dt as CreateError, ft as ForkSourceNotFound, gt as InvalidEpochSeq, ht as InvalidCreateRequest, j as Collected, jt as isProtocolError, k as AppendFailure, kt as StreamGone, lt as CreateConflict, mt as InvalidAppendRequest, ot as AppendConflict, pt as HeadError, st as AppendError, t as index_d_exports, ut as CreateConflictReason, vt as InvalidReadRequest, wt as ReadNextError, xt as ProducerGap, yt as NotSupported, z as LiveBatch } from "./index-DIx4D2t0.js";
3
+ export { AppendBaseError, type AppendCallOptions, AppendConflict, AppendError, AppendErrorFor, type AppendFailure, type AppendOptions, AppendResult, Batch, ChangeSnapshot, type Collected, CreateConflict, CreateConflictReason, CreateError, type CreateFailure, type CreateOptions, CreateResult, type DecideSpec, type Decided, type Decision, DecodeFault, durable_state_d_exports as DurableState, EncodeFault, type Folded, type FollowFailure, ForkSourceNotFound, HeadError, type HeadFailure, type HeadResult, index_d_exports as Http, InvalidAppendRequest, InvalidCreateRequest, InvalidEpochSeq, InvalidForkRequest, InvalidReadRequest, InvalidStreamParams, type LiveBatch, streams_d_exports as MemoryStorage, MessageWindow, Mutation, MutationApplied, MutationRejected, Mutations, NotSupported, Offset, OffsetMismatch, Operation, OperationResult, OperationResults, Operations, type OwnerId, producer_d_exports as Producer, ProducerGap, ProducerId, type ProducerOptions, ProducerPrecondition, ProducerState, ProtocolError, ReadError, type ReadFailure, type ReadMessage, ReadNextError, type ReadNextOptions, type ReadNextResult, type ReadOptions, type ReadResult, RecordPatch, RemoveError, type RemoveFailure, StaleEpoch, type StartOffset, StorageCapabilities, StorageFault, StorageOwner, type StorageOwnerApi, type StorageShape, StoredMessage, address_d_exports as StreamAddress, StreamBusy, StreamClosed, StreamConfig, StreamGone, StreamId, StreamLifecycle, StreamNotFound, StreamRecord, StreamsFault, streamsy_d_exports as Streamsy, StreamsyOffset, TransportFault, ZERO_OFFSET, compare, isProtocolError, isRetryableFault, isStreamsFault };
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D8jQpDG7.js";
2
- import { $ as ProducerState, A as StreamBusy, C as InvalidEpochSeq, D as OffsetMismatch, E as NotSupported, G as StreamsFault, H as DecodeFault, J as isStreamsFault, K as TransportFault, L as Storage, M as StreamGone, N as StreamNotFound, O as ProducerGap, P as isProtocolError, Q as ProducerId, R as ZERO_OFFSET, S as InvalidCreateRequest, T as InvalidReadRequest, U as EncodeFault, W as StorageFault, X as MessageWindow, Y as ChangeSnapshot, Z as Offset, _ as CreateResult, a as custom, at as StreamRecord, b as ForkSourceNotFound, c as state, d as address_exports, et as RecordPatch, f as isControl, g as AppendResult, h as stateControl, it as StreamLifecycle, j as StreamClosed, k as StaleEpoch, m as stateChange, n as bind, nt as StreamConfig, o as group, p as isUpsert, q as isRetryableFault, r as bytes, rt as StreamId, s as json, t as Wildcard, tt as StoredMessage, v as AppendConflict, w as InvalidForkRequest, x as InvalidAppendRequest, y as CreateConflict, z as compare } from "./streamsy-HKC10a_V.js";
3
- import { p as CommitBoundary } from "./boundary-f1biibJ1.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$1, u as Operations } from "./layer-DjKTdIY5.js";
5
- import { t as layer$2 } from "./layer-J6sV3UXD.js";
6
- import { t as http_exports } from "./http-YoA8cUTN.js";
2
+ import { $ as StreamLifecycle, A as ProducerGap, B as compare, C as InvalidAppendRequest, D as InvalidReadRequest, E as InvalidForkRequest, F as StreamNotFound, G as MessageWindow, H as isValid, I as isProtocolError, J as ProducerState, K as Offset, M as StreamBusy, N as StreamClosed, O as NotSupported, P as StreamGone, Q as StreamId, S as ForkSourceNotFound, T as InvalidEpochSeq, W as ChangeSnapshot, X as StoredMessage, Y as RecordPatch, Z as StreamConfig, _ as isUpsert, a as custom, b as AppendConflict, c as state, et as StreamRecord, f as address_exports, g as isControl, h as durable_state_exports, j as StaleEpoch, k as OffsetMismatch, l as Batch, m as controlCodec, n as bind, o as group, p as changeCodec, q as ProducerId, r as bytes, s as json, t as Wildcard, tt as StreamsyOffset, v as AppendResult, w as InvalidCreateRequest, x as CreateConflict, y as CreateResult, z as ZERO_OFFSET } from "./streamsy-DiAjZWlT.js";
3
+ import { A as DecodeFault, F as TransportFault, I as isRetryableFault, L as isStreamsFault, M as InvalidStreamParams, N as StorageFault, P as StreamsFault, j as EncodeFault, k as StorageOwner } from "./read-message-DP1UpEFl.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$1, u as Operations } from "./layer-DTOhxWkw.js";
5
+ import { t as layer$2 } from "./layer-Dv_LBCgD.js";
6
+ import { t as http_exports } from "./http-aCMEaxro.js";
7
7
  import { Array, Data, Effect, Layer, Option, Predicate, Record, Schema, Stream } from "effect";
8
8
  // src/storage/capabilities.ts
9
9
  const StorageCapabilities = Schema.Struct({
@@ -28,150 +28,6 @@ function layer(group, options = {}) {
28
28
  const protocol = layer$1(options).pipe(Layer.provideMerge(storage));
29
29
  return bind(protocol, group).pipe(Layer.provideMerge(storage));
30
30
  }
31
- // src/toolkit/durable-state.ts
32
- var durable_state_exports = /* @__PURE__ */ __exportAll({
33
- changes: () => changes,
34
- materialize: () => materialize,
35
- materialized: () => materialized,
36
- remove: () => remove,
37
- upsert: () => upsert
38
- });
39
- const operations = Data.taggedEnum();
40
- const isOperation = (entry) => Predicate.isTagged(entry, "Upsert") || Predicate.isTagged(entry, "Delete");
41
- /** Describe an upsert into a collection. The key is read from the value. */
42
- const upsert = (type, value, options = {}) => operations.Upsert({
43
- type,
44
- value,
45
- ...options
46
- });
47
- /** Describe a delete from a collection by key. An `oldValue` is written as `old_value`. */
48
- const remove = (type, key, options = {}) => operations.Delete({
49
- type,
50
- key,
51
- ...options
52
- });
53
- /** Reject keys that Durable State clients cannot address. */
54
- const checkKey = (type, source, raw) => {
55
- if (raw === null || raw === void 0 || raw === "") throw new TypeError(`Invalid state key for type "${type}": ${source} must not be null, undefined, or empty`);
56
- return String(raw);
57
- };
58
- /** Read the key field of a value. `StateKey` limits the field to strings and numbers. */
59
- const readKey = (type, field, value) => checkKey(type, `field "${String(field)}"`, String(value[field] ?? ""));
60
- function changes(address, options, entries) {
61
- const { offset } = options;
62
- return Array.map(entries, (entry, index) => isOperation(entry) ? stampChange(address.collections, entry, offset, index) : stampControl(entry, offset));
63
- }
64
- const stampChange = (collections, entry, offset, index) => {
65
- const collection = Record.has(collections, entry.type) ? collections[entry.type] : void 0;
66
- if (collection === void 0) throw new TypeError(`Unknown state collection "${entry.type}"`);
67
- const override = entry.headers ?? {};
68
- const txid = override.txid ?? (offset === void 0 ? void 0 : `${offset}:${index}`);
69
- const headers = {};
70
- if (offset !== void 0) headers.offset = offset;
71
- if (txid !== void 0) headers.txid = txid;
72
- if (override.timestamp !== void 0) headers.timestamp = override.timestamp;
73
- if (override.from !== void 0) headers.from = override.from;
74
- if (Predicate.isTagged(entry, "Upsert")) {
75
- const key = readKey(entry.type, collection.key, entry.value);
76
- return {
77
- type: entry.type,
78
- key,
79
- value: entry.value,
80
- headers: {
81
- operation: "upsert",
82
- ...headers
83
- }
84
- };
85
- }
86
- const key = checkKey(entry.type, "key", entry.key);
87
- return entry.oldValue === void 0 ? {
88
- type: entry.type,
89
- key,
90
- headers: {
91
- operation: "delete",
92
- ...headers
93
- }
94
- } : {
95
- type: entry.type,
96
- key,
97
- old_value: entry.oldValue,
98
- headers: {
99
- operation: "delete",
100
- ...headers
101
- }
102
- };
103
- };
104
- const stampControl = (entry, offset) => offset === void 0 || entry.headers.offset !== void 0 ? entry : { headers: {
105
- control: entry.headers.control,
106
- offset
107
- } };
108
- /** A row key that is unique across collections, for snapshot bookkeeping. */
109
- const snapshotKey = (type, key) => `${type}\u0000${key}`;
110
- /** Empty materialized state for the collections of `address`. */
111
- function materialized(address) {
112
- const rows = {};
113
- for (const type of Record.keys(address.collections)) rows[type] = /* @__PURE__ */ new Map();
114
- return {
115
- rows,
116
- snapshot: void 0
117
- };
118
- }
119
- /**
120
- * Fold State events into materialized state, with the State protocol rules:
121
- *
122
- * - `upsert` sets the row of its key, and `delete` removes it.
123
- * - `reset` clears every collection.
124
- * - `snapshot-end` removes each row that no change since `snapshot-start` named.
125
- * A snapshot may span several calls.
126
- *
127
- * The input state is not changed. Only the collections that `events` touch are copied.
128
- */
129
- function materialize(state, events) {
130
- const rows = /* @__PURE__ */ new Map();
131
- let cleared = false;
132
- let snapshot = state.snapshot === void 0 ? void 0 : new Set(state.snapshot);
133
- const source = (type) => cleared ? void 0 : Record.has(state.rows, type) ? state.rows[type] : void 0;
134
- const writable = (type) => {
135
- const existing = rows.get(type);
136
- if (existing !== void 0) return existing;
137
- const copy = new Map(source(type));
138
- rows.set(type, copy);
139
- return copy;
140
- };
141
- for (const event of events) {
142
- if (isControl(event)) {
143
- const control = event.headers.control;
144
- if (control === "reset") {
145
- cleared = true;
146
- rows.clear();
147
- snapshot = void 0;
148
- } else if (control === "snapshot-start") snapshot = /* @__PURE__ */ new Set();
149
- else if (snapshot !== void 0) {
150
- const seen = snapshot;
151
- for (const type of Record.keys(state.rows)) {
152
- const table = writable(type);
153
- for (const key of Array.fromIterable(table.keys())) if (!seen.has(snapshotKey(type, key))) table.delete(key);
154
- }
155
- snapshot = void 0;
156
- }
157
- continue;
158
- }
159
- const table = writable(event.type);
160
- if (isUpsert(event)) {
161
- table.set(event.key, event.value);
162
- snapshot?.add(snapshotKey(event.type, event.key));
163
- } else {
164
- table.delete(event.key);
165
- snapshot?.delete(snapshotKey(event.type, event.key));
166
- }
167
- }
168
- const next = {};
169
- for (const type of Record.keys(state.rows)) next[type] = rows.get(type) ?? (cleared ? /* @__PURE__ */ new Map() : state.rows[type]);
170
- return {
171
- rows: next,
172
- snapshot
173
- };
174
- }
175
31
  // src/toolkit/producer.ts
176
32
  var producer_exports = /* @__PURE__ */ __exportAll({ next: () => next });
177
33
  /** Advance only after the caller has acknowledged appended or duplicate. Persist this tuple at the owning edge. */
@@ -179,72 +35,89 @@ const next = (position) => ({
179
35
  ...position,
180
36
  producerSeq: position.producerSeq + 1
181
37
  });
182
- // src/toolkit/wake.ts
38
+ // src/toolkit/frontier.ts
39
+ /** "The stream holding this row reflects `stream` up to `offset`." Offsets of one source are fixed-width strings. `closed` is present when the source is closed. */
40
+ const Frontier = Schema.Struct({
41
+ stream: Schema.String,
42
+ offset: Schema.String,
43
+ closed: Schema.optionalKey(Schema.Literal(true))
44
+ });
45
+ /** Spread into a State declaration's collections under any name. */
46
+ const frontier = {
47
+ schema: Frontier,
48
+ key: "stream"
49
+ };
50
+ /**
51
+ * "A reader sees this write once it reflects `stream` up to `offset`." A server answers one after
52
+ * an append. It has the shape of a `Frontier` row, as a separate schema, so a collection declared
53
+ * with `Token` is not taken for a frontier collection.
54
+ */
55
+ const Token = Schema.Struct({
56
+ stream: Schema.String,
57
+ offset: Schema.String
58
+ });
59
+ /** The token of an append to `address`: its stream id and the tail after the write. */
60
+ const token = (address, appended) => Token.make({
61
+ stream: address.id,
62
+ offset: appended.offset
63
+ });
64
+ // src/toolkit/frontier-stream.ts
183
65
  /**
184
- * Wake streams: one Durable State stream that indexes the writes of a family of
66
+ * Frontier streams: one Durable State stream that indexes the writes of a family of
185
67
  * source streams.
186
68
  *
187
- * A wake declaration is a State stream with one `stream` collection. Each row
69
+ * A frontier stream declaration is a State stream with one `stream` collection. Each row
188
70
  * is the latest known state of one source stream. A projection writes the rows:
189
- * `Projection.wake` in `@streamsy/projection` reads one source stream and
71
+ * `Projection.frontier` in `@streamsy/projection` reads one source stream and
190
72
  * appends its row with a producer tuple, on the same owner or another one. A
191
- * wake stream on another owner must exist first: its owner creates it at start.
73
+ * frontier stream on another owner must exist first: its owner creates it at start.
192
74
  * The typed service is the normal State service.
193
75
  */
194
- /** One row of a wake stream: the latest known state of one source stream. */
195
- const WakeRow = Schema.Struct({
196
- /** Canonical id of the source stream. It is also the State key. */
197
- stream: StreamId,
198
- /**
199
- * A position in the source that the row's writer vouches for. The stream
200
- * holding the row says what is vouched: written in a source wake stream,
201
- * or accepted in a projection's accepted stream.
202
- */
203
- offset: Offset,
204
- /** Present when the source stream is closed. */
205
- closed: Schema.optionalKey(Schema.Literal(true))
206
- });
207
- /** The one collection of every wake stream. Its State `type` is `stream`. */
208
- const wakeCollections = { stream: {
209
- schema: WakeRow,
210
- key: "stream"
211
- } };
212
76
  /**
213
- * The codec of one wake stream message: a `stream` change or a State control.
77
+ * The one collection of every frontier stream. Its State `type` is `stream`, and each row is a
78
+ * `Frontier`: the source stream id, a position in the source that the row's writer vouches
79
+ * for, and `closed` when the source is closed. The stream holding the row says what is
80
+ * vouched: written in a source frontier stream, or accepted in a projection's frontier stream.
81
+ */
82
+ const frontierStreamCollections = { stream: frontier };
83
+ /**
84
+ * The codec of one frontier stream message: a `stream` change or a State control.
214
85
  * A client that decodes raw JSON pages uses it in place of a typed service.
215
86
  */
216
- const WakeMessage = Schema.Union([stateChange({
87
+ const FrontierMessage = Schema.Union([changeCodec({
217
88
  type: "stream",
218
- schema: WakeRow
219
- }), stateControl]);
89
+ schema: Frontier
90
+ }), controlCodec]);
220
91
  /**
221
- * Declare a wake stream: a State stream of `WakeRow`s at a template.
92
+ * Declare a frontier stream: a State stream of `Frontier` rows at a template.
222
93
  *
223
94
  * ```ts
224
- * class UserWake extends Streamsy.wake<UserWake>()("App/UserWake", "users/:user/wake", {
95
+ * class UserFrontier extends Streamsy.frontierStream<UserFrontier>()("App/UserFrontier", "users/:user/frontier", {
225
96
  * params: { user: UserKey },
226
97
  * }) {}
227
98
  * ```
228
99
  *
229
- * The declaration names no sources. A `Projection.wake` binding links one
230
- * source stream to one wake stream, with params of its own.
100
+ * A template without `:name` declares a singleton frontier stream and may omit `params`,
101
+ * and so the whole options argument: `Streamsy.frontierStream<Wake>()("App/Wake", "wake")`.
102
+ * The declaration names no sources. A `Projection.frontier` binding links one
103
+ * source stream to one frontier stream, with params of its own.
231
104
  */
232
- const wake = () => (name, template, options) => state()(name, template, {
233
- params: options.params,
234
- collections: wakeCollections
105
+ const frontierStream = () => (name, template, ...[options]) => state()(name, template, {
106
+ ...options,
107
+ collections: frontierStreamCollections
235
108
  });
236
- /** Constructors and matchers for `WakeItem`. */
237
- const WakeItem = Data.taggedEnum();
109
+ /** Constructors and matchers for `FrontierItem`. */
110
+ const FrontierItem = Data.taggedEnum();
238
111
  /**
239
- * The actions for one batch of wake messages. The function is pure: it reads
112
+ * The actions for one batch of frontier stream messages. The function is pure: it reads
240
113
  * no stream and changes none of its inputs. Rows for one stream collapse to one
241
114
  * item; a delete then an upsert of one stream gives `Removed`, then `Dirty` from
242
115
  * `-1`. Pass the returned `snapshot` to the call for the next batch.
243
116
  *
244
- * `followWake` uses it over a typed service. A client with its own HTTP reader
245
- * decodes each page with `WakeMessage` and calls it directly.
117
+ * `followFrontier` uses it over a typed service. A client with its own HTTP reader
118
+ * decodes each page with `FrontierMessage` and calls it directly.
246
119
  */
247
- function wakeActions(events, options) {
120
+ function frontierActions(events, options) {
248
121
  const { cursors } = options;
249
122
  const items = [];
250
123
  let pending = /* @__PURE__ */ new Map();
@@ -252,8 +125,8 @@ function wakeActions(events, options) {
252
125
  let open = options.snapshot === void 0 ? void 0 : new Set(options.snapshot);
253
126
  const flush = () => {
254
127
  for (const [stream, entry] of pending) {
255
- if (entry.removed) items.push(WakeItem.Removed({ stream }));
256
- if (Option.isSome(entry.dirty)) items.push(WakeItem.Dirty({
128
+ if (entry.removed) items.push(FrontierItem.Removed({ stream }));
129
+ if (Option.isSome(entry.dirty)) items.push(FrontierItem.Dirty({
257
130
  stream,
258
131
  ...entry.dirty.value
259
132
  }));
@@ -266,13 +139,13 @@ function wakeActions(events, options) {
266
139
  if (control === "reset") {
267
140
  pending = /* @__PURE__ */ new Map();
268
141
  items.length = 0;
269
- items.push(WakeItem.Reset());
142
+ items.push(FrontierItem.Reset());
270
143
  reset = true;
271
144
  open = void 0;
272
145
  } else if (control === "snapshot-start") open = /* @__PURE__ */ new Set();
273
146
  else if (open !== void 0) {
274
147
  flush();
275
- items.push(WakeItem.Snapshot({ streams: open }));
148
+ items.push(FrontierItem.Snapshot({ streams: open }));
276
149
  open = void 0;
277
150
  }
278
151
  continue;
@@ -291,12 +164,13 @@ function wakeActions(events, options) {
291
164
  const row = event.value;
292
165
  const removed = prior?.removed ?? false;
293
166
  const base = removed || reset ? "-1" : cursors.get(stream) ?? "-1";
294
- const dirty = compare(row.offset, base) > 0 || row.closed === true;
167
+ const offset = isValid(row.offset) ? row.offset : void 0;
168
+ const dirty = offset !== void 0 && (compare(offset, base) > 0 || row.closed === true);
295
169
  pending.set(stream, {
296
170
  removed,
297
171
  dirty: dirty ? Option.some({
298
172
  from: base,
299
- offset: row.offset,
173
+ offset,
300
174
  closed: row.closed === true
301
175
  }) : Option.none()
302
176
  });
@@ -309,60 +183,96 @@ function wakeActions(events, options) {
309
183
  };
310
184
  }
311
185
  /**
312
- * Follow one wake stream and give the actions for each batch: which source
186
+ * Follow one frontier stream and give the actions for each batch: which source
313
187
  * streams to read, from which cursor, and which to drop. The helper reads no
314
- * source stream. Save each source cursor first and the wake cursor (`offset`)
188
+ * source stream. Save each source cursor first and the frontier cursor (`offset`)
315
189
  * last; a stop between the two reads the same rows again, and the offset check
316
190
  * skips the streams that were already read.
317
191
  */
318
- function followWake(declaration, params, options) {
192
+ function followFrontier(stream, options) {
319
193
  const { from, cursors, ...follow } = options;
320
- return Stream.unwrap(Effect.map(Effect.service(declaration), (service) => service.follow(params, {
194
+ return stream.follow({
321
195
  ...follow,
322
196
  offset: from
323
197
  }).pipe(Stream.mapAccum(() => void 0, (snapshot, batch) => {
324
- const next = wakeActions(batch.items, {
198
+ const next = frontierActions(batch.items, {
325
199
  cursors,
326
200
  snapshot
327
201
  });
328
202
  const out = {
329
203
  items: next.items,
330
- offset: batch.nextOffset,
204
+ offset: batch.offset,
331
205
  upToDate: batch.upToDate
332
206
  };
333
207
  return [next.snapshot, [out]];
334
- }))));
208
+ }));
335
209
  }
336
210
  /**
337
- * Wait until a wake row for `stream` reaches `offset`. Works with local and
338
- * remote services. Callers choose their own timeout. Removed source ids must
339
- * not be reused; a new generation needs a new wake stream or a State reset.
340
- * Without `options.from`, each call reads the wake history from the start.
211
+ * The collections of a State address. The handle types its address as a plain stream address,
212
+ * so the collections are read from the value. A stream that is not State has none.
341
213
  */
342
- const awaitWake = (declaration, params, target, options = {}) => followWake(declaration, params, {
343
- ...options,
344
- cursors: /* @__PURE__ */ new Map()
345
- }).pipe(Stream.mapAccum(() => Option.none(), (observed, batch) => {
346
- let current = observed;
347
- for (const item of batch.items) if (WakeItem.$is("Reset")(item) || WakeItem.$is("Removed")(item) && item.stream === target.stream || WakeItem.$is("Snapshot")(item) && !item.streams.has(target.stream)) current = Option.none();
348
- else if (WakeItem.$is("Dirty")(item) && item.stream === target.stream) current = Option.some(item.offset);
349
- return [current, [batch.upToDate && Option.isSome(current) && compare(current.value, target.offset) >= 0]];
350
- }), Stream.filter((reached) => reached), Stream.runHead, Effect.flatMap((found) => Option.isSome(found) ? Effect.void : Effect.never));
214
+ const collectionsOf = (address) => {
215
+ if (!Predicate.hasProperty(address, "collections") || !Predicate.isObject(address.collections)) return {};
216
+ return address.collections;
217
+ };
218
+ /** The name of the collection declared with `Streamsy.frontier`, found by schema identity. */
219
+ const frontierCollection = (collections) => {
220
+ const names = Array.filter(Record.keys(collections), (name) => collections[name]?.schema === Frontier && collections[name]?.key === "stream");
221
+ const [name] = names;
222
+ if (name === void 0 || names.length > 1) throw new RangeError("awaitFrontier requires a State class with one Streamsy.frontier collection");
223
+ return name;
224
+ };
225
+ /**
226
+ * Wait until the frontier row for `stream` reaches `offset`. `stream` is the handle of a
227
+ * frontier stream or of any State stream with one `Streamsy.frontier` collection; the
228
+ * other collections are read and skipped. Another stream dies with a `RangeError`. Works
229
+ * with local and remote services. Callers choose their own timeout. Removed source ids
230
+ * must not be reused; a new generation needs a new stream or a State reset. Without
231
+ * `options.from`, each call reads the history from the start.
232
+ */
233
+ const awaitFrontier = (stream, target, options = {}) => {
234
+ const source = StreamId.make(target.stream);
235
+ const { from, ...follow } = options;
236
+ return Stream.unwrap(Effect.map(stream.address, (address) => {
237
+ const type = frontierCollection(collectionsOf(address));
238
+ return stream.follow({
239
+ ...follow,
240
+ offset: from
241
+ }).pipe(Stream.mapAccum(() => void 0, (snapshot, batch) => {
242
+ const next = frontierActions(Array.filter(batch.items, (event) => isControl(event) || event.type === type), {
243
+ cursors: /* @__PURE__ */ new Map(),
244
+ snapshot
245
+ });
246
+ return [next.snapshot, [{
247
+ items: next.items,
248
+ upToDate: batch.upToDate
249
+ }]];
250
+ }));
251
+ })).pipe(Stream.mapAccum(() => Option.none(), (observed, batch) => {
252
+ let current = observed;
253
+ for (const item of batch.items) if (FrontierItem.$is("Reset")(item) || FrontierItem.$is("Removed")(item) && item.stream === source || FrontierItem.$is("Snapshot")(item) && !item.streams.has(source)) current = Option.none();
254
+ else if (FrontierItem.$is("Dirty")(item) && item.stream === source) current = Option.some(item.offset);
255
+ return [current, [batch.upToDate && Option.isSome(current) && compare(current.value, target.offset) >= 0]];
256
+ }), Stream.filter((reached) => reached), Stream.runHead, Effect.flatMap((found) => Option.isSome(found) ? Effect.void : Effect.never));
257
+ };
351
258
  // src/streamsy.ts
352
259
  var streamsy_exports = /* @__PURE__ */ __exportAll({
353
- WakeItem: () => WakeItem,
354
- WakeMessage: () => WakeMessage,
355
- WakeRow: () => WakeRow,
260
+ Frontier: () => Frontier,
261
+ FrontierItem: () => FrontierItem,
262
+ FrontierMessage: () => FrontierMessage,
263
+ Token: () => Token,
356
264
  Wildcard: () => Wildcard,
357
- awaitWake: () => awaitWake,
265
+ awaitFrontier: () => awaitFrontier,
358
266
  bytes: () => bytes,
359
267
  custom: () => custom,
360
- followWake: () => followWake,
268
+ followFrontier: () => followFrontier,
269
+ frontier: () => frontier,
270
+ frontierActions: () => frontierActions,
271
+ frontierStream: () => frontierStream,
272
+ frontierStreamCollections: () => frontierStreamCollections,
361
273
  group: () => group,
362
274
  json: () => json,
363
275
  state: () => state,
364
- wake: () => wake,
365
- wakeActions: () => wakeActions,
366
- wakeCollections: () => wakeCollections
276
+ token: () => token
367
277
  });
368
- export { AppendConflict, AppendResult, ChangeSnapshot, CommitBoundary, CreateConflict, CreateResult, DecodeFault, durable_state_exports as DurableState, EncodeFault, ForkSourceNotFound, http_exports as Http, InvalidAppendRequest, InvalidCreateRequest, 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 };
278
+ export { AppendConflict, AppendResult, Batch, ChangeSnapshot, CreateConflict, CreateResult, DecodeFault, durable_state_exports as DurableState, EncodeFault, ForkSourceNotFound, http_exports as Http, InvalidAppendRequest, InvalidCreateRequest, InvalidEpochSeq, InvalidForkRequest, InvalidReadRequest, InvalidStreamParams, 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, StorageCapabilities, StorageFault, StorageOwner, StoredMessage, address_exports as StreamAddress, StreamBusy, StreamClosed, StreamConfig, StreamGone, StreamId, StreamLifecycle, StreamNotFound, StreamRecord, StreamsFault, streamsy_exports as Streamsy, StreamsyOffset, TransportFault, ZERO_OFFSET, compare, isProtocolError, isRetryableFault, isStreamsFault };