@loozo/angular-launch 0.0.4 → 0.0.6

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.
Files changed (59) hide show
  1. package/README.md +695 -102
  2. package/builders/application.d.ts +4 -0
  3. package/builders/application.js +71 -0
  4. package/builders/options.d.ts +10 -0
  5. package/builders/options.js +64 -0
  6. package/builders/serve.d.ts +8 -0
  7. package/builders/serve.js +248 -0
  8. package/builders.json +15 -0
  9. package/channel.d.ts +53 -0
  10. package/channel.js +231 -0
  11. package/client.d.ts +59 -16
  12. package/client.js +3 -2
  13. package/connect.d.ts +201 -0
  14. package/connect.js +148 -0
  15. package/generated.d.ts +1 -1
  16. package/generated.js +86 -3
  17. package/generation/context-file.d.ts +2 -0
  18. package/generation/context-file.js +3 -0
  19. package/generation/index.js +77 -36
  20. package/index.d.ts +6 -1
  21. package/index.js +2 -0
  22. package/json.d.ts +9 -0
  23. package/json.js +24 -0
  24. package/navigation.d.ts +36 -0
  25. package/navigation.js +47 -0
  26. package/node/index.d.ts +57 -0
  27. package/node/index.js +175 -0
  28. package/outcomes.d.ts +55 -0
  29. package/outcomes.js +100 -0
  30. package/package.json +14 -4
  31. package/schemas/application.json +756 -0
  32. package/schemas/serve.json +153 -0
  33. package/server/backend.d.ts +42 -23
  34. package/server/backend.js +137 -47
  35. package/server/channel-messages.d.ts +54 -0
  36. package/server/channel-messages.js +84 -0
  37. package/server/channel-socket.d.ts +67 -0
  38. package/server/channel-socket.js +322 -0
  39. package/server/definitions.d.ts +463 -181
  40. package/server/definitions.js +90 -103
  41. package/server/dispatch.d.ts +99 -20
  42. package/server/dispatch.js +337 -89
  43. package/server/event-stream.d.ts +63 -0
  44. package/server/event-stream.js +173 -0
  45. package/server/generated.d.ts +1 -0
  46. package/server/generated.js +1 -0
  47. package/server/index.d.ts +6 -3
  48. package/server/index.js +2 -1
  49. package/server/outcomes.d.ts +75 -0
  50. package/server/outcomes.js +90 -0
  51. package/server/response-effects.d.ts +105 -0
  52. package/server/response-effects.js +78 -0
  53. package/server/upgrade.d.ts +58 -0
  54. package/server/upgrade.js +117 -0
  55. package/stream.d.ts +31 -0
  56. package/stream.js +159 -0
  57. package/tanstack-query/README.md +110 -22
  58. package/tanstack-query/generated.js +5 -2
  59. package/tanstack-query/queries.d.ts +8 -6
