vortez-io 1.0.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.
Files changed (52) hide show
  1. package/.gitignore +15 -0
  2. package/LICENSE +201 -0
  3. package/PROTOCOL.md +245 -0
  4. package/README.md +103 -0
  5. package/build/Frame.d.ts +118 -0
  6. package/build/Frame.js +241 -0
  7. package/build/Frame.js.map +1 -0
  8. package/build/Isomorphic.d.ts +7 -0
  9. package/build/Isomorphic.js +2 -0
  10. package/build/Isomorphic.js.map +1 -0
  11. package/build/RequestManager.d.ts +74 -0
  12. package/build/RequestManager.js +61 -0
  13. package/build/RequestManager.js.map +1 -0
  14. package/build/VIO.d.ts +82 -0
  15. package/build/VIO.js +219 -0
  16. package/build/VIO.js.map +1 -0
  17. package/build/VIOError.d.ts +17 -0
  18. package/build/VIOError.js +25 -0
  19. package/build/VIOError.js.map +1 -0
  20. package/build/VIOStrict.d.ts +62 -0
  21. package/build/VIOStrict.js +103 -0
  22. package/build/VIOStrict.js.map +1 -0
  23. package/build/index.d.ts +4 -0
  24. package/build/index.js +5 -0
  25. package/build/index.js.map +1 -0
  26. package/build/support/LineParser.d.ts +25 -0
  27. package/build/support/LineParser.js +50 -0
  28. package/build/support/LineParser.js.map +1 -0
  29. package/build/support/UTF8Codec.d.ts +34 -0
  30. package/build/support/UTF8Codec.js +155 -0
  31. package/build/support/UTF8Codec.js.map +1 -0
  32. package/build/support/UUID.d.ts +62 -0
  33. package/build/support/UUID.js +109 -0
  34. package/build/support/UUID.js.map +1 -0
  35. package/build/support/Varint.d.ts +26 -0
  36. package/build/support/Varint.js +61 -0
  37. package/build/support/Varint.js.map +1 -0
  38. package/docs/PROTOCOL-PROPOSE.md +252 -0
  39. package/package.json +35 -0
  40. package/scripts/build.sh +14 -0
  41. package/src/Frame.ts +312 -0
  42. package/src/Isomorphic.ts +7 -0
  43. package/src/RequestManager.ts +114 -0
  44. package/src/VIO.ts +194 -0
  45. package/src/VIOError.ts +22 -0
  46. package/src/VIOStrict.ts +123 -0
  47. package/src/index.ts +4 -0
  48. package/src/support/LineParser.ts +55 -0
  49. package/src/support/UTF8Codec.ts +166 -0
  50. package/src/support/UUID.ts +125 -0
  51. package/src/support/Varint.ts +62 -0
  52. package/tsconfig.json +17 -0
