@moq/net 0.4.0 → 0.4.2

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 (204) hide show
  1. package/announced.d.ts +14 -0
  2. package/announced.d.ts.map +1 -1
  3. package/announced.js.map +1 -1
  4. package/broadcast.d.ts +27 -10
  5. package/broadcast.d.ts.map +1 -1
  6. package/broadcast.js +47 -21
  7. package/broadcast.js.map +1 -1
  8. package/connection/accept.js +14 -4
  9. package/connection/accept.js.map +1 -1
  10. package/connection/connect.d.ts.map +1 -1
  11. package/connection/connect.js +14 -4
  12. package/connection/connect.js.map +1 -1
  13. package/connection/established.d.ts +2 -1
  14. package/connection/established.d.ts.map +1 -1
  15. package/connection/established.js.map +1 -1
  16. package/connection/forward.js +61 -47
  17. package/connection/forward.js.map +1 -1
  18. package/connection/goaway.d.ts +34 -0
  19. package/connection/goaway.d.ts.map +1 -0
  20. package/connection/goaway.js +176 -0
  21. package/connection/goaway.js.map +1 -0
  22. package/connection/handshake.d.ts +5 -2
  23. package/connection/handshake.d.ts.map +1 -1
  24. package/connection/handshake.js +45 -10
  25. package/connection/handshake.js.map +1 -1
  26. package/connection/pool.d.ts +24 -11
  27. package/connection/pool.d.ts.map +1 -1
  28. package/connection/pool.js +50 -18
  29. package/connection/pool.js.map +1 -1
  30. package/connection/reload.d.ts.map +1 -1
  31. package/connection/reload.js +189 -35
  32. package/connection/reload.js.map +1 -1
  33. package/error.d.ts +11 -0
  34. package/error.d.ts.map +1 -1
  35. package/error.js +35 -0
  36. package/error.js.map +1 -1
  37. package/errors.d.ts +1 -1
  38. package/errors.d.ts.map +1 -1
  39. package/errors.js +1 -1
  40. package/errors.js.map +1 -1
  41. package/group.d.ts.map +1 -1
  42. package/group.js +5 -4
  43. package/group.js.map +1 -1
  44. package/hop.d.ts +8 -0
  45. package/hop.d.ts.map +1 -1
  46. package/hop.js +16 -0
  47. package/hop.js.map +1 -1
  48. package/ietf/adapter.d.ts +9 -1
  49. package/ietf/adapter.d.ts.map +1 -1
  50. package/ietf/adapter.js +46 -17
  51. package/ietf/adapter.js.map +1 -1
  52. package/ietf/cluster.d.ts +3 -3
  53. package/ietf/cluster.js +3 -3
  54. package/ietf/cluster.js.map +1 -1
  55. package/ietf/connection.d.ts +1 -1
  56. package/ietf/connection.d.ts.map +1 -1
  57. package/ietf/connection.js +118 -41
  58. package/ietf/connection.js.map +1 -1
  59. package/ietf/error.js +27 -2
  60. package/ietf/error.js.map +1 -1
  61. package/ietf/fetch.d.ts +7 -20
  62. package/ietf/fetch.d.ts.map +1 -1
  63. package/ietf/fetch.js +52 -22
  64. package/ietf/fetch.js.map +1 -1
  65. package/ietf/filter.d.ts +2 -0
  66. package/ietf/filter.d.ts.map +1 -1
  67. package/ietf/filter.js +4 -0
  68. package/ietf/filter.js.map +1 -1
  69. package/ietf/goaway.d.ts +9 -1
  70. package/ietf/goaway.d.ts.map +1 -1
  71. package/ietf/goaway.js +20 -0
  72. package/ietf/goaway.js.map +1 -1
  73. package/ietf/hidden.d.ts +2 -0
  74. package/ietf/hidden.d.ts.map +1 -0
  75. package/ietf/hidden.js +30 -0
  76. package/ietf/hidden.js.map +1 -0
  77. package/ietf/index.d.ts +2 -1
  78. package/ietf/index.d.ts.map +1 -1
  79. package/ietf/index.js +2 -1
  80. package/ietf/index.js.map +1 -1
  81. package/ietf/object.d.ts +15 -8
  82. package/ietf/object.d.ts.map +1 -1
  83. package/ietf/object.js +54 -36
  84. package/ietf/object.js.map +1 -1
  85. package/ietf/parameters.d.ts +12 -0
  86. package/ietf/parameters.d.ts.map +1 -1
  87. package/ietf/parameters.js +82 -12
  88. package/ietf/parameters.js.map +1 -1
  89. package/ietf/properties.d.ts +1 -0
  90. package/ietf/properties.d.ts.map +1 -1
  91. package/ietf/properties.js +14 -0
  92. package/ietf/properties.js.map +1 -1
  93. package/ietf/publish.d.ts +19 -2
  94. package/ietf/publish.d.ts.map +1 -1
  95. package/ietf/publish.js +40 -6
  96. package/ietf/publish.js.map +1 -1
  97. package/ietf/publish_namespace.d.ts +2 -2
  98. package/ietf/publish_namespace.js +2 -2
  99. package/ietf/publish_namespace.js.map +1 -1
  100. package/ietf/publisher.js +383 -214
  101. package/ietf/publisher.js.map +1 -1
  102. package/ietf/subscribe.d.ts +7 -1
  103. package/ietf/subscribe.d.ts.map +1 -1
  104. package/ietf/subscribe.js +25 -18
  105. package/ietf/subscribe.js.map +1 -1
  106. package/ietf/subscribe_namespace.d.ts +8 -2
  107. package/ietf/subscribe_namespace.d.ts.map +1 -1
  108. package/ietf/subscribe_namespace.js +20 -11
  109. package/ietf/subscribe_namespace.js.map +1 -1
  110. package/ietf/subscriber.js +226 -88
  111. package/ietf/subscriber.js.map +1 -1
  112. package/ietf/token.d.ts +2 -0
  113. package/ietf/token.d.ts.map +1 -0
  114. package/ietf/token.js +99 -0
  115. package/ietf/token.js.map +1 -0
  116. package/ietf/track.d.ts +4 -0
  117. package/ietf/track.d.ts.map +1 -1
  118. package/ietf/track.js +6 -20
  119. package/ietf/track.js.map +1 -1
  120. package/index.d.ts +1 -1
  121. package/index.d.ts.map +1 -1
  122. package/index.js.map +1 -1
  123. package/internal.d.ts +19 -3
  124. package/internal.d.ts.map +1 -1
  125. package/internal.js +43 -0
  126. package/internal.js.map +1 -1
  127. package/lite/announce.d.ts +46 -2
  128. package/lite/announce.d.ts.map +1 -1
  129. package/lite/announce.js +133 -15
  130. package/lite/announce.js.map +1 -1
  131. package/lite/connection.d.ts +1 -1
  132. package/lite/connection.d.ts.map +1 -1
  133. package/lite/connection.js +30 -9
  134. package/lite/connection.js.map +1 -1
  135. package/lite/datagram.d.ts +3 -2
  136. package/lite/datagram.d.ts.map +1 -1
  137. package/lite/datagram.js +7 -8
  138. package/lite/datagram.js.map +1 -1
  139. package/lite/group.d.ts +12 -8
  140. package/lite/group.d.ts.map +1 -1
  141. package/lite/group.js +37 -16
  142. package/lite/group.js.map +1 -1
  143. package/lite/message.d.ts +2 -2
  144. package/lite/message.d.ts.map +1 -1
  145. package/lite/message.js +14 -5
  146. package/lite/message.js.map +1 -1
  147. package/lite/publisher.js +174 -133
  148. package/lite/publisher.js.map +1 -1
  149. package/lite/setup.d.ts +1 -1
  150. package/lite/setup.d.ts.map +1 -1
  151. package/lite/setup.js +22 -19
  152. package/lite/setup.js.map +1 -1
  153. package/lite/subscribe.d.ts +10 -4
  154. package/lite/subscribe.d.ts.map +1 -1
  155. package/lite/subscribe.js +20 -10
  156. package/lite/subscribe.js.map +1 -1
  157. package/lite/subscriber.d.ts +10 -2
  158. package/lite/subscriber.d.ts.map +1 -1
  159. package/lite/subscriber.js +333 -188
  160. package/lite/subscriber.js.map +1 -1
  161. package/lite/version.d.ts +11 -0
  162. package/lite/version.d.ts.map +1 -1
  163. package/lite/version.js +56 -0
  164. package/lite/version.js.map +1 -1
  165. package/origin.d.ts +46 -19
  166. package/origin.d.ts.map +1 -1
  167. package/origin.js +529 -189
  168. package/origin.js.map +1 -1
  169. package/package.json +8 -4
  170. package/stream.d.ts +79 -14
  171. package/stream.d.ts.map +1 -1
  172. package/stream.js +375 -133
  173. package/stream.js.map +1 -1
  174. package/tail.d.ts +18 -0
  175. package/tail.d.ts.map +1 -0
  176. package/tail.js +167 -0
  177. package/tail.js.map +1 -0
  178. package/track.d.ts +46 -7
  179. package/track.d.ts.map +1 -1
  180. package/track.js +263 -101
  181. package/track.js.map +1 -1
  182. package/util/abort.d.ts +2 -0
  183. package/util/abort.d.ts.map +1 -0
  184. package/util/abort.js +20 -0
  185. package/util/abort.js.map +1 -0
  186. package/util/u64.d.ts +39 -0
  187. package/util/u64.d.ts.map +1 -0
  188. package/util/u64.js +83 -0
  189. package/util/u64.js.map +1 -0
  190. package/util/varint.d.ts +29 -0
  191. package/util/varint.d.ts.map +1 -0
  192. package/util/varint.js +198 -0
  193. package/util/varint.js.map +1 -0
  194. package/varint.d.ts +10 -6
  195. package/varint.d.ts.map +1 -1
  196. package/varint.js +40 -237
  197. package/varint.js.map +1 -1
  198. package/wire.d.ts +19 -3
  199. package/wire.d.ts.map +1 -1
  200. package/wire.js.map +1 -1
  201. package/ietf/control.d.ts +0 -135
  202. package/ietf/control.d.ts.map +0 -1
  203. package/ietf/control.js +0 -242
  204. package/ietf/control.js.map +0 -1