package/channel.js ADDED
@@ -0,0 +1,231 @@
1
+ import { parseJson, serializeJson } from "./json.js";
2
+ import { failureRejection } from "./stream.js";
3
+ /** How many values the server sends before this side must grant more. */
4
+ const valueWindow = 256;
5
+ /** How many messages this side sends before the server must grant more. */
6
+ const messageWindow = 32;
7
+ /**
8
+ * Opens one channel call over the browser `WebSocket`.
9
+ *
10
+ * @remarks
11
+ * Internal. The socket's URL is `path` resolved against the page, with a `ws:` or `wss:`
12
+ * scheme. Not `HttpClient`, and no Angular pending task: an open channel never keeps the app
13
+ * unstable. See {@link Channel} for the caller-facing behavior. Values that arrive before
14
+ * they're read are kept; the server sends no more than its window.
15
+ *
16
+ * @param path - The procedure's `/_rpc/<namespace>/<procedure>?input=…` path.
17
+ * @param declared - The procedure's declared error metadata.
18
+ * @param own - Associates a converted error with its procedure for `isError`.
19
+ * @param options - The call options.
20
+ * @param opened - Called once the socket opens.
21
+ * @param refused - Fails the channel at once with this error, without a connection.
22
+ */
23
+ export function openChannel(path, declared, own, { signal }, opened = () => undefined, refused) {
24
+ const values = [];
25
+ const sends = [];
26
+ let socket;
27
+ let sendCredit = messageWindow;
28
+ let readSinceGrant = 0;
29
+ // No more frames either way: the call ended, failed, was aborted or left.
30
+ let closed = false;
31
+ let failure;
32
+ // The consumer is done: it read the end, caught the failure or left the loop.
33
+ let settled = false;
34
+ let iterated = false;
35
+ let wake;
36
+ // Each read waits for the one before it, so concurrent `next()` calls settle in order.
37
+ let reading = Promise.resolve();
38
+ function finish(error) {
39
+ if (closed) {
40
+ return;
41
+ }
42
+ closed = true;
43
+ failure = error;
44
+ const reason = error ?? new TypeError("Launch channel closed");
45
+ for (const pending of sends.splice(0)) {
46
+ pending.reject(reason);
47
+ }
48
+ // Closing again after the server's own close is harmless.
49
+ socket?.close(1000);
50
+ wake?.();
51
+ }
52
+ function settle() {
53
+ settled = true;
54
+ values.length = 0;
55
+ signal?.removeEventListener("abort", abort);
56
+ }
57
+ // Also after the last frame: values the consumer hasn't read yet aren't delivered.
58
+ function abort() {
59
+ if (settled) {
60
+ return;
61
+ }
62
+ const reason = new DOMException("RPC channel aborted", "AbortError");
63
+ values.length = 0;
64
+ if (closed) {
65
+ failure = reason;
66
+ wake?.();
67
+ return;
68
+ }
69
+ finish(reason);
70
+ }
71
+ function flush() {
72
+ while (socket?.readyState === 1 && !closed && sendCredit > 0 && sends.length > 0) {
73
+ const pending = sends.shift();
74
+ socket.send(pending.frame);
75
+ sendCredit -= 1;
76
+ pending.resolve();
77
+ }
78
+ }
79
+ function malformed() {
80
+ finish(new TypeError("Launch channel sent a malformed frame"));
81
+ }
82
+ function onMessage(event) {
83
+ if (closed) {
84
+ return;
85
+ }
86
+ if (typeof event.data !== "string") {
87
+ malformed();
88
+ return;
89
+ }
90
+ let frame;
91
+ try {
92
+ frame = parseJson(event.data);
93
+ }
94
+ catch {
95
+ malformed();
96
+ return;
97
+ }
98
+ if (typeof frame !== "object" || frame === null || Array.isArray(frame)) {
99
+ malformed();
100
+ return;
101
+ }
102
+ const single = Object.keys(frame).length === 1;
103
+ if (single && Object.hasOwn(frame, "value")) {
104
+ values.push(frame.value);
105
+ wake?.();
106
+ return;
107
+ }
108
+ if (single && Object.hasOwn(frame, "ready")) {
109
+ const granted = frame.ready;
110
+ if (typeof granted !== "number" || !Number.isSafeInteger(granted) || granted <= 0) {
111
+ malformed();
112
+ return;
113
+ }
114
+ sendCredit += granted;
115
+ flush();
116
+ return;
117
+ }
118
+ if (single &&
119
+ Object.hasOwn(frame, "end") &&
120
+ frame.end === null) {
121
+ finish();
122
+ return;
123
+ }
124
+ if (Object.hasOwn(frame, "status")) {
125
+ const { status, ...body } = frame;
126
+ let error;
127
+ if (typeof status === "number") {
128
+ error = failureRejection(body, status, declared, own);
129
+ }
130
+ finish(error ?? new TypeError("Launch channel sent an unrecognized error"));
131
+ return;
132
+ }
133
+ malformed();
134
+ }
135
+ function read() {
136
+ readSinceGrant += 1;
137
+ if (readSinceGrant >= valueWindow / 2 && !closed) {
138
+ socket.send(serializeJson({ ready: readSinceGrant }));
139
+ readSinceGrant = 0;
140
+ }
141
+ }
142
+ if (refused) {
143
+ finish(refused);
144
+ }
145
+ else if (signal?.aborted) {
146
+ abort();
147
+ }
148
+ else {
149
+ try {
150
+ // Resolved against the page's base URL, with its http(s) scheme turned into ws(s).
151
+ socket = new WebSocket(path);
152
+ }
153
+ catch (error) {
154
+ finish(new TypeError("Launch channel couldn't connect", { cause: error }));
155
+ }
156
+ }
157
+ if (socket) {
158
+ const opening = socket;
159
+ signal?.addEventListener("abort", abort, { once: true });
160
+ opening.addEventListener("open", () => {
161
+ if (!closed) {
162
+ opened();
163
+ flush();
164
+ }
165
+ });
166
+ opening.addEventListener("message", onMessage);
167
+ // A refused handshake fires error, then close; a dropped connection only close.
168
+ opening.addEventListener("close", () => {
169
+ finish(new TypeError("Launch channel closed before it ended"));
170
+ });
171
+ }
172
+ return {
173
+ send(message) {
174
+ if (closed) {
175
+ return Promise.reject(new TypeError("Launch channel is closed"));
176
+ }
177
+ let frame;
178
+ try {
179
+ frame = serializeJson({ message });
180
+ }
181
+ catch (error) {
182
+ return Promise.reject(error);
183
+ }
184
+ return new Promise((resolve, reject) => {
185
+ sends.push({ frame, resolve, reject });
186
+ flush();
187
+ });
188
+ },
189
+ [Symbol.asyncIterator]() {
190
+ if (iterated) {
191
+ throw new TypeError("A Launch channel has one consumer: iterate it once");
192
+ }
193
+ iterated = true;
194
+ async function step() {
195
+ while (true) {
196
+ if (values.length > 0) {
197
+ const value = values.shift();
198
+ read();
199
+ return { done: false, value };
200
+ }
201
+ if (closed) {
202
+ if (settled) {
203
+ return { done: true, value: undefined };
204
+ }
205
+ settle();
206
+ if (failure) {
207
+ throw failure;
208
+ }
209
+ return { done: true, value: undefined };
210
+ }
211
+ await new Promise((resolve) => {
212
+ wake = resolve;
213
+ });
214
+ wake = undefined;
215
+ }
216
+ }
217
+ return {
218
+ next() {
219
+ const result = reading.then(step);
220
+ reading = result.catch(() => undefined);
221
+ return result;
222
+ },
223
+ async return() {
224
+ settle();
225
+ finish();
226
+ return { done: true, value: undefined };
227
+ },
228
+ };
229
+ },
230
+ };
231
+ }
package/client.d.ts CHANGED
@@ -1,4 +1,6 @@
1
- import type { ErrorDefinitions, Group, OutputOf, Procedure, ProcedureKind, Schema } from "./server/definitions.js";
1
+ import type { ErrorDefinitions, Group, InputOf, OutputOf, Procedure, ProcedureKind, Schema } from "./server/definitions.js";
2
+ import type { Channel } from "./channel.js";
3
+ import type { ChannelConnector, ConnectInput, OptionalConnectInput, StreamConnector } from "./connect.js";
2
4
  import { type InvalidInputData } from "./input-issues.js";
