@moqtap/codec 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.
Files changed (71) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +95 -0
  3. package/dist/chunk-23YG7F46.js +764 -0
  4. package/dist/chunk-2NARXGVA.cjs +194 -0
  5. package/dist/chunk-3BSZ55L3.cjs +307 -0
  6. package/dist/chunk-5WFXFLL4.cjs +1185 -0
  7. package/dist/chunk-DC4L6ZIT.js +307 -0
  8. package/dist/chunk-GDRGWFEK.cjs +498 -0
  9. package/dist/chunk-IQPDRQVC.js +1185 -0
  10. package/dist/chunk-QYG6KGOV.cjs +101 -0
  11. package/dist/chunk-UOBWHJA5.js +101 -0
  12. package/dist/chunk-WNTXF3DE.cjs +764 -0
  13. package/dist/chunk-YBSEOSSP.js +194 -0
  14. package/dist/chunk-YPXLV5YK.js +498 -0
  15. package/dist/codec-CTvFtQQI.d.cts +86 -0
  16. package/dist/codec-qPzfmLNu.d.ts +86 -0
  17. package/dist/draft14-session.cjs +6 -0
  18. package/dist/draft14-session.d.cts +8 -0
  19. package/dist/draft14-session.d.ts +8 -0
  20. package/dist/draft14-session.js +6 -0
  21. package/dist/draft14.cjs +121 -0
  22. package/dist/draft14.d.cts +96 -0
  23. package/dist/draft14.d.ts +96 -0
  24. package/dist/draft14.js +121 -0
  25. package/dist/draft7-session.cjs +7 -0
  26. package/dist/draft7-session.d.cts +7 -0
  27. package/dist/draft7-session.d.ts +7 -0
  28. package/dist/draft7-session.js +7 -0
  29. package/dist/draft7.cjs +60 -0
  30. package/dist/draft7.d.cts +72 -0
  31. package/dist/draft7.d.ts +72 -0
  32. package/dist/draft7.js +60 -0
  33. package/dist/index.cjs +40 -0
  34. package/dist/index.d.cts +40 -0
  35. package/dist/index.d.ts +40 -0
  36. package/dist/index.js +40 -0
  37. package/dist/session-types-B9NIf7_F.d.ts +101 -0
  38. package/dist/session-types-CCo-oA-d.d.cts +101 -0
  39. package/dist/session.cjs +27 -0
  40. package/dist/session.d.cts +24 -0
  41. package/dist/session.d.ts +24 -0
  42. package/dist/session.js +27 -0
  43. package/dist/types-CIk5W10V.d.cts +249 -0
  44. package/dist/types-CIk5W10V.d.ts +249 -0
  45. package/dist/types-ClXELFGN.d.cts +241 -0
  46. package/dist/types-ClXELFGN.d.ts +241 -0
  47. package/package.json +84 -0
  48. package/src/core/buffer-reader.ts +107 -0
  49. package/src/core/buffer-writer.ts +91 -0
  50. package/src/core/errors.ts +1 -0
  51. package/src/core/session-types.ts +103 -0
  52. package/src/core/types.ts +363 -0
  53. package/src/drafts/draft07/announce-fsm.ts +2 -0
  54. package/src/drafts/draft07/codec.ts +874 -0
  55. package/src/drafts/draft07/index.ts +70 -0
  56. package/src/drafts/draft07/messages.ts +44 -0
  57. package/src/drafts/draft07/parameters.ts +12 -0
  58. package/src/drafts/draft07/rules.ts +75 -0
  59. package/src/drafts/draft07/session-fsm.ts +353 -0
  60. package/src/drafts/draft07/session.ts +21 -0
  61. package/src/drafts/draft07/subscription-fsm.ts +3 -0
  62. package/src/drafts/draft07/varint.ts +23 -0
  63. package/src/drafts/draft14/codec.ts +1330 -0
  64. package/src/drafts/draft14/index.ts +132 -0
  65. package/src/drafts/draft14/messages.ts +76 -0
  66. package/src/drafts/draft14/rules.ts +70 -0
  67. package/src/drafts/draft14/session-fsm.ts +480 -0
  68. package/src/drafts/draft14/session.ts +26 -0
  69. package/src/drafts/draft14/types.ts +365 -0
  70. package/src/index.ts +85 -0
  71. package/src/session.ts +58 -0
