@snap-rail/protocol 0.0.0-stage → 0.1.3

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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,54 @@
1
+ //#region lib/types/contract.js
2
+ /**
3
+ * Single-source wire contracts: one {@link defineContract} declaration per
4
+ * domain yields everything a domain's wire surface needs — the rows that
5
+ * merge into the protocol's open maps (via `interface RpcMethodMap extends
6
+ * MethodRows<typeof contract> {}` in the same module), the request schemas
7
+ * that ride with registration, and the frame payload schemas for
8
+ * registration and client parsing. The hand-written trio (Api interface +
9
+ * merge rows + schema table) said the same thing three times; here it is
10
+ * said once.
11
+ *
12
+ * A row's response value type is declared through the phantom `res` field
13
+ * (the builders lie about it so the type is reachable without a runtime
14
+ * schema); runtime rows carry only `request` and, optionally, `response`.
15
+ *
16
+ * @module @snap-rail/protocol/contract
17
+ */
18
+ /**
19
+ * Open one method row: the request schema is mandatory (it is the
20
+ * trust-boundary validator), the response value type is declared through
21
+ * `.ret<T>()` or, with a runtime schema, `.res(schema)`.
22
+ *
23
+ * @param request - the request schema.
24
+ */
25
+ function method(request) {
26
+ return {
27
+ ret() {
28
+ return { request };
29
+ },
30
+ res(response) {
31
+ return {
32
+ request,
33
+ response
34
+ };
35
+ }
36
+ };
37
+ }
38
+ /**
39
+ * Declare one domain's wire surface. Keys are full wire names; every
40
+ * conventional call site passes both tables (`methods: {}` when the domain
41
+ * only pushes frames, `frames: {}` when it only serves methods).
42
+ *
43
+ * @param domain - the wire domain (diagnostic metadata; claims are separate).
44
+ * @param def - the method and frame tables.
45
+ */
46
+ function defineContract(domain, def) {
47
+ return {
48
+ domain,
49
+ methods: def.methods,
50
+ frames: def.frames
51
+ };
52
+ }
53
+ //#endregion
54
+ export { defineContract, method };
package/lib/index.js ADDED
@@ -0,0 +1,182 @@
1
+ import { defineContract, method } from "./contract.js";
2
+ import { RpcBusinessError, RpcId, err, isRpcError, ok } from "./rpc.js";
3
+ import { z } from "zod";
4
+ //#region lib/types/surfaces.js
5
+ /**
6
+ * The surface vocabulary: one renderer window role. `main` is the operator
7
+ * window (the app's only always-present surface); `ball` is the auxiliary
8
+ * always-on-top surface a plugin drives through the Shell seam — the floating
9
+ * ball.
10
+ *
11
+ * A surface is an identity, not a layout. Every surface boots the same
12
+ * renderer with its own client entry (`snapRail.client.surfaces`) and its own
13
+ * seed set; a plugin face binds to exactly one surface and reads
14
+ * `ctx.client.surface` to know which. Auxiliary surfaces never subscribe to
15
+ * equipment points directly — they consume host-aggregated frames, because a
16
+ * hidden surface must not keep a data path alive and a shown one must not
17
+ * need a second subscription graph.
18
+ *
19
+ * The whitelist is closed on purpose: a plugin may not name an arbitrary URL
20
+ * or spawn an arbitrary window — the Shell owns every window and only these
21
+ * two roles exist.
22
+ *
23
+ * @module @snap-rail/protocol/surfaces
24
+ */
25
+ /** Every surface id, in boot order (`main` first). */
26
+ const SURFACE_IDS = ["main", "ball"];
27
+ /** The always-on-top auxiliary surfaces: windows the Shell creates lazily. */
28
+ const AUX_SURFACE_IDS = ["ball"];
29
+ /**
30
+ * Whether a wire value names a surface.
31
+ *
32
+ * @param value - the candidate (any wire value).
33
+ * @returns true when the value is a {@link SurfaceId}.
34
+ */
35
+ function isSurfaceId(value) {
36
+ return typeof value === "string" && SURFACE_IDS.includes(value);
37
+ }
38
+ /**
39
+ * Whether a wire value names an auxiliary surface.
40
+ *
41
+ * @param value - the candidate (any wire value).
42
+ * @returns true when the value is an {@link AuxSurfaceId}.
43
+ */
44
+ function isAuxSurfaceId(value) {
45
+ return typeof value === "string" && AUX_SURFACE_IDS.includes(value);
46
+ }
47
+ //#endregion
48
+ //#region lib/types/schemas.js
49
+ /**
50
+ * Envelope validation at the trust boundary: the type/rpcId/method
51
+ * structure of every inbound message. Per-method payload schemas travel
52
+ * with each registration (`ctx.rpc.method`) — there is no central method
53
+ * table. Host responses are produced by trusted code and are not
54
+ * re-validated in phase 1.
55
+ *
56
+ * @module @snap-rail/protocol/schemas
57
+ */
58
+ const rpcIdSchema = z.string().min(1).transform(RpcId);
59
+ const clientRequestShape = z.object({
60
+ type: z.literal("client-request"),
61
+ rpcId: rpcIdSchema,
62
+ method: z.string().min(1),
63
+ payload: z.unknown()
64
+ });
65
+ /**
66
+ * Parse an inbound client request envelope.
67
+ * @param raw - the untrusted wire value.
68
+ * @returns the parsed envelope with a branded rpcId.
69
+ * @throws a zod error naming every envelope violation.
70
+ */
71
+ function parseClientRequest(raw) {
72
+ return clientRequestShape.parse(raw);
73
+ }
74
+ const serverRequestShape = z.object({
75
+ type: z.literal("server-request"),
76
+ rpcId: rpcIdSchema,
77
+ method: z.string().min(1),
78
+ payload: z.unknown()
79
+ });
80
+ /**
81
+ * Parse an inbound host frame on a client.
82
+ * @param raw - the untrusted wire value.
83
+ * @returns the parsed frame.
84
+ * @throws a zod error naming every envelope violation.
85
+ */
86
+ function parseServerRequest(raw) {
87
+ return serverRequestShape.parse(raw);
88
+ }
89
+ //#endregion
90
+ //#region lib/types/client.js
91
+ /**
92
+ * The client carrier family: protocol invariants live in the base class;
93
+ * platform differences are transport aspects only. Business failures come
94
+ * back as `RpcResult` (never thrown here); transport failures are thrown by
95
+ * the carrier; the two layers never mix.
96
+ *
97
+ * @module @snap-rail/protocol/client
98
+ */
99
+ /**
100
+ * Mint a fresh rpc id. `globalThis.crypto` keeps the client family free of
101
+ * Node builtins so the same code bundles into the browser renderer.
102
+ */
103
+ function freshId() {
104
+ return globalThis.crypto.randomUUID();
105
+ }
106
+ /** A thrown transport failure; carries no business semantics. */
107
+ var RpcTransportError = class extends Error {
108
+ constructor(message, options) {
109
+ super(message, options);
110
+ this.name = "RpcTransportError";
111
+ }
112
+ };
113
+ /**
114
+ * Protocol client base. Subclasses supply the unary transport; rpcId minting
115
+ * and the echo check live here and nowhere else.
116
+ */
117
+ var AbstractApiClient = class {
118
+ async call(method, payload) {
119
+ const rpcId = RpcId(freshId());
120
+ const response = await this.transport({
121
+ type: "client-request",
122
+ rpcId,
123
+ method,
124
+ payload
125
+ });
126
+ if (response.type !== "server-response") throw new RpcTransportError(`expected a server-response, received ${String(response.type)}`);
127
+ if (response.rpcId !== rpcId) throw new RpcTransportError(`rpcId echo mismatch: sent ${rpcId}, received ${response.rpcId}`);
128
+ return response.result;
129
+ }
130
+ };
131
+ /**
132
+ * The isomorphic carrier: runs the real protocol against an injected handler
133
+ * with no IPC at all. Tests exercise the exact envelope/result path a real
134
+ * carrier travels.
135
+ */
136
+ var InProcessApiClient = class extends AbstractApiClient {
137
+ queue = [];
138
+ resolvers = [];
139
+ finished = false;
140
+ transport;
141
+ /**
142
+ * @param handler - the gateway-side unary entry (`handleClientRequest`).
143
+ */
144
+ constructor(handler) {
145
+ super();
146
+ this.transport = handler;
147
+ }
148
+ /** Deliver a host frame into the client's mux stream (test/pump side). */
149
+ pushFrame(frame) {
150
+ const resolver = this.resolvers.shift();
151
+ if (resolver !== void 0) resolver({
152
+ done: false,
153
+ value: frame
154
+ });
155
+ else this.queue.push(frame);
156
+ }
157
+ /** The mux stream as an async iterable; ends when {@link end} is called. */
158
+ frames() {
159
+ return { [Symbol.asyncIterator]: () => ({ next: () => {
160
+ const frame = this.queue.shift();
161
+ if (frame !== void 0) return Promise.resolve({
162
+ done: false,
163
+ value: frame
164
+ });
165
+ if (this.finished) return Promise.resolve({
166
+ done: true,
167
+ value: void 0
168
+ });
169
+ return new Promise((resolve) => this.resolvers.push(resolve));
170
+ } }) };
171
+ }
172
+ /** End the mux stream; pending and future iterations finish. */
173
+ end() {
174
+ this.finished = true;
175
+ for (const resolve of this.resolvers.splice(0)) resolve({
176
+ done: true,
177
+ value: void 0
178
+ });
179
+ }
180
+ };
181
+ //#endregion
182
+ export { AUX_SURFACE_IDS, AbstractApiClient, InProcessApiClient, RpcBusinessError, RpcId, RpcTransportError, SURFACE_IDS, defineContract, err, isAuxSurfaceId, isRpcError, isSurfaceId, method, ok, parseClientRequest, parseServerRequest };
package/lib/rpc.js ADDED
@@ -0,0 +1,67 @@
1
+ //#region lib/types/rpc.js
2
+ /**
3
+ * The four-quadrant message model: every logical message is classified by
4
+ * "who initiates × request/response", decoupled from the physical channel.
5
+ * Swapping the carrier (in-process, Electron IPC, a future WebSocket) leaves
6
+ * the quadrants unchanged; direction is a property of the message, never
7
+ * inferred from the channel.
8
+ *
9
+ * rpcId discipline: whoever initiates mints; a response always echoes the
10
+ * corresponding request's rpcId and never mints a new id. Pure-push frames
11
+ * mint a fresh id per push; answerable frames (a future approval/question
12
+ * family) reuse one stable id until answered.
13
+ *
14
+ * @module @snap-rail/protocol/rpc
15
+ */
16
+ /** Mint an rpc identifier. Only carriers and frame pumps mint; business code never does. */
17
+ function RpcId(value) {
18
+ return value;
19
+ }
20
+ /**
21
+ * Construct a success result.
22
+ * @param value - the method's return value.
23
+ */
24
+ function ok(value) {
25
+ return {
26
+ ok: true,
27
+ value
28
+ };
29
+ }
30
+ /**
31
+ * Construct a business-error result.
32
+ * @param code - the error code.
33
+ * @param details - code-specific details (required).
34
+ */
35
+ function err(code, details) {
36
+ return {
37
+ ok: false,
38
+ error: {
39
+ code,
40
+ details
41
+ }
42
+ };
43
+ }
44
+ /**
45
+ * Thrown by method handlers to fail with a business error; the gateway
46
+ * converts it into `{ ok: false, error }` on the wire. Carrying it as a
47
+ * throw keeps handler happy paths free of result wrapping.
48
+ */
49
+ var RpcBusinessError = class extends Error {
50
+ error;
51
+ constructor(error) {
52
+ super(`rpc business error: ${error.code}`);
53
+ this.error = error;
54
+ this.name = "RpcBusinessError";
55
+ }
56
+ };
57
+ /**
58
+ * Type guard narrowing an unknown value to {@link RpcError}.
59
+ * @param value - candidate error.
60
+ */
61
+ function isRpcError(value) {
62
+ if (value === null || typeof value !== "object") return false;
63
+ const record = value;
64
+ return typeof record.code === "string" && "details" in record;
65
+ }
66
+ //#endregion
67
+ export { RpcBusinessError, RpcId, err, isRpcError, ok };
@@ -0,0 +1,66 @@
1
+ /**
2
+ * The client carrier family: protocol invariants live in the base class;
3
+ * platform differences are transport aspects only. Business failures come
4
+ * back as `RpcResult` (never thrown here); transport failures are thrown by
5
+ * the carrier; the two layers never mix.
6
+ *
7
+ * @module @snap-rail/protocol/client
8
+ */
9
+ import type { ClientRequest, RpcResult, ServerRequest, ServerResponse } from './rpc.ts';
10
+ import type { MethodName, RequestPayload, ResponseValue } from './methods.ts';
11
+ /** A thrown transport failure; carries no business semantics. */
12
+ export declare class RpcTransportError extends Error {
13
+ constructor(message: string, options?: ErrorOptions);
14
+ }
15
+ /** Signature of the raw unary transport: send one full-form request, get its full-form response. */
16
+ export type UnaryTransport = (request: ClientRequest) => Promise<ServerResponse>;
17
+ /**
18
+ * Protocol client base. Subclasses supply the unary transport; rpcId minting
19
+ * and the echo check live here and nowhere else.
20
+ */
21
+ export declare abstract class AbstractApiClient {
22
+ /**
23
+ * The transport aspect: deliver one full-form client request and settle
24
+ * with its full-form server response.
25
+ */
26
+ protected abstract transport: UnaryTransport;
27
+ /**
28
+ * Call a unary method with the business payload directly; the carrier
29
+ * mints the rpcId and wraps the envelope.
30
+ *
31
+ * Two overloads, one open-world rule: a method known to {@link RpcMethodMap}
32
+ * (directly or via the caller's own declaration merge) is fully typed;
33
+ * any other method name is accepted as `(string, unknown)` — the caller
34
+ * owns the payload contract in that position. The same dual shape the
35
+ * cordis service surface uses: augmentation is opt-in, never required.
36
+ *
37
+ * @param method - the wire method name.
38
+ * @param payload - the business payload.
39
+ * @returns the business result; `ok: false` is a normal outcome, not an
40
+ * exception. Transport failures and rpcId echo mismatches throw.
41
+ */
42
+ call<K extends MethodName>(method: K, payload: RequestPayload<K>): Promise<RpcResult<ResponseValue<K>>>;
43
+ call(method: string, payload: unknown): Promise<RpcResult<unknown>>;
44
+ }
45
+ /**
46
+ * The isomorphic carrier: runs the real protocol against an injected handler
47
+ * with no IPC at all. Tests exercise the exact envelope/result path a real
48
+ * carrier travels.
49
+ */
50
+ export declare class InProcessApiClient extends AbstractApiClient {
51
+ private readonly queue;
52
+ private resolvers;
53
+ private finished;
54
+ protected readonly transport: UnaryTransport;
55
+ /**
56
+ * @param handler - the gateway-side unary entry (`handleClientRequest`).
57
+ */
58
+ constructor(handler: (request: ClientRequest) => Promise<ServerResponse>);
59
+ /** Deliver a host frame into the client's mux stream (test/pump side). */
60
+ pushFrame(frame: ServerRequest): void;
61
+ /** The mux stream as an async iterable; ends when {@link end} is called. */
62
+ frames(): AsyncIterable<ServerRequest>;
63
+ /** End the mux stream; pending and future iterations finish. */
64
+ end(): void;
65
+ }
66
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1,93 @@
1
+ /**
2
+ * The client carrier family: protocol invariants live in the base class;
3
+ * platform differences are transport aspects only. Business failures come
4
+ * back as `RpcResult` (never thrown here); transport failures are thrown by
5
+ * the carrier; the two layers never mix.
6
+ *
7
+ * @module @snap-rail/protocol/client
8
+ */
9
+ import { RpcId } from "./rpc.js";
10
+ /**
11
+ * Mint a fresh rpc id. `globalThis.crypto` keeps the client family free of
12
+ * Node builtins so the same code bundles into the browser renderer.
13
+ */
14
+ function freshId() {
15
+ return globalThis.crypto.randomUUID();
16
+ }
17
+ /** A thrown transport failure; carries no business semantics. */
18
+ export class RpcTransportError extends Error {
19
+ constructor(message, options) {
20
+ super(message, options);
21
+ this.name = 'RpcTransportError';
22
+ }
23
+ }
24
+ /**
25
+ * Protocol client base. Subclasses supply the unary transport; rpcId minting
26
+ * and the echo check live here and nowhere else.
27
+ */
28
+ export class AbstractApiClient {
29
+ async call(method, payload) {
30
+ const rpcId = RpcId(freshId());
31
+ const response = await this.transport({
32
+ type: 'client-request',
33
+ rpcId,
34
+ method,
35
+ payload,
36
+ });
37
+ if (response.type !== 'server-response') {
38
+ throw new RpcTransportError(`expected a server-response, received ${String(response.type)}`);
39
+ }
40
+ if (response.rpcId !== rpcId) {
41
+ throw new RpcTransportError(`rpcId echo mismatch: sent ${rpcId}, received ${response.rpcId}`);
42
+ }
43
+ return response.result;
44
+ }
45
+ }
46
+ /**
47
+ * The isomorphic carrier: runs the real protocol against an injected handler
48
+ * with no IPC at all. Tests exercise the exact envelope/result path a real
49
+ * carrier travels.
50
+ */
51
+ export class InProcessApiClient extends AbstractApiClient {
52
+ queue = [];
53
+ resolvers = [];
54
+ finished = false;
55
+ transport;
56
+ /**
57
+ * @param handler - the gateway-side unary entry (`handleClientRequest`).
58
+ */
59
+ constructor(handler) {
60
+ super();
61
+ this.transport = handler;
62
+ }
63
+ /** Deliver a host frame into the client's mux stream (test/pump side). */
64
+ pushFrame(frame) {
65
+ const resolver = this.resolvers.shift();
66
+ if (resolver !== undefined)
67
+ resolver({ done: false, value: frame });
68
+ else
69
+ this.queue.push(frame);
70
+ }
71
+ /** The mux stream as an async iterable; ends when {@link end} is called. */
72
+ frames() {
73
+ return {
74
+ [Symbol.asyncIterator]: () => ({
75
+ next: () => {
76
+ const frame = this.queue.shift();
77
+ if (frame !== undefined)
78
+ return Promise.resolve({ done: false, value: frame });
79
+ if (this.finished)
80
+ return Promise.resolve({ done: true, value: undefined });
81
+ return new Promise(resolve => this.resolvers.push(resolve));
82
+ },
83
+ }),
84
+ };
85
+ }
86
+ /** End the mux stream; pending and future iterations finish. */
87
+ end() {
88
+ this.finished = true;
89
+ for (const resolve of this.resolvers.splice(0))
90
+ resolve({ done: true, value: undefined });
91
+ }
92
+ }
93
+ //# sourceMappingURL=client.js.map