@avatarsd-llc/libtracer-client 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,87 @@
1
+ # @avatarsd-llc/libtracer-client (EXPERIMENTAL)
2
+
3
+ The libtracer **client SDK** the strawberry web-UI builds against
4
+ ([#56](https://github.com/avatarsd-llc/libtracer/issues/56),
5
+ [ADR-0034](../../../../docs/adr/0034-typescript-client-sdk.md) /
6
+ [ADR-0035](../../../../docs/adr/0035-implementing-rfc-0004-remote-operation-addressing.md)).
7
+ It composes the cross-validated wire codec (`@avatarsd-llc/libtracer`) over an
8
+ **injected** transport seam (`@avatarsd-llc/libtracer-ws`'s `TransportWs` satisfies
9
+ it structurally), so it runs in the browser or Node and is testable against an
10
+ in-memory fake with no socket.
11
+
12
+ > **Experimental — `0.1.0`, pre-1.0.** The client speaks the
13
+ > [RFC-0004](../../../../docs/spec/rfcs/0004-remote-operation-addressing.md)
14
+ > remote-operation envelope (`FWD` / `FIELD`) the v1 spec §3 fast-tracks: a
15
+ > path-addressed `read` / `write` / `await` / `readField` / `subscribe`, each a
16
+ > `FWD` frame whose source-routed `FWD{REPLY}` is decoded back. Error-reply codes
17
+ > are **provisional** until the ERROR registry
18
+ > ([#8](https://github.com/avatarsd-llc/libtracer/issues/8)) pins them.
19
+
20
+ ## What it does
21
+
22
+ ```ts
23
+ import { LibtracerClient, encodeValue } from '@avatarsd-llc/libtracer-client';
24
+ import { TransportWs } from '@avatarsd-llc/libtracer-ws';
25
+
26
+ const transport = new TransportWs('ws://robot.local:9000');
27
+ await transport.connect();
28
+ const client = new LibtracerClient(transport);
29
+
30
+ // Path-addressed remote operations over RFC-0004 FWD — each resolves its FWD{REPLY}:
31
+ const temp = await client.read('/sensor/temp'); // -> VALUE TLV
32
+ await client.write('/sensor/temp', encodeValue(new Uint8Array([0x01])));
33
+ const next = await client.await_('/sensor/temp', 1_000_000_000n); // block for the next write (1 s)
34
+ const subs = await client.readField('/sensor/temp', ':subscribers[]'); // -> POINT of SUBSCRIBER slots
35
+
36
+ // subscribe = a field-write of a SUBSCRIBER into :subscribers[]; deliveries fire the handler.
37
+ const unsubscribe = await client.subscribe('/sensor/temp', (value) => render(value));
38
+ unsubscribe(); // local detach
39
+
40
+ // A kind=ERROR reply rejects with a typed FwdError (.code / .codeName, e.g. "NOT_FOUND").
41
+ client.onError((err) => console.error('inbound decode error', err));
42
+ ```
43
+
44
+ The pure builders (the exact bytes, transport-free) are also exported — the FWD /
45
+ FIELD envelope builders and the payload builders, each pinned to a conformance
46
+ vector:
47
+
48
+ ```ts
49
+ import { encodeFwd, encodeField, FWD_OP, encodeSubscriber } from '@avatarsd-llc/libtracer-client';
50
+
51
+ encodeSubscriber(['sensor', 'temp']); // === subscriber-path vector
52
+ encodeFwd({ op: FWD_OP.READ, dst: ['sensor', 'temp'], src: ['client'] }); // === fwd-read vector
53
+ encodeField(':subscribers[]'); // === field-append vector
54
+ ```
55
+
56
+ ## Surfaces
57
+
58
+ | Surface | Status | Pinned by |
59
+ | --- | --- | --- |
60
+ | `read` / `write` / `await_` / `readField` / `subscribe` over `FWD` | **implemented** (RFC-0004) | `fwd-read`, `fwd-write-value`, `fwd-await-timeout`, `fwd-write-subscriber-field` |
61
+ | `encodeFwd` / `encodeField` builders + `decodeFwd` | **implemented** | `fwd-*`, `field-*`, `fwd-reply-*` |
62
+ | `encodeValue` / `encodeSubscriber` / `encodePath` payload builders | **implemented** | `value-bool-true`, `value-ll-u32`, `value-ts-abs`, `subscriber-path`, `path-sensor-temp` |
63
+ | inbound VALUE delivery (FWD{WRITE} / bare / ROUTER-shed) | **implemented** | `router-wrapped` + all vectors |
64
+ | typed `FwdError` on `kind=ERROR` reply | **implemented** (codes provisional) | `fwd-reply-error`; ERROR registry (#8) pins the code set |
65
+
66
+ ## Dependencies
67
+
68
+ `@avatarsd-llc/libtracer` is a required `peerDependency` (the cross-validated
69
+ codec — [ADR-0033](../../../../docs/adr/0033-npm-subpackage-monorepo.md)).
70
+ `@avatarsd-llc/libtracer-ws` is an **optional** peer (the seam is structural; the
71
+ client never imports it — inject any `{ send, onFrame }`). ESM-only, `node >= 18`.
72
+
73
+ ## Tests
74
+
75
+ ```sh
76
+ npm run build && npm test # from bindings/typescript/
77
+ ```
78
+
79
+ - `test/vectors.test.mjs` — every outbound builder (`encodeValue`/`encodeSubscriber`/
80
+ `encodePath`/`encodeFwd`/`encodeField`) matches its conformance vector
81
+ byte-for-byte; `decodeFwd` parses the `fwd-reply-*` vectors.
82
+ - `test/roundtrip.test.mjs` — mock-transport round-trip: the exact `FWD` bytes each
83
+ op emits, REPLY-resolves-the-op / ERROR-rejects, injected deliveries, and a real
84
+ `TransportWs` echo.
85
+ - `test/interop.test.mjs` — **end-to-end** against a live C++ `fwd_node_server` over
86
+ a real socket (all five ops, incl. a live subscribe delivery). Guarded on
87
+ `LIBTRACER_FWD_NODE_SERVER`; the CI `fwd-interop` job builds the binary and runs it.
@@ -0,0 +1,139 @@
1
+ import type { Tlv } from '@avatarsd-llc/libtracer';
2
+ import type { ValueOptions, SubscriberOptions } from './tlv.js';
3
+ import type { FieldLevel } from './fwd.js';
4
+ /**
5
+ * The minimal connection seam the client drives. `TransportWs` from
6
+ * `@avatarsd-llc/libtracer-ws` satisfies this structurally (so the client never
7
+ * imports it — keeping the transport an optional peer).
8
+ */
9
+ export interface ClientTransport {
10
+ /** Put one complete libtracer TLV frame on the wire. */
11
+ send(frame: Uint8Array): void;
12
+ /** Register (or clear with `null`) the inbound-frame receiver. */
13
+ onFrame(receiver: ((bytes: Uint8Array) => void) | null): void;
14
+ }
15
+ /** A delivered VALUE: its opaque payload bytes plus the decoded TLV it came from. */
16
+ export type ValueHandler = (value: Uint8Array, tlv: Tlv) => void;
17
+ /** Detach a {@link LibtracerClient.subscribe} handler (a local detach — see its docs). */
18
+ export type Unsubscribe = () => void;
19
+ /** Options for {@link LibtracerClient}. */
20
+ export interface ClientOptions {
21
+ /**
22
+ * The originator's reply endpoint, as path segments — the `src` route seeded on
23
+ * every outbound FWD and the SUBSCRIBER `target` on a subscribe. Over a single
24
+ * ws hop the responder replies back over the same link, so any 1+-segment path
25
+ * is fine; default `["client"]`.
26
+ */
27
+ readonly replyEndpoint?: string[];
28
+ }
29
+ /**
30
+ * A `kind=ERROR` FWD reply, surfaced as a typed rejection. `.code` is the wire
31
+ * ERROR byte (see {@link FWD_ERROR}); `.codeName` its symbolic name.
32
+ */
33
+ export declare class FwdError extends Error {
34
+ /** The wire ERROR code (a {@link FWD_ERROR} value). */
35
+ readonly code: number;
36
+ /** The symbolic ERROR name (e.g. `"NOT_FOUND"`, `"TIMEOUT"`). */
37
+ readonly codeName: string;
38
+ /** @param code the wire ERROR code carried in the reply's `STATUS{ ERROR u8 }`. */
39
+ constructor(code: number);
40
+ }
41
+ /**
42
+ * A WebSocket/transport-agnostic libtracer client over the RFC-0004 `FWD` plane.
43
+ *
44
+ * Construct over any {@link ClientTransport}; issue {@link read} / {@link write} /
45
+ * {@link await_} / {@link readField} (resolving the responder's FWD{REPLY}), or
46
+ * {@link subscribe} to register a SUBSCRIBER and receive its deliveries. Inbound
47
+ * decode errors are routed to {@link onError}, never thrown across the transport's
48
+ * receive callback.
49
+ */
50
+ export declare class LibtracerClient {
51
+ private readonly transport;
52
+ private readonly replyEndpoint;
53
+ private readonly valueHandlers;
54
+ private readonly pending;
55
+ private errorHandler;
56
+ /**
57
+ * @param transport the injected connection seam (e.g. a connected `TransportWs`).
58
+ * @param options optional reply-endpoint override (default `["client"]`).
59
+ */
60
+ constructor(transport: ClientTransport, options?: ClientOptions);
61
+ /**
62
+ * Register a handler for inbound VALUE deliveries. A delivery is a FWD{WRITE}
63
+ * (delivery-is-a-write, RFC-0004 §D); a bare VALUE or a single ROUTER wrapper is
64
+ * also accepted. Multiple handlers may be registered; each receives every delivery.
65
+ */
66
+ onValue(handler: ValueHandler): void;
67
+ /** Register the sink for inbound decode failures and other client-side errors. */
68
+ onError(handler: (err: Error) => void): void;
69
+ /** Decode one inbound frame: correlate a REPLY, deliver a write, or shed/deliver a VALUE. */
70
+ private dispatch;
71
+ private deliver;
72
+ private emitError;
73
+ /** Send a one-shot FWD and resolve its FWD{REPLY} (FIFO correlation). */
74
+ private request;
75
+ /** Turn a RESULT reply into its payload TLV; throw {@link FwdError} on ERROR. */
76
+ private result;
77
+ /**
78
+ * Read a remote vertex's value: `FWD{ op=READ, dst=path, src=<reply-ep> }`.
79
+ *
80
+ * @param path the destination path (a `/`-string like `"/sensor/temp"`, or segments)
81
+ * @returns the RESULT's value TLV (decoded)
82
+ * @throws {FwdError} when the responder replies `kind=ERROR` (e.g. NOT_FOUND)
83
+ */
84
+ read(path: string | string[]): Promise<Tlv>;
85
+ /**
86
+ * Read a remote vertex's `:field`: `FWD{ op=READ, dst=path, FIELD=selector, src=… }`.
87
+ * A whole-array field (e.g. `:subscribers[]`) resolves to a POINT of the slot TLVs.
88
+ *
89
+ * @param path the destination path (string or segments)
90
+ * @param selector the `:field` string (e.g. `":subscribers[]"`) or pre-parsed levels
91
+ * @returns the RESULT's payload TLV (a slot TLV, or a POINT for a whole array)
92
+ * @throws {FwdError} when the responder replies `kind=ERROR`
93
+ */
94
+ readField(path: string | string[], selector: string | FieldLevel[]): Promise<Tlv>;
95
+ /**
96
+ * Write a value to a remote vertex: `FWD{ op=WRITE, dst=path, src=…, payload }`.
97
+ *
98
+ * @param path the destination path (string or segments)
99
+ * @param valueTLV a complete VALUE TLV's bytes (e.g. from {@link encodeValue})
100
+ * @returns once the responder acks `kind=RESULT`
101
+ * @throws {FwdError} when the responder replies `kind=ERROR`
102
+ */
103
+ write(path: string | string[], valueTLV: Uint8Array): Promise<void>;
104
+ /**
105
+ * Block for the next write to a remote vertex: `FWD{ op=AWAIT, dst=path, src=…,
106
+ * await_timeout? }`. Named `await_` because `await` is reserved; an `await`
107
+ * alias is installed on the prototype for the RFC-0004-spelled call site.
108
+ *
109
+ * @param path the destination path (string or segments)
110
+ * @param timeoutNs the await timeout in ns (absent ⇒ the responder's 1 s default)
111
+ * @returns the next write's value TLV
112
+ * @throws {FwdError} with code TIMEOUT when the responder's deadline elapses
113
+ */
114
+ await_(path: string | string[], timeoutNs?: bigint): Promise<Tlv>;
115
+ /**
116
+ * Subscribe to a remote producer: a `WRITE` of a `SUBSCRIBER{ target=<reply-ep> }`
117
+ * into `producer:subscribers[]` (RFC-0004 §C/§D — subscribe is a field-write).
118
+ * Once the responder acks, `handler` fires for every inbound VALUE delivery.
119
+ *
120
+ * SCOPE: this issues the SUBSCRIBER and receives VALUEs the producer directly
121
+ * delivers to this client's reply endpoint. Full standing-stream delivery
122
+ * additionally needs the producer auto-promote / flush seam (#136 / RFC-0004 §E)
123
+ * — out of scope for this client slice. `unsubscribe()` is a LOCAL detach: it
124
+ * stops firing `handler` but does not clear the remote slot (an indexed
125
+ * `:subscribers[N]` field-write, additive).
126
+ *
127
+ * @param producerPath the producer vertex path (string or segments)
128
+ * @param handler invoked with each inbound VALUE delivery
129
+ * @returns a function that locally detaches `handler`
130
+ * @throws {FwdError} when the subscribe-write is rejected
131
+ */
132
+ subscribe(producerPath: string | string[], handler: ValueHandler): Promise<Unsubscribe>;
133
+ /** {@link encodeValue} — the exact VALUE TLV bytes, independently of any transport. */
134
+ static encodeValue(value: Uint8Array, opts?: ValueOptions): Uint8Array;
135
+ /** {@link encodePath} — the exact PATH TLV bytes. */
136
+ static encodePath(segments: string[]): Uint8Array;
137
+ /** {@link encodeSubscriber} — the exact SUBSCRIBER TLV bytes. */
138
+ static encodeSubscriber(targetPath: string[], opts?: SubscriberOptions): Uint8Array;
139
+ }
package/dist/client.js ADDED
@@ -0,0 +1,277 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // SPDX-FileCopyrightText: Copyright 2026 avatarsd LLC
3
+ // LibtracerClient — the experimental browser/Node client SDK (#56, ADR-0034).
4
+ //
5
+ // It composes the cross-validated codec (@avatarsd-llc/libtracer) over an
6
+ // INJECTED transport seam (`@avatarsd-llc/libtracer-ws`'s TransportWs satisfies
7
+ // it structurally), so it is browser/Node-agnostic and testable against an
8
+ // in-memory fake with no live socket.
9
+ //
10
+ // Now that RFC-0004 fills spec §3 (the remote-operation envelope ADR-0034
11
+ // deferred), the client speaks the path-addressed higher operations over `FWD`:
12
+ // - read(path) — FWD{ op=READ, dst=path, src=<reply-ep> }
13
+ // - write(path, valueTLV) — FWD{ op=WRITE, dst=path, src=…, payload }
14
+ // - await(path, ns?) — FWD{ op=AWAIT, dst=path, src=…, await_timeout? }
15
+ // - readField(path, sel) — FWD{ op=READ, dst=path, FIELD=sel, src=… }
16
+ // - subscribe(prod, h) — FWD{ op=WRITE, dst=prod, FIELD=:subscribers[],
17
+ // src=…, payload=SUBSCRIBER{ target=<reply-ep> } }
18
+ // Each one-shot op sends a FWD and resolves the FWD{REPLY} the responder
19
+ // source-routes back (RESULT → the value, ERROR → a typed {@link FwdError}).
20
+ //
21
+ // Reply correlation is the transport's concern (RFC-0004 §D): over a single ws
22
+ // link the responder replies in request order, so a simple per-link FIFO of
23
+ // pending requests matches each REPLY to its request. `FWD` stays pure — no
24
+ // end-to-end correlation id.
25
+ import { TYPE, decode, CodecError } from '@avatarsd-llc/libtracer';
26
+ import { encodeValue, encodePath, encodeSubscriber } from './tlv.js';
27
+ import { FWD_OP, FWD_KIND, encodeFwd, parseFwdTlv, replyErrorCode, fwdErrorName } from './fwd.js';
28
+ /**
29
+ * A `kind=ERROR` FWD reply, surfaced as a typed rejection. `.code` is the wire
30
+ * ERROR byte (see {@link FWD_ERROR}); `.codeName` its symbolic name.
31
+ */
32
+ export class FwdError extends Error {
33
+ /** @param code the wire ERROR code carried in the reply's `STATUS{ ERROR u8 }`. */
34
+ constructor(code) {
35
+ const name = fwdErrorName(code);
36
+ super(`FWD reply ERROR ${name} (0x${code.toString(16).padStart(2, '0')})`);
37
+ this.name = 'FwdError';
38
+ this.code = code;
39
+ this.codeName = name;
40
+ }
41
+ }
42
+ /**
43
+ * A WebSocket/transport-agnostic libtracer client over the RFC-0004 `FWD` plane.
44
+ *
45
+ * Construct over any {@link ClientTransport}; issue {@link read} / {@link write} /
46
+ * {@link await_} / {@link readField} (resolving the responder's FWD{REPLY}), or
47
+ * {@link subscribe} to register a SUBSCRIBER and receive its deliveries. Inbound
48
+ * decode errors are routed to {@link onError}, never thrown across the transport's
49
+ * receive callback.
50
+ */
51
+ export class LibtracerClient {
52
+ /**
53
+ * @param transport the injected connection seam (e.g. a connected `TransportWs`).
54
+ * @param options optional reply-endpoint override (default `["client"]`).
55
+ */
56
+ constructor(transport, options = {}) {
57
+ this.valueHandlers = new Set();
58
+ this.pending = [];
59
+ this.errorHandler = null;
60
+ this.transport = transport;
61
+ this.replyEndpoint = [...(options.replyEndpoint ?? ['client'])];
62
+ transport.onFrame((bytes) => this.dispatch(bytes));
63
+ }
64
+ /* ---------------------------------------------------------- inbound --- */
65
+ /**
66
+ * Register a handler for inbound VALUE deliveries. A delivery is a FWD{WRITE}
67
+ * (delivery-is-a-write, RFC-0004 §D); a bare VALUE or a single ROUTER wrapper is
68
+ * also accepted. Multiple handlers may be registered; each receives every delivery.
69
+ */
70
+ onValue(handler) {
71
+ this.valueHandlers.add(handler);
72
+ }
73
+ /** Register the sink for inbound decode failures and other client-side errors. */
74
+ onError(handler) {
75
+ this.errorHandler = handler;
76
+ }
77
+ /** Decode one inbound frame: correlate a REPLY, deliver a write, or shed/deliver a VALUE. */
78
+ dispatch(bytes) {
79
+ let tlv;
80
+ try {
81
+ tlv = decode(bytes);
82
+ }
83
+ catch (err) {
84
+ this.emitError(err instanceof Error ? err : new CodecError(String(err)));
85
+ return;
86
+ }
87
+ if (tlv.type === TYPE.FWD) {
88
+ let parsed;
89
+ try {
90
+ parsed = parseFwdTlv(tlv);
91
+ }
92
+ catch (err) {
93
+ this.emitError(err instanceof Error ? err : new Error(String(err)));
94
+ return;
95
+ }
96
+ if (parsed.op === FWD_OP.REPLY) {
97
+ const waiter = this.pending.shift();
98
+ if (waiter)
99
+ waiter.resolve(parsed);
100
+ return;
101
+ }
102
+ // A delivery IS a FWD{WRITE} (RFC-0004 §D): deliver its VALUE payload.
103
+ if (parsed.op === FWD_OP.WRITE && parsed.payload && parsed.payload.type === TYPE.VALUE) {
104
+ this.deliver(parsed.payload);
105
+ }
106
+ return;
107
+ }
108
+ // Non-FWD frame: shed exactly one ROUTER envelope, then deliver a VALUE
109
+ // (the directly-delivered / bridge-mounted path, ADR-0034 inbound rule).
110
+ const data = tlv.type === TYPE.ROUTER && tlv.children.length > 0 ? tlv.children[tlv.children.length - 1] : tlv;
111
+ if (data.type === TYPE.VALUE)
112
+ this.deliver(data);
113
+ }
114
+ deliver(value) {
115
+ for (const handler of this.valueHandlers)
116
+ handler(value.payload, value);
117
+ }
118
+ emitError(err) {
119
+ if (this.errorHandler)
120
+ this.errorHandler(err);
121
+ }
122
+ /** Send a one-shot FWD and resolve its FWD{REPLY} (FIFO correlation). */
123
+ request(frame) {
124
+ return new Promise((resolve, reject) => {
125
+ this.pending.push({ resolve, reject });
126
+ try {
127
+ this.transport.send(frame);
128
+ }
129
+ catch (err) {
130
+ this.pending.pop();
131
+ reject(err instanceof Error ? err : new Error(String(err)));
132
+ }
133
+ });
134
+ }
135
+ /** Turn a RESULT reply into its payload TLV; throw {@link FwdError} on ERROR. */
136
+ result(reply) {
137
+ if (reply.kind === FWD_KIND.ERROR)
138
+ throw new FwdError(replyErrorCode(reply));
139
+ return reply.payload;
140
+ }
141
+ /* --------------------------------------------------------- one-shot --- */
142
+ /**
143
+ * Read a remote vertex's value: `FWD{ op=READ, dst=path, src=<reply-ep> }`.
144
+ *
145
+ * @param path the destination path (a `/`-string like `"/sensor/temp"`, or segments)
146
+ * @returns the RESULT's value TLV (decoded)
147
+ * @throws {FwdError} when the responder replies `kind=ERROR` (e.g. NOT_FOUND)
148
+ */
149
+ async read(path) {
150
+ const reply = await this.request(encodeFwd({ op: FWD_OP.READ, dst: splitPath(path), src: this.replyEndpoint }));
151
+ const value = this.result(reply);
152
+ if (!value)
153
+ throw new FwdError(0); // RESULT with no payload — malformed read reply
154
+ return value;
155
+ }
156
+ /**
157
+ * Read a remote vertex's `:field`: `FWD{ op=READ, dst=path, FIELD=selector, src=… }`.
158
+ * A whole-array field (e.g. `:subscribers[]`) resolves to a POINT of the slot TLVs.
159
+ *
160
+ * @param path the destination path (string or segments)
161
+ * @param selector the `:field` string (e.g. `":subscribers[]"`) or pre-parsed levels
162
+ * @returns the RESULT's payload TLV (a slot TLV, or a POINT for a whole array)
163
+ * @throws {FwdError} when the responder replies `kind=ERROR`
164
+ */
165
+ async readField(path, selector) {
166
+ const reply = await this.request(encodeFwd({ op: FWD_OP.READ, dst: splitPath(path), field: selector, src: this.replyEndpoint }));
167
+ const value = this.result(reply);
168
+ if (!value)
169
+ throw new FwdError(0);
170
+ return value;
171
+ }
172
+ /**
173
+ * Write a value to a remote vertex: `FWD{ op=WRITE, dst=path, src=…, payload }`.
174
+ *
175
+ * @param path the destination path (string or segments)
176
+ * @param valueTLV a complete VALUE TLV's bytes (e.g. from {@link encodeValue})
177
+ * @returns once the responder acks `kind=RESULT`
178
+ * @throws {FwdError} when the responder replies `kind=ERROR`
179
+ */
180
+ async write(path, valueTLV) {
181
+ const reply = await this.request(encodeFwd({ op: FWD_OP.WRITE, dst: splitPath(path), src: this.replyEndpoint, payload: valueTLV }));
182
+ this.result(reply); // throws on ERROR; RESULT carries no payload
183
+ }
184
+ /**
185
+ * Block for the next write to a remote vertex: `FWD{ op=AWAIT, dst=path, src=…,
186
+ * await_timeout? }`. Named `await_` because `await` is reserved; an `await`
187
+ * alias is installed on the prototype for the RFC-0004-spelled call site.
188
+ *
189
+ * @param path the destination path (string or segments)
190
+ * @param timeoutNs the await timeout in ns (absent ⇒ the responder's 1 s default)
191
+ * @returns the next write's value TLV
192
+ * @throws {FwdError} with code TIMEOUT when the responder's deadline elapses
193
+ */
194
+ async await_(path, timeoutNs) {
195
+ const reply = await this.request(encodeFwd({
196
+ op: FWD_OP.AWAIT,
197
+ dst: splitPath(path),
198
+ src: this.replyEndpoint,
199
+ awaitTimeoutNs: timeoutNs,
200
+ }));
201
+ const value = this.result(reply);
202
+ if (!value)
203
+ throw new FwdError(0);
204
+ return value;
205
+ }
206
+ /**
207
+ * Subscribe to a remote producer: a `WRITE` of a `SUBSCRIBER{ target=<reply-ep> }`
208
+ * into `producer:subscribers[]` (RFC-0004 §C/§D — subscribe is a field-write).
209
+ * Once the responder acks, `handler` fires for every inbound VALUE delivery.
210
+ *
211
+ * SCOPE: this issues the SUBSCRIBER and receives VALUEs the producer directly
212
+ * delivers to this client's reply endpoint. Full standing-stream delivery
213
+ * additionally needs the producer auto-promote / flush seam (#136 / RFC-0004 §E)
214
+ * — out of scope for this client slice. `unsubscribe()` is a LOCAL detach: it
215
+ * stops firing `handler` but does not clear the remote slot (an indexed
216
+ * `:subscribers[N]` field-write, additive).
217
+ *
218
+ * @param producerPath the producer vertex path (string or segments)
219
+ * @param handler invoked with each inbound VALUE delivery
220
+ * @returns a function that locally detaches `handler`
221
+ * @throws {FwdError} when the subscribe-write is rejected
222
+ */
223
+ async subscribe(producerPath, handler) {
224
+ const subscriber = encodeSubscriber(this.replyEndpoint);
225
+ // Register the handler BEFORE awaiting the ack: a producer may stream its
226
+ // first delivery before its subscribe REPLY is seen on the wire, and we must
227
+ // not drop it. On a rejected subscribe we detach again.
228
+ this.valueHandlers.add(handler);
229
+ try {
230
+ const reply = await this.request(encodeFwd({
231
+ op: FWD_OP.WRITE,
232
+ dst: splitPath(producerPath),
233
+ field: ':subscribers[]',
234
+ src: this.replyEndpoint,
235
+ payload: subscriber,
236
+ }));
237
+ this.result(reply); // throws on ERROR
238
+ }
239
+ catch (err) {
240
+ this.valueHandlers.delete(handler);
241
+ throw err;
242
+ }
243
+ return () => {
244
+ this.valueHandlers.delete(handler);
245
+ };
246
+ }
247
+ /* ------------------------------------------- pure builders (static) --- */
248
+ /** {@link encodeValue} — the exact VALUE TLV bytes, independently of any transport. */
249
+ static encodeValue(value, opts) {
250
+ return encodeValue(value, opts);
251
+ }
252
+ /** {@link encodePath} — the exact PATH TLV bytes. */
253
+ static encodePath(segments) {
254
+ return encodePath(segments);
255
+ }
256
+ /** {@link encodeSubscriber} — the exact SUBSCRIBER TLV bytes. */
257
+ static encodeSubscriber(targetPath, opts) {
258
+ return encodeSubscriber(targetPath, opts);
259
+ }
260
+ }
261
+ // `await` is a reserved word, so the method is `await_`; expose `client.await(...)`
262
+ // too (a member name may be a keyword) for the RFC-0004-spelled ergonomic call.
263
+ Object.defineProperty(LibtracerClient.prototype, 'await', {
264
+ value: LibtracerClient.prototype.await_,
265
+ writable: true,
266
+ configurable: true,
267
+ enumerable: false,
268
+ });
269
+ /** Normalize a `/`-path string (or segment array) into validated segments. */
270
+ function splitPath(path) {
271
+ if (Array.isArray(path))
272
+ return path;
273
+ const segs = path.split('/').filter((s) => s.length > 0);
274
+ if (segs.length === 0)
275
+ throw new RangeError(`path ${JSON.stringify(path)} has no segments`);
276
+ return segs;
277
+ }
package/dist/fwd.d.ts ADDED
@@ -0,0 +1,127 @@
1
+ import type { Opt, Tlv } from '@avatarsd-llc/libtracer';
2
+ /** FWD `op` discriminant (RFC-0004 §B — the first child, a VALUE u8). */
3
+ export declare const FWD_OP: Readonly<{
4
+ readonly READ: 0;
5
+ readonly WRITE: 1;
6
+ readonly AWAIT: 2;
7
+ readonly REPLY: 3;
8
+ }>;
9
+ /** FWD{REPLY} `kind` discriminant (RFC-0004 §D — a VALUE u8 after `src`). */
10
+ export declare const FWD_KIND: Readonly<{
11
+ readonly RESULT: 0;
12
+ readonly ERROR: 1;
13
+ }>;
14
+ /**
15
+ * Wire ERROR codes for a `kind=ERROR` reply's `STATUS{ ERROR u8 }` payload.
16
+ * Mirrors the C++ reference `op_resolve.cpp` `error_code()` map (provisional
17
+ * pending the ERROR registry, RFC-0001 §C/E / #8).
18
+ */
19
+ export declare const FWD_ERROR: Readonly<{
20
+ readonly NOT_FOUND: 1;
21
+ readonly PERMISSION_DENIED: 2;
22
+ readonly INVALID_PATH: 3;
23
+ readonly TYPE_MISMATCH: 4;
24
+ readonly BACKPRESSURE: 7;
25
+ readonly TIMEOUT: 8;
26
+ readonly SCHEMA_NOT_FOUND: 10;
27
+ readonly PATH_IN_USE: 14;
28
+ }>;
29
+ /** The human name of a wire ERROR code (or `UNKNOWN(0x..)`). */
30
+ export declare function fwdErrorName(code: number): string;
31
+ /** One level of a `:field` selector chain (RFC-0004 §C, one NAME + optional index). */
32
+ export interface FieldLevel {
33
+ /** The level's field name (e.g. `"subscribers"`, `"settings"`). */
34
+ readonly name: string;
35
+ /**
36
+ * The index when this level is an element selector (`[N]`). When set, the level
37
+ * is encoded as `ELEMENT` regardless of {@link FieldLevel.mode}.
38
+ */
39
+ readonly index?: number;
40
+ /**
41
+ * `SCALAR` (no brackets, default), `ELEMENT` (`[N]` / append `[]`), or `WILDCARD`
42
+ * (`[*]` — subscriber-path targets only).
43
+ */
44
+ readonly mode?: 'SCALAR' | 'ELEMENT' | 'WILDCARD';
45
+ }
46
+ /**
47
+ * Parse a `:field` selector string into its levels. Accepts an optional leading
48
+ * `:`; levels are split on `.`; each level may carry a trailing `[N]`, `[]`
49
+ * (append), or `[*]` (wildcard).
50
+ *
51
+ * `":subscribers[]"` → `[{ name: "subscribers", mode: "ELEMENT" }]`;
52
+ * `":subscribers[3]"` → `[{ name: "subscribers", index: 3, mode: "ELEMENT" }]`;
53
+ * `":settings.deadline_ns"` → `[{ name: "settings" }, { name: "deadline_ns" }]`.
54
+ *
55
+ * @param field the selector string (with or without the leading `:`)
56
+ * @returns the parsed levels
57
+ * @throws {RangeError} on an empty selector or a malformed level
58
+ */
59
+ export declare function parseField(field: string): FieldLevel[];
60
+ /**
61
+ * Build a FIELD TLV (`type=0x10`, PL=1) from a selector string or pre-parsed
62
+ * levels. Vector-pinned: `field-indexed`, `field-nested`, `field-append`.
63
+ *
64
+ * @param field a `:field` string (see {@link parseField}) or its levels
65
+ * @returns the encoded FIELD TLV bytes
66
+ */
67
+ export declare function encodeField(field: string | FieldLevel[]): Uint8Array;
68
+ /** Request to build a {@link encodeFwd} frame. `op` selects the child layout. */
69
+ export interface FwdRequest {
70
+ /** The operation (a {@link FWD_OP} value). */
71
+ readonly op: number;
72
+ /** Forward route: the unresolved destination path segments (the PATH `dst`). */
73
+ readonly dst: string[];
74
+ /** Accumulated return route: the originator's reply endpoint segments (the PATH `src`). */
75
+ readonly src: string[];
76
+ /** Optional `:field` selector (string or levels). */
77
+ readonly field?: string | FieldLevel[];
78
+ /**
79
+ * Optional payload — a complete TLV's encoded bytes (a VALUE to WRITE, a
80
+ * SUBSCRIBER to subscribe, the RESULT/STATUS of a REPLY). Embedded verbatim.
81
+ */
82
+ readonly payload?: Uint8Array;
83
+ /** REPLY only — the reply {@link FWD_KIND}. */
84
+ readonly kind?: number;
85
+ /** AWAIT only — the `await_timeout` in ns (absent ⇒ the responder's 1 s default). */
86
+ readonly awaitTimeoutNs?: bigint;
87
+ }
88
+ /**
89
+ * Build a FWD TLV (`type=0x0F`, PL=1) — the remote-operation envelope (RFC-0004
90
+ * §B). The children are assembled in the normative order for the request's `op`.
91
+ * Vector-pinned: `fwd-read`, `fwd-write-value`, `fwd-await-timeout`,
92
+ * `fwd-write-subscriber-field`, `fwd-reply-result`, `fwd-reply-error`.
93
+ *
94
+ * @param req the operation, routes, and optional selector/payload/kind/timeout
95
+ * @returns the encoded FWD TLV bytes (one complete frame)
96
+ */
97
+ export declare function encodeFwd(req: FwdRequest): Uint8Array;
98
+ /** A decoded FWD frame, its children parsed positionally (RFC-0004 §B order). */
99
+ export interface ParsedFwd {
100
+ /** The operation (a {@link FWD_OP} value). */
101
+ readonly op: number;
102
+ /** The `dst` PATH child. */
103
+ readonly dst: Tlv;
104
+ /** The optional FIELD selector child (or `null`). */
105
+ readonly field: Tlv | null;
106
+ /** The `src` PATH child. */
107
+ readonly src: Tlv;
108
+ /** The reply {@link FWD_KIND} (REPLY frames only, else `null`). */
109
+ readonly kind: number | null;
110
+ /** The payload TLV child (WRITE payload / REPLY result / RESULT VALUE), or `null`. */
111
+ readonly payload: Tlv | null;
112
+ /** The AWAIT `await_timeout` ns (else `null`). */
113
+ readonly awaitTimeoutNs: bigint | null;
114
+ }
115
+ /** Parse an already-decoded FWD {@link Tlv} positionally (RFC-0004 §B). */
116
+ export declare function parseFwdTlv(fwd: Tlv): ParsedFwd;
117
+ /**
118
+ * Decode a complete FWD frame's bytes into its parsed children.
119
+ *
120
+ * @param bytes one complete FWD TLV frame
121
+ * @returns the parsed FWD
122
+ * @throws if the bytes do not decode, or are not a FWD
123
+ */
124
+ export declare function decodeFwd(bytes: Uint8Array): ParsedFwd;
125
+ /** The wire ERROR code of a `kind=ERROR` reply's `STATUS{ ERROR u8 }` payload (or 0). */
126
+ export declare function replyErrorCode(reply: ParsedFwd): number;
127
+ export type { Opt };
package/dist/fwd.js ADDED
@@ -0,0 +1,228 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // SPDX-FileCopyrightText: Copyright 2026 avatarsd LLC
3
+ // FWD (0x0F) / FIELD (0x10) builders + decoder for the libtracer client SDK
4
+ // (#56, RFC-0004, ADR-0034/0035). RFC-0004 §3 pins the remote-operation envelope
5
+ // the conservative ADR-0034 slice deferred: a self-describing FWD frame carries a
6
+ // `read`/`write`/`await`/`subscribe` to a path-as-route, and a FWD{REPLY} routes
7
+ // the result back. These builders produce the EXACT bytes the shared conformance
8
+ // vectors pin (`tests/conformance/vectors/v1/fwd/`, `.../field/`) via the
9
+ // cross-validated core codec — nothing here invents wire structure.
10
+ //
11
+ // Child order (RFC-0004 §B): op, dst (PATH), FIELD? selector, src (PATH), then
12
+ // - REPLY: kind (VALUE u8), payload?
13
+ // - WRITE: payload?
14
+ // - AWAIT: await_timeout? (VALUE u64 ns)
15
+ // - READ : nothing
16
+ import { TYPE, encode, decode } from '@avatarsd-llc/libtracer';
17
+ import { opt, pathTlv, nameTlv } from './tlv.js';
18
+ /** FWD `op` discriminant (RFC-0004 §B — the first child, a VALUE u8). */
19
+ export const FWD_OP = Object.freeze({
20
+ READ: 0,
21
+ WRITE: 1,
22
+ AWAIT: 2,
23
+ REPLY: 3,
24
+ });
25
+ /** FWD{REPLY} `kind` discriminant (RFC-0004 §D — a VALUE u8 after `src`). */
26
+ export const FWD_KIND = Object.freeze({
27
+ RESULT: 0,
28
+ ERROR: 1,
29
+ });
30
+ /**
31
+ * Wire ERROR codes for a `kind=ERROR` reply's `STATUS{ ERROR u8 }` payload.
32
+ * Mirrors the C++ reference `op_resolve.cpp` `error_code()` map (provisional
33
+ * pending the ERROR registry, RFC-0001 §C/E / #8).
34
+ */
35
+ export const FWD_ERROR = Object.freeze({
36
+ NOT_FOUND: 0x01,
37
+ PERMISSION_DENIED: 0x02,
38
+ INVALID_PATH: 0x03,
39
+ TYPE_MISMATCH: 0x04,
40
+ BACKPRESSURE: 0x07,
41
+ TIMEOUT: 0x08,
42
+ SCHEMA_NOT_FOUND: 0x0a,
43
+ PATH_IN_USE: 0x0e,
44
+ });
45
+ const FWD_ERROR_NAME = Object.freeze(Object.fromEntries(Object.entries(FWD_ERROR).map(([k, v]) => [v, k])));
46
+ /** The human name of a wire ERROR code (or `UNKNOWN(0x..)`). */
47
+ export function fwdErrorName(code) {
48
+ return FWD_ERROR_NAME[code] ?? `UNKNOWN(0x${code.toString(16)})`;
49
+ }
50
+ /* ----------------------------------------------------------- value nodes --- */
51
+ /** A 1-byte VALUE TLV node (the op / kind discriminants). */
52
+ function valueU8(v) {
53
+ return { type: TYPE.VALUE, opt: opt(), payload: Uint8Array.of(v & 0xff), children: [], trailer: null };
54
+ }
55
+ /** A little-endian u32 VALUE TLV node (a FIELD `[N]` index). */
56
+ function valueU32(v) {
57
+ const p = new Uint8Array(4);
58
+ new DataView(p.buffer).setUint32(0, v >>> 0, true);
59
+ return { type: TYPE.VALUE, opt: opt(), payload: p, children: [], trailer: null };
60
+ }
61
+ /** A little-endian u64 VALUE TLV node (the AWAIT `await_timeout` ns). */
62
+ function valueU64(v) {
63
+ const p = new Uint8Array(8);
64
+ new DataView(p.buffer).setBigUint64(0, v, true);
65
+ return { type: TYPE.VALUE, opt: opt(), payload: p, children: [], trailer: null };
66
+ }
67
+ /**
68
+ * Parse a `:field` selector string into its levels. Accepts an optional leading
69
+ * `:`; levels are split on `.`; each level may carry a trailing `[N]`, `[]`
70
+ * (append), or `[*]` (wildcard).
71
+ *
72
+ * `":subscribers[]"` → `[{ name: "subscribers", mode: "ELEMENT" }]`;
73
+ * `":subscribers[3]"` → `[{ name: "subscribers", index: 3, mode: "ELEMENT" }]`;
74
+ * `":settings.deadline_ns"` → `[{ name: "settings" }, { name: "deadline_ns" }]`.
75
+ *
76
+ * @param field the selector string (with or without the leading `:`)
77
+ * @returns the parsed levels
78
+ * @throws {RangeError} on an empty selector or a malformed level
79
+ */
80
+ export function parseField(field) {
81
+ const body = field.startsWith(':') ? field.slice(1) : field;
82
+ if (body.length === 0)
83
+ throw new RangeError('a :field selector must name at least one level');
84
+ return body.split('.').map((part) => {
85
+ const m = /^([^.[\]]+)(?:\[(\*|\d*)\])?$/.exec(part);
86
+ if (!m)
87
+ throw new RangeError(`malformed :field level ${JSON.stringify(part)}`);
88
+ const name = m[1];
89
+ if (m[2] === undefined)
90
+ return { name };
91
+ if (m[2] === '*')
92
+ return { name, mode: 'WILDCARD' };
93
+ if (m[2] === '')
94
+ return { name, mode: 'ELEMENT' };
95
+ return { name, index: Number(m[2]), mode: 'ELEMENT' };
96
+ });
97
+ }
98
+ /** Build a FIELD TLV node from its levels (RFC-0004 §C). */
99
+ function fieldTlv(levels) {
100
+ if (levels.length < 1)
101
+ throw new RangeError('a FIELD selector needs at least one level');
102
+ if (levels.length > 8)
103
+ throw new RangeError(`a FIELD selector may have at most 8 levels (got ${levels.length})`);
104
+ const children = [];
105
+ for (const level of levels) {
106
+ children.push(nameTlv(level.name));
107
+ const mode = level.mode ?? (level.index !== undefined ? 'ELEMENT' : 'SCALAR');
108
+ if (mode === 'WILDCARD') {
109
+ children.push(valueU8(2)); // index_mode=WILDCARD
110
+ }
111
+ else if (mode === 'ELEMENT') {
112
+ if (level.index !== undefined)
113
+ children.push(valueU32(level.index)); // [N]
114
+ children.push(valueU8(1)); // index_mode=ELEMENT (append "[]" when no index)
115
+ }
116
+ // SCALAR: just the NAME (index_mode default 0).
117
+ }
118
+ return { type: TYPE.FIELD, opt: opt({ pl: true }), payload: new Uint8Array(0), children, trailer: null };
119
+ }
120
+ /**
121
+ * Build a FIELD TLV (`type=0x10`, PL=1) from a selector string or pre-parsed
122
+ * levels. Vector-pinned: `field-indexed`, `field-nested`, `field-append`.
123
+ *
124
+ * @param field a `:field` string (see {@link parseField}) or its levels
125
+ * @returns the encoded FIELD TLV bytes
126
+ */
127
+ export function encodeField(field) {
128
+ return encode(fieldTlv(typeof field === 'string' ? parseField(field) : field));
129
+ }
130
+ /** Build the FWD child node for an embedded payload (decode the caller's TLV bytes). */
131
+ function payloadNode(payload) {
132
+ return decode(payload);
133
+ }
134
+ /**
135
+ * Build a FWD TLV (`type=0x0F`, PL=1) — the remote-operation envelope (RFC-0004
136
+ * §B). The children are assembled in the normative order for the request's `op`.
137
+ * Vector-pinned: `fwd-read`, `fwd-write-value`, `fwd-await-timeout`,
138
+ * `fwd-write-subscriber-field`, `fwd-reply-result`, `fwd-reply-error`.
139
+ *
140
+ * @param req the operation, routes, and optional selector/payload/kind/timeout
141
+ * @returns the encoded FWD TLV bytes (one complete frame)
142
+ */
143
+ export function encodeFwd(req) {
144
+ const children = [valueU8(req.op), pathTlv(req.dst)];
145
+ if (req.field !== undefined) {
146
+ children.push(fieldTlv(typeof req.field === 'string' ? parseField(req.field) : req.field));
147
+ }
148
+ children.push(pathTlv(req.src));
149
+ if (req.op === FWD_OP.REPLY) {
150
+ children.push(valueU8(req.kind ?? FWD_KIND.RESULT));
151
+ if (req.payload !== undefined)
152
+ children.push(payloadNode(req.payload));
153
+ }
154
+ else if (req.op === FWD_OP.WRITE) {
155
+ if (req.payload !== undefined)
156
+ children.push(payloadNode(req.payload));
157
+ }
158
+ else if (req.op === FWD_OP.AWAIT) {
159
+ if (req.awaitTimeoutNs !== undefined)
160
+ children.push(valueU64(req.awaitTimeoutNs));
161
+ }
162
+ const fwd = {
163
+ type: TYPE.FWD,
164
+ opt: opt({ pl: true }),
165
+ payload: new Uint8Array(0),
166
+ children,
167
+ trailer: null,
168
+ };
169
+ return encode(fwd);
170
+ }
171
+ const u8 = (t) => (t.payload.length > 0 ? t.payload[0] : 0);
172
+ /** Parse an already-decoded FWD {@link Tlv} positionally (RFC-0004 §B). */
173
+ export function parseFwdTlv(fwd) {
174
+ if (fwd.type !== TYPE.FWD)
175
+ throw new RangeError(`not a FWD TLV (type 0x${fwd.type.toString(16)})`);
176
+ const ch = fwd.children;
177
+ let i = 0;
178
+ if (ch[i]?.type !== TYPE.VALUE)
179
+ throw new RangeError('FWD: missing op VALUE child');
180
+ const op = u8(ch[i++]);
181
+ if (ch[i]?.type !== TYPE.PATH)
182
+ throw new RangeError('FWD: missing dst PATH child');
183
+ const dst = ch[i++];
184
+ let field = null;
185
+ if (ch[i]?.type === TYPE.FIELD)
186
+ field = ch[i++];
187
+ if (ch[i]?.type !== TYPE.PATH)
188
+ throw new RangeError('FWD: missing src PATH child');
189
+ const src = ch[i++];
190
+ let kind = null;
191
+ let payload = null;
192
+ let awaitTimeoutNs = null;
193
+ if (op === FWD_OP.REPLY) {
194
+ if (ch[i]?.type === TYPE.VALUE)
195
+ kind = u8(ch[i++]);
196
+ if (i < ch.length)
197
+ payload = ch[i++];
198
+ }
199
+ else if (op === FWD_OP.WRITE) {
200
+ if (i < ch.length)
201
+ payload = ch[i++];
202
+ }
203
+ else if (op === FWD_OP.AWAIT) {
204
+ if (ch[i]?.type === TYPE.VALUE && ch[i].payload.length >= 8) {
205
+ awaitTimeoutNs = new DataView(ch[i].payload.buffer, ch[i].payload.byteOffset, 8).getBigUint64(0, true);
206
+ i++;
207
+ }
208
+ }
209
+ return { op, dst, field, src, kind, payload, awaitTimeoutNs };
210
+ }
211
+ /**
212
+ * Decode a complete FWD frame's bytes into its parsed children.
213
+ *
214
+ * @param bytes one complete FWD TLV frame
215
+ * @returns the parsed FWD
216
+ * @throws if the bytes do not decode, or are not a FWD
217
+ */
218
+ export function decodeFwd(bytes) {
219
+ return parseFwdTlv(decode(bytes));
220
+ }
221
+ /** The wire ERROR code of a `kind=ERROR` reply's `STATUS{ ERROR u8 }` payload (or 0). */
222
+ export function replyErrorCode(reply) {
223
+ const status = reply.payload;
224
+ if (status && status.type === TYPE.STATUS && status.children[0]?.type === TYPE.ERROR) {
225
+ return u8(status.children[0]);
226
+ }
227
+ return 0;
228
+ }
@@ -0,0 +1,7 @@
1
+ export declare const CLIENT_EXPERIMENTAL: true;
2
+ export { LibtracerClient, FwdError } from './client.js';
3
+ export type { ClientTransport, ValueHandler, Unsubscribe, ClientOptions, } from './client.js';
4
+ export { encodeValue, encodePath, encodeSubscriber } from './tlv.js';
5
+ export type { ValueOptions, SubscriberOptions } from './tlv.js';
6
+ export { FWD_OP, FWD_KIND, FWD_ERROR, fwdErrorName, encodeFwd, encodeField, parseField, decodeFwd, parseFwdTlv, replyErrorCode, } from './fwd.js';
7
+ export type { FwdRequest, ParsedFwd, FieldLevel } from './fwd.js';
package/dist/index.js ADDED
@@ -0,0 +1,17 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // SPDX-FileCopyrightText: Copyright 2026 avatarsd LLC
3
+ // @avatarsd-llc/libtracer-client — the experimental libtracer client SDK (#56,
4
+ // ADR-0034). A curated composition over the cross-validated codec
5
+ // (@avatarsd-llc/libtracer, a peerDependency) and an injected transport seam
6
+ // (@avatarsd-llc/libtracer-ws's TransportWs satisfies it structurally).
7
+ //
8
+ // EXPERIMENTAL / pre-1.0 (0.1.0). With RFC-0004 (spec §3, the remote-operation
9
+ // envelope) implemented, the client now speaks the path-addressed higher
10
+ // operations over `FWD`: read / write / await / readField / subscribe, each a
11
+ // FWD frame whose FWD{REPLY} is source-routed back. The pure payload builders
12
+ // (VALUE / SUBSCRIBER / PATH) and the FWD / FIELD builders are independently
13
+ // exported and vector-pinned — see docs/spec/rfcs/0004-remote-operation-addressing.md.
14
+ export const CLIENT_EXPERIMENTAL = true;
15
+ export { LibtracerClient, FwdError } from './client.js';
16
+ export { encodeValue, encodePath, encodeSubscriber } from './tlv.js';
17
+ export { FWD_OP, FWD_KIND, FWD_ERROR, fwdErrorName, encodeFwd, encodeField, parseField, decodeFwd, parseFwdTlv, replyErrorCode, } from './fwd.js';
package/dist/tlv.d.ts ADDED
@@ -0,0 +1,67 @@
1
+ import type { Opt, Tlv } from '@avatarsd-llc/libtracer';
2
+ /**
3
+ * A fully-cleared option byte (all flags false), with selected flags overridden.
4
+ * Shared by the payload builders here and the FWD/FIELD builders in `./fwd.ts`.
5
+ *
6
+ * @param over flags to set true (e.g. `{ pl: true }` for a structured TLV)
7
+ * @returns a complete {@link Opt}
8
+ */
9
+ export declare function opt(over?: Partial<Opt>): Opt;
10
+ /** Options for {@link encodeValue}. Mirror the wire opt/trailer fields the codec pins. */
11
+ export interface ValueOptions {
12
+ /** Use the 32-bit length field (opt.LL=1, 6-byte header). Default: 16-bit. */
13
+ longLength?: boolean;
14
+ /** Emit a CRC trailer over the payload (+ timestamp bytes). Default: none. */
15
+ crc?: boolean;
16
+ /** With {@link ValueOptions.crc}, use CRC-16-CCITT (opt.CW=1) instead of CRC-32C. */
17
+ crc16?: boolean;
18
+ /** Absolute u64 wire timestamp (ns since epoch) → opt.TS=1, TF=0 (absolute). */
19
+ timestampNs?: bigint;
20
+ /** Relative i32 wire timestamp (ns) → opt.TS=1, TF=1 (relative). Ignored if {@link ValueOptions.timestampNs} is set. */
21
+ timestampRelNs?: number;
22
+ }
23
+ /**
24
+ * Build a VALUE TLV (`type=0x01`) carrying an opaque application payload.
25
+ * Vector-pinned: `value-bool-true`, `value-ll-u32`, `value-ts-abs`.
26
+ *
27
+ * @param value the opaque payload bytes (the publisher/subscriber agree on the shape out-of-band)
28
+ * @param opts optional length-width / CRC / wire-timestamp selectors
29
+ * @returns the encoded VALUE TLV bytes (one complete frame)
30
+ */
31
+ export declare function encodeValue(value: Uint8Array, opts?: ValueOptions): Uint8Array;
32
+ /**
33
+ * Build a NAME TLV (`type=0x02`) for one path segment, after validating it
34
+ * against the addressing rules (1..64 UTF-8 bytes, no reserved characters).
35
+ *
36
+ * @param segment the segment text
37
+ * @returns a NAME TLV node (no trailer)
38
+ * @throws {RangeError} if the segment is empty, over 64 bytes, or holds a reserved char
39
+ */
40
+ export declare function nameTlv(segment: string): Tlv;
41
+ /**
42
+ * Build a PATH TLV (`type=0x06`, PL=1) from path segments — a NAME child per
43
+ * segment. Vector-pinned: `path-sensor-temp`; normative byte layout: spec/v1.md §3.1.
44
+ *
45
+ * @param segments the path segments, e.g. `["sensor", "temp"]` for `/sensor/temp`
46
+ * @returns the encoded PATH TLV bytes
47
+ * @throws {RangeError} on an empty path or an invalid segment
48
+ */
49
+ export declare function encodePath(segments: string[]): Uint8Array;
50
+ /** The PATH TLV node (shared by {@link encodePath}, {@link encodeSubscriber}, and `./fwd.ts`). */
51
+ export declare function pathTlv(segments: string[]): Tlv;
52
+ /** Options for {@link encodeSubscriber}. Optional QoS/ACL/id children are deferred (ADR-0034). */
53
+ export interface SubscriberOptions {
54
+ }
55
+ /**
56
+ * Build a SUBSCRIBER TLV (`type=0x04`, PL=1) wrapping a target PATH — the
57
+ * payload of a subscribe-write (reference/04 §Subscribe). Vector-pinned:
58
+ * `subscriber-path` = `SUBSCRIBER{ PATH{ NAME "sensor", NAME "temp" } }`.
59
+ *
60
+ * The `targetPath` is the SUBSCRIBER's `target_path` child: where the producer
61
+ * dispatches matched writes (reference/05 §SUBSCRIBER).
62
+ *
63
+ * @param targetPath the delivery target path segments
64
+ * @param _opts reserved for future optional children (none in this slice)
65
+ * @returns the encoded SUBSCRIBER TLV bytes
66
+ */
67
+ export declare function encodeSubscriber(targetPath: string[], _opts?: SubscriberOptions): Uint8Array;
package/dist/tlv.js ADDED
@@ -0,0 +1,123 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // SPDX-FileCopyrightText: Copyright 2026 avatarsd LLC
3
+ // Pure, side-effect-free TLV builders for the libtracer client SDK (#56,
4
+ // ADR-0034). Each function produces the EXACT wire bytes the shared conformance
5
+ // vectors pin (`tests/conformance/vectors/v1/`) via the cross-validated core
6
+ // codec (`@avatarsd-llc/libtracer`) — nothing here invents wire structure:
7
+ //
8
+ // - encodeValue -> VALUE TLV (0x01) : value-bool-true / value-ll-u32 / value-ts-abs
9
+ // - encodePath -> PATH TLV (0x06, PL=1) : path-sensor-temp + spec/v1.md §3.1
10
+ // - encodeSubscriber -> SUBSCRIBER TLV (0x04) : subscriber-path (the subscribe-write payload)
11
+ //
12
+ // These are the payload TLVs. The path-ADDRESSED request envelope (verb +
13
+ // destination vertex:field) is the FWD/FIELD frame RFC-0004 (spec §3) fixes — it
14
+ // is built in `./fwd.ts`, not here; these payloads ride inside it.
15
+ import { TYPE, encode } from '@avatarsd-llc/libtracer';
16
+ /** Path-segment constraints from reference/03-addressing.md §path syntax. */
17
+ const MAX_SEGMENT_BYTES = 64;
18
+ /** Reserved characters that MUST NOT appear inside a NAME segment (reference/03, /05 §NAME). */
19
+ const RESERVED_SEGMENT_CHARS = /[/:.[\]*?]/;
20
+ const utf8 = new TextEncoder();
21
+ /**
22
+ * A fully-cleared option byte (all flags false), with selected flags overridden.
23
+ * Shared by the payload builders here and the FWD/FIELD builders in `./fwd.ts`.
24
+ *
25
+ * @param over flags to set true (e.g. `{ pl: true }` for a structured TLV)
26
+ * @returns a complete {@link Opt}
27
+ */
28
+ export function opt(over = {}) {
29
+ return { pl: false, ts: false, cr: false, ll: false, cw: false, tf: false, ...over };
30
+ }
31
+ /**
32
+ * Build a VALUE TLV (`type=0x01`) carrying an opaque application payload.
33
+ * Vector-pinned: `value-bool-true`, `value-ll-u32`, `value-ts-abs`.
34
+ *
35
+ * @param value the opaque payload bytes (the publisher/subscriber agree on the shape out-of-band)
36
+ * @param opts optional length-width / CRC / wire-timestamp selectors
37
+ * @returns the encoded VALUE TLV bytes (one complete frame)
38
+ */
39
+ export function encodeValue(value, opts = {}) {
40
+ const hasAbs = opts.timestampNs !== undefined;
41
+ const hasRel = !hasAbs && opts.timestampRelNs !== undefined;
42
+ const hasTs = hasAbs || hasRel;
43
+ const tlv = {
44
+ type: TYPE.VALUE,
45
+ opt: opt({ ll: !!opts.longLength, cr: !!opts.crc, cw: !!opts.crc16, ts: hasTs, tf: hasRel }),
46
+ payload: value,
47
+ children: [],
48
+ trailer: hasTs
49
+ ? {
50
+ ts: hasAbs
51
+ ? { relative: false, value: opts.timestampNs }
52
+ : { relative: true, value: BigInt(opts.timestampRelNs) },
53
+ crc: null,
54
+ }
55
+ : null,
56
+ };
57
+ return encode(tlv);
58
+ }
59
+ /**
60
+ * Build a NAME TLV (`type=0x02`) for one path segment, after validating it
61
+ * against the addressing rules (1..64 UTF-8 bytes, no reserved characters).
62
+ *
63
+ * @param segment the segment text
64
+ * @returns a NAME TLV node (no trailer)
65
+ * @throws {RangeError} if the segment is empty, over 64 bytes, or holds a reserved char
66
+ */
67
+ export function nameTlv(segment) {
68
+ if (RESERVED_SEGMENT_CHARS.test(segment)) {
69
+ throw new RangeError(`path segment ${JSON.stringify(segment)} contains a reserved character (/ : . [ ] * ?)`);
70
+ }
71
+ const bytes = utf8.encode(segment);
72
+ if (bytes.length < 1 || bytes.length > MAX_SEGMENT_BYTES) {
73
+ throw new RangeError(`path segment ${JSON.stringify(segment)} must be 1..${MAX_SEGMENT_BYTES} UTF-8 bytes (got ${bytes.length})`);
74
+ }
75
+ return { type: TYPE.NAME, opt: opt(), payload: bytes, children: [], trailer: null };
76
+ }
77
+ /**
78
+ * Build a PATH TLV (`type=0x06`, PL=1) from path segments — a NAME child per
79
+ * segment. Vector-pinned: `path-sensor-temp`; normative byte layout: spec/v1.md §3.1.
80
+ *
81
+ * @param segments the path segments, e.g. `["sensor", "temp"]` for `/sensor/temp`
82
+ * @returns the encoded PATH TLV bytes
83
+ * @throws {RangeError} on an empty path or an invalid segment
84
+ */
85
+ export function encodePath(segments) {
86
+ return encode(pathTlv(segments));
87
+ }
88
+ /** The PATH TLV node (shared by {@link encodePath}, {@link encodeSubscriber}, and `./fwd.ts`). */
89
+ export function pathTlv(segments) {
90
+ if (segments.length < 1)
91
+ throw new RangeError('a path must have at least one segment');
92
+ if (segments.length > 32)
93
+ throw new RangeError(`a path may have at most 32 segments (got ${segments.length})`);
94
+ return {
95
+ type: TYPE.PATH,
96
+ opt: opt({ pl: true }),
97
+ payload: new Uint8Array(0),
98
+ children: segments.map(nameTlv),
99
+ trailer: null,
100
+ };
101
+ }
102
+ /**
103
+ * Build a SUBSCRIBER TLV (`type=0x04`, PL=1) wrapping a target PATH — the
104
+ * payload of a subscribe-write (reference/04 §Subscribe). Vector-pinned:
105
+ * `subscriber-path` = `SUBSCRIBER{ PATH{ NAME "sensor", NAME "temp" } }`.
106
+ *
107
+ * The `targetPath` is the SUBSCRIBER's `target_path` child: where the producer
108
+ * dispatches matched writes (reference/05 §SUBSCRIBER).
109
+ *
110
+ * @param targetPath the delivery target path segments
111
+ * @param _opts reserved for future optional children (none in this slice)
112
+ * @returns the encoded SUBSCRIBER TLV bytes
113
+ */
114
+ export function encodeSubscriber(targetPath, _opts = {}) {
115
+ const tlv = {
116
+ type: TYPE.SUBSCRIBER,
117
+ opt: opt({ pl: true }),
118
+ payload: new Uint8Array(0),
119
+ children: [pathTlv(targetPath)],
120
+ trailer: null,
121
+ };
122
+ return encode(tlv);
123
+ }
package/package.json ADDED
@@ -0,0 +1,56 @@
1
+ {
2
+ "name": "@avatarsd-llc/libtracer-client",
3
+ "version": "0.1.0",
4
+ "description": "EXPERIMENTAL libtracer client SDK (#56, ADR-0034/0035) — a path-addressed client over the cross-validated codec (@avatarsd-llc/libtracer) and an injected transport seam (e.g. @avatarsd-llc/libtracer-ws). Speaks the RFC-0004 remote operations over FWD: read / write / await / readField / subscribe, each a FWD frame whose source-routed FWD{REPLY} is decoded back. Pre-1.0 and experimental.",
5
+ "author": "avatarsd LLC",
6
+ "license": "Apache-2.0",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/avatarsd-llc/libtracer.git",
10
+ "directory": "bindings/typescript/packages/client"
11
+ },
12
+ "homepage": "https://github.com/avatarsd-llc/libtracer#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/avatarsd-llc/libtracer/issues"
15
+ },
16
+ "keywords": ["protocol", "iot", "graph", "tlv", "client", "sdk", "websocket"],
17
+ "type": "module",
18
+ "engines": {
19
+ "node": ">=18"
20
+ },
21
+ "sideEffects": false,
22
+ "main": "dist/index.js",
23
+ "types": "dist/index.d.ts",
24
+ "exports": {
25
+ ".": {
26
+ "types": "./dist/index.d.ts",
27
+ "default": "./dist/index.js"
28
+ },
29
+ "./package.json": "./package.json"
30
+ },
31
+ "files": ["dist", "README.md", "LICENSE"],
32
+ "publishConfig": {
33
+ "access": "public"
34
+ },
35
+ "peerDependencies": {
36
+ "@avatarsd-llc/libtracer": "^0.0.1",
37
+ "@avatarsd-llc/libtracer-ws": "^0.1.0"
38
+ },
39
+ "peerDependenciesMeta": {
40
+ "@avatarsd-llc/libtracer-ws": {
41
+ "optional": true
42
+ }
43
+ },
44
+ "scripts": {
45
+ "build": "tsc",
46
+ "test": "node --test test/*.test.mjs",
47
+ "prepublishOnly": "npm run build"
48
+ },
49
+ "devDependencies": {
50
+ "@avatarsd-llc/libtracer": "*",
51
+ "@avatarsd-llc/libtracer-ws": "*",
52
+ "@types/node": "^20.0.0",
53
+ "typescript": "^5.4.0",
54
+ "ws": "^8.16.0"
55
+ }
56
+ }