@@ -0,0 +1,194 @@
1
+ // src/core/types.ts
2
+ var DecodeError = class extends Error {
3
+ code;
4
+ offset;
5
+ constructor(code, message, offset) {
6
+ super(message);
7
+ this.name = "DecodeError";
8
+ this.code = code;
9
+ this.offset = offset;
10
+ }
11
+ };
12
+
13
+ // src/core/buffer-reader.ts
14
+ var BufferReader = class {
15
+ constructor(buffer, offset = 0) {
16
+ this.buffer = buffer;
17
+ this.view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
18
+ this.pos = offset;
19
+ }
20
+ view;
21
+ pos;
22
+ get offset() {
23
+ return this.pos;
24
+ }
25
+ get remaining() {
26
+ return this.buffer.byteLength - this.pos;
27
+ }
28
+ readUint8() {
29
+ if (this.remaining < 1) {
30
+ throw new DecodeError("UNEXPECTED_END", "Not enough bytes to read uint8", this.pos);
31
+ }
32
+ const value = this.view.getUint8(this.pos);
33
+ this.pos += 1;
34
+ return value;
35
+ }
36
+ readBytes(length) {
37
+ if (this.remaining < length) {
38
+ throw new DecodeError("UNEXPECTED_END", `Not enough bytes: need ${length}, have ${this.remaining}`, this.pos);
39
+ }
40
+ const slice = this.buffer.slice(this.pos, this.pos + length);
41
+ this.pos += length;
42
+ return slice;
43
+ }
44
+ readVarInt() {
45
+ if (this.remaining < 1) {
46
+ throw new DecodeError("UNEXPECTED_END", "Not enough bytes for varint", this.pos);
47
+ }
48
+ const first = this.view.getUint8(this.pos);
49
+ const prefix = first >> 6;
50
+ let length;
51
+ let value;
52
+ switch (prefix) {
53
+ case 0:
54
+ length = 1;
55
+ value = BigInt(first & 63);
56
+ break;
57
+ case 1:
58
+ length = 2;
59
+ if (this.remaining < 2) {
60
+ throw new DecodeError("UNEXPECTED_END", "Not enough bytes for 2-byte varint", this.pos);
61
+ }
62
+ value = BigInt(this.view.getUint16(this.pos) & 16383);
63
+ break;
64
+ case 2:
65
+ length = 4;
66
+ if (this.remaining < 4) {
67
+ throw new DecodeError("UNEXPECTED_END", "Not enough bytes for 4-byte varint", this.pos);
68
+ }
69
+ value = BigInt(this.view.getUint32(this.pos)) & 0x3fffffffn;
70
+ break;
71
+ case 3:
72
+ length = 8;
73
+ if (this.remaining < 8) {
74
+ throw new DecodeError("UNEXPECTED_END", "Not enough bytes for 8-byte varint", this.pos);
75
+ }
76
+ value = this.view.getBigUint64(this.pos) & 0x3fffffffffffffffn;
77
+ break;
78
+ default:
79
+ throw new DecodeError("INVALID_VARINT", "Invalid varint prefix", this.pos);
80
+ }
81
+ this.pos += length;
82
+ return value;
83
+ }
84
+ readString() {
85
+ const length = Number(this.readVarInt());
86
+ const bytes = this.readBytes(length);
87
+ return new TextDecoder().decode(bytes);
88
+ }
89
+ readTuple() {
90
+ const count = Number(this.readVarInt());
91
+ const result = [];
92
+ for (let i = 0; i < count; i++) {
93
+ result.push(this.readString());
94
+ }
95
+ return result;
96
+ }
97
+ readParameters() {
98
+ const count = Number(this.readVarInt());
99
+ const params = /* @__PURE__ */ new Map();
100
+ for (let i = 0; i < count; i++) {
101
+ const key = this.readVarInt();
102
+ const length = Number(this.readVarInt());
103
+ const value = this.readBytes(length);
104
+ params.set(key, value);
105
+ }
106
+ return params;
107
+ }
108
+ };
109
+
110
+ // src/core/buffer-writer.ts
111
+ var BufferWriter = class {
112
+ buffer;
113
+ view;
114
+ pos;
115
+ constructor(initialSize = 256) {
116
+ this.buffer = new Uint8Array(initialSize);
117
+ this.view = new DataView(this.buffer.buffer);
118
+ this.pos = 0;
119
+ }
120
+ get offset() {
121
+ return this.pos;
122
+ }
123
+ ensureCapacity(needed) {
124
+ const required = this.pos + needed;
125
+ if (required <= this.buffer.byteLength) return;
126
+ let newSize = this.buffer.byteLength * 2;
127
+ while (newSize < required) newSize *= 2;
128
+ const newBuffer = new Uint8Array(newSize);
129
+ newBuffer.set(this.buffer);
130
+ this.buffer = newBuffer;
131
+ this.view = new DataView(this.buffer.buffer);
132
+ }
133
+ writeUint8(value) {
134
+ this.ensureCapacity(1);
135
+ this.view.setUint8(this.pos, value);
136
+ this.pos += 1;
137
+ }
138
+ writeBytes(bytes) {
139
+ this.ensureCapacity(bytes.byteLength);
140
+ this.buffer.set(bytes, this.pos);
141
+ this.pos += bytes.byteLength;
142
+ }
143
+ writeVarInt(value) {
144
+ const v = BigInt(value);
145
+ if (v < 0n) throw new Error("VarInt value must be non-negative");
146
+ if (v < 0x40n) {
147
+ this.ensureCapacity(1);
148
+ this.view.setUint8(this.pos, Number(v));
149
+ this.pos += 1;
150
+ } else if (v < 0x4000n) {
151
+ this.ensureCapacity(2);
152
+ this.view.setUint16(this.pos, Number(v) | 16384);
153
+ this.pos += 2;
154
+ } else if (v < 0x40000000n) {
155
+ this.ensureCapacity(4);
156
+ this.view.setUint32(this.pos, Number(v) | 2147483648);
157
+ this.pos += 4;
158
+ } else if (v < 0x4000000000000000n) {
159
+ this.ensureCapacity(8);
160
+ this.view.setBigUint64(this.pos, v | 0xc000000000000000n);
161
+ this.pos += 8;
162
+ } else {
163
+ throw new Error("VarInt value exceeds 62-bit range");
164
+ }
165
+ }
166
+ writeString(str) {
167
+ const encoded = new TextEncoder().encode(str);
168
+ this.writeVarInt(encoded.byteLength);
169
+ this.writeBytes(encoded);
170
+ }
171
+ writeTuple(values) {
172
+ this.writeVarInt(values.length);
173
+ for (const v of values) {
174
+ this.writeString(v);
175
+ }
176
+ }
177
+ writeParameters(params) {
178
+ this.writeVarInt(params.size);
179
+ for (const [key, value] of params) {
180
+ this.writeVarInt(key);
181
+ this.writeVarInt(value.byteLength);
182
+ this.writeBytes(value);
183
+ }
184
+ }
185
+ finish() {
186
+ return this.buffer.slice(0, this.pos);
187
+ }
188
+ };
189
+
190
+ export {
191
+ DecodeError,
192
+ BufferReader,
193
+ BufferWriter
194
+ };
@@ -0,0 +1,498 @@
1
+ // src/drafts/draft14/rules.ts
2
+ var CONTROL_MESSAGES = /* @__PURE__ */ new Set([
3
+ "client_setup",
4
+ "server_setup",
5
+ "subscribe",
6
+ "subscribe_ok",
7
+ "subscribe_update",
8
+ "subscribe_error",
9
+ "unsubscribe",
10
+ "publish",
11
+ "publish_ok",
12
+ "publish_error",
13
+ "publish_done",
14
+ "publish_namespace",
15
+ "publish_namespace_ok",
16
+ "publish_namespace_error",
17
+ "publish_namespace_done",
18
+ "publish_namespace_cancel",
19
+ "subscribe_namespace",
20
+ "subscribe_namespace_ok",
21
+ "subscribe_namespace_error",
22
+ "unsubscribe_namespace",
23
+ "fetch",
24
+ "fetch_ok",
25
+ "fetch_error",
26
+ "fetch_cancel",
27
+ "track_status",
28
+ "track_status_ok",
29
+ "track_status_error",
30
+ "goaway",
31
+ "max_request_id",
32
+ "requests_blocked"
33
+ ]);
34
+ var CLIENT_ONLY_MESSAGES = /* @__PURE__ */ new Set([
35
+ "client_setup"
36
+ ]);
37
+ var SERVER_ONLY_MESSAGES = /* @__PURE__ */ new Set([
38
+ "server_setup"
39
+ ]);
40
+ var BIDIRECTIONAL_MESSAGES = /* @__PURE__ */ new Set([
41
+ "subscribe",
42
+ "subscribe_ok",
43
+ "subscribe_update",
44
+ "subscribe_error",
45
+ "unsubscribe",
46
+ "publish",
47
+ "publish_ok",
48
+ "publish_error",
49
+ "publish_done",
50
+ "publish_namespace",
51
+ "publish_namespace_ok",
52
+ "publish_namespace_error",
53
+ "publish_namespace_done",
54
+ "publish_namespace_cancel",
55
+ "subscribe_namespace",
56
+ "subscribe_namespace_ok",
57
+ "subscribe_namespace_error",
58
+ "unsubscribe_namespace",
59
+ "fetch",
60
+ "fetch_ok",
61
+ "fetch_error",
62
+ "fetch_cancel",
63
+ "track_status",
64
+ "track_status_ok",
65
+ "track_status_error",
66
+ "goaway",
67
+ "max_request_id",
68
+ "requests_blocked"
69
+ ]);
70
+ function getLegalOutgoing(phase, role) {
71
+ const legal = /* @__PURE__ */ new Set();
72
+ switch (phase) {
73
+ case "idle":
74
+ if (role === "client") legal.add("client_setup");
75
+ break;
76
+ case "setup":
77
+ if (role === "server") legal.add("server_setup");
78
+ break;
79
+ case "ready": {
80
+ legal.add("goaway");
81
+ for (const msg of BIDIRECTIONAL_MESSAGES) {
82
+ legal.add(msg);
83
+ }
84
+ break;
85
+ }
86
+ case "draining":
87
+ break;
88
+ }
89
+ return legal;
90
+ }
91
+ function getLegalIncoming(phase, role) {
92
+ const remoteRole = role === "client" ? "server" : "client";
93
+ return getLegalOutgoing(phase, remoteRole);
94
+ }
95
+
96
+ // src/drafts/draft14/session-fsm.ts
97
+ function violation(code, message, currentPhase, offendingMessage) {
98
+ return { code, message, currentPhase, offendingMessage };
99
+ }
100
+ var Draft14SessionFSM = class {
101
+ _phase = "idle";
102
+ _role;
103
+ _subscriptions = /* @__PURE__ */ new Map();
104
+ _publishes = /* @__PURE__ */ new Map();
105
+ _fetches = /* @__PURE__ */ new Map();
106
+ _requestIds = /* @__PURE__ */ new Set();
107
+ constructor(role) {
108
+ this._role = role;
109
+ }
110
+ get phase() {
111
+ return this._phase;
112
+ }
113
+ get role() {
114
+ return this._role;
115
+ }
116
+ get subscriptions() {
117
+ return this._subscriptions;
118
+ }
119
+ get announces() {
120
+ return /* @__PURE__ */ new Map();
121
+ }
122
+ get publishes() {
123
+ return this._publishes;
124
+ }
125
+ get fetches() {
126
+ return this._fetches;
127
+ }
128
+ get legalOutgoing() {
129
+ return getLegalOutgoing(this._phase, this._role);
130
+ }
131
+ get legalIncoming() {
132
+ return getLegalIncoming(this._phase, this._role);
133
+ }
134
+ // Validate role constraints
135
+ checkRole(message, direction) {
136
+ const senderRole = direction === "outbound" ? this._role : this._role === "client" ? "server" : "client";
137
+ if (CLIENT_ONLY_MESSAGES.has(message.type) && senderRole !== "client") {
138
+ return violation("ROLE_VIOLATION", `${message.type} can only be sent by client`, this._phase, message.type);
139
+ }
140
+ if (SERVER_ONLY_MESSAGES.has(message.type) && senderRole !== "server") {
141
+ return violation("ROLE_VIOLATION", `${message.type} can only be sent by server`, this._phase, message.type);
142
+ }
143
+ return null;
144
+ }
145
+ checkDuplicateRequestId(requestId, msgType) {
146
+ if (this._requestIds.has(requestId)) {
147
+ return violation("DUPLICATE_REQUEST_ID", `Request ID ${requestId} already in use`, this._phase, msgType);
148
+ }
149
+ return null;
150
+ }
151
+ checkKnownRequestId(requestId, msgType) {
152
+ if (!this._requestIds.has(requestId)) {
153
+ return violation("UNKNOWN_REQUEST_ID", `No request with ID ${requestId}`, this._phase, msgType);
154
+ }
155
+ return null;
156
+ }
157
+ validateOutgoing(message) {
158
+ const roleViolation = this.checkRole(message, "outbound");
159
+ if (roleViolation) return { ok: false, violation: roleViolation };
160
+ if (!this.legalOutgoing.has(message.type)) {
161
+ return {
162
+ ok: false,
163
+ violation: violation(
164
+ this._phase === "idle" || this._phase === "setup" ? "MESSAGE_BEFORE_SETUP" : "UNEXPECTED_MESSAGE",
165
+ `Cannot send ${message.type} in phase ${this._phase}`,
166
+ this._phase,
167
+ message.type
168
+ )
169
+ };
170
+ }
171
+ return { ok: true };
172
+ }
173
+ receive(message) {
174
+ const roleViolation = this.checkRole(message, "inbound");
175
+ if (roleViolation) return { ok: false, violation: roleViolation };
176
+ return this.applyTransition(message, "inbound");
177
+ }
178
+ send(message) {
179
+ const roleViolation = this.checkRole(message, "outbound");
180
+ if (roleViolation) return { ok: false, violation: roleViolation };
181
+ return this.applyTransition(message, "outbound");
182
+ }
183
+ applyTransition(message, direction) {
184
+ const sideEffects = [];
185
+ switch (message.type) {
186
+ case "client_setup":
187
+ return this.handleClientSetup(message, direction);
188
+ case "server_setup":
189
+ return this.handleServerSetup(message, direction);
190
+ case "goaway":
191
+ return this.handleGoAway(message, direction, sideEffects);
192
+ // Subscribe lifecycle
193
+ case "subscribe":
194
+ return this.handleSubscribe(message, direction, sideEffects);
195
+ case "subscribe_ok":
196
+ return this.handleSubscribeOk(message, direction, sideEffects);
197
+ case "subscribe_error":
198
+ return this.handleSubscribeError(message, direction, sideEffects);
199
+ case "subscribe_update":
200
+ return this.handleSubscribeUpdate(message, direction, sideEffects);
201
+ case "unsubscribe":
202
+ return this.handleUnsubscribe(message, direction, sideEffects);
203
+ // Publish lifecycle
204
+ case "publish":
205
+ return this.handlePublish(message, direction, sideEffects);
206
+ case "publish_ok":
207
+ return this.handlePublishOk(message, direction, sideEffects);
208
+ case "publish_error":
209
+ return this.handlePublishError(message, direction, sideEffects);
210
+ case "publish_done":
211
+ return this.handlePublishDone(message, direction, sideEffects);
212
+ // Fetch lifecycle
213
+ case "fetch":
214
+ return this.handleFetch(message, direction, sideEffects);
215
+ case "fetch_ok":
216
+ return this.handleFetchOk(message, direction, sideEffects);
217
+ case "fetch_error":
218
+ return this.handleFetchError(message, direction, sideEffects);
219
+ case "fetch_cancel":
220
+ return this.handleFetchCancel(message, direction, sideEffects);
221
+ // Publish namespace, subscribe namespace, track status, and other ready-phase messages
222
+ default:
223
+ return this.handleReadyPhaseMessage(message);
224
+ }
225
+ }
226
+ handleClientSetup(_message, direction) {
227
+ if (this._phase !== "idle") {
228
+ return { ok: false, violation: violation("SETUP_VIOLATION", "CLIENT_SETUP already sent/received", this._phase, "client_setup") };
229
+ }
230
+ if (direction === "outbound" && this._role !== "client") {
231
+ return { ok: false, violation: violation("ROLE_VIOLATION", "Only client can send CLIENT_SETUP", this._phase, "client_setup") };
232
+ }
233
+ this._phase = "setup";
234
+ return { ok: true, phase: this._phase, sideEffects: [] };
235
+ }
236
+ handleServerSetup(_message, direction) {
237
+ if (this._phase !== "setup") {
238
+ return { ok: false, violation: violation("SETUP_VIOLATION", "SERVER_SETUP before CLIENT_SETUP", this._phase, "server_setup") };
239
+ }
240
+ if (direction === "outbound" && this._role !== "server") {
241
+ return { ok: false, violation: violation("ROLE_VIOLATION", "Only server can send SERVER_SETUP", this._phase, "server_setup") };
242
+ }
243
+ this._phase = "ready";
244
+ return { ok: true, phase: this._phase, sideEffects: [{ type: "session-ready" }] };
245
+ }
246
+ handleGoAway(message, _direction, sideEffects) {
247
+ if (this._phase !== "ready" && this._phase !== "draining") {
248
+ return { ok: false, violation: violation("UNEXPECTED_MESSAGE", `GOAWAY not valid in phase ${this._phase}`, this._phase, "goaway") };
249
+ }
250
+ this._phase = "draining";
251
+ const goaway = message;
252
+ sideEffects.push({ type: "session-draining", goAwayUri: goaway.new_session_uri });
253
+ return { ok: true, phase: this._phase, sideEffects };
254
+ }
255
+ requireReady(msgType) {
256
+ if (this._phase !== "ready" && this._phase !== "draining") {
257
+ return violation(
258
+ this._phase === "idle" || this._phase === "setup" ? "MESSAGE_BEFORE_SETUP" : "UNEXPECTED_MESSAGE",
259
+ `${msgType} requires ready phase, current: ${this._phase}`,
260
+ this._phase,
261
+ msgType
262
+ );
263
+ }
264
+ return null;
265
+ }
266
+ // ─── Subscribe lifecycle ──────────────────────────────────────────────────────
267
+ handleSubscribe(message, _direction, sideEffects) {
268
+ const err = this.requireReady(message.type);
269
+ if (err) return { ok: false, violation: err };
270
+ const sub = message;
271
+ const dupErr = this.checkDuplicateRequestId(sub.request_id, message.type);
272
+ if (dupErr) return { ok: false, violation: dupErr };
273
+ this._requestIds.add(sub.request_id);
274
+ this._subscriptions.set(sub.request_id, {
275
+ subscribeId: sub.request_id,
276
+ phase: "pending",
277
+ trackNamespace: sub.track_namespace,
278
+ trackName: sub.track_name
279
+ });
280
+ return { ok: true, phase: this._phase, sideEffects };
281
+ }
282
+ handleSubscribeOk(message, _direction, sideEffects) {
283
+ const err = this.requireReady(message.type);
284
+ if (err) return { ok: false, violation: err };
285
+ const ok = message;
286
+ const idErr = this.checkKnownRequestId(ok.request_id, message.type);
287
+ if (idErr) return { ok: false, violation: idErr };
288
+ const existing = this._subscriptions.get(ok.request_id);
289
+ if (!existing) {
290
+ return { ok: false, violation: violation("UNKNOWN_REQUEST_ID", `No subscription with request ID ${ok.request_id}`, this._phase, message.type) };
291
+ }
292
+ if (existing.phase !== "pending") {
293
+ return { ok: false, violation: violation("STATE_VIOLATION", `Subscription ${ok.request_id} is ${existing.phase}, not pending`, this._phase, message.type) };
294
+ }
295
+ this._subscriptions.set(ok.request_id, { ...existing, phase: "active" });
296
+ sideEffects.push({ type: "subscription-activated", subscribeId: ok.request_id });
297
+ return { ok: true, phase: this._phase, sideEffects };
298
+ }
299
+ handleSubscribeError(message, _direction, sideEffects) {
300
+ const err = this.requireReady(message.type);
301
+ if (err) return { ok: false, violation: err };
302
+ const subErr = message;
303
+ const idErr = this.checkKnownRequestId(subErr.request_id, message.type);
304
+ if (idErr) return { ok: false, violation: idErr };
305
+ const existing = this._subscriptions.get(subErr.request_id);
306
+ if (!existing) {
307
+ return { ok: false, violation: violation("UNKNOWN_REQUEST_ID", `No subscription with request ID ${subErr.request_id}`, this._phase, message.type) };
308
+ }
309
+ if (existing.phase !== "pending") {
310
+ return { ok: false, violation: violation("STATE_VIOLATION", `Subscription ${subErr.request_id} is ${existing.phase}, not pending`, this._phase, message.type) };
311
+ }
312
+ this._subscriptions.set(subErr.request_id, { ...existing, phase: "error" });
313
+ sideEffects.push({ type: "subscription-ended", subscribeId: subErr.request_id, reason: subErr.reason_phrase });
314
+ return { ok: true, phase: this._phase, sideEffects };
315
+ }
316
+ handleSubscribeUpdate(message, _direction, sideEffects) {
317
+ const err = this.requireReady(message.type);
318
+ if (err) return { ok: false, violation: err };
319
+ const update = message;
320
+ const idErr = this.checkKnownRequestId(update.request_id, message.type);
321
+ if (idErr) return { ok: false, violation: idErr };
322
+ const existing = this._subscriptions.get(update.request_id);
323
+ if (!existing) {
324
+ return { ok: false, violation: violation("UNKNOWN_REQUEST_ID", `No subscription with request ID ${update.request_id}`, this._phase, message.type) };
325
+ }
326
+ if (existing.phase !== "active") {
327
+ return { ok: false, violation: violation("STATE_VIOLATION", `Subscription ${update.request_id} is ${existing.phase}, not active`, this._phase, message.type) };
328
+ }
329
+ return { ok: true, phase: this._phase, sideEffects };
330
+ }
331
+ handleUnsubscribe(message, _direction, sideEffects) {
332
+ const err = this.requireReady(message.type);
333
+ if (err) return { ok: false, violation: err };
334
+ const unsub = message;
335
+ const idErr = this.checkKnownRequestId(unsub.request_id, message.type);
336
+ if (idErr) return { ok: false, violation: idErr };
337
+ const existing = this._subscriptions.get(unsub.request_id);
338
+ if (!existing) {
339
+ return { ok: false, violation: violation("UNKNOWN_REQUEST_ID", `No subscription with request ID ${unsub.request_id}`, this._phase, message.type) };
340
+ }
341
+ this._subscriptions.set(unsub.request_id, { ...existing, phase: "done" });
342
+ sideEffects.push({ type: "subscription-ended", subscribeId: unsub.request_id, reason: "unsubscribed" });
343
+ return { ok: true, phase: this._phase, sideEffects };
344
+ }
345
+ // ─── Publish lifecycle ────────────────────────────────────────────────────────
346
+ handlePublish(message, _direction, sideEffects) {
347
+ const err = this.requireReady(message.type);
348
+ if (err) return { ok: false, violation: err };
349
+ const pub = message;
350
+ const dupErr = this.checkDuplicateRequestId(pub.request_id, message.type);
351
+ if (dupErr) return { ok: false, violation: dupErr };
352
+ this._requestIds.add(pub.request_id);
353
+ this._publishes.set(pub.request_id, {
354
+ requestId: pub.request_id,
355
+ phase: "pending"
356
+ });
357
+ return { ok: true, phase: this._phase, sideEffects };
358
+ }
359
+ handlePublishOk(message, _direction, sideEffects) {
360
+ const err = this.requireReady(message.type);
361
+ if (err) return { ok: false, violation: err };
362
+ const ok = message;
363
+ const idErr = this.checkKnownRequestId(ok.request_id, message.type);
364
+ if (idErr) return { ok: false, violation: idErr };
365
+ const existing = this._publishes.get(ok.request_id);
366
+ if (!existing) {
367
+ return { ok: false, violation: violation("UNKNOWN_REQUEST_ID", `No publish with request ID ${ok.request_id}`, this._phase, message.type) };
368
+ }
369
+ if (existing.phase !== "pending") {
370
+ return { ok: false, violation: violation("STATE_VIOLATION", `Publish ${ok.request_id} is ${existing.phase}, not pending`, this._phase, message.type) };
371
+ }
372
+ this._publishes.set(ok.request_id, { ...existing, phase: "active" });
373
+ sideEffects.push({ type: "publish-activated", requestId: ok.request_id });
374
+ return { ok: true, phase: this._phase, sideEffects };
375
+ }
376
+ handlePublishError(message, _direction, sideEffects) {
377
+ const err = this.requireReady(message.type);
378
+ if (err) return { ok: false, violation: err };
379
+ const pubErr = message;
380
+ const idErr = this.checkKnownRequestId(pubErr.request_id, message.type);
381
+ if (idErr) return { ok: false, violation: idErr };
382
+ const existing = this._publishes.get(pubErr.request_id);
383
+ if (!existing) {
384
+ return { ok: false, violation: violation("UNKNOWN_REQUEST_ID", `No publish with request ID ${pubErr.request_id}`, this._phase, message.type) };
385
+ }
386
+ if (existing.phase !== "pending") {
387
+ return { ok: false, violation: violation("STATE_VIOLATION", `Publish ${pubErr.request_id} is ${existing.phase}, not pending`, this._phase, message.type) };
388
+ }
389
+ this._publishes.set(pubErr.request_id, { ...existing, phase: "error" });
390
+ sideEffects.push({ type: "publish-ended", requestId: pubErr.request_id, reason: pubErr.reason_phrase });
391
+ return { ok: true, phase: this._phase, sideEffects };
392
+ }
393
+ handlePublishDone(message, _direction, sideEffects) {
394
+ const err = this.requireReady(message.type);
395
+ if (err) return { ok: false, violation: err };
396
+ const done = message;
397
+ const idErr = this.checkKnownRequestId(done.request_id, message.type);
398
+ if (idErr) return { ok: false, violation: idErr };
399
+ const existing = this._publishes.get(done.request_id);
400
+ if (!existing) {
401
+ return { ok: false, violation: violation("UNKNOWN_REQUEST_ID", `No publish with request ID ${done.request_id}`, this._phase, message.type) };
402
+ }
403
+ this._publishes.set(done.request_id, { ...existing, phase: "done" });
404
+ sideEffects.push({ type: "publish-ended", requestId: done.request_id, reason: done.reason_phrase });
405
+ return { ok: true, phase: this._phase, sideEffects };
406
+ }
407
+ // ─── Fetch lifecycle ──────────────────────────────────────────────────────────
408
+ handleFetch(message, _direction, sideEffects) {
409
+ const err = this.requireReady(message.type);
410
+ if (err) return { ok: false, violation: err };
411
+ const fetch = message;
412
+ const dupErr = this.checkDuplicateRequestId(fetch.request_id, message.type);
413
+ if (dupErr) return { ok: false, violation: dupErr };
414
+ this._requestIds.add(fetch.request_id);
415
+ this._fetches.set(fetch.request_id, {
416
+ requestId: fetch.request_id,
417
+ phase: "pending"
418
+ });
419
+ return { ok: true, phase: this._phase, sideEffects };
420
+ }
421
+ handleFetchOk(message, _direction, sideEffects) {
422
+ const err = this.requireReady(message.type);
423
+ if (err) return { ok: false, violation: err };
424
+ const ok = message;
425
+ const idErr = this.checkKnownRequestId(ok.request_id, message.type);
426
+ if (idErr) return { ok: false, violation: idErr };
427
+ const existing = this._fetches.get(ok.request_id);
428
+ if (!existing) {
429
+ return { ok: false, violation: violation("UNKNOWN_REQUEST_ID", `No fetch with request ID ${ok.request_id}`, this._phase, message.type) };
430
+ }
431
+ if (existing.phase !== "pending") {
432
+ return { ok: false, violation: violation("STATE_VIOLATION", `Fetch ${ok.request_id} is ${existing.phase}, not pending`, this._phase, message.type) };
433
+ }
434
+ this._fetches.set(ok.request_id, { ...existing, phase: "active" });
435
+ sideEffects.push({ type: "fetch-activated", requestId: ok.request_id });
436
+ return { ok: true, phase: this._phase, sideEffects };
437
+ }
438
+ handleFetchError(message, _direction, sideEffects) {
439
+ const err = this.requireReady(message.type);
440
+ if (err) return { ok: false, violation: err };
441
+ const fetchErr = message;
442
+ const idErr = this.checkKnownRequestId(fetchErr.request_id, message.type);
443
+ if (idErr) return { ok: false, violation: idErr };
444
+ const existing = this._fetches.get(fetchErr.request_id);
445
+ if (!existing) {
446
+ return { ok: false, violation: violation("UNKNOWN_REQUEST_ID", `No fetch with request ID ${fetchErr.request_id}`, this._phase, message.type) };
447
+ }
448
+ if (existing.phase !== "pending") {
449
+ return { ok: false, violation: violation("STATE_VIOLATION", `Fetch ${fetchErr.request_id} is ${existing.phase}, not pending`, this._phase, message.type) };
450
+ }
451
+ this._fetches.set(fetchErr.request_id, { ...existing, phase: "error" });
452
+ sideEffects.push({ type: "fetch-ended", requestId: fetchErr.request_id, reason: fetchErr.reason_phrase });
453
+ return { ok: true, phase: this._phase, sideEffects };
454
+ }
455
+ handleFetchCancel(message, _direction, sideEffects) {
456
+ const err = this.requireReady(message.type);
457
+ if (err) return { ok: false, violation: err };
458
+ const cancel = message;
459
+ const idErr = this.checkKnownRequestId(cancel.request_id, message.type);
460
+ if (idErr) return { ok: false, violation: idErr };
461
+ const existing = this._fetches.get(cancel.request_id);
462
+ if (!existing) {
463
+ return { ok: false, violation: violation("UNKNOWN_REQUEST_ID", `No fetch with request ID ${cancel.request_id}`, this._phase, message.type) };
464
+ }
465
+ this._fetches.set(cancel.request_id, { ...existing, phase: "cancelled" });
466
+ sideEffects.push({ type: "fetch-ended", requestId: cancel.request_id, reason: "cancelled" });
467
+ return { ok: true, phase: this._phase, sideEffects };
468
+ }
469
+ // ─── Generic ready-phase handler ──────────────────────────────────────────────
470
+ handleReadyPhaseMessage(message) {
471
+ const err = this.requireReady(message.type);
472
+ if (err) return { ok: false, violation: err };
473
+ return { ok: true, phase: this._phase, sideEffects: [] };
474
+ }
475
+ reset() {
476
+ this._phase = "idle";
477
+ this._subscriptions.clear();
478
+ this._publishes.clear();
479
+ this._fetches.clear();
480
+ this._requestIds.clear();
481
+ }
482
+ };
483
+
484
+ // src/drafts/draft14/session.ts
485
+ function createDraft14SessionState(options) {
486
+ return new Draft14SessionFSM(options.role);
487
+ }
488
+
489
+ export {
490
+ CONTROL_MESSAGES,
491
+ CLIENT_ONLY_MESSAGES,
492
+ SERVER_ONLY_MESSAGES,
493
+ BIDIRECTIONAL_MESSAGES,
494
+ getLegalOutgoing,
495
+ getLegalIncoming,
496
+ Draft14SessionFSM,
497
+ createDraft14SessionState
498
+ };