package/stream.js CHANGED
@@ -1,12 +1,16 @@
1
1
  /* @ts-self-types="./stream.d.ts" */
2
+ import { race } from "@moq/signals";
2
3
  import { fromTransport, StreamCode, StreamError, toStreamCode, toTransport } from "./error.js";
3
4
  import { Version } from "./ietf/version.js";
5
+ import { Version as Lite } from "./lite/version.js";
4
6
  import { TimeoutError, withTimeout } from "./util/timeout.js";
7
+ import { POW32, toBigInt, toNumber, U64 } from "./util/u64.js";
5
8
  import { decodeUtf8 } from "./util/utf8.js";
6
- import * as Varint from "./varint.js";
9
+ import { lengthLeadingOnes, lengthQuic, parts, peekLeadingOnes, peekQuic, readLeadingOnes, readQuic, split, writeLeadingOnes, writeQuic, } from "./util/varint.js";
7
10
  // Decode raw transport errors before mapping so they cannot bypass the negotiated
8
11
  // registry. Ordinary errors already send 0 and retain their local identity.
9
- function withCode(reason, version) {
12
+ function withCode(reason, stream) {
13
+ const version = asIetf(stream);
10
14
  const decoded = fromTransport(reason, { version });
11
15
  const code = toStreamCode(decoded, { version });
12
16
  return code === StreamCode.Internal && decoded === reason ? reason : toTransport(code, decoded.message);
@@ -42,18 +46,56 @@ async function openWithin(opening, timeout, discard) {
42
46
  throw err;
43
47
  }
44
48
  }
49
+ const LITE = new Set(Object.values(Lite));
50
+ function isLite(version) {
51
+ return LITE.has(version);
52
+ }
53
+ /** The moq-transport draft a stream follows, or undefined on moq-lite, whose stream codes are the same on every draft. */
54
+ export function asIetf(version) {
55
+ return isLite(version) ? undefined : version;
56
+ }
57
+ // Every draft newer than these counts leading ones, so a new version falls forward.
45
58
  function isLeadingOnes(version) {
46
- return (version !== undefined &&
47
- version !== Version.DRAFT_14 &&
48
- version !== Version.DRAFT_15 &&
49
- version !== Version.DRAFT_16);
59
+ switch (version) {
60
+ case Version.DRAFT_14:
61
+ case Version.DRAFT_15:
62
+ case Version.DRAFT_16:
63
+ case Lite.DRAFT_01:
64
+ case Lite.DRAFT_02:
65
+ case Lite.DRAFT_03:
66
+ case Lite.DRAFT_04:
67
+ case Lite.DRAFT_05:
68
+ case Lite.DRAFT_06:
69
+ return false;
70
+ default:
71
+ return true;
72
+ }
73
+ }
74
+ // Encode `hi`/`lo` into `dst` in the varint form `version` uses: QUIC up to 2^62-1, leading-ones up to 2^64-1.
75
+ function encodeTo(dst, hi, lo, version) {
76
+ let buf;
77
+ if (isLeadingOnes(version)) {
78
+ buf = new Uint8Array(dst, 0, lengthLeadingOnes(hi, lo));
79
+ writeLeadingOnes(buf, hi, lo, buf.length);
80
+ }
81
+ else {
82
+ buf = new Uint8Array(dst, 0, lengthQuic(hi, lo));
83
+ writeQuic(buf, hi, lo, buf.length);
84
+ }
85
+ return buf;
86
+ }
87
+ /** Encode one varint in the form `version` uses, for a body written outside a {@link Writer}. */
88
+ export function encodeVarint(v, version) {
89
+ const lo = split(v);
90
+ return encodeTo(new ArrayBuffer(9), parts.hi, lo, version);
50
91
  }
51
92
  export class Stream {
52
93
  reader;
53
94
  writer;
54
95
  constructor(props) {
55
- const writer = props.writer ?? (props.writable && new Writer(props.writable, props.version));
56
- const reader = props.reader ?? (props.readable && new Reader(props.readable, undefined, props.version));
96
+ const version = props.version;
97
+ const writer = props.writer ?? (props.writable && version !== undefined && new Writer(props.writable, version));
98
+ const reader = props.reader ?? (props.readable && version !== undefined && new Reader(props.readable, undefined, version));
57
99
  if (!writer || !reader)
58
100
  throw new Error("stream needs both halves");
59
101
  this.writer = writer;
@@ -81,7 +123,7 @@ export class Stream {
81
123
  void stream.writable.abort().catch(() => void 0);
82
124
  void stream.readable.cancel().catch(() => void 0);
83
125
  });
84
- return new Stream({ readable, writable, version: options?.version });
126
+ return new Stream({ readable, writable, version: options.version });
85
127
  }
86
128
  close() {
87
129
  this.writer.close();
@@ -98,10 +140,16 @@ export class Stream {
98
140
  // Reader wraps a stream and provides convience methods for reading pieces from a stream
99
141
  // Unfortunately we can't use a BYOB reader because it's not supported with WebTransport+WebWorkers yet.
100
142
  export class Reader {
143
+ // Contiguous unread bytes, followed by chunks not yet joined onto it. Joining only once a
144
+ // read needs the bytes keeps a frame arriving in N chunks linear rather than quadratic.
101
145
  #buffer;
146
+ #chunks = [];
147
+ #chunked = 0; // bytes across #chunks
102
148
  #stream; // if undefined, the buffer is consumed then EOF
103
149
  #reader;
104
150
  #closed;
151
+ // The decode that last ran short and how far, so a retry can wait for those bytes.
152
+ #short;
105
153
  version;
106
154
  constructor(stream, buffer, version) {
107
155
  this.#buffer = buffer ?? new Uint8Array();
@@ -117,7 +165,7 @@ export class Reader {
117
165
  // Every read of this stream funnels through here, so decoding the peer's reset code
118
166
  // once is enough to keep the raw transport error out of every caller (and every app).
119
167
  const result = await this.#reader.read().catch((err) => {
120
- throw fromTransport(err, { version: this.version });
168
+ throw fromTransport(err, { version: asIetf(this.version) });
121
169
  });
122
170
  if (result.done) {
123
171
  return false;
@@ -125,16 +173,8 @@ export class Reader {
125
173
  if (result.value.byteLength === 0) {
126
174
  throw new Error("unexpected empty chunk");
127
175
  }
128
- const buffer = result.value;
129
- if (this.#buffer.byteLength === 0) {
130
- this.#buffer = new Uint8Array(buffer);
131
- }
132
- else {
133
- const temp = new Uint8Array(this.#buffer.byteLength + buffer.byteLength);
134
- temp.set(this.#buffer);
135
- temp.set(buffer, this.#buffer.byteLength);
136
- this.#buffer = temp;
137
- }
176
+ this.#chunks.push(result.value);
177
+ this.#chunked += result.value.byteLength;
138
178
  return true;
139
179
  }
140
180
  // Add more data to the buffer until it's at least size bytes.
@@ -142,11 +182,34 @@ export class Reader {
142
182
  if (size > MAX_READ_SIZE) {
143
183
  throw new Error(`read size ${size} exceeds max size ${MAX_READ_SIZE}`);
144
184
  }
145
- while (this.#buffer.byteLength < size) {
185
+ if (this.#buffer.byteLength >= size)
186
+ return;
187
+ while (this.#buffer.byteLength + this.#chunked < size) {
146
188
  if (!(await this.#fill())) {
147
- throw new Error("unexpected end of stream");
189
+ throw new UnexpectedEnd();
190
+ }
191
+ }
192
+ this.#join();
193
+ }
194
+ // Move every pending chunk into the buffer, copying only when there's more than one piece.
195
+ #join() {
196
+ if (this.#chunks.length === 0)
197
+ return;
198
+ if (this.#buffer.byteLength === 0 && this.#chunks.length === 1) {
199
+ this.#buffer = this.#chunks[0];
200
+ }
201
+ else {
202
+ const joined = new Uint8Array(this.#buffer.byteLength + this.#chunked);
203
+ joined.set(this.#buffer);
204
+ let offset = this.#buffer.byteLength;
205
+ for (const chunk of this.#chunks) {
206
+ joined.set(chunk, offset);
207
+ offset += chunk.byteLength;
148
208
  }
209
+ this.#buffer = joined;
149
210
  }
211
+ this.#chunks = [];
212
+ this.#chunked = 0;
150
213
  }
151
214
  // Consumes the first size bytes of the buffer.
152
215
  #slice(size) {
@@ -154,113 +217,118 @@ export class Reader {
154
217
  this.#buffer = new Uint8Array(this.#buffer.buffer, this.#buffer.byteOffset + size, this.#buffer.byteLength - size);
155
218
  return result;
156
219
  }
220
+ /**
221
+ * Run a synchronous decode over the buffered bytes and consume what it read.
222
+ *
223
+ * Returns undefined and consumes nothing when the decode ran past the buffered bytes, so a
224
+ * caller can drain every complete message already here without waiting on the stream.
225
+ */
226
+ tryDecode(decode) {
227
+ const result = this.#try(decode);
228
+ return result instanceof Short ? undefined : result;
229
+ }
230
+ /** Run a synchronous decode, filling from the stream until it has the bytes it needs. */
231
+ async decode(decode) {
232
+ for (;;) {
233
+ const result = this.#try(decode);
234
+ if (!(result instanceof Short))
235
+ return result;
236
+ await this.#fillTo(result.need);
237
+ }
238
+ }
239
+ // Like decode, but leaves the bytes buffered for the next read.
240
+ async #peek(decode) {
241
+ for (;;) {
242
+ const result = this.#try(decode, false);
243
+ if (!(result instanceof Short))
244
+ return result;
245
+ await this.#fillTo(result.need);
246
+ }
247
+ }
248
+ /** Like {@link decode}, but returns undefined if the stream ends cleanly first. */
249
+ async decodeMaybe(decode) {
250
+ if (await this.done())
251
+ return undefined;
252
+ return this.decode(decode);
253
+ }
254
+ #try(decode, consume = true) {
255
+ // A retry of the decode that last ran short, before the bytes it needs have arrived,
256
+ // would only throw again. Every decode reads at least a byte, so none can succeed on
257
+ // an empty buffer either.
258
+ const available = this.#buffer.byteLength + this.#chunked;
259
+ if (available === 0)
260
+ return EMPTY;
261
+ if (decode === this.#short?.decode && available < this.#short.err.need)
262
+ return this.#short.err;
263
+ this.#join();
264
+ const cursor = new Cursor(this.#buffer, this.version);
265
+ try {
266
+ const result = decode(cursor);
267
+ if (consume)
268
+ this.#slice(cursor.offset);
269
+ this.#short = undefined;
270
+ return result;
271
+ }
272
+ catch (err) {
273
+ if (!(err instanceof Short))
274
+ throw err;
275
+ // Filling could never satisfy it, so retrying would spin.
276
+ if (err.need <= this.#buffer.byteLength)
277
+ throw new Error("decode ran short of bytes it already had");
278
+ this.#short = { decode, err };
279
+ return err;
280
+ }
281
+ }
157
282
  async read(size) {
158
283
  if (size === 0)
159
284
  return new Uint8Array();
160
- await this.#fillTo(size);
161
- return this.#slice(size);
285
+ return this.decode((c) => c.read(size));
162
286
  }
163
287
  async readAll() {
164
288
  while (await this.#fill()) {
165
289
  // keep going
166
290
  }
291
+ this.#join();
167
292
  return this.#slice(this.#buffer.byteLength);
168
293
  }
294
+ // Reads to the end of the stream, dropping every byte instead of buffering it.
295
+ async discard() {
296
+ this.#buffer = new Uint8Array();
297
+ do {
298
+ this.#chunks = [];
299
+ this.#chunked = 0;
300
+ } while (await this.#fill());
301
+ }
169
302
  async string() {
170
- const length = await this.u53();
171
- const buffer = await this.read(length);
172
- return decodeUtf8(buffer);
303
+ return this.decode(STRING);
173
304
  }
174
305
  async bool() {
175
- const v = await this.u8();
176
- if (v === 0)
177
- return false;
178
- if (v === 1)
179
- return true;
180
- throw new Error("invalid bool value");
306
+ return this.decode(BOOL);
181
307
  }
182
308
  async u8() {
183
- await this.#fillTo(1);
184
- return this.#slice(1)[0];
309
+ return this.decode(U8);
185
310
  }
186
311
  async u16() {
187
- await this.#fillTo(2);
188
- const view = new DataView(this.#buffer.buffer, this.#buffer.byteOffset, 2);
189
- const result = view.getUint16(0);
190
- this.#slice(2);
191
- return result;
312
+ return this.decode(U16);
192
313
  }
193
314
  // Returns a Number using 53-bits, the max Javascript can use for integer math.
194
315
  async u53() {
195
- const v = await this.u62();
196
- if (v > Varint.MAX_U53) {
197
- throw new Error(`value larger than 53-bits: ${v.toString()}`);
198
- }
199
- return Number(v);
316
+ return this.decode(U53);
200
317
  }
201
318
  // NOTE: Returns a bigint instead of a number since it may be larger than 53-bits
202
319
  async u62() {
203
- if (isLeadingOnes(this.version)) {
204
- return this.#readLeadingOnes();
205
- }
206
- return this.#readQuicVarint();
207
- }
208
- async #readQuicVarint() {
209
- await this.#fillTo(1);
210
- const size = (this.#buffer[0] & 0xc0) >> 6;
211
- if (size === 0) {
212
- const first = this.#slice(1)[0];
213
- return BigInt(first) & 0x3fn;
214
- }
215
- if (size === 1) {
216
- await this.#fillTo(2);
217
- const slice = this.#slice(2);
218
- const view = new DataView(slice.buffer, slice.byteOffset, slice.byteLength);
219
- return BigInt(view.getUint16(0)) & 0x3fffn;
220
- }
221
- if (size === 2) {
222
- await this.#fillTo(4);
223
- const slice = this.#slice(4);
224
- const view = new DataView(slice.buffer, slice.byteOffset, slice.byteLength);
225
- return BigInt(view.getUint32(0)) & 0x3fffffffn;
226
- }
227
- await this.#fillTo(8);
228
- const slice = this.#slice(8);
229
- const view = new DataView(slice.buffer, slice.byteOffset, slice.byteLength);
230
- return view.getBigUint64(0) & 0x3fffffffffffffffn;
231
- }
232
- async #readLeadingOnes() {
233
- await this.#fillTo(1);
234
- const b = this.#buffer[0];
235
- // Count leading 1-bits
236
- let ones = 0;
237
- for (let bit = 7; bit >= 0; bit--) {
238
- if (b & (1 << bit))
239
- ones++;
240
- else
241
- break;
242
- }
243
- // 1111110x is a 7-byte form. Draft-17 rejects it; draft-18+ allows it per #1595.
244
- if (ones === 6 && this.version === Version.DRAFT_17) {
245
- throw new Error("invalid leading-ones varint: 1111110x prefix is reserved on draft-17");
246
- }
247
- let totalSize;
248
- if (ones <= 5)
249
- totalSize = ones + 1;
250
- else if (ones === 6)
251
- totalSize = 7;
252
- else if (ones === 7)
253
- totalSize = 8;
254
- else
255
- totalSize = 9; // ones === 8
256
- await this.#fillTo(totalSize);
257
- const slice = this.#slice(totalSize);
258
- const [value] = Varint.decodeLeadingOnes(slice);
259
- return value;
320
+ return this.decode(U62);
321
+ }
322
+ /** Like {@link u62}, but leaves the varint buffered, so a stream's type can be read twice. */
323
+ async peekU62() {
324
+ return this.#peek(U62);
325
+ }
326
+ async varint() {
327
+ return this.decode(VARINT);
260
328
  }
261
329
  // Returns false if there is more data to read, blocking if it hasn't been received yet.
262
330
  async done() {
263
- if (this.#buffer.byteLength > 0)
331
+ if (this.#buffer.byteLength > 0 || this.#chunked > 0)
264
332
  return false;
265
333
  return !(await this.#fill());
266
334
  }
@@ -271,18 +339,191 @@ export class Reader {
271
339
  // shape depending on which one won. Derived once, so racing it per frame doesn't allocate.
272
340
  get closed() {
273
341
  this.#closed ??= (this.#reader?.closed ?? Promise.resolve()).catch((err) => {
274
- throw fromTransport(err, { version: this.version });
342
+ throw fromTransport(err, { version: asIetf(this.version) });
275
343
  });
276
344
  return this.#closed;
277
345
  }
278
346
  }
347
+ /** The stream ended cleanly partway through a read. */
348
+ export class UnexpectedEnd extends Error {
349
+ constructor() {
350
+ super("unexpected end of stream");
351
+ }
352
+ }
353
+ // Thrown by a Cursor read that runs past the buffered bytes, carrying how many bytes from the
354
+ // start of the buffer the decode needs. Not an Error: it ends every chunk, so it must not
355
+ // capture a stack.
356
+ class Short {
357
+ need;
358
+ constructor(need) {
359
+ this.need = need;
360
+ }
361
+ }
362
+ const EMPTY = new Short(1);
363
+ /**
364
+ * A synchronous view over a {@link Reader}'s buffered bytes, handed to {@link Reader.decode}.
365
+ *
366
+ * A read past the buffered bytes throws an internal signal that the Reader catches: it consumes
367
+ * nothing, fills, and runs the decode again from the start. A decode must therefore not mutate
368
+ * anything before its last read, must not swallow what it throws, and must read at least a byte.
369
+ */
370
+ export class Cursor {
371
+ version;
372
+ #buffer;
373
+ #offset = 0;
374
+ // Resolved once, since every varint read branches on it.
375
+ #leadingOnes;
376
+ // First bytes below this are a whole 1-byte varint, and below this + 0x40 a 2-byte one whose
377
+ // value is the low 6 bits and the next byte. Both formats share that shape; only the bound moves.
378
+ #short;
379
+ // First bytes below this are a varint of at most 4 bytes: 0xc0 for QUIC, 0xf0 for leading-ones.
380
+ #word;
381
+ constructor(buffer, version) {
382
+ this.#buffer = buffer;
383
+ this.version = version;
384
+ this.#leadingOnes = isLeadingOnes(version);
385
+ this.#short = this.#leadingOnes ? 0x80 : 0x40;
386
+ this.#word = this.#leadingOnes ? 0xf0 : 0xc0;
387
+ }
388
+ /** How many bytes have been read. */
389
+ get offset() {
390
+ return this.#offset;
391
+ }
392
+ /** How many buffered bytes are left to read. */
393
+ get remaining() {
394
+ return this.#buffer.byteLength - this.#offset;
395
+ }
396
+ /**
397
+ * Decode the next `size` bytes on their own. Running past them, or leaving any unread, is
398
+ * malformed rather than a reason to wait for more.
399
+ */
400
+ exact(size, decode) {
401
+ const inner = new Cursor(this.read(size), this.version);
402
+ let result;
403
+ try {
404
+ result = decode(inner);
405
+ }
406
+ catch (err) {
407
+ if (err instanceof Short)
408
+ throw new Error(`message is shorter than its fields: ${size} bytes`);
409
+ throw err;
410
+ }
411
+ if (inner.remaining > 0)
412
+ throw new Error(`message has ${inner.remaining} unread bytes`);
413
+ return result;
414
+ }
415
+ #ensure(size) {
416
+ const need = this.#offset + size;
417
+ // Checked here too, and on the whole decode like the fill, since bytes that are already
418
+ // buffered never reach the fill.
419
+ if (need > MAX_READ_SIZE)
420
+ throw new Error(`read size ${need} exceeds max size ${MAX_READ_SIZE}`);
421
+ if (need > this.#buffer.byteLength)
422
+ throw new Short(need);
423
+ }
424
+ /** Read `size` bytes, as a view onto the buffer rather than a copy. */
425
+ read(size) {
426
+ this.#ensure(size);
427
+ const start = this.#offset;
428
+ this.#offset += size;
429
+ return this.#buffer.subarray(start, this.#offset);
430
+ }
431
+ string() {
432
+ return decodeUtf8(this.read(this.u53()));
433
+ }
434
+ bool() {
435
+ const v = this.u8();
436
+ if (v === 0)
437
+ return false;
438
+ if (v === 1)
439
+ return true;
440
+ throw new Error("invalid bool value");
441
+ }
442
+ u8() {
443
+ this.#ensure(1);
444
+ return this.#buffer[this.#offset++];
445
+ }
446
+ u16() {
447
+ this.#ensure(2);
448
+ const b = this.#buffer;
449
+ const o = this.#offset;
450
+ this.#offset += 2;
451
+ return (b[o] << 8) | b[o + 1];
452
+ }
453
+ /** Read a varint as a `number`, throwing if it is above `Number.MAX_SAFE_INTEGER`. */
454
+ u53() {
455
+ // Most varints are 1 or 2 bytes, which skip the general decode.
456
+ this.#ensure(1);
457
+ const b = this.#buffer;
458
+ const o = this.#offset;
459
+ const first = b[o];
460
+ if (first < this.#short) {
461
+ this.#offset = o + 1;
462
+ return first;
463
+ }
464
+ if (first < this.#short + 0x40) {
465
+ this.#ensure(2);
466
+ this.#offset = o + 2;
467
+ return ((first & 0x3f) << 8) | b[o + 1];
468
+ }
469
+ // Up to 4 bytes still fits 28 (leading-ones) or 30 (QUIC) bits, with no upper half.
470
+ if (first < this.#word) {
471
+ const size = this.#leadingOnes ? peekLeadingOnes(first) : 4;
472
+ this.#ensure(size);
473
+ this.#offset = o + size;
474
+ if (size === 3)
475
+ return ((first & 0x1f) << 16) | (b[o + 1] << 8) | b[o + 2];
476
+ return ((first & (this.#leadingOnes ? 0x0f : 0x3f)) << 24) | (b[o + 1] << 16) | (b[o + 2] << 8) | b[o + 3];
477
+ }
478
+ const lo = this.#varint();
479
+ return toNumber(parts.hi, lo);
480
+ }
481
+ /** Read a varint as a bigint. A leading-ones varint may exceed 62 bits. */
482
+ u62() {
483
+ const lo = this.#varint();
484
+ return toBigInt(parts.hi, lo);
485
+ }
486
+ /** Read a varint. */
487
+ varint() {
488
+ const lo = this.#varint();
489
+ return new U64(parts.hi, lo);
490
+ }
491
+ // Decode the next varint in the version's format, returning its lower half and leaving the upper in `parts`.
492
+ #varint() {
493
+ this.#ensure(1);
494
+ const b = this.#buffer;
495
+ const o = this.#offset;
496
+ let size;
497
+ if (this.#leadingOnes) {
498
+ size = peekLeadingOnes(b[o]);
499
+ // 1111110x is a 7-byte form. Draft-17 rejects it; draft-18+ allows it per #1595.
500
+ if (size === 7 && this.version === Version.DRAFT_17) {
501
+ throw new Error("invalid leading-ones varint: 1111110x prefix is reserved on draft-17");
502
+ }
503
+ this.#ensure(size);
504
+ this.#offset += size;
505
+ return readLeadingOnes(b, o, size);
506
+ }
507
+ size = peekQuic(b[o]);
508
+ this.#ensure(size);
509
+ this.#offset += size;
510
+ return readQuic(b, o, size);
511
+ }
512
+ }
513
+ // Shared decodes for the Reader's async primitives, so a read allocates no closure.
514
+ const STRING = (c) => c.string();
515
+ const BOOL = (c) => c.bool();
516
+ const U8 = (c) => c.u8();
517
+ const U16 = (c) => c.u16();
518
+ const U53 = (c) => c.u53();
519
+ const U62 = (c) => c.u62();
520
+ const VARINT = (c) => c.varint();
279
521
  // Writer wraps a stream and writes chunks of data
280
522
  export class Writer {
281
523
  #writer;
282
524
  #stream;
283
525
  #closed;
284
- // Scratch buffer for writing varints.
285
- // Fixed at 9 bytes (leading-ones max).
526
+ // Scratch buffer for each primitive write, sized for the longest (a 9-byte leading-ones varint).
286
527
  #scratch;
287
528
  version;
288
529
  constructor(stream, version) {
@@ -320,7 +561,7 @@ export class Writer {
320
561
  if (Math.abs(v) > MAX_U31) {
321
562
  throw new Error(`overflow, value larger than 32-bits: ${v.toString()}`);
322
563
  }
323
- // We don't use a VarInt, so it always takes 4 bytes.
564
+ // We don't use a varint, so it always takes 4 bytes.
324
565
  // This could be improved but nothing is standardized yet.
325
566
  await this.write(setInt32(this.#scratch, v));
326
567
  }
@@ -328,26 +569,23 @@ export class Writer {
328
569
  if (!Number.isSafeInteger(v) || v < 0) {
329
570
  throw new RangeError(`invalid u53: ${v}`);
330
571
  }
331
- if (isLeadingOnes(this.version)) {
332
- await this.write(Varint.encodeLeadingOnesTo(this.#scratch, v));
333
- }
334
- else {
335
- await this.write(Varint.encodeTo(this.#scratch, v));
336
- }
572
+ await this.#varint(Math.floor(v / POW32), v >>> 0);
337
573
  }
338
574
  async u62(v) {
339
- if (isLeadingOnes(this.version)) {
340
- await this.write(Varint.encodeLeadingOnesTo(this.#scratch, v));
341
- }
342
- else {
343
- await this.write(Varint.encodeTo(this.#scratch, v));
344
- }
575
+ const lo = split(v);
576
+ await this.#varint(parts.hi, lo);
577
+ }
578
+ async varint(v) {
579
+ await this.#varint(v.hi, v.lo);
580
+ }
581
+ #varint(hi, lo) {
582
+ return this.write(encodeTo(this.#scratch, hi, lo, this.version));
345
583
  }
346
584
  async write(v) {
347
585
  // Mirrors Reader.#fill: every write funnels through here, so a STOP_SENDING from the
348
586
  // peer surfaces as a typed code rather than the transport's own error shape.
349
587
  await this.#writer.write(v).catch((err) => {
350
- throw fromTransport(err, { version: this.version });
588
+ throw fromTransport(err, { version: asIetf(this.version) });
351
589
  });
352
590
  }
353
591
  async string(str) {
@@ -362,7 +600,7 @@ export class Writer {
362
600
  // typed code it would get from a write.
363
601
  get closed() {
364
602
  this.#closed ??= this.#writer.closed.catch((err) => {
365
- throw fromTransport(err, { version: this.version });
603
+ throw fromTransport(err, { version: asIetf(this.version) });
366
604
  });
367
605
  return this.#closed;
368
606
  }
@@ -377,7 +615,7 @@ export class Writer {
377
615
  */
378
616
  static async open(quic, options) {
379
617
  const writable = await openWithin(quic.createUnidirectionalStream(sendOptions(options)), options?.timeout ?? OPEN_TIMEOUT_MS, (stream) => void stream.abort().catch(() => void 0));
380
- return new Writer(writable, options?.version);
618
+ return new Writer(writable, options.version);
381
619
  }
382
620
  /**
383
621
  * Like {@link Writer.open}, but gives up when `cancel` settles or `timeout` elapses,
@@ -388,25 +626,29 @@ export class Writer {
388
626
  * an over-limit open instead of rejecting it.
389
627
  */
390
628
  static async tryOpen(quic, options) {
391
- // A rejected `cancel` (STOP_SENDING) means the peer is gone too, so both settle
392
- // paths mean "give up" and neither is left unhandled. Built before the open, and
393
- // raced ahead of it, so an already-cancelled caller wins even against a slot that
394
- // is free right now.
395
- const cancelled = options.cancel.then(() => undefined, () => undefined);
629
+ // Raced ahead of the open, so an already-cancelled caller wins even against a slot
630
+ // that is free right now. `race` rather than `Promise.race`: the caller shares one
631
+ // `cancel` across every group of a subscription, which must not gain a reaction per call.
396
632
  const open = Writer.open(quic, options);
633
+ // Resets a stream that opens after we gave up; a no-op if the open itself failed.
634
+ const abandon = () => {
635
+ const abandoned = new Error("abandoned waiting for a stream slot");
636
+ open.then((w) => w.reset(abandoned)).catch(() => void 0);
637
+ };
397
638
  try {
398
- const stream = await Promise.race([cancelled, open]);
639
+ const stream = await race([options.cancel, open]);
399
640
  if (stream)
400
641
  return stream;
401
642
  }
402
643
  catch (err) {
403
644
  // open already discarded the late stream on its way out.
404
- if (!(err instanceof TimeoutError))
405
- throw err;
406
- return undefined;
645
+ if (err instanceof TimeoutError)
646
+ return undefined;
647
+ // A rejected `cancel` still leaves the open pending.
648
+ abandon();
649
+ throw err;
407
650
  }
408
- const abandoned = new Error("abandoned waiting for a stream slot");
409
- open.then((w) => w.reset(abandoned)).catch(() => void 0);
651
+ abandon();
410
652
  return undefined;
411
653
  }
412
654
  }