package/.gitignore ADDED
@@ -0,0 +1,15 @@
1
+ # Build setting
2
+ **/node_modules/
3
+ **/build/
4
+ **/build-*/
5
+ **/.**
6
+ **/*.log
7
+ **/*.env
8
+ **/*.tsbuildinfo
9
+ !.gitignore
10
+
11
+ # Work space setting
12
+ !.vscode/
13
+
14
+ # Test setting
15
+ test.ts
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 2026 NetFeez
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/PROTOCOL.md ADDED
@@ -0,0 +1,245 @@
1
+ # Vortez IO Protocol
2
+
3
+ Vortez IO Protocol works over WebSocket protocol and defines a binary frame structure for multiplexed messaging (events, requests, responses and errors).
4
+
5
+ Each WebSocket frame **MUST** contain exactly **one Vortez frame**.
6
+
7
+ ---
8
+
9
+ ## Protocol Frame Description
10
+
11
+ ### Header description map
12
+
13
+ | byte | bit | Function | description |
14
+ | ---- | --- | -------- | --------------------------------- |
15
+ | 0 | 0-3 | TYPE | [Reference for type](#type) |
16
+ | 0 | 4-7 | MODE | [Reference for mode](#mode) |
17
+ | 1 | all | RESERVED | Future use |
18
+ | 2 | 0-1 | ID_TYPE | [Reference for id-type](#id_type) |
19
+ | 2 | 2-7 | RESERVED | MUST be `0` |
20
+
21
+ > [!IMPORTANT]
22
+ >
23
+ > 🔒 **Invariant:** Header bytes (0, 1, 2) are always present.
24
+ >
25
+ > 🔒 **Invariant:** Reserved bits **MUST** be `0`.
26
+
27
+ ---
28
+
29
+ ## Frame Layout
30
+
31
+ After byte `2`, the frame continues depending on `ID_TYPE`.
32
+
33
+ ---
34
+
35
+ ### If `ID_TYPE = 0x0 (NONE)`
36
+
37
+ | byte | Function | description |
38
+ | ---- | -------- | ----------- |
39
+ | 3.. | DATA | Payload |
40
+
41
+ ---
42
+
43
+ ### If `ID_TYPE = 0x1 (UUID)`
44
+
45
+ | byte | Function | description |
46
+ | ---- | -------- | --------------------------- |
47
+ | 3-18 | UUID | 16-byte identifier (binary) |
48
+ | 19.. | DATA | Payload |
49
+
50
+ ---
51
+
52
+ ### If `ID_TYPE = 0x2 (STRING)`
53
+
54
+ | byte | Function | description |
55
+ | ------ |----------------|------------------------------------|
56
+ | 3..N | VARINT LENGTH | Length of the string |
57
+ | N+1..M | STRING | UTF-8 identifier |
58
+ | M+1.. | DATA | Payload |
59
+
60
+ ---
61
+
62
+ ## ID_TYPE
63
+
64
+ Defines the type of identifier present in the frame.
65
+
66
+ | Value | Name | Description |
67
+ | ----- |----------|----------------------------|
68
+ | `0x0` | NONE | No identifier |
69
+ | `0x1` | UUID | 16-byte binary identifier |
70
+ | `0x2` | STRING | UTF-8 string identifier |
71
+ | `0x3` | RESERVED | Reserved for future use |
72
+
73
+ ---
74
+
75
+ ## UUID Specification
76
+
77
+ * UUID **MUST** be exactly **16 bytes**
78
+ * UUID **MUST** be treated as opaque binary (no string encoding)
79
+ * Endianness is **network order (big-endian)**
80
+ * UUID is used for **request-response correlation**
81
+
82
+ ---
83
+
84
+ ## STRING Specification
85
+
86
+ * Length **MUST** be encoded using varint
87
+ * Content **MUST** be valid UTF-8
88
+ * SHOULD be used for event names or routing keys
89
+
90
+ ---
91
+
92
+ ## Varint Encoding
93
+
94
+ Used for encoding STRING length.
95
+
96
+ | bit | Function |
97
+ |-----|----------|
98
+ | 7 | CONTINUE |
99
+ | 0-6 | VALUE |
100
+
101
+ Rules:
102
+
103
+ * CONTINUE = `1` → more bytes follow
104
+ * CONTINUE = `0` → last byte
105
+ * Encoding uses **unsigned LEB128 (base-128)**
106
+
107
+ ---
108
+
109
+ ## TYPE
110
+
111
+ Defines the semantic meaning of the frame.
112
+
113
+ | Value | Name | Description |
114
+ | ----- | -------- | -------------------------- |
115
+ | `0x0` | RAW | Unstructured binary data |
116
+ | `0x1` | EVENT | Fire-and-forget message |
117
+ | `0x2` | REQUEST | Request expecting response |
118
+ | `0x3` | RESPONSE | Response to a request |
119
+ | `0x4` | ERROR | Error frame |
120
+
121
+ ---
122
+
123
+ ### TYPE Rules
124
+
125
+ #### `0x0` RAW
126
+
127
+ * **MAY** include any MODE
128
+ * **MUST NOT** rely on protocol-level semantics
129
+
130
+ ---
131
+
132
+ #### `0x1` EVENT
133
+
134
+ * MUST use STRING identifier
135
+ * MUST NOT require response
136
+
137
+ ---
138
+
139
+ #### `0x2` REQUEST
140
+
141
+ * MUST use `UUID`
142
+ * UUID MUST be unique per connection
143
+ * Receiver MUST respond with:
144
+
145
+ * `RESPONSE (0x3)`
146
+ * or `ERROR (0x4)`
147
+
148
+ ---
149
+
150
+ #### `0x3` RESPONSE
151
+
152
+ * MUST use `UUID`
153
+ * MUST match an existing request
154
+
155
+ ---
156
+
157
+ #### `0x4` ERROR
158
+
159
+ * MAY include identifier
160
+ * Behavior depends on context
161
+
162
+ ---
163
+
164
+ ## ERROR Semantics
165
+
166
+ ### 1. Error Response (Request-bound)
167
+
168
+ * TYPE: `0x4`
169
+ * ID_TYPE: `UUID`
170
+ * MUST reference an existing request
171
+
172
+ ---
173
+
174
+ ### 2. Error Feedback (Protocol-level)
175
+
176
+ * TYPE: `0x4`
177
+ * ID_TYPE: `NONE`
178
+ * MUST NOT include identifier
179
+
180
+ ---
181
+
182
+ ### Error Behavior Rules
183
+
184
+ If a frame violates protocol:
185
+
186
+ * Receiver **MUST** send `ERROR (0x4)`
187
+ * If request context exists → **MUST include UUID**
188
+ * Otherwise → **MUST use ID_TYPE = NONE**
189
+
190
+ ---
191
+
192
+ ## MODE
193
+
194
+ Defines how DATA should be interpreted.
195
+
196
+ | Value | Name | Description |
197
+ | ----- | ------ | ------------------------------------ |
198
+ | `0x0` | BINARY | Raw binary |
199
+ | `0x1` | JSON | UTF-8 encoded JSON |
200
+ | `0x2` | LINE | UTF-8 text terminated by LF (`0x0A`) |
201
+ | `0x3` | CUSTOM | Application-defined |
202
+
203
+ ---
204
+
205
+ ### MODE Rules
206
+
207
+ #### JSON (`0x1`)
208
+
209
+ * DATA **MUST** be valid UTF-8 JSON
210
+
211
+ ---
212
+
213
+ #### LINE (`0x2`)
214
+
215
+ * DATA **MUST** be UTF-8 text
216
+ * Messages **SHOULD** end with `\n` (`0x0A`)
217
+ * Receiver **MAY** trim trailing newline
218
+
219
+ ---
220
+
221
+ #### CUSTOM (`0x3`)
222
+
223
+ * Interpretation is application-defined
224
+ * Protocol **MUST NOT** enforce structure
225
+
226
+ ---
227
+
228
+ ## Reserved Space (Future Use)
229
+
230
+ * Byte `1` is reserved
231
+ * ID_META reserved bits MUST be `0`
232
+ * Future versions MAY introduce:
233
+
234
+ * flags
235
+ * compression
236
+ * fragmentation
237
+
238
+ ---
239
+
240
+ ## Protocol Guarantees
241
+
242
+ * One WebSocket frame = one Vortez frame
243
+ * No internal framing is used
244
+ * Ordering is delegated to WebSocket
245
+ * Reliability is delegated to transport
package/README.md ADDED
@@ -0,0 +1,103 @@
1
+ # Vortez IO Protocol
2
+
3
+ `vortez-io-protocol` is a small TypeScript library for encoding and decoding the Vortez IO binary frame format used over WebSocket connections. It implements the protocol described in [PROTOCOL.md](PROTOCOL.md) and provides helpers for request/response correlation, event delivery, and frame validation.
4
+
5
+ ## Features
6
+
7
+ - Binary frame encoding and decoding
8
+ - Request/response correlation with UUID identifiers
9
+ - Event frames with string identifiers
10
+ - Support for `BINARY`, `JSON`, `LINE`, and `CUSTOM` payload modes
11
+ - Strict protocol validation with typed errors
12
+ - Higher-level typed wrapper via `VIOStrict`
13
+
14
+ ## Installation
15
+
16
+ ```bash
17
+ npm install vortez-io
18
+ ```
19
+
20
+ The library is published from the TypeScript source in this repository and targets an ES module environment.
21
+
22
+ ## Quick Start
23
+
24
+ ```ts
25
+ import VIO from './build/VIO.js';
26
+ import VIOError from './build/VIOError.js';
27
+
28
+ const vio = new VIO({
29
+ setTimeout,
30
+ clearTimeout,
31
+ createUUID: () => crypto.randomUUID()
32
+ });
33
+
34
+ vio.transport.on('send', (frame) => {
35
+ websocket.send(frame);
36
+ });
37
+
38
+ websocket.onmessage = (event) => {
39
+ vio.handle(event.data);
40
+ };
41
+
42
+ vio.on('event', (name, mode, data) => {
43
+ console.log('event:', name, mode, data);
44
+ });
45
+
46
+ vio.on('request', (mode, data, respond, reject) => {
47
+ if (mode !== 'JSON') {
48
+ reject(new VIOError(VIOError.Code.INVALID_DATA, 'Unsupported request mode'));
49
+ return;
50
+ }
51
+
52
+ respond({ ok: true });
53
+ });
54
+
55
+ vio.event('connected', { ok: true });
56
+ const response = await vio.request({ action: 'ping' });
57
+ ```
58
+
59
+ ## Core API
60
+
61
+ ### `VIO`
62
+
63
+ The main transport-aware protocol runtime.
64
+
65
+ - `request(data, options?)`: send a request and await a response
66
+ - `event(name, data)`: send an event frame
67
+ - `handle(data)`: decode an incoming frame and dispatch it
68
+ - `transport`: event emitter that exposes outgoing frames through `send`
69
+
70
+ ### `Frame`
71
+
72
+ Low-level frame encoder/decoder for protocol payloads.
73
+
74
+ - `Frame.encode(...)`
75
+ - `Frame.decode(...)`
76
+
77
+ Use this when you need direct access to protocol bytes instead of the higher-level `VIO` API.
78
+
79
+ ### `VIOStrict`
80
+
81
+ Typed wrapper for validating request and event payloads with schemas from `@netfeez/common`.
82
+
83
+ ## Protocol Summary
84
+
85
+ The protocol is described in detail in [PROTOCOL.md](PROTOCOL.md). In short:
86
+
87
+ - Each WebSocket message contains exactly one Vortez frame
88
+ - Every frame starts with three header bytes
89
+ - `REQUEST` and `RESPONSE` frames use UUID identifiers
90
+ - `EVENT` frames use string identifiers
91
+ - `ERROR` frames can be protocol-level (`NONE`) or request-bound (`UUID`)
92
+
93
+ ## Development
94
+
95
+ ```bash
96
+ npm run build
97
+ ```
98
+
99
+ The build script compiles the TypeScript sources into the `build/` directory.
100
+
101
+ ## License
102
+
103
+ Apache-2.0
@@ -0,0 +1,118 @@
1
+ import VIOError from "./VIOError.js";
2
+ export declare class Frame<T extends Frame.Type = Frame.Type> implements Frame.Frame<T> {
3
+ readonly type: T;
4
+ readonly mode: Frame.Mode;
5
+ readonly identifier: Frame.IdentifierMap[T];
6
+ readonly data: ArrayBuffer;
7
+ readonly reservedRaw: number;
8
+ protected static readonly TYPE_TO_BITS: Record<Frame.Type, number>;
9
+ protected static readonly TYPE_MAP: Record<number, Frame.Type>;
10
+ protected static readonly MODE_TO_BITS: Record<Frame.Mode, number>;
11
+ protected static readonly MODE_MAP: Record<number, Frame.Mode>;
12
+ protected static readonly ID_TYPE_TO_BITS: Record<Frame.IDType, number>;
13
+ protected static readonly ID_TYPE_MAP: Record<number, Frame.IDType>;
14
+ constructor(type: T, mode: Frame.Mode, identifier: Frame.IdentifierMap[T], data: ArrayBuffer, reservedRaw: number);
15
+ /**
16
+ * Decodes a binary frame from the given ArrayBuffer or Uint8Array according to the protocol specification.
17
+ * The method parses the frame header to determine the type, mode, and identifier, and then extracts the payload data.
18
+ * It performs various validations to ensure the frame adheres to the protocol rules, such as checking reserved bits and validating identifier types based on frame type.
19
+ * @param buffer The input buffer containing the binary frame data to decode.
20
+ * @returns A Frame object representing the decoded frame with its components (type, mode, identifier, data).
21
+ * @throws VIOError if the buffer is too short, contains invalid header values, or violates protocol rules regarding type and identifier combinations.
22
+ */
23
+ static decode(buffer: ArrayBuffer | Uint8Array): Frame.FrameUnion;
24
+ /**
25
+ * Assembles a Frame object from the given components, performing additional validation to ensure that the combination of type and identifier adheres to protocol rules.
26
+ * This method is called after decoding the raw components of a frame to construct the final Frame object with proper typing and validation.
27
+ * It checks that REQUEST and RESPONSE frames use UUID identifiers, EVENT frames use STRING identifiers, and ERROR frames can use either NONE or UUID identifiers.
28
+ * If the components are valid, it returns a new Frame object; otherwise, it throws a VIOError indicating the specific protocol violation.
29
+ * @param parts An object containing the decoded components of the frame (type, mode, identifier, data, reservedRaw) to be assembled into a Frame object.
30
+ * @returns A Frame object representing the assembled frame with its components.
31
+ * @throws VIOError if the combination of type and identifier is invalid according to protocol rules.
32
+ */
33
+ protected static assemble(parts: Frame.Frame): Frame.FrameUnion;
34
+ /**
35
+ * Encodes the given frame components into a binary format according to the protocol specification.
36
+ * The resulting ArrayBuffer will contain the frame header followed by the identifier (if applicable) and the payload data.
37
+ * @param type The type of the frame (e.g., 'REQUEST', 'RESPONSE', etc.).
38
+ * @param mode The mode of the frame (e.g., 'BINARY', 'JSON', etc.).
39
+ * @param data The payload data to include in the frame, as an ArrayBuffer or Uint8Array.
40
+ * @param identifier An optional identifier for the frame, which can be of type NONE, UUID, or STRING. Defaults to NONE if not provided.
41
+ * @returns An ArrayBuffer containing the encoded frame ready for transmission.
42
+ * @throws VIOError if the provided type, mode, or identifier combination is invalid according to the protocol rules.
43
+ */
44
+ static encode(type: 'RAW', mode: Frame.Mode, data: ArrayBuffer | Uint8Array, identifier?: Frame.IdentifierMap['RAW']): ArrayBuffer;
45
+ static encode(type: 'EVENT', mode: Frame.Mode, data: ArrayBuffer | Uint8Array, identifier: Frame.IdentifierMap['EVENT']): ArrayBuffer;
46
+ static encode(type: 'REQUEST', mode: Frame.Mode, data: ArrayBuffer | Uint8Array, identifier: Frame.IdentifierMap['REQUEST']): ArrayBuffer;
47
+ static encode(type: 'RESPONSE', mode: Frame.Mode, data: ArrayBuffer | Uint8Array, identifier: Frame.IdentifierMap['RESPONSE']): ArrayBuffer;
48
+ static encode(type: 'ERROR', mode: Frame.Mode, data: ArrayBuffer | Uint8Array, identifier?: Frame.IdentifierMap['ERROR']): ArrayBuffer;
49
+ /**
50
+ * Validates the combination of frame type and identifier type according to protocol rules:
51
+ * - REQUEST and RESPONSE frames MUST use UUID identifiers.
52
+ * - EVENT frames MUST NOT use UUID identifiers (they can use STRING or NONE).
53
+ * - ERROR and RAW frames have no restrictions on identifier type.
54
+ * @param type The frame type to validate.
55
+ * @param idType The identifier type to validate against the frame type.
56
+ * @throws VIOError if the combination of type and idType is invalid according to the protocol rules.
57
+ */
58
+ protected static validate(type: Frame.Type, idType: Frame.IDType): void;
59
+ /**
60
+ * Creates a copy of the ArrayBuffer from a Uint8Array view, ensuring it is not a shared buffer.
61
+ * This is necessary because the input Uint8Array may be a view into a larger buffer, and we want to ensure that the Frame's data is isolated and immutable.
62
+ * @param view The Uint8Array view to convert into an ArrayBuffer.
63
+ * @returns A new ArrayBuffer containing the data from the view.
64
+ */
65
+ protected static toArrayBuffer(view: Uint8Array): ArrayBuffer;
66
+ /**
67
+ * Utility method to assert that a value is defined (not undefined) and throw a VIOError with the provided message if it is not.
68
+ * This is used to ensure that required values are present during decoding and validation processes.
69
+ * @param value The value to check for being defined.
70
+ * @param code The VIOError code to use if the value is undefined.
71
+ * @param msg The error message to include in the VIOError if the value is undefined.
72
+ * @returns The input value if it is defined, otherwise throws a VIOError.
73
+ * @throws VIOError if the value is undefined, with the provided message.
74
+ */
75
+ protected static assertDefined<T>(value: T | undefined, code: VIOError.Code, msg: string): T;
76
+ }
77
+ export declare namespace Frame {
78
+ type Type = 'RAW' | 'EVENT' | 'REQUEST' | 'RESPONSE' | 'ERROR';
79
+ type Mode = 'BINARY' | 'JSON' | 'LINE' | 'CUSTOM';
80
+ type IDType = 'NONE' | 'UUID' | 'STRING';
81
+ namespace Identifier {
82
+ interface Base {
83
+ type: IDType;
84
+ }
85
+ interface None extends Base {
86
+ type: 'NONE';
87
+ }
88
+ interface UUID extends Base {
89
+ type: 'UUID';
90
+ id: string;
91
+ idRaw?: Uint8Array;
92
+ }
93
+ interface String extends Base {
94
+ type: 'STRING';
95
+ id: string;
96
+ idRaw?: Uint8Array;
97
+ }
98
+ }
99
+ type Identifier = Identifier.None | Identifier.UUID | Identifier.String;
100
+ interface IdentifierMap {
101
+ RAW: Identifier.None | Identifier.UUID | Identifier.String;
102
+ EVENT: Identifier.String;
103
+ REQUEST: Identifier.UUID;
104
+ RESPONSE: Identifier.UUID;
105
+ ERROR: Identifier.None | Identifier.UUID;
106
+ }
107
+ interface Frame<T extends Type = Type> {
108
+ type: T;
109
+ mode: Mode;
110
+ identifier: IdentifierMap[T];
111
+ data: ArrayBuffer;
112
+ reservedRaw: number;
113
+ }
114
+ type FrameUnion = {
115
+ [K in Type]: Frame<K>;
116
+ }[Type];
117
+ }
118
+ export default Frame;