@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.
@@ -0,0 +1,836 @@
1
+ import { $ as StreamsFault, A as ReadResult, D as HeadResult, E as CreateResult, F as ReadOptions$1, G as StreamId, I as StartOffset, M as AppendOptions, N as ProducerOptions, P as ReadNextOptions, Q as StorageFault, S as StorageOwner, T as AppendResult, X as EncodeFault, Y as DecodeFault, Z as InvalidStreamParams, _ as CollectionsEncodingServices, d as StateAddress, et as TransportFault, f as StreamAddress, g as CollectionsEncodedEvent, h as CollectionsDecodingServices, j as AppendCallOptions, k as ReadNextResult, m as Collections, v as CollectionsEvent, x as OwnerId, y as ValidCollections, z as Offset } from "./storage-xTb82JxJ.js";
2
+ import { Array, Context, Data, Duration, Effect, Function, Layer, Option, Schedule, Schema, Stream } from "effect";
3
+ import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http";
4
+ /** Private pure-policy input, promoted to protocol options in Batch 3. */
5
+ interface CreateOptions {
6
+ readonly contentType?: string;
7
+ readonly ttlSeconds?: number;
8
+ readonly expiresAt?: string;
9
+ readonly closed?: boolean;
10
+ readonly forkedFrom?: string;
11
+ readonly forkOffset?: string;
12
+ readonly forkSubOffset?: number;
13
+ readonly initialData?: Uint8Array;
14
+ }
15
+ declare const StreamNotFound_base: Schema.Class<StreamNotFound, Schema.TaggedStruct<"StreamNotFound", {
16
+ readonly id: Schema.brand<Schema.String, "StreamId">;
17
+ }>, import("effect/Cause").YieldableError>;
18
+ /** Protocol rejections. Optional create reasons reflect the public HTTP wire's loss of detail. */
19
+ declare class StreamNotFound extends StreamNotFound_base {
20
+ get message(): string;
21
+ }
22
+ declare const StreamGone_base: Schema.Class<StreamGone, Schema.TaggedStruct<"StreamGone", {
23
+ readonly id: Schema.brand<Schema.String, "StreamId">;
24
+ }>, import("effect/Cause").YieldableError>;
25
+ declare class StreamGone extends StreamGone_base {
26
+ get message(): string;
27
+ }
28
+ declare const StreamClosed_base: Schema.Class<StreamClosed, Schema.TaggedStruct<"StreamClosed", {
29
+ readonly id: Schema.brand<Schema.String, "StreamId">;
30
+ readonly offset: Schema.brand<Schema.String, "Offset">;
31
+ }>, import("effect/Cause").YieldableError>;
32
+ declare class StreamClosed extends StreamClosed_base {
33
+ get message(): string;
34
+ }
35
+ declare const OffsetMismatch_base: Schema.Class<OffsetMismatch, Schema.TaggedStruct<"OffsetMismatch", {
36
+ readonly id: Schema.brand<Schema.String, "StreamId">;
37
+ readonly expected: Schema.brand<Schema.String, "Offset">;
38
+ readonly actual: Schema.brand<Schema.String, "Offset">;
39
+ }>, import("effect/Cause").YieldableError>;
40
+ declare class OffsetMismatch extends OffsetMismatch_base {
41
+ get message(): string;
42
+ }
43
+ declare const AppendConflict_base: Schema.Class<AppendConflict, Schema.TaggedStruct<"AppendConflict", {
44
+ readonly id: Schema.brand<Schema.String, "StreamId">;
45
+ /**
46
+ * `sequence` when the `Stream-Seq` does not sort after the last one, `content-type` when the
47
+ * content type differs. Absent when the cause is unknown, for example from a server that does
48
+ * not send `stream-conflict-reason`.
49
+ */
50
+ readonly reason: Schema.optionalKey<Schema.Literals<readonly ["sequence", "content-type"]>>;
51
+ readonly message: Schema.String;
52
+ }>, import("effect/Cause").YieldableError>;
53
+ declare class AppendConflict extends AppendConflict_base {}
54
+ declare const StreamBusy_base: Schema.Class<StreamBusy, Schema.TaggedStruct<"StreamBusy", {
55
+ readonly id: Schema.brand<Schema.String, "StreamId">;
56
+ }>, import("effect/Cause").YieldableError>;
57
+ declare class StreamBusy extends StreamBusy_base {
58
+ get message(): string;
59
+ }
60
+ declare const StaleEpoch_base: Schema.Class<StaleEpoch, Schema.TaggedStruct<"StaleEpoch", {
61
+ readonly id: Schema.brand<Schema.String, "StreamId">;
62
+ readonly currentEpoch: Schema.Finite;
63
+ }>, import("effect/Cause").YieldableError>;
64
+ declare class StaleEpoch extends StaleEpoch_base {
65
+ get message(): string;
66
+ }
67
+ declare const ProducerGap_base: Schema.Class<ProducerGap, Schema.TaggedStruct<"ProducerGap", {
68
+ readonly id: Schema.brand<Schema.String, "StreamId">;
69
+ readonly expectedSeq: Schema.Finite;
70
+ readonly receivedSeq: Schema.Finite;
71
+ }>, import("effect/Cause").YieldableError>;
72
+ declare class ProducerGap extends ProducerGap_base {
73
+ get message(): string;
74
+ }
75
+ declare const InvalidEpochSeq_base: Schema.Class<InvalidEpochSeq, Schema.TaggedStruct<"InvalidEpochSeq", {
76
+ readonly id: Schema.brand<Schema.String, "StreamId">;
77
+ }>, import("effect/Cause").YieldableError>;
78
+ declare class InvalidEpochSeq extends InvalidEpochSeq_base {
79
+ get message(): string;
80
+ }
81
+ declare const InvalidAppendRequest_base: Schema.Class<InvalidAppendRequest, Schema.TaggedStruct<"InvalidAppendRequest", {
82
+ readonly id: Schema.brand<Schema.String, "StreamId">;
83
+ readonly message: Schema.String;
84
+ }>, import("effect/Cause").YieldableError>;
85
+ declare class InvalidAppendRequest extends InvalidAppendRequest_base {}
86
+ declare const InvalidCreateRequest_base: Schema.Class<InvalidCreateRequest, Schema.TaggedStruct<"InvalidCreateRequest", {
87
+ readonly id: Schema.brand<Schema.String, "StreamId">;
88
+ readonly message: Schema.String;
89
+ }>, import("effect/Cause").YieldableError>;
90
+ declare class InvalidCreateRequest extends InvalidCreateRequest_base {}
91
+ declare const CreateConflict_base: Schema.Class<CreateConflict, Schema.TaggedStruct<"CreateConflict", {
92
+ readonly id: Schema.brand<Schema.String, "StreamId">;
93
+ readonly reason: Schema.optionalKey<Schema.Literals<readonly ["config-mismatch", "soft-deleted", "fork-content-type", "fork-source-soft-deleted"]>>;
94
+ readonly message: Schema.String;
95
+ }>, import("effect/Cause").YieldableError>;
96
+ declare class CreateConflict extends CreateConflict_base {}
97
+ declare const ForkSourceNotFound_base: Schema.Class<ForkSourceNotFound, Schema.TaggedStruct<"ForkSourceNotFound", {
98
+ readonly id: Schema.brand<Schema.String, "StreamId">;
99
+ readonly source: Schema.brand<Schema.String, "StreamId">;
100
+ }>, import("effect/Cause").YieldableError>;
101
+ declare class ForkSourceNotFound extends ForkSourceNotFound_base {
102
+ get message(): string;
103
+ }
104
+ declare const InvalidForkRequest_base: Schema.Class<InvalidForkRequest, Schema.TaggedStruct<"InvalidForkRequest", {
105
+ readonly id: Schema.brand<Schema.String, "StreamId">;
106
+ readonly message: Schema.String;
107
+ }>, import("effect/Cause").YieldableError>;
108
+ declare class InvalidForkRequest extends InvalidForkRequest_base {}
109
+ declare const NotSupported_base: Schema.Class<NotSupported, Schema.TaggedStruct<"NotSupported", {
110
+ readonly id: Schema.brand<Schema.String, "StreamId">;
111
+ readonly feature: Schema.String;
112
+ }>, import("effect/Cause").YieldableError>;
113
+ declare class NotSupported extends NotSupported_base {
114
+ get message(): string;
115
+ }
116
+ type CreateConflictReason = NonNullable<CreateConflict["reason"]>;
117
+ type HeadError = StreamNotFound | StreamGone;
118
+ declare const InvalidReadRequest_base: Schema.Class<InvalidReadRequest, Schema.TaggedStruct<"InvalidReadRequest", {
119
+ readonly id: Schema.brand<Schema.String, "StreamId">;
120
+ readonly message: Schema.String;
121
+ }>, import("effect/Cause").YieldableError>;
122
+ declare class InvalidReadRequest extends InvalidReadRequest_base {}
123
+ type ReadError = StreamNotFound | StreamGone | InvalidReadRequest;
124
+ type ReadNextError = ReadError | NotSupported;
125
+ type CreateError = CreateConflict | InvalidCreateRequest | ForkSourceNotFound | InvalidForkRequest | NotSupported;
126
+ /**
127
+ * Append rejections that any call can get, whatever its options. The memory and
128
+ * storage hosts never answer `NotSupported`; the remote client does when the server
129
+ * or its own capabilities refuse a feature.
130
+ */
131
+ type AppendBaseError = StreamNotFound | StreamGone | StreamClosed | StreamBusy | AppendConflict | NotSupported;
132
+ type AppendError = AppendBaseError | InvalidAppendRequest | OffsetMismatch | StaleEpoch | ProducerGap | InvalidEpochSeq;
133
+ /**
134
+ * The append rejections that call options `O` make possible. `OffsetMismatch`
135
+ * needs `expectedOffset`, and the producer rejections need `producer`. An option
136
+ * that may be set counts as set.
137
+ */
138
+ type AppendErrorFor<O> = AppendBaseError | (true extends MaySet<O, "expectedOffset"> ? OffsetMismatch : never) | (true extends MaySet<O, "producer"> ? StaleEpoch | ProducerGap : never);
139
+ /** Whether options `O` may hold a value for `K`. A union holds it if any member may. */
140
+ type MaySet<O, K extends PropertyKey> = O extends unknown ? K extends keyof O ? [Exclude<O[K], undefined>] extends [never] ? false : true : false : never;
141
+ type RemoveError = StreamNotFound | StreamGone | StreamBusy;
142
+ type ProtocolError = HeadError | ReadNextError | CreateError | AppendError | RemoveError;
143
+ /** The HTTP edge answers every protocol rejection through one mapper, so it needs one guard. */
144
+ declare const isProtocolError: (error: {
145
+ readonly _tag: string;
146
+ }) => error is ProtocolError;
147
+ interface Reader<E = StorageFault> {
148
+ readonly head: (id: StreamId) => Effect.Effect<HeadResult, HeadError | E>;
149
+ readonly read: (id: StreamId, options?: ReadOptions$1) => Effect.Effect<ReadResult, ReadError | E>;
150
+ readonly readNext: (id: StreamId, options: ReadNextOptions) => Effect.Effect<ReadNextResult, ReadNextError | E>;
151
+ }
152
+ interface Writer<E = StorageFault> {
153
+ readonly create: (id: StreamId, options?: CreateOptions) => Effect.Effect<CreateResult, CreateError | E>;
154
+ readonly fork: (id: StreamId, source: StreamId, options?: Omit<CreateOptions, "forkedFrom">) => Effect.Effect<CreateResult, CreateError | E>;
155
+ readonly append: (id: StreamId, options: AppendOptions) => Effect.Effect<AppendResult, AppendError | E>;
156
+ readonly remove: (id: StreamId) => Effect.Effect<void, RemoveError | E>;
157
+ }
158
+ declare const StreamsReader_base: Context.ServiceClass<StreamsReader, "@streamsy/core/StreamsReader", Reader<StorageFault | TransportFault>>;
159
+ declare class StreamsReader extends StreamsReader_base {}
160
+ declare const StreamsWriter_base: Context.ServiceClass<StreamsWriter, "@streamsy/core/StreamsWriter", Writer<StorageFault | TransportFault>>;
161
+ declare class StreamsWriter extends StreamsWriter_base {}
162
+ interface HttpOptions {
163
+ readonly pathPrefix?: string;
164
+ /** Lifetime of an SSE response. Default 60 seconds. */
165
+ readonly sseDeadlineMs?: number;
166
+ readonly maxMessageSize?: number;
167
+ readonly cacheVisibility?: "private" | "public";
168
+ }
169
+ /**
170
+ * The public HTTP program. It is the whole application an Effect host serves.
171
+ *
172
+ * Its success type is `HttpServerResponse` alone, its error channel is closed,
173
+ * and it requires exactly `HttpServerRequest | StreamsReader | StreamsWriter`.
174
+ * Those three facts are what let a host type it as an Alchemy `HttpEffect` and
175
+ * what let one composition serve several backends.
176
+ */
177
+ declare function app(options?: HttpOptions): Effect.Effect<HttpServerResponse.HttpServerResponse, never, HttpServerRequest.HttpServerRequest | StreamsReader | StreamsWriter>;
178
+ /** Prefix helpers shared by protocol and host routers. */
179
+ declare const streamPath: (pathPrefix?: string) => {
180
+ requiredPathPattern: () => string;
181
+ strip: (pathname: string) => string;
182
+ canonicalizeForkSource: (source: string) => string;
183
+ };
184
+ declare namespace route_d_exports {
185
+ export { BytesOptions, ExactTemplateParams, IsSingleton, LiteralTemplate, Matcher, ParamCodecs, Params, ParamsOption, PathSchema, StateRoute, StreamRoute, bytes$1 as bytes, custom$1 as custom, json$1 as json, state$1 as state };
186
+ }
187
+ /**
188
+ * Inert id stream. Constructing a route acquires no service and no resource.
189
+ *
190
+ * A route owns one id grammar and the address constructor for its addresses. A stream
191
+ * binds the route to a storage graph, and `Placement.byRoute` picks the Durable
192
+ * Object that owns it.
193
+ */
194
+ interface StreamRoute<RouteParams, A, RD = never, RE = never, Template extends string = string> {
195
+ readonly _tag: "StreamRoute";
196
+ /** Relative template, for example `journal/:user`. Empty for a custom route. */
197
+ readonly template: Template;
198
+ readonly paramSchema?: PathSchema<RouteParams>;
199
+ /** The router-facing contract. True when this route owns the id. */
200
+ readonly match: (id: string) => boolean;
201
+ /** The primitive. `None` when the id does not match or a parameter fails to decode. */
202
+ readonly parse: (id: string) => Option.Option<RouteParams>;
203
+ /**
204
+ * Build the address. `parse(address(params).id)` must be `Some(params)`. Throws a `RangeError`
205
+ * when a param value cannot form an id; its `cause` is an `InvalidStreamParams`.
206
+ */
207
+ readonly address: (params: RouteParams) => StreamAddress<A, RD, RE>;
208
+ }
209
+ /** The stream codecs exposed to HTTP path decoding. */
210
+ type PathSchema<P> = Schema.Codec<P, Readonly<Record<string, string | undefined>>>;
211
+ type WithPathSchema<P> = {
212
+ readonly paramSchema: PathSchema<P>;
213
+ };
214
+ /** The codec record a State route was declared with, one codec per template parameter. */
215
+ type WithParamCodecs<Codecs extends ParamCodecs> = {
216
+ readonly paramCodecs: Codecs;
217
+ };
218
+ /** A route whose address refs retain their declared State collections. */
219
+ type StateRoute<P, C extends Collections, Template extends string = string> = Omit<StreamRoute<P, CollectionsEvent<C>, CollectionsDecodingServices<C>, CollectionsEncodingServices<C>, Template>, "address"> & {
220
+ readonly collections: C;
221
+ readonly address: (params: P) => StateAddress<C>;
222
+ };
223
+ /** The route predicate used by stream validation and HTTP dispatch. */
224
+ interface Matcher {
225
+ readonly match: (id: string) => boolean;
226
+ }
227
+ /** One codec per template parameter. Decoding runs from a string with no services. */
228
+ type ParamCodecs = Readonly<Record<string, Schema.Codec<unknown, string>>>;
229
+ type Params<Codecs extends ParamCodecs> = { readonly [Name in keyof Codecs]: Codecs[Name]["Type"]; };
230
+ type TemplateNames<Template extends string> = Template extends `${string}:${infer Name}/${infer Rest}` ? Name | TemplateNames<Rest> : Template extends `${string}:${infer Name}` ? Name : never;
231
+ /** The compile error for a template parameter without a codec: the message names it. */
232
+ type MissingCodecs<Names extends PropertyKey> = { readonly [Name in Names]: "Add a codec for this template parameter to `params`"; };
233
+ /** The compile error for a codec that names no template parameter: the message names it. */
234
+ type ExtraCodecs<Names extends PropertyKey> = { readonly [Name in Names]: "This codec names no `:name` in the template"; };
235
+ /**
236
+ * The compile error for a template whose type is the widened `string`. The parameter
237
+ * check and the choice between `singleton` and `at` both read the template type, so a
238
+ * template must be a string literal. A template literal with a `${number}` or `${string}`
239
+ * hole is accepted: the names in its literal parts are checked at compile time, and a
240
+ * hole whose value adds a `:name` throws a `RangeError` when the route is built.
241
+ */
242
+ type LiteralTemplate<Template extends string> = string extends Template ? "The template must be a string literal: write it inline, or declare it `as const`" : unknown;
243
+ /**
244
+ * Every `:name` must have a codec, and every codec must appear in the template. A mismatch
245
+ * resolves to a record whose keys are the wrong names and whose values say what to fix.
246
+ */
247
+ type ExactTemplateParams<Template extends string, Codecs extends ParamCodecs> = string extends Template ? unknown : [Exclude<TemplateNames<Template>, keyof Codecs>] extends [never] ? [Exclude<keyof Codecs, TemplateNames<Template>>] extends [never] ? unknown : ExtraCodecs<Exclude<keyof Codecs, TemplateNames<Template>>> : MissingCodecs<Exclude<TemplateNames<Template>, keyof Codecs>>;
248
+ /**
249
+ * True when the template is known and names no parameter: a singleton stream. A custom
250
+ * route is never a singleton. The template constructors reject a widened `string`
251
+ * template, so the `false` branch for `string` only covers a cast or a custom route.
252
+ */
253
+ type IsSingleton<Template extends string> = string extends Template ? false : [TemplateNames<Template>] extends [never] ? true : false;
254
+ /**
255
+ * The `params` option of a template route. It is optional for a singleton template and
256
+ * required when the template names a parameter. `params: {}` stays legal on a singleton.
257
+ */
258
+ type ParamsOption<Template extends string, Codecs extends ParamCodecs> = IsSingleton<Template> extends true ? {
259
+ readonly params?: Codecs & ExactTemplateParams<Template, Codecs>;
260
+ } : {
261
+ readonly params: Codecs & ExactTemplateParams<Template, Codecs>;
262
+ };
263
+ /** The options of `bytes`. A singleton template needs no options, so the argument is optional. */
264
+ type BytesOptions<Template extends string, Codecs extends ParamCodecs> = IsSingleton<Template> extends true ? [options?: ParamsOption<Template, Codecs> & {
265
+ readonly contentType?: string;
266
+ }] : [options: ParamsOption<Template, Codecs> & {
267
+ readonly contentType?: string;
268
+ }];
269
+ declare function json$1<const Template extends string, Codecs extends ParamCodecs = {}, A = never, I = never, RD = never, RE = never>(template: Template & LiteralTemplate<Template>, options: ParamsOption<Template, Codecs> & {
270
+ readonly schema: Schema.Codec<A, I, RD, RE>;
271
+ }): StreamRoute<Params<Codecs>, A, RD, RE, Template> & WithPathSchema<Params<Codecs>>;
272
+ declare function state$1<const Template extends string, Codecs extends ParamCodecs = {}, const C extends Collections = {}>(template: Template & LiteralTemplate<Template>, options: ParamsOption<Template, Codecs> & {
273
+ readonly collections: C & ValidCollections<C>;
274
+ readonly strict?: boolean;
275
+ }): StateRoute<Params<Codecs>, C, Template> & WithPathSchema<Params<Codecs>> & WithParamCodecs<Codecs>;
276
+ declare function bytes$1<const Template extends string, Codecs extends ParamCodecs = {}>(template: Template & LiteralTemplate<Template>, ...[options]: BytesOptions<Template, Codecs>): StreamRoute<Params<Codecs>, Uint8Array, never, never, Template> & WithPathSchema<Params<Codecs>>;
277
+ /** Escape hatch for a grammar a template cannot express, such as a regex stream. */
278
+ declare function custom$1<RouteParams, A, RD, RE>(options: {
279
+ readonly parse: (id: string) => Option.Option<RouteParams>;
280
+ readonly address: (params: RouteParams) => StreamAddress<A, RD, RE>;
281
+ }): StreamRoute<RouteParams, A, RD, RE>;
282
+ declare const ZERO_OFFSET: string & import("effect/Brand").Brand<"Offset"> & import("effect/Brand").Brand<"StreamsyOffset">;
283
+ /** Lexicographic order. The Durable Streams protocol guarantees it for offsets of one stream. */
284
+ declare const compare: (a: string, b: string) => number;
285
+ /** One host-triggered sweep; the host owns scheduling and cancellation. */
286
+ declare const expireDue: () => Effect.Effect<void, StorageFault, StorageOwner>;
287
+ declare namespace layer_d_exports {
288
+ export { ProtocolOptions, bind, expireDue, layer$1 as layer };
289
+ }
290
+ interface ProtocolOptions {
291
+ /** Maximum messages per catch-up page; live reads return the whole tail. Default 1000. */
292
+ readonly readLimit?: number;
293
+ readonly longPollTimeoutMs?: number;
294
+ }
295
+ declare const layer$1: (options?: ProtocolOptions) => Layer.Layer<StreamsReader | StreamsWriter, never, StorageOwner>;
296
+ interface MemoryOptions {
297
+ readonly constrained?: boolean;
298
+ readonly pollIntervalMs?: number;
299
+ }
300
+ declare namespace streams_d_exports$1 {
301
+ export { Options, layer, layerProtocol };
302
+ }
303
+ /** Options for `layer` and `layerProtocol`. */
304
+ interface Options extends MemoryOptions, ProtocolOptions {}
305
+ /** Generic reader and writer over memory storage, for protocol tools. */
306
+ declare const layerProtocol: (options?: Options) => Layer.Layer<StorageOwner | StreamsReader | StreamsWriter, never, never>;
307
+ /** Memory host. Streams and their feeds share the exposed storage owner. */
308
+ declare function layer<const Keys extends ReadonlyArray<Any>>(group: Group<Keys>, options?: Options): Layer.Layer<StorageOwner | Host<Group<Keys>>>;
309
+ declare namespace producer_d_exports {
310
+ export { Position, next };
311
+ }
312
+ type Position = ProducerOptions;
313
+ /** Advance only after the caller has acknowledged appended or duplicate. Persist this tuple at the owning edge. */
314
+ declare const next: (position: Position) => Position;
315
+ /**
316
+ * The one collection of every frontier stream. Its State `type` is `stream`, and each row is a
317
+ * `Frontier`: the source stream id, a position in the source that the row's writer vouches
318
+ * for, and `closed` when the source is closed. The stream holding the row says what is
319
+ * vouched: written in a source frontier stream, or accepted in a projection's frontier stream.
320
+ */
321
+ declare const frontierStreamCollections: {
322
+ readonly stream: {
323
+ readonly schema: Schema.Struct<{
324
+ readonly stream: Schema.String;
325
+ readonly offset: Schema.String;
326
+ readonly closed: Schema.optionalKey<Schema.Literal<true>>;
327
+ }>;
328
+ readonly key: "stream";
329
+ };
330
+ };
331
+ type FrontierStreamCollections = typeof frontierStreamCollections;
332
+ /** One item of a frontier stream. */
333
+ type FrontierEvent = CollectionsEvent<FrontierStreamCollections>;
334
+ /**
335
+ * The codec of one frontier stream message: a `stream` change or a State control.
336
+ * A client that decodes raw JSON pages uses it in place of a typed service.
337
+ */
338
+ declare const FrontierMessage: Schema.Codec<FrontierEvent, CollectionsEncodedEvent<FrontierStreamCollections>>;
339
+ /** The options of `frontierStream`. A singleton template needs no options, so the argument is optional. */
340
+ type FrontierStreamOptions<Template extends string, C extends ParamCodecs> = IsSingleton<Template> extends true ? [options?: ParamsOption<Template, C>] : [options: ParamsOption<Template, C>];
341
+ /**
342
+ * Declare a frontier stream: a State stream of `Frontier` rows at a template.
343
+ *
344
+ * ```ts
345
+ * class UserFrontier extends Streamsy.frontierStream<UserFrontier>()("App/UserFrontier", "users/:user/frontier", {
346
+ * params: { user: UserKey },
347
+ * }) {}
348
+ * ```
349
+ *
350
+ * A template without `:name` declares a singleton frontier stream and may omit `params`,
351
+ * and so the whole options argument: `Streamsy.frontierStream<Wake>()("App/Wake", "wake")`.
352
+ * The declaration names no sources. A `Projection.frontier` binding links one
353
+ * source stream to one frontier stream, with params of its own.
354
+ */
355
+ declare const frontierStream: <Self>() => <const Name extends string, const Template extends string, C extends ParamCodecs = {}>(name: Name, template: Template & LiteralTemplate<Template>, ...[options]: FrontierStreamOptions<Template, C>) => StateClass<Self, Name, Template, C, {
356
+ readonly stream: {
357
+ readonly schema: Schema.Struct<{
358
+ readonly stream: Schema.String;
359
+ readonly offset: Schema.String;
360
+ readonly closed: Schema.optionalKey<Schema.Literal<true>>;
361
+ }>;
362
+ readonly key: "stream";
363
+ };
364
+ }>;
365
+ /** One action for a consumer of a frontier stream. */
366
+ type FrontierItem = Data.TaggedEnum<{
367
+ /** Read `stream` from `from` up to at least `offset`, then save its cursor. */
368
+ Dirty: {
369
+ readonly stream: StreamId;
370
+ /** The saved cursor of `stream`, or `-1`. Pass it as the `offset` of a read. */
371
+ readonly from: StartOffset;
372
+ /** The position the frontier row reports for `stream`. */
373
+ readonly offset: Offset;
374
+ readonly closed: boolean;
375
+ };
376
+ /** The stream was removed. Drop its cursor and its local data. */
377
+ Removed: {
378
+ readonly stream: StreamId;
379
+ };
380
+ /** Drop every cursor. The items after this one start each stream from `-1`. */
381
+ Reset: {};
382
+ /** A complete snapshot ended. Drop each stream that `streams` does not hold. */
383
+ Snapshot: {
384
+ readonly streams: ReadonlySet<StreamId>;
385
+ };
386
+ }>;
387
+ /** Constructors and matchers for `FrontierItem`. */
388
+ declare const FrontierItem: Data.TaggedEnum.Constructor<{
389
+ readonly _tag: "Dirty";
390
+ readonly stream: StreamId;
391
+ readonly from: StartOffset;
392
+ readonly offset: Offset;
393
+ readonly closed: boolean;
394
+ } | {
395
+ readonly _tag: "Removed";
396
+ readonly stream: StreamId;
397
+ } | {
398
+ readonly _tag: "Reset";
399
+ } | {
400
+ readonly _tag: "Snapshot";
401
+ readonly streams: ReadonlySet<StreamId>;
402
+ }>;
403
+ /** One batch of frontier actions. Save `offset` as the frontier cursor after every item is handled. */
404
+ interface FrontierBatch {
405
+ readonly items: ReadonlyArray<FrontierItem>;
406
+ readonly offset: Offset;
407
+ readonly upToDate: boolean;
408
+ }
409
+ interface FollowFrontierOptions extends Omit<FollowOptions, "offset"> {
410
+ /** The saved frontier stream cursor. Default: `-1`, a cold start. */
411
+ readonly from?: StartOffset;
412
+ /** Saved source cursors. Read again for each batch, so the consumer may update the map. */
413
+ readonly cursors: ReadonlyMap<StreamId, Offset>;
414
+ }
415
+ /** Follow options for a wait, including a saved frontier stream cursor. */
416
+ type AwaitFrontierOptions = Omit<FollowFrontierOptions, "cursors">;
417
+ interface FrontierActionsOptions {
418
+ /** Saved source cursors. A missing entry starts from `-1`. */
419
+ readonly cursors: ReadonlyMap<StreamId, Offset>;
420
+ /** The streams of a snapshot that an earlier batch left open. */
421
+ readonly snapshot?: ReadonlySet<StreamId> | undefined;
422
+ }
423
+ /** The actions of one frontier batch, and the snapshot state for the next batch. */
424
+ interface FrontierActions {
425
+ readonly items: ReadonlyArray<FrontierItem>;
426
+ /** The streams of a snapshot that is still open. Pass it to the next call. */
427
+ readonly snapshot: ReadonlySet<StreamId> | undefined;
428
+ }
429
+ /**
430
+ * The actions for one batch of frontier stream messages. The function is pure: it reads
431
+ * no stream and changes none of its inputs. Rows for one stream collapse to one
432
+ * item; a delete then an upsert of one stream gives `Removed`, then `Dirty` from
433
+ * `-1`. Pass the returned `snapshot` to the call for the next batch.
434
+ *
435
+ * `followFrontier` uses it over a typed service. A client with its own HTTP reader
436
+ * decodes each page with `FrontierMessage` and calls it directly.
437
+ */
438
+ declare function frontierActions(events: ReadonlyArray<FrontierEvent>, options: FrontierActionsOptions): FrontierActions;
439
+ /**
440
+ * Follow one frontier stream and give the actions for each batch: which source
441
+ * streams to read, from which cursor, and which to drop. The helper reads no
442
+ * source stream. Save each source cursor first and the frontier cursor (`offset`)
443
+ * last; a stop between the two reads the same rows again, and the offset check
444
+ * skips the streams that were already read.
445
+ */
446
+ declare function followFrontier<E, RD, RE>(stream: StreamHandle<FrontierEvent, E, RD, RE>, options: FollowFrontierOptions): Stream.Stream<FrontierBatch, FollowFailure | E, RD>;
447
+ /**
448
+ * Wait until the frontier row for `stream` reaches `offset`. `stream` is the handle of a
449
+ * frontier stream or of any State stream with one `Streamsy.frontier` collection; the
450
+ * other collections are read and skipped. Another stream dies with a `RangeError`. Works
451
+ * with local and remote services. Callers choose their own timeout. Removed source ids
452
+ * must not be reused; a new generation needs a new stream or a State reset. Without
453
+ * `options.from`, each call reads the history from the start.
454
+ */
455
+ declare const awaitFrontier: <C extends Collections, E, RD, RE>(stream: StreamHandle<CollectionsEvent<C>, E, RD, RE>, target: {
456
+ readonly stream: string;
457
+ readonly offset: string;
458
+ }, options?: AwaitFrontierOptions) => Effect.Effect<void, FollowFailure | E, RD>;
459
+ /** "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. */
460
+ declare const Frontier: Schema.Struct<{
461
+ readonly stream: Schema.String;
462
+ readonly offset: Schema.String;
463
+ readonly closed: Schema.optionalKey<Schema.Literal<true>>;
464
+ }>;
465
+ /** Spread into a State declaration's collections under any name. */
466
+ declare const frontier: {
467
+ readonly schema: Schema.Struct<{
468
+ readonly stream: Schema.String;
469
+ readonly offset: Schema.String;
470
+ readonly closed: Schema.optionalKey<Schema.Literal<true>>;
471
+ }>;
472
+ readonly key: "stream";
473
+ };
474
+ type Frontier = typeof Frontier.Type;
475
+ /**
476
+ * "A reader sees this write once it reflects `stream` up to `offset`." A server answers one after
477
+ * an append. It has the shape of a `Frontier` row, as a separate schema, so a collection declared
478
+ * with `Token` is not taken for a frontier collection.
479
+ */
480
+ declare const Token: Schema.Struct<{
481
+ readonly stream: Schema.String;
482
+ readonly offset: Schema.String;
483
+ }>;
484
+ type Token = typeof Token.Type;
485
+ /** The token of an append to `address`: its stream id and the tail after the write. */
486
+ declare const token: (address: {
487
+ readonly id: string;
488
+ }, appended: Pick<AppendResult, "offset">) => Token;
489
+ declare namespace streamsy_d_exports {
490
+ export { Address, Any, AwaitFrontierOptions, Bindings, BytesClass, Class, CustomClass, FollowFrontierOptions, ForkableStreamHandle, Frontier, FrontierActions, FrontierActionsOptions, FrontierBatch, FrontierEvent, FrontierItem, FrontierMessage, FrontierStreamCollections, FrontierStreamOptions, Group, Host, JsonClass, Services, StateClass, StreamFamily, StreamHandle, StreamService, Token, Wildcard, awaitFrontier, bytes, custom, followFrontier, frontier, frontierActions, frontierStream, frontierStreamCollections, group, json, state, token };
491
+ }
492
+ declare namespace streams_d_exports {
493
+ export { AppendFailure, AppendItems, Batch, Collected, CreateFailure, DecideSpec, Decided, Decision, Folded, FollowFailure, FollowOptions, HeadFailure, LiveBatch$1 as LiveBatch, ReadFailure, RemoveFailure, append, collect, create, decide, fold, follow, head, read$1 as read, readNext, remove };
494
+ }
495
+ /** Full toolkit failures, including protocol rejections and infrastructure faults. */
496
+ type ReadFailure = StreamNotFound | StreamGone | InvalidReadRequest | StreamsFault | DecodeFault;
497
+ type FollowFailure = ReadFailure | NotSupported;
498
+ type AppendFailure<O = AppendCallOptions> = AppendErrorFor<O> | StreamsFault | EncodeFault;
499
+ type CreateFailure = CreateError | StreamsFault;
500
+ type HeadFailure = HeadError | StreamsFault;
501
+ type RemoveFailure = RemoveError | StreamsFault;
502
+ /**
503
+ * One page of a read. A batch is the unit of a read because it holds the offset: pass `offset`
504
+ * back to read on after the last item.
505
+ */
506
+ interface Batch<A> {
507
+ readonly items: ReadonlyArray<A>;
508
+ /** The position after the last item. Pass it back as `offset` to read on. */
509
+ readonly offset: Offset;
510
+ readonly upToDate: boolean;
511
+ readonly closed: boolean;
512
+ }
513
+ /** Operators for streams of batches. */
514
+ declare const Batch: {
515
+ /**
516
+ * Flatten a stream of batches into its items. The items carry no offset, so keep the batches
517
+ * when you need to resume from where you stopped.
518
+ */
519
+ items: <A, E, R>(batches: Stream.Stream<Batch<A>, E, R>) => Stream.Stream<A, E, R>;
520
+ };
521
+ declare const create: <A, RD, RE>(address: StreamAddress<A, RD, RE>, options?: Omit<CreateOptions, "contentType"> | undefined) => Effect.Effect<CreateResult, CreateFailure, StreamsWriter>;
522
+ /**
523
+ * The items one append takes. An append carries at least one item, unless it
524
+ * closes the stream. Caller-bug rejections from a host are defects.
525
+ */
526
+ type AppendItems<A, O> = O extends {
527
+ readonly close: true;
528
+ } ? ReadonlyArray<A> : Array.NonEmptyReadonlyArray<A>;
529
+ /**
530
+ * Append items to one stream. The error type lists only the rejections that the
531
+ * options make possible; a host that answers another one dies.
532
+ */
533
+ declare const append: <A, RD, RE, const O extends AppendCallOptions = {}>(address: StreamAddress<A, RD, RE>, items: AppendItems<NoInfer<A>, O>, options?: O | undefined) => Effect.Effect<AppendResult, AppendFailure<O>, RE | StreamsWriter>;
534
+ declare function read$1<A, RD, RE>(address: StreamAddress<A, RD, RE>, options?: ReadOptions$1): Stream.Stream<Batch<A>, ReadFailure, StreamsReader | RD>;
535
+ /** A folded value and the tail it was read up to. `offset` is this stream's CAS token. */
536
+ interface Folded<S> {
537
+ readonly state: S;
538
+ readonly offset: Offset;
539
+ }
540
+ /** Every item read and the tail they were read up to. */
541
+ interface Collected<A> {
542
+ readonly items: ReadonlyArray<A>;
543
+ readonly offset: Offset;
544
+ }
545
+ /**
546
+ * Read the stream up to its tail and fold every item into one value. Pass
547
+ * `options.offset` to fold on from a tail that an earlier fold returned.
548
+ */
549
+ declare const fold: <A, RD, RE, S>(address: StreamAddress<A, RD, RE>, initial: Function.LazyArg<S>, f: (state: S, item: A) => S, options?: ReadOptions$1 | undefined) => Effect.Effect<Folded<S>, ReadFailure, RD | StreamsReader>;
550
+ /** Read the stream up to its tail and return its items. */
551
+ declare const collect: <A, RD, RE>(address: StreamAddress<A, RD, RE>, options?: ReadOptions$1 | undefined) => Effect.Effect<Collected<A>, ReadFailure, RD | StreamsReader>;
552
+ /** What one `decide` step answers: a value, and the items to append for it. */
553
+ interface Decision<B, A> {
554
+ readonly value: B;
555
+ /** Items to append. Empty means "no write": the call returns without a tail check. */
556
+ readonly items: ReadonlyArray<A>;
557
+ }
558
+ /** The result of a read, decide, append loop. */
559
+ interface Decided<B> {
560
+ readonly value: B;
561
+ /** The new tail after a write, or the tail that was read when there was no write. */
562
+ readonly offset: Offset;
563
+ readonly appended: boolean;
564
+ }
565
+ interface DecideSpec<A, S, B, E, R> {
566
+ /** The start value of the fold. Each call starts from a new value. */
567
+ readonly initial: Function.LazyArg<S>;
568
+ readonly fold: (state: S, item: A) => S;
569
+ /**
570
+ * Decide what to append from the folded state. `offset` is the tail the state is
571
+ * at; the append checks it. This step must not write and must not change
572
+ * `state`: a retry folds on from the same state after a lost race.
573
+ */
574
+ readonly decide: (state: S, at: {
575
+ readonly offset: Offset;
576
+ }) => Effect.Effect<Decision<B, NoInfer<A>>, E, R>;
577
+ /** Retries after `OffsetMismatch`. Default: `Schedule.recurs(3)`. Nothing else is retried. */
578
+ readonly retry?: Schedule.Schedule<unknown, OffsetMismatch>;
579
+ }
580
+ /**
581
+ * Read, decide, append. Fold the stream to its tail, decide from the state, and
582
+ * append with `expectedOffset` set to the tail that was read. After an
583
+ * `OffsetMismatch`, fold on from that tail and decide again while `retry` allows;
584
+ * then fail with the last `OffsetMismatch`. Transport faults are not retried: a
585
+ * lost reply may hide an append that landed.
586
+ */
587
+ declare const decide: <A, RD, RE, S, B, E, R>(address: StreamAddress<A, RD, RE>, spec: DecideSpec<A, S, B, E, R>) => Effect.Effect<Decided<B>, E | AppendConflict | DecodeFault | EncodeFault | InvalidReadRequest | NotSupported | OffsetMismatch | StorageFault | StreamBusy | StreamClosed | StreamGone | StreamNotFound | TransportFault, R | RD | RE | StreamsReader | StreamsWriter>;
588
+ interface FollowOptions extends ReadOptions$1 {
589
+ /**
590
+ * Schedule for retrying a failed read after a retryable `TransportFault` or `StorageFault`.
591
+ * Default: exponential from 200 ms, jittered, capped at 30 s, forever. Other
592
+ * failures end the stream at once.
593
+ */
594
+ readonly retry?: Schedule.Schedule<unknown>;
595
+ }
596
+ /**
597
+ * Catch up, then wait one readNext at a time. A page with stored messages
598
+ * advances the reader even when all of its State changes are skipped.
599
+ * A read that fails with a retryable transport or storage fault is retried from the same
600
+ * offset, so a restart or network drop yields each item once.
601
+ */
602
+ declare function follow<A, RD, RE>(address: StreamAddress<A, RD, RE>, options?: FollowOptions): Stream.Stream<Batch<A>, FollowFailure, StreamsReader | RD>;
603
+ /** One batch from a live read, with the values the next call needs. */
604
+ interface LiveBatch$1<A> extends Batch<A> {
605
+ /** Send this back as `cursor` on the next `readNext`. */
606
+ readonly cursor: string;
607
+ /** `true` when the wait ended with no messages. */
608
+ readonly timedOut: boolean;
609
+ }
610
+ /**
611
+ * One live read: the items after `offset` if there are any, or else wait once for some. It
612
+ * decodes like `follow`, so a State reader skips changes to collections it does not declare.
613
+ */
614
+ declare const readNext: <A, RD, RE>(address: StreamAddress<A, RD, RE>, options: ReadNextOptions) => Effect.Effect<LiveBatch$1<A>, FollowFailure, RD | StreamsReader>;
615
+ declare const head: <A, RD, RE>(address: StreamAddress<A, RD, RE>) => Effect.Effect<HeadResult, HeadFailure, StreamsReader>;
616
+ declare const remove: <A, RD, RE>(address: StreamAddress<A, RD, RE>) => Effect.Effect<void, RemoveFailure, StreamsWriter>;
617
+ /**
618
+ * One stream, with named failures for each toolkit call. No method takes params: the handle
619
+ * already names its stream. `E` is `never` for a singleton stream and `InvalidStreamParams`
620
+ * for the handle from `at(params)` of a stream with params.
621
+ */
622
+ interface StreamHandle<A, E = never, RD = never, RE = never> {
623
+ readonly owner: OwnerId;
624
+ readonly wire: Reader<StreamsFault> & Writer<StreamsFault>;
625
+ /** The address of this stream. Fails with `E` when its params cannot form a stream id. */
626
+ readonly address: Effect.Effect<StreamAddress<A, RD, RE>, E>;
627
+ readonly create: (options?: Omit<CreateOptions, "contentType">) => Effect.Effect<CreateResult, CreateFailure | E>;
628
+ readonly append: <const O extends AppendCallOptions = {}>(items: AppendItems<A, O>, options?: O) => Effect.Effect<AppendResult, AppendFailure<O> | E, RE>;
629
+ readonly read: (options?: ReadOptions$1) => Stream.Stream<Batch<A>, ReadFailure | E, RD>;
630
+ readonly fold: <S>(initial: Function.LazyArg<S>, f: (state: S, item: A) => S, options?: ReadOptions$1) => Effect.Effect<Folded<S>, ReadFailure | E, RD>;
631
+ readonly collect: (options?: ReadOptions$1) => Effect.Effect<Collected<A>, ReadFailure | E, RD>;
632
+ readonly decide: <S, B, E2, R>(spec: DecideSpec<A, S, B, E2, R>) => Effect.Effect<Decided<B>, ReadFailure | AppendFailure<{
633
+ expectedOffset: Offset;
634
+ }> | E | E2, RD | RE | R>;
635
+ readonly follow: (options?: FollowOptions) => Stream.Stream<Batch<A>, FollowFailure | E, RD>;
636
+ readonly readNext: (options: ReadNextOptions) => Effect.Effect<LiveBatch$1<A>, FollowFailure | E, RD>;
637
+ readonly head: () => Effect.Effect<HeadResult, HeadFailure | E>;
638
+ readonly remove: () => Effect.Effect<void, RemoveFailure | E>;
639
+ }
640
+ /** The handle from `at(params)`: one stream of a declaration with params, which can fork. */
641
+ interface ForkableStreamHandle<P, A, RD = never, RE = never> extends StreamHandle<A, InvalidStreamParams, RD, RE> {
642
+ /** Create this stream as a fork of `source`, another stream of the same declaration. */
643
+ readonly fork: (source: P, options?: Omit<CreateOptions, "contentType" | "forkedFrom">) => Effect.Effect<CreateResult, CreateFailure | InvalidStreamParams>;
644
+ }
645
+ /**
646
+ * The service of a stream with params. `at(params)` gives the handle of one stream and never
647
+ * throws: each method of the handle fails with `InvalidStreamParams` when `params` cannot form
648
+ * a stream id.
649
+ */
650
+ interface StreamFamily<P, A, RD = never, RE = never> {
651
+ readonly owner: OwnerId;
652
+ readonly wire: Reader<StreamsFault> & Writer<StreamsFault>;
653
+ readonly at: (params: P) => ForkableStreamHandle<P, A, RD, RE>;
654
+ }
655
+ /** The service of a stream: a handle for a singleton stream, `at(params)` otherwise. */
656
+ type StreamService<P, A, RD, RE, Template extends string> = IsSingleton<Template> extends true ? StreamHandle<A, never, RD, RE> : StreamFamily<P, A, RD, RE>;
657
+ /** An address names one stream. It holds no data. It is not an Effect `Ref`. */
658
+ type Address<A, R, RD = never, RE = never> = StreamAddress<A, RD, RE> & {
659
+ readonly stream: Context.Key<R, {
660
+ readonly owner: OwnerId;
661
+ readonly wire: Reader<StreamsFault> & Writer<StreamsFault>;
662
+ }>;
663
+ };
664
+ /** The address type a declaration binds to: its route's address plus the service key. */
665
+ type Bound<Self, P, A, RD, RE, R extends StreamRoute<P, A, RD, RE>> = ReturnType<R["address"]> & Address<A, Self, RD, RE>;
666
+ /**
667
+ * The binding statics of a stream class. A singleton stream has `singleton`, its address.
668
+ * A stream with params has `at(params)` and `resolve(params)`.
669
+ */
670
+ type Bindings<Self, P, A, RD, RE, R extends StreamRoute<P, A, RD, RE>> = IsSingleton<R["template"]> extends true ? {
671
+ /** The address of this singleton stream. One cached object per declaration. */
672
+ readonly singleton: Bound<Self, P, A, RD, RE, R>;
673
+ } : {
674
+ /**
675
+ * Build the address for `params`. Throws a `RangeError` when a param value cannot form a
676
+ * stream id; its `cause` is the `InvalidStreamParams`. Use `resolve` for request values.
677
+ */
678
+ readonly at: (params: P) => Bound<Self, P, A, RD, RE, R>;
679
+ /** Build the address for `params`, or fail with `InvalidStreamParams`. Never throws. */
680
+ readonly resolve: (params: P) => Effect.Effect<Bound<Self, P, A, RD, RE, R>, InvalidStreamParams>;
681
+ };
682
+ type Class<Self, Name extends string, P, A, RD, RE, R extends StreamRoute<P, A, RD, RE>> = Context.ServiceClass<Self, `@streamsy/core/Stream/${Name}`, StreamService<P, A, RD, RE, R["template"]>> & R & Bindings<Self, P, A, RD, RE, R>;
683
+ type JsonClass<Self, Name extends string, T extends string, C extends ParamCodecs, A, I, RD, RE> = Class<Self, Name, Params<C>, A, RD, RE, ReturnType<typeof json$1<T, C, A, I, RD, RE>>>;
684
+ declare const json: <Self>() => <const Name extends string, const T extends string, C extends ParamCodecs = {}, A = never, I = never, RD = never, RE = never>(name: Name, ...args: Parameters<typeof json$1<T, C, A, I, RD, RE>>) => JsonClass<Self, Name, T, C, A, I, RD, RE>;
685
+ type StateClass<Self, Name extends string, T extends string, C extends ParamCodecs, Collections$2 extends Collections> = Class<Self, Name, Params<C>, CollectionsEvent<Collections$2>, CollectionsDecodingServices<Collections$2>, CollectionsEncodingServices<Collections$2>, ReturnType<typeof state$1<T, C, Collections$2>>>;
686
+ declare const state: <Self>() => <const Name extends string, const T extends string, C extends ParamCodecs = {}, const Collections$1 extends Collections = {}>(name: Name, ...args: Parameters<typeof state$1<T, C, Collections$1>>) => StateClass<Self, Name, T, C, Collections$1>;
687
+ type BytesClass<Self, Name extends string, T extends string, C extends ParamCodecs> = Class<Self, Name, Params<C>, Uint8Array, never, never, ReturnType<typeof bytes$1<T, C>>>;
688
+ declare const bytes: <Self>() => <const Name extends string, const T extends string, C extends ParamCodecs = {}>(name: Name, ...args: Parameters<typeof bytes$1<T, C>>) => BytesClass<Self, Name, T, C>;
689
+ type CustomClass<Self, Name extends string, P, A, RD, RE> = Class<Self, Name, P, A, RD, RE, ReturnType<typeof custom$1<P, A, RD, RE>>>;
690
+ declare const custom: <Self>() => <const Name extends string, P, A, RD, RE>(name: Name, options: Parameters<typeof custom$1<P, A, RD, RE>>[0]) => CustomClass<Self, Name, P, A, RD, RE>;
691
+ declare const Wildcard_base: Class<Wildcard, "Wildcard", {
692
+ id: string;
693
+ }, Uint8Array<ArrayBufferLike>, never, never, StreamRoute<{
694
+ id: string;
695
+ }, Uint8Array<ArrayBufferLike>, never, never, string>>;
696
+ declare class Wildcard extends Wildcard_base {}
697
+ /** Class instances carry Effect's service marker; individual Self types remain on each key. */
698
+ interface StreamIdentifier {
699
+ readonly [Context.ServiceTypeId]: typeof Context.ServiceTypeId;
700
+ }
701
+ /** The provider and HTTP boundary need only the wire and the route grammar. */
702
+ interface Any extends Context.Key<StreamIdentifier, {
703
+ readonly owner: OwnerId;
704
+ readonly wire: Reader<StreamsFault> & Writer<StreamsFault>;
705
+ }> {
706
+ readonly template: string;
707
+ readonly match: (id: string) => boolean;
708
+ }
709
+ type Identifiers<Keys extends ReadonlyArray<Any>> = Keys[number]["Identifier"];
710
+ /** Bind streams to their owning protocol graph. */
711
+ declare function bind<A, E, R, const Keys extends ReadonlyArray<Any>>(graph: Layer.Layer<A | StreamsReader | StreamsWriter, E, R>, streams: Group<Keys>): Layer.Layer<Identifiers<Keys>, E, R>;
712
+ interface Group<Keys extends ReadonlyArray<Any> = ReadonlyArray<Any>> {
713
+ readonly streams: Keys;
714
+ }
715
+ type Services<G extends Group> = G["streams"][number]["Identifier"];
716
+ /** What every host Layer gives for a group: its stream services. */
717
+ type Host<G extends Group> = Services<G>;
718
+ declare function group<const Keys extends ReadonlyArray<Any>>(...keys: Keys): Group<Keys>;
719
+ type RouteLayer<R> = Layer.Layer<never, never, HttpRouter.HttpRouter | HttpRouter.Request.From<"Requires", Exclude<R, HttpRouter.Provided>>>;
720
+ interface Access<S extends Any = Any> {
721
+ readonly stream: S;
722
+ /** append permits POST; full also permits PUT and DELETE. */
723
+ readonly access: "read" | "append" | "full";
724
+ }
725
+ interface RoutesOptions extends Omit<HttpOptions, "pathPrefix"> {
726
+ readonly prefix?: `/${string}`;
727
+ /** The access of each stream on this mount. */
728
+ readonly access: Access["access"] | ((stream: Any) => Access["access"]);
729
+ }
730
+ /** One prefix controls both route registration and protocol path stripping. */
731
+ declare function routes<const Keys extends ReadonlyArray<Any>>(group: Group<Keys>, options: RoutesOptions): RouteLayer<Identifiers<Keys>>;
732
+ interface ReadOptions {
733
+ readonly sseDeadlineMs?: number;
734
+ readonly cacheVisibility?: "private" | "public";
735
+ }
736
+ /** @internal Shared construction-time validation for HTTP read routes. */
737
+ declare function checkReadOptions(options: ReadOptions): void;
738
+ /** Read an already resolved id using the protocol's HTTP framing and live modes. */
739
+ declare function read(id: StreamId, options?: ReadOptions): Effect.Effect<HttpServerResponse.HttpServerResponse, InvalidReadRequest | NotSupported | StorageFault | StreamGone | StreamNotFound | TransportFault, HttpServerRequest.HttpServerRequest | StreamsReader>;
740
+ /** Shared protocol and host security headers. */
741
+ declare const securityHeaders: Readonly<{
742
+ "x-content-type-options": "nosniff";
743
+ "cross-origin-resource-policy": "cross-origin";
744
+ }>;
745
+ /**
746
+ * Tells live HTTP reads that the host is about to stop. A parked long poll then
747
+ * answers `204` with its offset and cursor, and an open SSE body ends after its
748
+ * last whole batch. Clients take their normal reconnect path.
749
+ *
750
+ * The service is optional. Live reads look it up with `Effect.serviceOption`, so
751
+ * a host without it (for example the Durable Object host) keeps its behaviour.
752
+ */
753
+ interface ShutdownSignalService {
754
+ /** Completes when the host starts to drain; never fails. */
755
+ readonly draining: Effect.Effect<void>;
756
+ /** Counts a live read while `effect` runs. */
757
+ readonly track: <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;
758
+ /** Counts a live read while `stream` runs. */
759
+ readonly trackStream: <A, E, R>(stream: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R>;
760
+ /**
761
+ * Starts the drain, then waits until no live read is running or `timeout`
762
+ * passes. Safe to call more than once.
763
+ */
764
+ readonly drain: (timeout: Duration.Input) => Effect.Effect<void>;
765
+ /** The number of live reads now running. */
766
+ readonly active: Effect.Effect<number>;
767
+ }
768
+ declare const ShutdownSignal_base: Context.ServiceClass<ShutdownSignal, "@streamsy/core/ShutdownSignal", ShutdownSignalService>;
769
+ declare class ShutdownSignal extends ShutdownSignal_base {}
770
+ /** A fresh signal. Provide it to the routes and call `drain` before they close. */
771
+ declare const layerShutdownSignal: Layer.Layer<ShutdownSignal, never, never>;
772
+ interface SseControlData {
773
+ streamNextOffset: string;
774
+ streamCursor?: string;
775
+ streamClosed?: true;
776
+ upToDate?: true;
777
+ }
778
+ /**
779
+ * Frames of `live=websocket`, a Streamsy extension to Durable Streams HTTP.
780
+ *
781
+ * The server sends one `open` text frame, then a binary `data` frame and a
782
+ * `control` text frame for each batch. A `data` frame holds the exact body of
783
+ * a catch-up `GET` for the batch. A `control` frame has the fields of an SSE
784
+ * control event, and a client moves its offset only on `control`.
785
+ */
786
+ declare const LIVE_SOCKET_PROTOCOL = "streamsy-live.v1";
787
+ /** The only client message. The runtime answers it without running the server. */
788
+ declare const LIVE_PING = "ping";
789
+ declare const LIVE_PONG = "pong";
790
+ /** The close codes of `streamsy-live.v1`. */
791
+ declare const LiveCloseCode: {
792
+ /** The stream closed. A `control` frame with `streamClosed` came first. */
793
+ readonly StreamClosed: 1000;
794
+ readonly InternalError: 1011;
795
+ /** The server restarted or cannot read the socket's state. Reconnect at once. */
796
+ readonly Restart: 1012;
797
+ /** The socket fell behind the byte cap. Read over HTTP, then reconnect. */
798
+ readonly CatchUpRequired: 4100;
799
+ readonly BadMessage: 4400;
800
+ readonly NotFound: 4404;
801
+ readonly Gone: 4410;
802
+ };
803
+ type LiveCloseCode = (typeof LiveCloseCode)[keyof typeof LiveCloseCode];
804
+ interface LiveOpenFrame {
805
+ readonly type: "open";
806
+ readonly protocol: typeof LIVE_SOCKET_PROTOCOL;
807
+ readonly contentType: string;
808
+ readonly streamNextOffset: string;
809
+ }
810
+ interface LiveControlFrame extends SseControlData {
811
+ readonly type: "control";
812
+ }
813
+ interface LiveBatch {
814
+ readonly nextOffset: string;
815
+ readonly cursor: string;
816
+ readonly upToDate: boolean;
817
+ readonly closed: boolean;
818
+ }
819
+ /** The browser socket API hides response headers, so `open` carries the content type. */
820
+ declare function openFrame(contentType: string, streamNextOffset: string): string;
821
+ /** The SSE control rules: no cursor on a closed stream, `upToDate` only while open. */
822
+ declare function controlFrame(batch: LiveBatch): string;
823
+ /** The cursor a long-poll response would carry after `previous`. */
824
+ declare const nextCursor: (previous: string | undefined) => Effect.Effect<string, never, never>;
825
+ /** The close code for a read that failed with an HTTP status. */
826
+ declare function closeCodeForStatus(status: number): LiveCloseCode;
827
+ /** A `GET` that asks for `live=websocket` with an `Upgrade: websocket` header. */
828
+ declare function isLiveUpgrade(request: Request): boolean;
829
+ /** The answer to `live=websocket` from a host or request that cannot upgrade. Clients fall back to long-poll. */
830
+ declare function upgradeRequired(): Response;
831
+ /** `websocket` is a Streamsy extension. Only a host that accepts the upgrade serves it. */
832
+ type HttpLiveMode = "long-poll" | "sse" | "websocket";
833
+ declare namespace index_d_exports {
834
+ export { Access, HttpLiveMode, HttpOptions, LIVE_PING, LIVE_PONG, LIVE_SOCKET_PROTOCOL, LiveBatch, LiveCloseCode, LiveControlFrame, LiveOpenFrame, ReadOptions, RoutesOptions, ShutdownSignal, ShutdownSignalService, app, checkReadOptions, closeCodeForStatus, controlFrame, isLiveUpgrade, layerShutdownSignal, nextCursor, openFrame, read, routes, securityHeaders, streamPath, upgradeRequired };
835
+ }
836
+ export { HttpOptions as $, Batch as A, StreamNotFound as At, ReadFailure as B, Access as C, ReadError as Ct, Group as D, StreamBusy as Dt, Any as E, StaleEpoch as Et, Decision as F, streams_d_exports$1 as G, streams_d_exports as H, Folded as I, layer_d_exports as J, MemoryOptions as K, FollowFailure as L, CreateFailure as M, CreateOptions as Mt, DecideSpec as N, Identifiers as O, StreamClosed as Ot, Decided as P, streamPath as Q, HeadFailure as R, read as S, ProtocolError as St, routes as T, RemoveError as Tt, streamsy_d_exports as U, RemoveFailure as V, producer_d_exports as W, compare as X, ZERO_OFFSET as Y, route_d_exports as Z, ShutdownSignalService as _, InvalidForkRequest as _t, LIVE_SOCKET_PROTOCOL as a, AppendBaseError as at, ReadOptions as b, OffsetMismatch as bt, LiveControlFrame as c, AppendErrorFor as ct, controlFrame as d, CreateError as dt, app as et, isLiveUpgrade as f, ForkSourceNotFound as ft, ShutdownSignal as g, InvalidEpochSeq as gt, upgradeRequired as h, InvalidCreateRequest as ht, LIVE_PONG as i, Writer as it, Collected as j, isProtocolError as jt, AppendFailure as k, StreamGone as kt, LiveOpenFrame as l, CreateConflict as lt, openFrame as m, InvalidAppendRequest as mt, HttpLiveMode as n, StreamsReader as nt, LiveBatch as o, AppendConflict as ot, nextCursor as p, HeadError as pt, ProtocolOptions as q, LIVE_PING as r, StreamsWriter as rt, LiveCloseCode as s, AppendError as st, index_d_exports as t, Reader as tt, closeCodeForStatus as u, CreateConflictReason as ut, layerShutdownSignal as v, InvalidReadRequest as vt, RoutesOptions as w, ReadNextError as wt, checkReadOptions as x, ProducerGap as xt, securityHeaders as y, NotSupported as yt, LiveBatch$1 as z };