3
5
  /** Per-call options for a generated query callable. */
4
6
  export interface CallOptions {
@@ -7,8 +9,9 @@ export interface CallOptions {
7
9
  * `DOMException` named `AbortError`.
8
10
  *
9
11
  * @remarks
10
- * An already aborted signal rejects without sending a request. Aborting doesn't
11
- * cancel server work that has already started.
12
+ * An already aborted signal rejects without sending a request. On the server, the
13
+ * call's middleware and handler see their `signal` abort. That's advisory: work that
14
+ * doesn't pass the signal on still finishes.
12
15
  */
13
16
  readonly signal?: AbortSignal;
14
17
  /**
@@ -24,13 +27,38 @@ export interface MutationCallOptions {
24
27
  * `DOMException` named `AbortError`.
25
28
  *
26
29
  * @remarks
27
- * Aborting doesn't cancel server work that has already started, so the write may
28
- * still complete.
30
+ * On the server, the call's middleware and handler see their `signal` abort. That's
31
+ * advisory: work that doesn't pass the signal on still finishes, and the write may
32
+ * already have committed.
29
33
  */
30
34
  readonly signal?: AbortSignal;
31
35
  /** Only `false` is accepted: mutations never use the HTTP transfer cache. */
32
36
  readonly transferCache?: false;
33
37
  }
38
+ /** Per-call options for a generated stream callable. */
39
+ export interface StreamCallOptions {
40
+ /**
41
+ * Aborts the stream: its request is cancelled and iteration rejects with a
42
+ * `DOMException` named `AbortError`.
43
+ *
44
+ * @remarks
45
+ * Ending iteration early, such as with `break`, also closes the request. On the server,
46
+ * the stream's middleware and handler see their `signal` abort.
47
+ */
48
+ readonly signal?: AbortSignal;
49
+ }
50
+ /** Per-call options for a generated channel callable. */
51
+ export interface ChannelCallOptions {
52
+ /**
53
+ * Aborts the channel: its socket closes, iteration rejects with a `DOMException` named
54
+ * `AbortError`, and messages waiting to be sent reject with it too.
55
+ *
56
+ * @remarks
57
+ * Ending iteration early, such as with `break`, also closes the socket. On the server, the
58
+ * channel's middleware and handler see their `signal` abort.
59
+ */
60
+ readonly signal?: AbortSignal;
61
+ }
34
62
  /**
35
63
  * Browser-safe metadata for one declared error of a procedure.
36
64
  *
@@ -53,8 +81,9 @@ export interface ErrorMetadata {
53
81
  * @remarks
54
82
  * - `INVALID_INPUT` (400): the request or its input failed validation. Its data is
55
83
  * {@link InvalidInputData}: the input schema's issues, or none for a malformed request.
56
- * - `FORBIDDEN` (403): a guard returned `false`, or a mutation was called during
57
- * server rendering.
84
+ * - `FORBIDDEN` (403): middleware or a handler threw `forbidden()`, the request wasn't
85
+ * proven to come from the app's own origin, or a mutation was called during server
86
+ * rendering.
58
87
  * - `RPC_NOT_FOUND` (404): no procedure exists at the requested path.
59
88
  * - `INTERNAL` (500): anything else. Details go to the server log, never to the client.
60
89
  *
@@ -198,23 +227,37 @@ type DeclaredError<Errors extends ErrorDefinitions> = {
198
227
  *
199
228
  * @typeParam Value - A procedure created by `query` or `mutation`.
200
229
  */
201
- export type ClientRpcError<Value> = Value extends Procedure<infer _Input, infer _Output, infer _Kind, infer Errors> ? FrameworkError | DeclaredError<Errors> : never;
202
- type Options<Kind extends ProcedureKind> = Kind extends "mutation" ? MutationCallOptions : CallOptions;
203
- type Callable<Input, Output, Kind extends ProcedureKind> = Input extends Schema<infer Caller, unknown> ? (input: Caller, options?: Options<Kind>) => Promise<Output> : (options?: Options<Kind>) => Promise<Output>;
230
+ export type ClientRpcError<Value> = Value extends Procedure<infer _Input, infer _Output, infer _Kind, infer Errors, infer _Message> ? FrameworkError | DeclaredError<Errors> : never;
231
+ type Options<Kind extends ProcedureKind> = Kind extends "mutation" ? MutationCallOptions : Kind extends "stream" ? StreamCallOptions : Kind extends "channel" ? ChannelCallOptions : CallOptions;
232
+ type Item<Output> = Output extends AsyncIterable<infer Value> ? Value : never;
233
+ type Sent<Message> = Message extends Schema ? InputOf<Message> : never;
234
+ type Result<Output, Kind extends ProcedureKind, Message> = Kind extends "stream" ? AsyncIterable<Item<Output>> : Kind extends "channel" ? Channel<Item<Output>, Sent<Message>> : Promise<Awaited<Output>>;
235
+ type Callable<Input, Output, Kind extends ProcedureKind, Message> = Input extends Schema<infer Caller, unknown> ? (input: Caller, options?: Options<Kind>) => Result<Output, Kind, Message> : (options?: Options<Kind>) => Result<Output, Kind, Message>;
236
+ type InputOption<Input> = Input extends Schema<infer Caller, unknown> ? ConnectInput<Caller> : OptionalConnectInput;
237
+ type Connectable<Input, Output, Kind extends ProcedureKind, Message> = Kind extends "stream" ? {
238
+ /** Follows the stream as signals; see {@link StreamConnector}. */
239
+ readonly connect: StreamConnector<InputOption<Input>, Item<Output>>;
240
+ } : Kind extends "channel" ? {
241
+ /** Runs the channel as signals; see {@link ChannelConnector}. */
242
+ readonly connect: ChannelConnector<InputOption<Input>, Item<Output>, Sent<Message>>;
243
+ } : {};
204
244
  /**
205
245
  * The generated client callable for a procedure.
206
246
  *
207
247
  * @remarks
208
248
  * The type of `Client<typeof group>["name"]`. A procedure with an input schema is called as
209
249
  * `(input, options?)`, where `input` is the schema's input type; one without input is
210
- * called as `(options?)`. Every call
211
- * returns a promise of the handler's awaited result. Queries take {@link CallOptions}
212
- * and mutations take {@link MutationCallOptions}.
250
+ * called as `(options?)`. A query or mutation call returns a promise of the handler's
251
+ * awaited result, a stream call an async iterable of its values, and a channel call an open
252
+ * {@link Channel}. Queries take {@link CallOptions}, mutations
253
+ * {@link MutationCallOptions}, streams {@link StreamCallOptions} and channels
254
+ * {@link ChannelCallOptions}. Streams and channels also have `connect()`, which follows them
255
+ * as signals.
213
256
  *
214
- * @typeParam Value - A procedure created by `query` or `mutation`.
257
+ * @typeParam Value - A procedure created by `query`, `mutation`, `stream` or `channel`.
215
258
  */
216
- export type ClientProcedure<Value> = Value extends Procedure<infer Input, infer Output, infer Kind, infer Errors> ? Callable<Input, Awaited<Output>, Kind> & {
217
- /** Whether the procedure is a `"query"` or a `"mutation"`. */
259
+ export type ClientProcedure<Value> = Value extends Procedure<infer Input, infer Output, infer Kind, infer Errors, infer Message> ? Callable<Input, Output, Kind, Message> & Connectable<Input, Output, Kind, Message> & {
260
+ /** Whether the procedure is a `"query"`, a `"mutation"`, a `"stream"` or a `"channel"`. */
218
261
  readonly kind: Kind;
219
262
  /**
220
263
  * Whether `error` is an {@link RpcError} returned by this exact procedure.
package/client.js CHANGED
@@ -6,8 +6,9 @@ import { isInvalidInputData } from "./input-issues.js";
6
6
  * @remarks
7
7
  * - `INVALID_INPUT` (400): the request or its input failed validation. Its data is
8
8
  * {@link InvalidInputData}: the input schema's issues, or none for a malformed request.
9
- * - `FORBIDDEN` (403): a guard returned `false`, or a mutation was called during
10
- * server rendering.
9
+ * - `FORBIDDEN` (403): middleware or a handler threw `forbidden()`, the request wasn't
10
+ * proven to come from the app's own origin, or a mutation was called during server
11
+ * rendering.
11
12
  * - `RPC_NOT_FOUND` (404): no procedure exists at the requested path.
12
13
  * - `INTERNAL` (500): anything else. Details go to the server log, never to the client.
13
14
  *
package/connect.d.ts ADDED
@@ -0,0 +1,201 @@
1
+ import { type Signal } from "@angular/core";
2
+ import type { Channel } from "./channel.js";
3
+ import type { RpcError } from "./client.js";
4
+ import type { RpcNotFound, RpcRedirect } from "./outcomes.js";
5
+ /**
6
+ * Where a connection is: `"idle"` without input or on the server, `"connecting"` until the
7
+ * server answers, `"open"` while it runs, `"ended"` once the handler ended, or `"failed"`.
8
+ */
9
+ export type ConnectionStatus = "idle" | "connecting" | "open" | "ended" | "failed";
10
+ /**
11
+ * Why a connection failed: the procedure's `RpcError`, an `RpcRedirect` or an `RpcNotFound`
12
+ * for a failure the server sent, a `TypeError` for a lost or refused connection, or the
13
+ * `Error` `reduce` threw.
14
+ *
15
+ * @remarks
16
+ * Narrow an `RpcError` with the callable's `isError`. A `reduce` that throws something other
17
+ * than an `Error` fails the connection with an `Error` whose `cause` is what it threw.
18
+ */
19
+ export type ConnectionError = RpcError<string, unknown> | RpcRedirect | RpcNotFound | TypeError | Error;
20
+ /**
21
+ * A stream's connection, created by its callable's `connect()`: its latest state as signals.
22
+ *
23
+ * @typeParam State - The state the values fold into.
24
+ */
25
+ export interface StreamConnection<State> {
26
+ /**
27
+ * The latest state: `initial()` until the first value arrives, then the latest value or
28
+ * what `reduce` made of it. Kept through failures and reconnects until a new value
29
+ * replaces it.
30
+ */
31
+ readonly value: Signal<State>;
32
+ /** Where the connection is. */
33
+ readonly status: Signal<ConnectionStatus>;
34
+ /** Why the connection failed, while `status` is `"failed"`; `undefined` otherwise. */
35
+ readonly error: Signal<ConnectionError | undefined>;
36
+ /**
37
+ * Opens a new call after the connection ended or failed, starting from the handler's first
38
+ * value. Does nothing in any other status.
39
+ */
40
+ reconnect(): void;
41
+ }
42
+ /**
43
+ * A channel's connection, created by its callable's `connect()`: a stream's connection, plus
44
+ * `send`.
45
+ *
46
+ * @typeParam State - The state the values fold into.
47
+ * @typeParam Sent - The messages the channel's `message` schema accepts.
48
+ */
49
+ export interface Connection<State, Sent> extends StreamConnection<State> {
50
+ /**
51
+ * Sends one message to the handler.
52
+ *
53
+ * @param message - The message, as strict JSON.
54
+ * @returns A promise that resolves once the message was handed to the socket: messages
55
+ * wait while connecting and for the server's room while open. It rejects with the error
56
+ * `error()` then shows when the connection fails first, also when `reduce` throws; with an
57
+ * `AbortError` when Launch closes the connection first, for a new input, `reconnect()` or
58
+ * the injection context's destruction; and with a `TypeError` while idle, ended or failed.
59
+ */
60
+ send(message: Sent): Promise<void>;
61
+ }
62
+ /**
63
+ * The `input` option of a procedure with an input schema.
64
+ *
65
+ * @typeParam Input - The input schema's input type.
66
+ */
67
+ export interface ConnectInput<Input> {
68
+ /**
69
+ * The call's input, read reactively: a change closes the connection and opens a new one,
70
+ * and `undefined` keeps it closed with status `"idle"`.
71
+ */
72
+ readonly input: () => Input | undefined;
73
+ }
74
+ /** The `input` option of a procedure without input. */
75
+ export interface OptionalConnectInput {
76
+ /**
77
+ * Whether to connect, read reactively: `null` connects, `undefined` keeps the connection
78
+ * closed with status `"idle"`. Defaults to always connecting.
79
+ */
80
+ readonly input?: () => null | undefined;
81
+ }
82
+ /**
83
+ * The options of `connect()` without `reduce`: the state is the latest value.
84
+ *
85
+ * @typeParam Initial - What to show before the first value.
86
+ */
87
+ export interface ConnectOptions<Initial> {
88
+ /**
89
+ * The state until the first value arrives, read reactively until then; also what the
90
+ * server renders.
91
+ */
92
+ readonly initial: () => Initial;
93
+ }
94
+ /**
95
+ * The options of `connect()` with `reduce`: each value folds into the state.
96
+ *
97
+ * @typeParam Value - The values the handler yields.
98
+ * @typeParam State - The state they fold into.
99
+ */
100
+ export interface ReducingConnectOptions<Value, State> {
101
+ /**
102
+ * The state until the first value arrives, read reactively until then; also what the
103
+ * server renders, and what a new call's first value folds into.
104
+ */
105
+ readonly initial: () => State;
106
+ /**
107
+ * Folds one value into the state. Runs untracked and must be pure; what it throws fails
108
+ * the connection.
109
+ *
110
+ * @param state - The current state.
111
+ * @param value - The value that arrived.
112
+ * @returns The new state.
113
+ */
114
+ readonly reduce: (state: State, value: Value) => State;
115
+ }
116
+ /**
117
+ * A stream callable's `connect()`.
118
+ *
119
+ * @typeParam InputOption - The `input` option the stream takes.
120
+ * @typeParam Value - The values its handler yields.
121
+ */
122
+ export interface StreamConnector<InputOption, Value> {
123
+ /**
124
+ * Follows the stream as signals, folding each value into the state with `reduce`.
125
+ *
126
+ * @remarks
127
+ * Call it in an injection context, such as a field initializer. It connects in the browser
128
+ * after the next render, never on the server, and never keeps the app from becoming
129
+ * stable. Destroying the injection context closes the connection.
130
+ *
131
+ * @param options - The input, the initial state and the fold.
132
+ * @returns The connection.
133
+ */
134
+ <State>(options: InputOption & ReducingConnectOptions<Value, State>): StreamConnection<State>;
135
+ /**
136
+ * Follows the stream as signals: the state is the latest value.
137
+ *
138
+ * @remarks
139
+ * As the `reduce` form.
140
+ *
141
+ * @param options - The input and what to show before the first value.
142
+ * @returns The connection.
143
+ */
144
+ <Initial>(options: InputOption & ConnectOptions<Initial>): StreamConnection<Value | Initial>;
145
+ }
146
+ /**
147
+ * A channel callable's `connect()`.
148
+ *
149
+ * @typeParam InputOption - The `input` option the channel takes.
150
+ * @typeParam Value - The values its handler yields.
151
+ * @typeParam Sent - The messages its `message` schema accepts.
152
+ */
153
+ export interface ChannelConnector<InputOption, Value, Sent> {
154
+ /**
155
+ * Runs the channel as signals, folding each value into the state with `reduce`.
156
+ *
157
+ * @remarks
158
+ * Call it in an injection context, such as a field initializer. It connects in the browser
159
+ * after the next render, never on the server, and never keeps the app from becoming
160
+ * stable. Destroying the injection context closes the connection. It reads every value as
161
+ * it arrives, so sending never stalls it.
162
+ *
163
+ * @param options - The input, the initial state and the fold.
164
+ * @returns The connection.
165
+ */
166
+ <State>(options: InputOption & ReducingConnectOptions<Value, State>): Connection<State, Sent>;
167
+ /**
168
+ * Runs the channel as signals: the state is the latest value.
169
+ *
170
+ * @remarks
171
+ * As the `reduce` form.
172
+ *
173
+ * @param options - The input and what to show before the first value.
174
+ * @returns The connection.
175
+ */
176
+ <Initial>(options: InputOption & ConnectOptions<Initial>): Connection<Value | Initial, Sent>;
177
+ }
178
+ /** What `connect` opens one call with. Internal. */
179
+ export type Opener = (input: unknown, signal: AbortSignal, opened: () => void) => AsyncIterable<unknown> | Channel<unknown, unknown>;
180
+ interface RuntimeOptions {
181
+ readonly input?: () => unknown;
182
+ readonly initial: () => unknown;
183
+ readonly reduce?: (state: unknown, value: unknown) => unknown;
184
+ }
185
+ /**
186
+ * Follows a stream or channel as signals. Internal: generated callables expose it as
187
+ * `connect()`.
188
+ *
189
+ * @remarks
190
+ * Must run in an injection context. On the server it never connects: status stays `"idle"`
191
+ * and `value` is `initial()`. In the browser it connects after the next render, and again
192
+ * whenever `input` changes; each connection reads every value as it arrives. A connection
193
+ * closed for a new input or by the injection context's destruction doesn't change `status`
194
+ * or `error`.
195
+ *
196
+ * @param open - Opens one call.
197
+ * @param options - The `connect()` options.
198
+ * @returns The connection; `send` delegates to the open channel.
199
+ */
200
+ export declare function connect(open: Opener, { input, initial, reduce }: RuntimeOptions): Connection<unknown, unknown>;
201
+ export {};