moqtail 0.12.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/client.d.cts CHANGED
@@ -1,49 +1,42 @@
1
- import { c as ControlMessage, U as MoqtObject, y as Location, u as FullTrackName, au as TrackExtension, ao as Subscribe, a4 as PublishDoneStatusCode, ae as RequestUpdate, F as Fetch, a2 as Publish, ad as RequestOk, aa as RequestError, a5 as PublishNamespace, p as FetchOk, aq as SubscribeOk, R as MessageParameter, ap as SubscribeNamespace, a8 as PublishOk, v as GroupOrder, q as FetchType, ak as SetupParameters, D as Datagram, r as FilterType, ay as Tuple, ac as RequestIdMap, a7 as PublishNamespaceDone, G as GoAway, an as SubgroupObject, al as SubgroupHeader, n as FetchObject, l as FetchHeader, a3 as PublishDone, ah as ServerSetup, a6 as PublishNamespaceCancel, X as NamespaceSubscribeOptions, aC as UnsubscribeNamespace, aw as TrackStatus, H as Header } from './setup_parameter-BgNrJRDS.cjs';
2
- import { L as LogLevel } from './logger-C6QS408Z.cjs';
1
+ import { $ as GoAway, En as Datagram, Fn as Tuple, G as SubscribeTracks, H as RequestError, J as RequestUpdate, K as SubscribeNamespace, Ln as Location, Q as Subscribe, St as MessageParameter, Tn as FetchHeader, U as RequestOk, V as ControlMessage, X as Publish, Y as SubscribeOk, Z as PublishDone, _n as ControlMessageType, _t as Fetch, bn as GroupOrder, cn as SubgroupHeader, dn as FullTrackName, hn as FetchObject, ln as MoqtObject, lt as TrackProperty, n as SetupOptions, nn as PublishBlocked, on as Header, q as TrackStatus, sn as RequestIdMap, tt as FetchOk, un as SubgroupObject, vn as FetchType, vt as Setup, x as StreamResetCode, xn as PublishDoneStatusCode, xt as PublishNamespace, yn as FilterType } from "./index-C8pNnaj0.cjs";
2
+ import { t as LogLevel } from "./logger-dEoueCj7.cjs";
3
3
 
4
+ //#region src/client/control_stream.d.ts
4
5
  /**
5
- * Copyright 2025 The MOQtail Authors
6
- *
7
- * Licensed under the Apache License, Version 2.0 (the "License");
8
- * you may not use this file except in compliance with the License.
9
- * You may obtain a copy of the License at
10
- *
11
- * http://www.apache.org/licenses/LICENSE-2.0
12
- *
13
- * Unless required by applicable law or agreed to in writing, software
14
- * distributed under the License is distributed on an "AS IS" BASIS,
15
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
- * See the License for the specific language governing permissions and
17
- * limitations under the License.
6
+ * Send half of the control plane: a unidirectional stream this endpoint opens and
7
+ * whose first message must be SETUP.
18
8
  */
19
-
20
- declare class ControlStream {
21
- #private;
22
- readonly stream: ReadableStream<ControlMessage>;
23
- onMessageSent?: (msg: ControlMessage) => void;
24
- onMessageReceived?: (msg: ControlMessage) => void;
25
- private constructor();
26
- static new(bidirectionalStream: WebTransportBidirectionalStream, partialMessageTimeoutMs?: number, onMessageSent?: (msg: ControlMessage) => void, onMessageReceived?: (msg: ControlMessage) => void): ControlStream;
27
- send(message: ControlMessage): Promise<void>;
28
- close(): Promise<void>;
9
+ declare class ControlSendStream {
10
+ #private;
11
+ onMessageSent?: (msg: ControlMessage) => void;
12
+ constructor(writeStream: WritableStream<Uint8Array>, onMessageSent?: (msg: ControlMessage) => void);
13
+ send(message: ControlMessage): Promise<void>;
14
+ close(): Promise<void>;
29
15
  }
30
-
31
16
  /**
32
- * Copyright 2025 The MOQtail Authors
33
- *
34
- * Licensed under the Apache License, Version 2.0 (the "License");
35
- * you may not use this file except in compliance with the License.
36
- * You may obtain a copy of the License at
37
- *
38
- * http://www.apache.org/licenses/LICENSE-2.0
39
- *
40
- * Unless required by applicable law or agreed to in writing, software
41
- * distributed under the License is distributed on an "AS IS" BASIS,
42
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
43
- * See the License for the specific language governing permissions and
44
- * limitations under the License.
17
+ * Receive half of the control plane: the unidirectional stream the peer opens,
18
+ * whose first message must be SETUP.
45
19
  */
46
-
20
+ declare class ControlRecvStream {
21
+ #private;
22
+ readonly stream: ReadableStream<ControlMessage>;
23
+ onMessageReceived?: (msg: ControlMessage) => void;
24
+ constructor(readStream: ReadableStream<Uint8Array>, partialMessageTimeoutMs?: number, onMessageReceived?: (msg: ControlMessage) => void);
25
+ close(): Promise<void>;
26
+ }
27
+ /**
28
+ * The control plane as a whole: the two independent unidirectional halves opened by
29
+ * each endpoint.
30
+ */
31
+ declare class ControlStream {
32
+ #private;
33
+ readonly stream: ReadableStream<ControlMessage>;
34
+ constructor(sendHalf: ControlSendStream, recvHalf: ControlRecvStream);
35
+ send(message: ControlMessage): Promise<void>;
36
+ close(): Promise<void>;
37
+ }
38
+ //#endregion
39
+ //#region src/client/track/object_cache.d.ts
47
40
  /**
48
41
  * In‑memory index of {@link MoqtObject} instances keyed by their {@link Location} (group/subgroup/object),
49
42
  * providing ordered insertion and range queries.
@@ -63,56 +56,41 @@ declare class ControlStream {
63
56
  * Concurrency: Implementations here are not thread‑safe; callers avoid concurrent mutation from workers.
64
57
  */
65
58
  interface ObjectCache {
66
- /** Insert a new {@link MoqtObject}, preserving sorted order (duplicates allowed or replaced impl‑defined). */
67
- add(obj: MoqtObject): void;
68
- /** Return a shallow copy array of objects whose Location is \>= start and \< end (end exclusive). */
69
- getRange(start?: Location, end?: Location): MoqtObject[];
70
- /** Return the object whose Location exactly matches (group & object) or undefined if absent. */
71
- getByLocation(location: Location): MoqtObject | undefined;
72
- /** Current number of cached objects. */
73
- size(): number;
74
- /** Remove all cached objects. */
75
- clear(): void;
59
+ /** Insert a new {@link MoqtObject}, preserving sorted order (duplicates allowed or replaced impl‑defined). */
60
+ add(obj: MoqtObject): void;
61
+ /** Return a shallow copy array of objects whose Location is \>= start and \< end (end exclusive). */
62
+ getRange(start?: Location, end?: Location): MoqtObject[];
63
+ /** Return the object whose Location exactly matches (group & object) or undefined if absent. */
64
+ getByLocation(location: Location): MoqtObject | undefined;
65
+ /** Current number of cached objects. */
66
+ size(): number;
67
+ /** Remove all cached objects. */
68
+ clear(): void;
76
69
  }
77
70
  declare class MemoryObjectCache implements ObjectCache {
78
- private objects;
79
- add(obj: MoqtObject): void;
80
- getRange(start?: Location, end?: Location): MoqtObject[];
81
- getByLocation(location: Location): MoqtObject | undefined;
82
- size(): number;
83
- clear(): void;
84
- private _findInsertIndex;
85
- private _findIndex;
71
+ private objects;
72
+ add(obj: MoqtObject): void;
73
+ getRange(start?: Location, end?: Location): MoqtObject[];
74
+ getByLocation(location: Location): MoqtObject | undefined;
75
+ size(): number;
76
+ clear(): void;
77
+ private _findInsertIndex;
78
+ private _findIndex;
86
79
  }
87
80
  declare class RingBufferObjectCache implements ObjectCache {
88
- private buffer;
89
- private maxSize;
90
- constructor(maxSize?: number);
91
- add(obj: MoqtObject): void;
92
- getRange(start?: Location, end?: Location): MoqtObject[];
93
- getByLocation(location: Location): MoqtObject | undefined;
94
- size(): number;
95
- clear(): void;
96
- private _findInsertIndex;
97
- private _findIndex;
81
+ private buffer;
82
+ private maxSize;
83
+ constructor(maxSize?: number);
84
+ add(obj: MoqtObject): void;
85
+ getRange(start?: Location, end?: Location): MoqtObject[];
86
+ getByLocation(location: Location): MoqtObject | undefined;
87
+ size(): number;
88
+ clear(): void;
89
+ private _findInsertIndex;
90
+ private _findIndex;
98
91
  }
99
-
100
- /**
101
- * Copyright 2025 The MOQtail Authors
102
- *
103
- * Licensed under the Apache License, Version 2.0 (the "License");
104
- * you may not use this file except in compliance with the License.
105
- * You may obtain a copy of the License at
106
- *
107
- * http://www.apache.org/licenses/LICENSE-2.0
108
- *
109
- * Unless required by applicable law or agreed to in writing, software
110
- * distributed under the License is distributed on an "AS IS" BASIS,
111
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
112
- * See the License for the specific language governing permissions and
113
- * limitations under the License.
114
- */
115
-
92
+ //#endregion
93
+ //#region src/client/track/content_source.d.ts
116
94
  /**
117
95
  * Source of already-produced (historical) objects for a track.
118
96
  * Backed by an {@link ObjectCache} allowing range retrieval using protocol {@link Location}s.
@@ -120,29 +98,29 @@ declare class RingBufferObjectCache implements ObjectCache {
120
98
  * if the requested window is outside the cached range.
121
99
  */
122
100
  interface PastObjectSource {
123
- /** Underlying cache from which objects are served */
124
- readonly cache: ObjectCache;
125
- /**
126
- * Fetch a (closed) range of objects. `start`/`end` are inclusive when provided.
127
- * Omitted bounds mean: from earliest cached (when `start` undefined) or up to latest cached (when `end` undefined).
128
- */
129
- getRange(start?: Location, end?: Location): Promise<MoqtObject[]>;
101
+ /** Underlying cache from which objects are served */
102
+ readonly cache: ObjectCache;
103
+ /**
104
+ * Fetch a (closed) range of objects. `start`/`end` are inclusive when provided.
105
+ * Omitted bounds mean: from earliest cached (when `start` undefined) or up to latest cached (when `end` undefined).
106
+ */
107
+ getRange(start?: Location, end?: Location): Promise<MoqtObject[]>;
130
108
  }
131
109
  /**
132
110
  * Push-oriented live object feed. Wraps a {@link https://developer.mozilla.org/docs/Web/API/ReadableStream | ReadableStream} plus lightweight event subscription helpers.
133
111
  * Implementations advance {@link LiveObjectSource.largestLocation | largestLocation} monotonically as objects arrive.
134
112
  */
135
113
  interface LiveObjectSource {
136
- /** Continuous stream yielding objects as they are produced */
137
- readonly stream: ReadableStream<MoqtObject>;
138
- /** Highest (latest) location observed so far; undefined until first object */
139
- readonly largestLocation: Location | undefined;
140
- /** Register a listener invoked (async) for each new object. Returns an unsubscribe function. */
141
- onNewObject(listener: (obj: MoqtObject) => void): () => void;
142
- /** Register a listener invoked when the live stream ends (normal or error). Returns an unsubscribe function. */
143
- onDone(listener: () => void): () => void;
144
- /** Stop ingestion and release underlying reader (idempotent). */
145
- stop(): void;
114
+ /** Continuous stream yielding objects as they are produced */
115
+ readonly stream: ReadableStream<MoqtObject>;
116
+ /** Highest (latest) location observed so far; undefined until first object */
117
+ readonly largestLocation: Location | undefined;
118
+ /** Register a listener invoked (async) for each new object. Returns an unsubscribe function. */
119
+ onNewObject(listener: (obj: MoqtObject) => void): () => void;
120
+ /** Register a listener invoked when the live stream ends (normal or error). Returns an unsubscribe function. */
121
+ onDone(listener: () => void): () => void;
122
+ /** Stop ingestion and release underlying reader (idempotent). */
123
+ stop(): void;
146
124
  }
147
125
  /**
148
126
  * Aggregates optional historical (`past`) and (`live`) sources for a single track.
@@ -156,47 +134,32 @@ interface LiveObjectSource {
156
134
  * expresses what content is available, independent of priority semantics.
157
135
  */
158
136
  interface TrackSource {
159
- /** Historical object access (optional) */
160
- readonly past?: PastObjectSource;
161
- /** Live object feed (optional) */
162
- readonly live?: LiveObjectSource;
137
+ /** Historical object access (optional) */
138
+ readonly past?: PastObjectSource;
139
+ /** Live object feed (optional) */
140
+ readonly live?: LiveObjectSource;
163
141
  }
164
142
  declare class StaticTrackSource implements PastObjectSource {
165
- readonly cache: ObjectCache;
166
- constructor(cache: ObjectCache);
167
- getRange(start?: Location, end?: Location): Promise<MoqtObject[]>;
143
+ readonly cache: ObjectCache;
144
+ constructor(cache: ObjectCache);
145
+ getRange(start?: Location, end?: Location): Promise<MoqtObject[]>;
168
146
  }
169
147
  declare class LiveTrackSource implements LiveObjectSource {
170
- #private;
171
- readonly stream: ReadableStream<MoqtObject>;
172
- constructor(stream: ReadableStream<MoqtObject>);
173
- get largestLocation(): Location | undefined;
174
- onNewObject(listener: (obj: MoqtObject) => Promise<void> | void): () => void;
175
- onDone(listener: () => void): () => void;
176
- stop(): void;
148
+ #private;
149
+ readonly stream: ReadableStream<MoqtObject>;
150
+ constructor(stream: ReadableStream<MoqtObject>);
151
+ get largestLocation(): Location | undefined;
152
+ onNewObject(listener: (obj: MoqtObject) => Promise<void> | void): () => void;
153
+ onDone(listener: () => void): () => void;
154
+ stop(): void;
177
155
  }
178
156
  declare class HybridTrackSource implements TrackSource {
179
- readonly past: PastObjectSource;
180
- readonly live: LiveObjectSource;
181
- constructor(cache: ObjectCache, stream: ReadableStream<MoqtObject>);
157
+ readonly past: PastObjectSource;
158
+ readonly live: LiveObjectSource;
159
+ constructor(cache: ObjectCache, stream: ReadableStream<MoqtObject>);
182
160
  }
183
-
184
- /**
185
- * Copyright 2025 The MOQtail Authors
186
- *
187
- * Licensed under the Apache License, Version 2.0 (the "License");
188
- * you may not use this file except in compliance with the License.
189
- * You may obtain a copy of the License at
190
- *
191
- * http://www.apache.org/licenses/LICENSE-2.0
192
- *
193
- * Unless required by applicable law or agreed to in writing, software
194
- * distributed under the License is distributed on an "AS IS" BASIS,
195
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
196
- * See the License for the specific language governing permissions and
197
- * limitations under the License.
198
- */
199
-
161
+ //#endregion
162
+ //#region src/client/track/track.d.ts
200
163
  /**
201
164
  * Describes a media/data track known to the client (either published locally or subscribed to).
202
165
  *
@@ -237,349 +200,308 @@ declare class HybridTrackSource implements TrackSource {
237
200
  * ```
238
201
  */
239
202
  type Track = {
240
- /**
241
- * Globally unique identifier for the track.
242
- */
243
- fullTrackName: FullTrackName;
244
- /**
245
- * Accessors for live and/or past objects belonging to this track.
246
- */
247
- trackSource: TrackSource;
248
- /**
249
- * 0 (highest) .. 255 (lowest) priority advertised with objects.
250
- * Values are rounded to nearest integer then clamped between 0 and 255.
251
- */
252
- publisherPriority: number;
253
- /**
254
- * Optional compact numeric alias assigned during protocol negotiation.
255
- */
256
- trackAlias?: bigint;
257
- /**
258
- * Track extensions advertised by the publisher.
259
- * Set before calling `publish()` to include extensions in the PUBLISH message.
260
- * Populated automatically on the subscriber side when SUBSCRIBE_OK or FETCH_OK is received.
261
- */
262
- trackExtensions?: TrackExtension[];
203
+ /**
204
+ * Globally unique identifier for the track.
205
+ */
206
+ fullTrackName: FullTrackName;
207
+ /**
208
+ * Accessors for live and/or past objects belonging to this track.
209
+ */
210
+ trackSource: TrackSource;
211
+ /**
212
+ * 0 (highest) .. 255 (lowest) priority advertised with objects.
213
+ * Values are rounded to nearest integer then clamped between 0 and 255.
214
+ */
215
+ publisherPriority: number;
216
+ /**
217
+ * Optional compact numeric alias assigned during protocol negotiation.
218
+ */
219
+ trackAlias?: bigint;
220
+ /**
221
+ * Track properties advertised by the publisher.
222
+ * Set before calling `publish()` to include properties in the PUBLISH message.
223
+ * Populated automatically on the subscriber side when SUBSCRIBE_OK or FETCH_OK is received.
224
+ */
225
+ trackProperties?: TrackProperty[];
263
226
  };
264
-
227
+ //#endregion
228
+ //#region src/client/request_stream.d.ts
265
229
  /**
266
- * Copyright 2025 The MOQtail Authors
267
- *
268
- * Licensed under the Apache License, Version 2.0 (the "License");
269
- * you may not use this file except in compliance with the License.
270
- * You may obtain a copy of the License at
271
- *
272
- * http://www.apache.org/licenses/LICENSE-2.0
273
- *
274
- * Unless required by applicable law or agreed to in writing, software
275
- * distributed under the License is distributed on an "AS IS" BASIS,
276
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
277
- * See the License for the specific language governing permissions and
278
- * limitations under the License.
230
+ * Wraps a WebTransport bidirectional stream carrying one MOQT request.
231
+ * Because a response is correlated by the stream it arrives on, nothing here needs a
232
+ * request id.
279
233
  */
280
-
234
+ declare class RequestStream {
235
+ #private;
236
+ readonly stream: ReadableStream<ControlMessage>;
237
+ /**
238
+ * The message this side opened the stream with, kept so the request can be re-issued
239
+ * on a fresh stream when the peer migrates it with a GOAWAY (§10.4). Undefined on a
240
+ * peer-opened stream, which is the peer's request to re-issue, not ours.
241
+ */
242
+ first?: ControlMessage;
243
+ /**
244
+ * The type of the message that opened this stream, whichever side opened it. It is
245
+ * what the request on this stream *is*, which decides what may follow — a
246
+ * REQUEST_UPDATE is only valid for the types §10.9 lists.
247
+ */
248
+ openingType?: ControlMessageType;
249
+ /** Set when the request this stream carried has been re-issued on a new stream. */
250
+ migrated: boolean;
251
+ constructor(biStream: WebTransportBidirectionalStream);
252
+ /**
253
+ * Opens a new bidi stream and writes `first` on it.
254
+ *
255
+ * @throws :{@link ProtocolViolationError} If `first` is not one of the seven types
256
+ * Table 5 marks `First`; those are the only ones allowed to open a request stream.
257
+ */
258
+ static open(webTransport: WebTransport, first: ControlMessage): Promise<RequestStream>;
259
+ /**
260
+ * Reads the next control message off this stream, or `undefined` once the peer has
261
+ * closed or reset it.
262
+ *
263
+ * Takes ownership of {@link RequestStream.stream}'s reader on first use, so callers
264
+ * must not mix `next()` with `stream.getReader()`.
265
+ */
266
+ next(): Promise<ControlMessage | undefined>;
267
+ send(message: ControlMessage): Promise<void>;
268
+ close(): Promise<void>;
269
+ /**
270
+ * Cancels the request by resetting its stream with `code` (§3.3.2), which is how
271
+ * draft-18 cancels a request now that the dedicated cancel messages are gone.
272
+ */
273
+ reset(code: StreamResetCode): Promise<void>;
274
+ }
275
+ //#endregion
276
+ //#region src/client/publication/subscribe.d.ts
281
277
  /**
282
278
  * @public
283
279
  * Manages the publication of MOQT objects to a subscriber for a specific track.
284
280
  * Handles live object streaming, subscription lifecycle, and stream management.
285
281
  */
286
282
  declare class SubscribePublication {
287
- #private;
288
- private readonly client;
289
- readonly track: Track;
290
- private readonly subscribeMsg;
291
- /**
292
- * The latest location that was published to the subscriber.
293
- */
294
- latestLocation: Location | undefined;
295
- /**
296
- * Creates a new SubscribePublication instance.
297
- * @param client - The MOQT client managing the subscription.
298
- * @param track - The track being published.
299
- * @param subscribeMsg - The subscribe message containing subscription details.
300
- * @param largestLocation - The largest location seen so far, used for determining start location.
301
- */
302
- constructor(client: MOQtailClient, track: Track, subscribeMsg: Subscribe, largestLocation?: Location);
303
- /**
304
- * Cancels the publication and cleans up resources.
305
- * Removes the publication from the client's publication map.
306
- */
307
- cancel(): void;
308
- /**
309
- * Marks the publication as done and sends a PublishDone message to the client.
310
- * @param statusCode - The status code indicating why the publication ended.
311
- * @throws :{@link InternalError} If sending the message fails.
312
- */
313
- done(statusCode: PublishDoneStatusCode): Promise<void>;
314
- /**
315
- * Updates the subscription parameters and locations based on a RequestUpdate message.
316
- * @param msg - The update message containing new request details.
317
- */
318
- update(msg: RequestUpdate): void;
319
- /**
320
- * Publishes MOQT objects to the subscriber as they become available.
321
- * Handles stream creation, object writing, and stream closure based on subscription parameters.
322
- * @throws :{@link InternalError} If the track does not support live content.
323
- */
324
- publish(): Promise<void>;
283
+ #private;
284
+ private readonly client;
285
+ readonly track: Track;
286
+ private readonly subscribeMsg;
287
+ private readonly requestStream;
288
+ /**
289
+ * The latest location that was published to the subscriber.
290
+ */
291
+ latestLocation: Location | undefined;
292
+ /**
293
+ * Creates a new SubscribePublication instance.
294
+ * @param client - The MOQT client managing the subscription.
295
+ * @param track - The track being published.
296
+ * @param subscribeMsg - The subscribe message containing subscription details.
297
+ * @param requestStream - The bidi request stream the SUBSCRIBE arrived on. Every
298
+ * message this publication sends back to the subscriber goes on it.
299
+ * @param largestLocation - The largest location seen so far, used for determining start location.
300
+ */
301
+ constructor(client: MOQtailClient, track: Track, subscribeMsg: Subscribe, requestStream: RequestStream, largestLocation?: Location);
302
+ /**
303
+ * Cancels the publication and cleans up resources.
304
+ * Removes the publication from the client's publication map.
305
+ */
306
+ cancel(): void;
307
+ /**
308
+ * Marks the publication as done and sends a PublishDone message to the client.
309
+ * @param statusCode - The status code indicating why the publication ended.
310
+ * @throws :{@link InternalError} If sending the message fails.
311
+ */
312
+ done(statusCode: PublishDoneStatusCode): Promise<void>;
313
+ /**
314
+ * Updates the subscription parameters and locations based on a RequestUpdate message.
315
+ * @param msg - The update message containing new request details.
316
+ */
317
+ update(msg: RequestUpdate): void;
318
+ /**
319
+ * Publishes MOQT objects to the subscriber as they become available.
320
+ * Handles stream creation, object writing, and stream closure based on subscription parameters.
321
+ * @throws :{@link InternalError} If the track does not support live content.
322
+ */
323
+ publish(): Promise<void>;
325
324
  }
326
-
327
- /**
328
- * Copyright 2025 The MOQtail Authors
329
- *
330
- * Licensed under the Apache License, Version 2.0 (the "License");
331
- * you may not use this file except in compliance with the License.
332
- * You may obtain a copy of the License at
333
- *
334
- * http://www.apache.org/licenses/LICENSE-2.0
335
- *
336
- * Unless required by applicable law or agreed to in writing, software
337
- * distributed under the License is distributed on an "AS IS" BASIS,
338
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
339
- * See the License for the specific language governing permissions and
340
- * limitations under the License.
341
- */
342
-
325
+ //#endregion
326
+ //#region src/client/publication/fetch.d.ts
343
327
  declare class FetchPublication {
344
- #private;
345
- constructor(client: MOQtailClient, track: Track, fetchRequest: Fetch);
346
- cancel(): void;
347
- publish(): Promise<void>;
328
+ #private;
329
+ constructor(client: MOQtailClient, track: Track, fetchRequest: Fetch);
330
+ cancel(): void;
331
+ /**
332
+ * Resets the data stream this fetch is being delivered on, which §10.9.1 requires when
333
+ * a REQUEST_UPDATE for a FETCH fails.
334
+ */
335
+ resetDataStream(code: StreamResetCode): Promise<void>;
336
+ publish(): Promise<void>;
348
337
  }
349
-
350
- /**
351
- * Copyright 2025 The MOQtail Authors
352
- *
353
- * Licensed under the Apache License, Version 2.0 (the "License");
354
- * you may not use this file except in compliance with the License.
355
- * You may obtain a copy of the License at
356
- *
357
- * http://www.apache.org/licenses/LICENSE-2.0
358
- *
359
- * Unless required by applicable law or agreed to in writing, software
360
- * distributed under the License is distributed on an "AS IS" BASIS,
361
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
362
- * See the License for the specific language governing permissions and
363
- * limitations under the License.
364
- */
365
-
338
+ //#endregion
339
+ //#region src/client/publication/publish.d.ts
366
340
  /**
367
341
  * @public
368
342
  * Manages the proactive publication of MOQT objects from a publisher to the relay.
369
343
  * Handles live object streaming and stream management.
370
344
  */
371
345
  declare class PublishPublication {
372
- #private;
373
- private readonly client;
374
- readonly track: Track;
375
- private readonly publishMsg;
376
- /**
377
- * The latest location that was published to the relay.
378
- */
379
- latestLocation: Location | undefined;
380
- /**
381
- * Creates a new PublishPublication instance.
382
- * @param client - The MOQT client managing the connection.
383
- * @param track - The track being proactively published.
384
- * @param publishMsg - The publish message that initiated this session.
385
- */
386
- constructor(client: MOQtailClient, track: Track, publishMsg: Publish);
387
- /**
388
- * Cancels the publication and cleans up resources.
389
- * Removes the publication from the client's publication map.
390
- */
391
- cancel(): void;
392
- /**
393
- * Publishes MOQT objects to the relay as they become available.
394
- * Handles stream creation, object writing, and stream closure.
395
- * @throws :{@link InternalError} If the track does not support live content.
396
- */
397
- publishToRelay(): Promise<void>;
346
+ #private;
347
+ private readonly client;
348
+ readonly track: Track;
349
+ private readonly publishMsg;
350
+ /**
351
+ * The latest location that was published to the relay.
352
+ */
353
+ latestLocation: Location | undefined;
354
+ /**
355
+ * Creates a new PublishPublication instance.
356
+ * @param client - The MOQT client managing the connection.
357
+ * @param track - The track being proactively published.
358
+ * @param publishMsg - The publish message that initiated this session.
359
+ */
360
+ constructor(client: MOQtailClient, track: Track, publishMsg: Publish);
361
+ /**
362
+ * How many data streams this publication has opened, which is what a PUBLISH_DONE
363
+ * reports to the subscriber.
364
+ */
365
+ get streamsOpened(): bigint;
366
+ /**
367
+ * Whether Objects are being sent right now. False while the peer holds this
368
+ * publication at FORWARD=0.
369
+ */
370
+ get forwarding(): boolean;
371
+ /**
372
+ * Moves the Forward State: false parks the publication, true resumes it. The
373
+ * application hears about the move through {@link MOQtailClient.onForwardStateChange},
374
+ * which is where a publisher starts or stops the work behind the track -- a camera
375
+ * and an encoder cost the same whether or not anything is listening.
376
+ */
377
+ setForwardState(forward: boolean): void;
378
+ /**
379
+ * Applies a REQUEST_UPDATE the peer sent on this publication's request stream. The
380
+ * Forward State is the one thing it can move; what a publisher sends, and when,
381
+ * is otherwise its own to decide.
382
+ */
383
+ update(msg: RequestUpdate): void;
384
+ /**
385
+ * Cancels the publication and cleans up resources.
386
+ * Removes the publication from the client's publication map.
387
+ */
388
+ cancel(): void;
389
+ /**
390
+ * Publishes MOQT objects to the relay as they become available.
391
+ * Handles stream creation, object writing, and stream closure.
392
+ * @throws :{@link InternalError} If the track does not support live content.
393
+ */
394
+ publishToRelay(): Promise<void>;
398
395
  }
399
-
400
- /**
401
- * Copyright 2026 The MOQtail Authors
402
- *
403
- * Licensed under the Apache License, Version 2.0 (the "License");
404
- * you may not use this file except in compliance with the License.
405
- * You may obtain a copy of the License at
406
- *
407
- * http://www.apache.org/licenses/LICENSE-2.0
408
- *
409
- * Unless required by applicable law or agreed to in writing, software
410
- * distributed under the License is distributed on an "AS IS" BASIS,
411
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
412
- * See the License for the specific language governing permissions and
413
- * limitations under the License.
414
- */
415
-
396
+ //#endregion
397
+ //#region src/client/request/publish_namespace.d.ts
416
398
  declare class PublishNamespaceRequest implements PromiseLike<RequestOk | RequestError> {
417
- readonly requestId: bigint;
418
- readonly message: PublishNamespace;
419
- private _resolve;
420
- private _reject;
421
- private promise;
422
- constructor(requestId: bigint, message: PublishNamespace);
423
- resolve(value: RequestOk | RequestError | PromiseLike<RequestOk | RequestError>): void;
424
- reject(reason?: any): void;
425
- then<TResult1 = RequestOk | RequestError, TResult2 = never>(onfulfilled?: ((value: RequestOk | RequestError) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): PromiseLike<TResult1 | TResult2>;
426
- catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null): Promise<RequestOk | RequestError | TResult>;
427
- finally(onfinally?: (() => void) | undefined | null): Promise<RequestOk | RequestError>;
399
+ readonly requestId: bigint;
400
+ readonly message: PublishNamespace;
401
+ private _resolve;
402
+ private _reject;
403
+ private promise;
404
+ constructor(requestId: bigint, message: PublishNamespace);
405
+ resolve(value: RequestOk | RequestError | PromiseLike<RequestOk | RequestError>): void;
406
+ reject(reason?: any): void;
407
+ then<TResult1 = RequestOk | RequestError, TResult2 = never>(onfulfilled?: ((value: RequestOk | RequestError) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): PromiseLike<TResult1 | TResult2>;
408
+ catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null): Promise<RequestOk | RequestError | TResult>;
409
+ finally(onfinally?: (() => void) | undefined | null): Promise<RequestOk | RequestError>;
428
410
  }
429
-
430
- /**
431
- * Copyright 2025 The MOQtail Authors
432
- *
433
- * Licensed under the Apache License, Version 2.0 (the "License");
434
- * you may not use this file except in compliance with the License.
435
- * You may obtain a copy of the License at
436
- *
437
- * http://www.apache.org/licenses/LICENSE-2.0
438
- *
439
- * Unless required by applicable law or agreed to in writing, software
440
- * distributed under the License is distributed on an "AS IS" BASIS,
441
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
442
- * See the License for the specific language governing permissions and
443
- * limitations under the License.
444
- */
445
-
411
+ //#endregion
412
+ //#region src/client/request/fetch.d.ts
446
413
  declare class FetchRequest implements PromiseLike<FetchOk | RequestError> {
447
- readonly requestId: bigint;
448
- readonly message: Fetch;
449
- private _resolve;
450
- private _reject;
451
- private promise;
452
- controller?: ReadableStreamDefaultController<MoqtObject>;
453
- stream: ReadableStream<MoqtObject>;
454
- isActive: boolean;
455
- isResolved: boolean;
456
- constructor(message: Fetch);
457
- resolve(value: FetchOk | RequestError | PromiseLike<FetchOk | RequestError>): void;
458
- reject(reason?: any): void;
459
- then<TResult1 = FetchOk | RequestError, TResult2 = never>(onfulfilled?: ((value: FetchOk | RequestError) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): PromiseLike<TResult1 | TResult2>;
460
- catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null): Promise<FetchOk | RequestError | TResult>;
461
- finally(onfinally?: (() => void) | undefined | null): Promise<FetchOk | RequestError>;
414
+ readonly requestId: bigint;
415
+ readonly message: Fetch;
416
+ private _resolve;
417
+ private _reject;
418
+ private promise;
419
+ controller?: ReadableStreamDefaultController<MoqtObject>;
420
+ stream: ReadableStream<MoqtObject>;
421
+ isActive: boolean;
422
+ isResolved: boolean;
423
+ constructor(message: Fetch);
424
+ resolve(value: FetchOk | RequestError | PromiseLike<FetchOk | RequestError>): void;
425
+ reject(reason?: any): void;
426
+ then<TResult1 = FetchOk | RequestError, TResult2 = never>(onfulfilled?: ((value: FetchOk | RequestError) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): PromiseLike<TResult1 | TResult2>;
427
+ catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null): Promise<FetchOk | RequestError | TResult>;
428
+ finally(onfinally?: (() => void) | undefined | null): Promise<FetchOk | RequestError>;
462
429
  }
463
-
464
- /**
465
- * Copyright 2025 The MOQtail Authors
466
- *
467
- * Licensed under the Apache License, Version 2.0 (the "License");
468
- * you may not use this file except in compliance with the License.
469
- * You may obtain a copy of the License at
470
- *
471
- * http://www.apache.org/licenses/LICENSE-2.0
472
- *
473
- * Unless required by applicable law or agreed to in writing, software
474
- * distributed under the License is distributed on an "AS IS" BASIS,
475
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
476
- * See the License for the specific language governing permissions and
477
- * limitations under the License.
478
- */
479
-
430
+ //#endregion
431
+ //#region src/client/request/subscribe.d.ts
480
432
  declare class SubscribeRequest implements PromiseLike<SubscribeOk | RequestError> {
481
- #private;
482
- requestId: bigint;
483
- fullTrackName: FullTrackName;
484
- isCanceled: boolean;
485
- startLocation: Location | undefined;
486
- endGroup: bigint | undefined;
487
- priority: number;
488
- forward: boolean;
489
- subscribeParameters: MessageParameter[];
490
- earlyDiscardPolicy: EarlyDiscardPolicyConfig | undefined;
491
- largestLocation: Location | undefined;
492
- streamsAccepted: bigint;
493
- expectedStreams: bigint | undefined;
494
- readonly controller: ReadableStreamDefaultController<MoqtObject>;
495
- readonly stream: ReadableStream<MoqtObject>;
496
- constructor(msg: Subscribe);
497
- update(msg: RequestUpdate): void;
498
- switch(newTrackName: FullTrackName, newParameters: MessageParameter[]): void;
499
- unsubscribe(): void;
500
- resolve(value: SubscribeOk | RequestError | PromiseLike<SubscribeOk | RequestError>): void;
501
- reject(reason?: any): void;
502
- then<TResult1 = SubscribeOk | RequestError, TResult2 = never>(onfulfilled?: ((value: SubscribeOk | RequestError) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): PromiseLike<TResult1 | TResult2>;
503
- catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null): Promise<SubscribeOk | RequestError | TResult>;
504
- finally(onfinally?: (() => void) | undefined | null): Promise<SubscribeOk | RequestError>;
433
+ #private;
434
+ requestId: bigint;
435
+ fullTrackName: FullTrackName;
436
+ isCanceled: boolean;
437
+ startLocation: Location | undefined;
438
+ endGroup: bigint | undefined;
439
+ priority: number;
440
+ forward: boolean;
441
+ subscribeParameters: MessageParameter[];
442
+ earlyDiscardPolicy: EarlyDiscardPolicyConfig | undefined;
443
+ largestLocation: Location | undefined;
444
+ streamsAccepted: bigint;
445
+ expectedStreams: bigint | undefined;
446
+ readonly controller: ReadableStreamDefaultController<MoqtObject>;
447
+ readonly stream: ReadableStream<MoqtObject>;
448
+ constructor(msg: Subscribe);
449
+ update(msg: RequestUpdate): void;
450
+ switch(newTrackName: FullTrackName, newParameters: MessageParameter[]): void;
451
+ unsubscribe(): void;
452
+ resolve(value: SubscribeOk | RequestError | PromiseLike<SubscribeOk | RequestError>): void;
453
+ reject(reason?: any): void;
454
+ then<TResult1 = SubscribeOk | RequestError, TResult2 = never>(onfulfilled?: ((value: SubscribeOk | RequestError) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): PromiseLike<TResult1 | TResult2>;
455
+ catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null): Promise<SubscribeOk | RequestError | TResult>;
456
+ finally(onfinally?: (() => void) | undefined | null): Promise<SubscribeOk | RequestError>;
505
457
  }
506
-
507
- /**
508
- * Copyright 2026 The MOQtail Authors
509
- *
510
- * Licensed under the Apache License, Version 2.0 (the "License");
511
- * you may not use this file except in compliance with the License.
512
- * You may obtain a copy of the License at
513
- *
514
- * http://www.apache.org/licenses/LICENSE-2.0
515
- *
516
- * Unless required by applicable law or agreed to in writing, software
517
- * distributed under the License is distributed on an "AS IS" BASIS,
518
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
519
- * See the License for the specific language governing permissions and
520
- * limitations under the License.
521
- */
522
-
458
+ //#endregion
459
+ //#region src/client/request/subscribe_namespace.d.ts
523
460
  declare class SubscribeNamespaceRequest implements PromiseLike<RequestOk | RequestError> {
524
- readonly requestId: bigint;
525
- readonly message: SubscribeNamespace;
526
- private _resolve;
527
- private _reject;
528
- private promise;
529
- constructor(msg: SubscribeNamespace);
530
- resolve(value: RequestOk | RequestError | PromiseLike<RequestOk | RequestError>): void;
531
- reject(reason?: any): void;
532
- then<TResult1 = RequestOk | RequestError, TResult2 = never>(onfulfilled?: ((value: RequestOk | RequestError) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): PromiseLike<TResult1 | TResult2>;
533
- catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null): Promise<RequestOk | RequestError | TResult>;
534
- finally(onfinally?: (() => void) | undefined | null): Promise<RequestOk | RequestError>;
461
+ readonly requestId: bigint;
462
+ readonly message: SubscribeNamespace;
463
+ private _resolve;
464
+ private _reject;
465
+ private promise;
466
+ constructor(msg: SubscribeNamespace);
467
+ resolve(value: RequestOk | RequestError | PromiseLike<RequestOk | RequestError>): void;
468
+ reject(reason?: any): void;
469
+ then<TResult1 = RequestOk | RequestError, TResult2 = never>(onfulfilled?: ((value: RequestOk | RequestError) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): PromiseLike<TResult1 | TResult2>;
470
+ catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null): Promise<RequestOk | RequestError | TResult>;
471
+ finally(onfinally?: (() => void) | undefined | null): Promise<RequestOk | RequestError>;
535
472
  }
536
-
537
- /**
538
- * Copyright 2025 The MOQtail Authors
539
- *
540
- * Licensed under the Apache License, Version 2.0 (the "License");
541
- * you may not use this file except in compliance with the License.
542
- * You may obtain a copy of the License at
543
- *
544
- * http://www.apache.org/licenses/LICENSE-2.0
545
- *
546
- * Unless required by applicable law or agreed to in writing, software
547
- * distributed under the License is distributed on an "AS IS" BASIS,
548
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
549
- * See the License for the specific language governing permissions and
550
- * limitations under the License.
551
- */
552
-
553
- declare class PublishRequest implements PromiseLike<PublishOk | RequestError> {
554
- readonly requestId: bigint;
555
- readonly message: Publish;
556
- private _resolve;
557
- private _reject;
558
- private promise;
559
- constructor(msg: Publish);
560
- resolve(value: PublishOk | RequestError | PromiseLike<PublishOk | RequestError>): void;
561
- reject(reason?: any): void;
562
- then<TResult1 = PublishOk | RequestError, TResult2 = never>(onfulfilled?: ((value: PublishOk | RequestError) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): PromiseLike<TResult1 | TResult2>;
563
- catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null): Promise<PublishOk | RequestError | TResult>;
564
- finally(onfinally?: (() => void) | undefined | null): Promise<PublishOk | RequestError>;
473
+ //#endregion
474
+ //#region src/client/request/publish.d.ts
475
+ declare class PublishRequest implements PromiseLike<RequestOk | RequestError> {
476
+ readonly requestId: bigint;
477
+ readonly message: Publish;
478
+ private _resolve;
479
+ private _reject;
480
+ private promise;
481
+ constructor(msg: Publish);
482
+ resolve(value: RequestOk | RequestError | PromiseLike<RequestOk | RequestError>): void;
483
+ reject(reason?: any): void;
484
+ then<TResult1 = RequestOk | RequestError, TResult2 = never>(onfulfilled?: ((value: RequestOk | RequestError) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): PromiseLike<TResult1 | TResult2>;
485
+ catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null): Promise<RequestOk | RequestError | TResult>;
486
+ finally(onfinally?: (() => void) | undefined | null): Promise<RequestOk | RequestError>;
565
487
  }
566
-
567
- /**
568
- * Copyright 2025 The MOQtail Authors
569
- *
570
- * Licensed under the Apache License, Version 2.0 (the "License");
571
- * you may not use this file except in compliance with the License.
572
- * You may obtain a copy of the License at
573
- *
574
- * http://www.apache.org/licenses/LICENSE-2.0
575
- *
576
- * Unless required by applicable law or agreed to in writing, software
577
- * distributed under the License is distributed on an "AS IS" BASIS,
578
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
579
- * See the License for the specific language governing permissions and
580
- * limitations under the License.
581
- */
582
-
488
+ //#endregion
489
+ //#region src/client/request/track_status.d.ts
490
+ declare class TrackStatusRequest implements PromiseLike<RequestOk | RequestError> {
491
+ readonly requestId: bigint;
492
+ readonly message: TrackStatus;
493
+ private _resolve;
494
+ private _reject;
495
+ private promise;
496
+ constructor(msg: TrackStatus);
497
+ resolve(value: RequestOk | RequestError | PromiseLike<RequestOk | RequestError>): void;
498
+ reject(reason?: any): void;
499
+ then<TResult1 = RequestOk | RequestError, TResult2 = never>(onfulfilled?: ((value: RequestOk | RequestError) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): PromiseLike<TResult1 | TResult2>;
500
+ catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null): Promise<RequestOk | RequestError | TResult>;
501
+ finally(onfinally?: (() => void) | undefined | null): Promise<RequestOk | RequestError>;
502
+ }
503
+ //#endregion
504
+ //#region src/client/types.d.ts
583
505
  /**
584
506
  * Discriminated union of every in‑flight MOQ‑tail control request tracked by the {@link MOQtailClient}.
585
507
  *
@@ -610,7 +532,7 @@ declare class PublishRequest implements PromiseLike<PublishOk | RequestError> {
610
532
  * }
611
533
  * ```
612
534
  */
613
- type MOQtailRequest = PublishRequest | PublishNamespaceRequest | SubscribeNamespaceRequest | FetchRequest | SubscribeRequest;
535
+ type MOQtailRequest = PublishRequest | PublishNamespaceRequest | SubscribeNamespaceRequest | FetchRequest | SubscribeRequest | TrackStatusRequest;
614
536
  /**
615
537
  * Options for {@link MOQtailClient.new} controlling connection target, protocol negotiation, timeouts,
616
538
  * and lifecycle callbacks.
@@ -639,33 +561,21 @@ type MOQtailRequest = PublishRequest | PublishNamespaceRequest | SubscribeNamesp
639
561
  * ```
640
562
  */
641
563
  type MOQtailClientOptions = {
642
- /** Relay / server endpoint for the underlying {@link https://developer.mozilla.org/docs/Web/API/WebTransport | WebTransport} session (can be absolute {@link https://developer.mozilla.org/en-US/docs/Web/API/URL | URL} or string).*/
643
- url: string | URL;
644
- /** {@link SetupParameters} customizations; if omitted a default instance is built.*/
645
- setupParameters?: SetupParameters;
646
- /** Passed directly to the browser's {@link https://developer.mozilla.org/docs/Web/API/WebTransport | WebTransport} constructor for {@link https://developer.mozilla.org/docs/Web/API/WebTransportOptions | WebTransportOptions}. */
647
- transportOptions?: WebTransportOptions & {
648
- protocols?: string[];
649
- };
650
- /** Per *data* uni-stream idle timeout in milliseconds. */
651
- dataStreamTimeoutMs?: number;
652
- /** Control stream read timeout in milliseconds. */
653
- controlStreamTimeoutMs?: number;
654
- /** If true, enables datagram support for the session. */
655
- enableDatagrams?: boolean;
656
- /** callbacks for observability and logging purposes: */
657
- callbacks?: {
658
- /** Called after a control message is successfully written to the {@link ControlStream}. */
659
- onMessageSent?: (msg: ControlMessage) => void;
660
- /** Called for each incoming control message before protocol handling. */
661
- onMessageReceived?: (msg: ControlMessage) => void;
662
- /** Fired once when the session ends (normal or error). Receives the reason passed to {@link MOQtailClient.disconnect | disconnect}. */
663
- onSessionTerminated?: (reason?: unknown) => void;
664
- /** Invoked for each decoded datagram object/status arriving. */
665
- onDatagramReceived?: (data: Datagram) => void;
666
- /** Invoked after enqueuing each outbound datagram object/status. */
667
- onDatagramSent?: (data: Datagram) => void;
668
- };
564
+ /** Relay / server endpoint for the underlying {@link https://developer.mozilla.org/docs/Web/API/WebTransport | WebTransport} session (can be absolute {@link https://developer.mozilla.org/en-US/docs/Web/API/URL | URL} or string).*/url: string | URL; /** {@link SetupOptions} customizations; if omitted a default instance is built.*/
565
+ setupOptions?: SetupOptions; /** Passed directly to the browser's {@link https://developer.mozilla.org/docs/Web/API/WebTransport | WebTransport} constructor for {@link https://developer.mozilla.org/docs/Web/API/WebTransportOptions | WebTransportOptions}. */
566
+ transportOptions?: WebTransportOptions & {
567
+ protocols?: string[];
568
+ }; /** Per *data* uni-stream idle timeout in milliseconds. */
569
+ dataStreamTimeoutMs?: number; /** Control stream read timeout in milliseconds. */
570
+ controlStreamTimeoutMs?: number; /** If true, enables datagram support for the session. */
571
+ enableDatagrams?: boolean; /** callbacks for observability and logging purposes: */
572
+ callbacks?: {
573
+ /** Called after a control message is successfully written to the {@link ControlStream}. */onMessageSent?: (msg: ControlMessage) => void; /** Called for each incoming control message before protocol handling. */
574
+ onMessageReceived?: (msg: ControlMessage) => void; /** Fired once when the session ends (normal or error). Receives the reason passed to {@link MOQtailClient.disconnect | disconnect}. */
575
+ onSessionTerminated?: (reason?: unknown) => void; /** Invoked for each decoded datagram object/status arriving. */
576
+ onDatagramReceived?: (data: Datagram) => void; /** Invoked after enqueuing each outbound datagram object/status. */
577
+ onDatagramSent?: (data: Datagram) => void;
578
+ };
669
579
  };
670
580
  /**
671
581
  * Parameters for {@link MOQtailClient.subscribe | subscribing} to a track's live objects.
@@ -694,24 +604,15 @@ type MOQtailClientOptions = {
694
604
  * ```
695
605
  */
696
606
  type SubscribeOptions = {
697
- /** Fully qualified track identifier ({@link FullTrackName}). */
698
- fullTrackName: FullTrackName;
699
- /** Subscriber priority (0 = highest, 255 = lowest). Values outside range are clamped. Fractional values are rounded. */
700
- priority: number;
701
- /** Desired {@link GroupOrder} (e.g. {@link GroupOrder.Original}) specifying delivery ordering semantics. */
702
- groupOrder: GroupOrder;
703
- /** If true, deliver objects forward (ascending); if false, reverse/backward semantics (implementation dependent). */
704
- forward: boolean;
705
- /** {@link FilterType} variant controlling starting subset (e.g. {@link FilterType.LatestObject}). */
706
- filterType: FilterType;
707
- /** Optional extension parameters appended to the SUBSCRIBE control message. */
708
- parameters?: MessageParameter[];
709
- /** Required for {@link FilterType.AbsoluteStart} / {@link FilterType.AbsoluteRange}; earliest {@link Location} to include. */
710
- startLocation?: Location;
711
- /** Required for {@link FilterType.AbsoluteRange}; exclusive upper group boundary (coerced to bigint if number provided). */
712
- endGroup?: bigint | number;
713
- /** Per-subscription early discard policy. Overrides the client-level default set via {@link MOQtailClient.setEarlyDiscardPolicy}. */
714
- earlyDiscardPolicy?: EarlyDiscardPolicyConfig;
607
+ /** Fully qualified track identifier ({@link FullTrackName}). */fullTrackName: FullTrackName; /** Subscriber priority (0 = highest, 255 = lowest). Values outside range are clamped. Fractional values are rounded. */
608
+ priority: number; /** Desired {@link (GroupOrder:enum)} (e.g. {@link (GroupOrder:enum).Original}) specifying delivery ordering semantics. */
609
+ groupOrder: GroupOrder; /** If true, deliver objects forward (ascending); if false, reverse/backward semantics (implementation dependent). */
610
+ forward: boolean; /** {@link FilterType} variant controlling starting subset (e.g. {@link FilterType.LatestObject}). */
611
+ filterType: FilterType; /** Optional extension parameters appended to the SUBSCRIBE control message. */
612
+ parameters?: MessageParameter[]; /** Required for {@link FilterType.AbsoluteStart} / {@link FilterType.AbsoluteRange}; earliest {@link Location} to include. */
613
+ startLocation?: Location; /** Required for {@link FilterType.AbsoluteRange}; exclusive upper group boundary (coerced to bigint if number provided). */
614
+ endGroup?: bigint | number; /** Per-subscription early discard policy. Overrides the client-level default set via {@link MOQtailClient.setEarlyDiscardPolicy}. */
615
+ earlyDiscardPolicy?: EarlyDiscardPolicyConfig;
715
616
  };
716
617
  /**
717
618
  * Narrowing update constraints applied to an existing SUBSCRIBE via {@link MOQtailClient.subscribeUpdate}.
@@ -730,18 +631,12 @@ type SubscribeOptions = {
730
631
  * ```
731
632
  */
732
633
  type SubscribeUpdateOptions = {
733
- /** The original SUBSCRIBE request id (bigint) being updated. */
734
- subscriptionRequestId: bigint;
735
- /** New narrowed {@link Location} start. */
736
- startLocation: Location;
737
- /** New narrowed end group (inclusive / protocol defined) must be \> start group. */
738
- endGroup: bigint;
739
- /** Updated subscriber priority (same constraints as initial subscribe). 0 is highest, 255 is lowest. */
740
- priority: number;
741
- /** Updated direction flag. */
742
- forward: boolean;
743
- /** Optional additional parameters; existing parameters persist if omitted. */
744
- parameters?: MessageParameter[];
634
+ /** The original SUBSCRIBE request id (bigint) being updated. */subscriptionRequestId: bigint; /** New narrowed {@link Location} start. */
635
+ startLocation: Location; /** New narrowed end group (inclusive / protocol defined) must be \> start group. */
636
+ endGroup: bigint; /** Updated subscriber priority (same constraints as initial subscribe). 0 is highest, 255 is lowest. */
637
+ priority: number; /** Updated direction flag. */
638
+ forward: boolean; /** Optional additional parameters; existing parameters persist if omitted. */
639
+ parameters?: MessageParameter[];
745
640
  };
746
641
  /**
747
642
  * Parameters for {@link MOQtailClient.switch | switching} an existing SUBSCRIBE to a new track.
@@ -755,12 +650,9 @@ type SubscribeUpdateOptions = {
755
650
  * ```
756
651
  */
757
652
  type SwitchOptions = {
758
- /** Fully qualified track identifier to switch to ({@link FullTrackName}). */
759
- fullTrackName: FullTrackName;
760
- /** The original SUBSCRIBE request id (bigint) being updated. */
761
- subscriptionRequestId: bigint;
762
- /** Optional additional parameters; existing parameters persist if omitted. */
763
- parameters?: MessageParameter[];
653
+ /** Fully qualified track identifier to switch to ({@link FullTrackName}). */fullTrackName: FullTrackName; /** The original SUBSCRIBE request id (bigint) being updated. */
654
+ subscriptionRequestId: bigint; /** Optional additional parameters; existing parameters persist if omitted. */
655
+ parameters?: MessageParameter[];
764
656
  };
765
657
  /**
766
658
  * Options for {@link MOQtailClient.fetch | performing a FETCH} operation for historical or relative object ranges.
@@ -799,65 +691,40 @@ type SwitchOptions = {
799
691
  * Configuration for the early discard policy applied to incoming subgroup streams.
800
692
  */
801
693
  type EarlyDiscardPolicyConfig = {
802
- /** Cancel a subgroup QUIC stream if it has not fully completed within this many milliseconds. */
803
- subgroupReceiveTimeout: number;
694
+ /** Cancel a subgroup QUIC stream if it has not fully completed within this many milliseconds. */subgroupReceiveTimeout: number;
804
695
  };
805
696
  type FetchOptions = {
806
- /** Request priority (0 = highest, 255 = lowest). Rounded & clamped. */
807
- priority: number;
808
- /** {@link GroupOrder} governing sequencing. */
809
- groupOrder: GroupOrder;
810
- /**
811
- * Discriminated union selecting the {@link FetchType} mode and its specific properties:
812
- * - Standalone: full explicit range on a {@link FullTrackName} with start/end {@link Location}s.
813
- * - Relative / Absolute: join an existing {@link SubscribeRequest} (identified by `joiningRequestId`) with starting position `joiningStart`.
814
- */
815
- typeAndProps: {
816
- /** Standalone historical/segment fetch for a specific {@link FullTrackName}. */
817
- type: FetchType.Standalone;
818
- /** Properties for standalone fetch: explicit track and range. */
819
- props: {
820
- fullTrackName: FullTrackName;
821
- startLocation: Location;
822
- endLocation: Location;
823
- };
824
- } | {
825
- /** Fetch a range relative to an existing {@link SubscribeRequest} identified by `joiningRequestId`. */
826
- type: FetchType.Relative;
827
- /** Properties for relative fetch: subscription id and starting position. */
828
- props: {
829
- joiningRequestId: bigint;
830
- joiningStart: bigint;
831
- };
832
- } | {
833
- /** Fetch an absolute group/object range relative to a {@link SubscribeRequest}. */
834
- type: FetchType.Absolute;
835
- /** Properties for absolute fetch: subscription id and starting position. */
836
- props: {
837
- joiningRequestId: bigint;
838
- joiningStart: bigint;
839
- };
697
+ /** Request priority (0 = highest, 255 = lowest). Rounded & clamped. */priority: number; /** {@link (GroupOrder:enum)} governing sequencing. */
698
+ groupOrder: GroupOrder;
699
+ /**
700
+ * Discriminated union selecting the {@link (FetchType:enum)} mode and its specific properties:
701
+ * - Standalone: full explicit range on a {@link FullTrackName} with start/end {@link Location}s.
702
+ * - Relative / Absolute: join an existing {@link SubscribeRequest} (identified by `joiningRequestId`) with starting position `joiningStart`.
703
+ */
704
+ typeAndProps: {
705
+ /** Standalone historical/segment fetch for a specific {@link FullTrackName}. */type: FetchType.Standalone; /** Properties for standalone fetch: explicit track and range. */
706
+ props: {
707
+ fullTrackName: FullTrackName;
708
+ startLocation: Location;
709
+ endLocation: Location;
710
+ };
711
+ } | {
712
+ /** Fetch a range relative to an existing {@link SubscribeRequest} identified by `joiningRequestId`. */type: FetchType.Relative; /** Properties for relative fetch: subscription id and starting position. */
713
+ props: {
714
+ joiningRequestId: bigint;
715
+ joiningStart: bigint;
840
716
  };
841
- /** Optional parameters block. */
842
- parameters?: MessageParameter[];
717
+ } | {
718
+ /** Fetch an absolute group/object range relative to a {@link SubscribeRequest}. */type: FetchType.Absolute; /** Properties for absolute fetch: subscription id and starting position. */
719
+ props: {
720
+ joiningRequestId: bigint;
721
+ joiningStart: bigint;
722
+ };
723
+ }; /** Optional parameters block. */
724
+ parameters?: MessageParameter[];
843
725
  };
844
-
845
- /**
846
- * Copyright 2025 The MOQtail Authors
847
- *
848
- * Licensed under the Apache License, Version 2.0 (the "License");
849
- * you may not use this file except in compliance with the License.
850
- * You may obtain a copy of the License at
851
- *
852
- * http://www.apache.org/licenses/LICENSE-2.0
853
- *
854
- * Unless required by applicable law or agreed to in writing, software
855
- * distributed under the License is distributed on an "AS IS" BASIS,
856
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
857
- * See the License for the specific language governing permissions and
858
- * limitations under the License.
859
- */
860
-
726
+ //#endregion
727
+ //#region src/client/datagram_stream.d.ts
861
728
  /**
862
729
  * Sends MoqtObjects as WebTransport datagrams.
863
730
  * Parallel to SendStream but for datagram-based delivery.
@@ -869,43 +736,43 @@ type FetchOptions = {
869
736
  * ```
870
737
  */
871
738
  declare class SendDatagramStream {
872
- #private;
873
- readonly onDataSent?: (data: Datagram) => void;
874
- constructor(writer: WritableStreamDefaultWriter<Uint8Array>, trackAlias: bigint, onDataSent?: (data: Datagram) => void);
875
- /**
876
- * Create a new datagram sender for a specific track.
877
- *
878
- * @param writeStream - WebTransport datagram writable stream
879
- * @param trackAlias - Track alias for this datagram stream
880
- * @param onDataSent - Optional callback fired when datagram is sent
881
- * @returns SendDatagramStream instance
882
- */
883
- static new(writeStream: WritableStream<Uint8Array>, trackAlias: bigint, onDataSent?: (data: Datagram) => void): Promise<SendDatagramStream>;
884
- /**
885
- * Create a datagram sender using an existing shared writer.
886
- * Use this when multiple senders need to share a single writer.
887
- *
888
- * @param writer - Existing WritableStreamDefaultWriter
889
- * @param trackAlias - Track alias for this datagram stream
890
- * @param onDataSent - Optional callback fired when datagram is sent
891
- * @returns SendDatagramStream instance
892
- */
893
- static fromWriter(writer: WritableStreamDefaultWriter<Uint8Array>, trackAlias: bigint, onDataSent?: (data: Datagram) => void): SendDatagramStream;
894
- /**
895
- * Write a MoqtObject as a datagram.
896
- * Converts to Datagram automatically based on object state.
897
- *
898
- * @param object - MoqtObject to send (must have Datagram forwarding preference)
899
- */
900
- write(object: MoqtObject): Promise<void>;
901
- /**
902
- * Close the datagram writer.
903
- */
904
- close(): Promise<void>;
905
- /**
906
- * Release the writer lock without closing.
907
- */
908
- releaseLock(): void;
739
+ #private;
740
+ readonly onDataSent?: (data: Datagram) => void;
741
+ constructor(writer: WritableStreamDefaultWriter<Uint8Array>, trackAlias: bigint, onDataSent?: (data: Datagram) => void);
742
+ /**
743
+ * Create a new datagram sender for a specific track.
744
+ *
745
+ * @param writeStream - WebTransport datagram writable stream
746
+ * @param trackAlias - Track alias for this datagram stream
747
+ * @param onDataSent - Optional callback fired when datagram is sent
748
+ * @returns SendDatagramStream instance
749
+ */
750
+ static new(writeStream: WritableStream<Uint8Array>, trackAlias: bigint, onDataSent?: (data: Datagram) => void): Promise<SendDatagramStream>;
751
+ /**
752
+ * Create a datagram sender using an existing shared writer.
753
+ * Use this when multiple senders need to share a single writer.
754
+ *
755
+ * @param writer - Existing WritableStreamDefaultWriter
756
+ * @param trackAlias - Track alias for this datagram stream
757
+ * @param onDataSent - Optional callback fired when datagram is sent
758
+ * @returns SendDatagramStream instance
759
+ */
760
+ static fromWriter(writer: WritableStreamDefaultWriter<Uint8Array>, trackAlias: bigint, onDataSent?: (data: Datagram) => void): SendDatagramStream;
761
+ /**
762
+ * Write a MoqtObject as a datagram.
763
+ * Converts to Datagram automatically based on object state.
764
+ *
765
+ * @param object - MoqtObject to send (must have Datagram forwarding preference)
766
+ */
767
+ write(object: MoqtObject): Promise<void>;
768
+ /**
769
+ * Close the datagram writer.
770
+ */
771
+ close(): Promise<void>;
772
+ /**
773
+ * Release the writer lock without closing.
774
+ */
775
+ releaseLock(): void;
909
776
  }
910
777
  /**
911
778
  * Receives and parses WebTransport datagrams as MoqtObjects.
@@ -928,45 +795,30 @@ declare class SendDatagramStream {
928
795
  * ```
929
796
  */
930
797
  declare class RecvDatagramStream {
931
- #private;
932
- readonly stream: ReadableStream<MoqtObject>;
933
- readonly onDataReceived?: (data: Datagram) => void;
934
- private constructor();
935
- /**
936
- * Create a new datagram receiver.
937
- *
938
- * @param readStream - WebTransport datagram readable stream
939
- * @param trackAliasResolver - Function to resolve track alias to full track name
940
- * @param onDataReceived - Optional callback fired when datagram is received
941
- * @returns RecvDatagramStream instance
942
- */
943
- static new(readStream: ReadableStream<Uint8Array>, trackAliasResolver: (trackAlias: bigint) => FullTrackName, onDataReceived?: (data: Datagram) => void): Promise<RecvDatagramStream>;
944
- /**
945
- * Cancel the datagram reader.
946
- */
947
- cancel(): Promise<void>;
948
- /**
949
- * Release the reader lock without canceling.
950
- */
951
- releaseLock(): void;
798
+ #private;
799
+ readonly stream: ReadableStream<MoqtObject>;
800
+ readonly onDataReceived?: (data: Datagram) => void;
801
+ private constructor();
802
+ /**
803
+ * Create a new datagram receiver.
804
+ *
805
+ * @param readStream - WebTransport datagram readable stream
806
+ * @param trackAliasResolver - Function to resolve track alias to full track name
807
+ * @param onDataReceived - Optional callback fired when datagram is received
808
+ * @returns RecvDatagramStream instance
809
+ */
810
+ static new(readStream: ReadableStream<Uint8Array>, trackAliasResolver: (trackAlias: bigint) => FullTrackName, onDataReceived?: (data: Datagram) => void): Promise<RecvDatagramStream>;
811
+ /**
812
+ * Cancel the datagram reader.
813
+ */
814
+ cancel(): Promise<void>;
815
+ /**
816
+ * Release the reader lock without canceling.
817
+ */
818
+ releaseLock(): void;
952
819
  }
953
-
954
- /**
955
- * Copyright 2025 The MOQtail Authors
956
- *
957
- * Licensed under the Apache License, Version 2.0 (the "License");
958
- * you may not use this file except in compliance with the License.
959
- * You may obtain a copy of the License at
960
- *
961
- * http://www.apache.org/licenses/LICENSE-2.0
962
- *
963
- * Unless required by applicable law or agreed to in writing, software
964
- * distributed under the License is distributed on an "AS IS" BASIS,
965
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
966
- * See the License for the specific language governing permissions and
967
- * limitations under the License.
968
- */
969
-
820
+ //#endregion
821
+ //#region src/client/client.d.ts
970
822
  /**
971
823
  * @public
972
824
  * Represents a Media Over QUIC Transport (MOQT) client session.
@@ -1011,833 +863,844 @@ declare class RecvDatagramStream {
1011
863
  * ```
1012
864
  */
1013
865
  declare class MOQtailClient {
1014
- #private;
1015
- /**
1016
- * Namespace prefixes (tuples) the peer has requested announce notifications for via SUBSCRIBE_NAMESPACE.
1017
- * Used to decide which locally issued ANNOUNCE messages should be forwarded (future optimization: prefix trie).
1018
- */
1019
- readonly peerSubscribeNamespace: Set<Tuple>;
1020
- /**
1021
- * Namespace prefixes this client has subscribed to (issued SUBSCRIBE_NAMESPACE). Enables automatic filtering
1022
- * of incoming PUBLISH_NAMESPACE / PUBLISH_NAMESPACE_DONE. Maintained locally; no dedupe of overlapping / shadowing prefixes yet.
1023
- */
1024
- readonly subscribedAnnounces: Set<Tuple>;
1025
- /**
1026
- * Track namespaces this client has successfully announced (received ANNOUNCE_OK). Source of truth for
1027
- * deciding what to PUBLISH_NAMESPACE_DONE on teardown or targeted withdrawal.(future optimization: prefix trie).
1028
- */
1029
- readonly announcedNamespaces: Set<Tuple>;
1030
- /**
1031
- * Locally registered track definitions keyed by full track name string. Populated via addOrUpdateTrack.
1032
- * Does not imply the track has been announced or has active publications.
1033
- */
1034
- readonly trackSources: Map<string, Track>;
1035
- /**
1036
- * All in‑flight request objects keyed by requestId (SUBSCRIBE, FETCH, ANNOUNCE, etc). Facilitates lookup
1037
- * when responses / data arrive. Entries are removed on completion or error.
1038
- */
1039
- readonly requests: Map<bigint, MOQtailRequest>;
1040
- /**
1041
- * Active publications (SUBSCRIBE or FETCH) keyed by requestId to manage object stream controllers and lifecycle.
1042
- * Subset / specialization view of `requests`.
1043
- */
1044
- readonly publications: Map<bigint, SubscribePublication | FetchPublication | PublishPublication>;
1045
- /**
1046
- * Active SUBSCRIBE request wrappers keyed by track alias for rapid alias -\> subscription resolution during
1047
- * incoming unidirectional data handling.
1048
- */
1049
- readonly subscriptions: Map<bigint, any>;
1050
- /**
1051
- * Bidirectional track alias \<-\> subscription requestId mapping
1052
- */
1053
- readonly subscriptionAliasMap: Map<bigint, bigint>;
1054
- /**
1055
- * Bidirectional requestId \<-\> full track name mapping to reconstruct metadata for incoming objects.
1056
- */
1057
- readonly requestIdMap: RequestIdMap;
1058
- /**
1059
- * Maps track aliases to full track names for quick resolution during data handling.
1060
- */
1061
- readonly aliasFullTrackNameMap: Map<bigint, FullTrackName>;
1062
- /**
1063
- * Pending state updates keyed by requestId and applied once a new track alias is seen.
1064
- * Used to avoid premature state updates.
1065
- */
1066
- readonly pendingStateUpdates: Map<bigint, (newTrackAlias: bigint) => boolean>;
1067
- /** Underlying WebTransport session (set after successful construction in MOQtailClient.new). */
1068
- webTransport: WebTransport;
1069
- /** Outgoing / incoming control message bidirectional stream wrapper. */
1070
- controlStream: ControlStream;
1071
- /** Timeout (ms) applied to reading incoming data streams; undefined =\> no explicit timeout. */
1072
- dataStreamTimeoutMs?: number;
1073
- /** Timeout (ms) for control stream read operations; undefined =\> no explicit timeout. */
1074
- controlStreamTimeoutMs?: number;
1075
- /** Optional highest request id allowed (enforced externally / via configuration). */
1076
- maxRequestId?: bigint;
1077
- /**
1078
- * TODO: onNamespaceAnnounced may be a better name
1079
- * Fired when an PUBLISH_NAMESPACE control message is processed for a track namespace.
1080
- * Use to update UI or trigger discovery logic.
1081
- * Discovery event.
1082
- */
1083
- onNamespacePublished?: (msg: PublishNamespace) => void;
1084
- /**
1085
- * Fired when an PUBLISH_NAMESPACE_DONE control message is processed for a namespace.
1086
- * Use to remove tracks from UI or stop discovery.
1087
- * Discovery event.
1088
- */
1089
- onNamespaceDone?: (msg: PublishNamespaceDone) => void;
1090
- /**
1091
- * Fired on GOAWAY reception signaling graceful session wind-down.
1092
- * Use to prepare for disconnect or cleanup.
1093
- * Lifecycle handler.
1094
- */
1095
- onGoaway?: (msg: GoAway) => void;
1096
- /**
1097
- * Fired if the underlying WebTransport session fails (ready -\> closed prematurely).
1098
- * Use to log or alert on transport errors.
1099
- * Lifecycle/error handler.
1100
- */
1101
- onWebTransportFail?: () => void;
1102
- /**
1103
- * Fired exactly once when the client transitions to terminated (disconnect).
1104
- * Use to clean up resources or notify user.
1105
- * Lifecycle handler.
1106
- */
1107
- onSessionTerminated?: (reason?: unknown) => void;
1108
- /**
1109
- * Invoked after each outbound control message is sent.
1110
- * Use for logging or analytics.
1111
- * Informational event.
1112
- */
1113
- onMessageSent?: (msg: ControlMessage) => void;
1114
- /**
1115
- * Invoked upon receiving each inbound control message before handling.
1116
- * Use for logging or debugging.
1117
- * Informational event.
1118
- */
1119
- onMessageReceived?: (msg: ControlMessage) => void;
1120
- /**
1121
- * Invoked for each decoded data object/header arriving on a uni stream (fetch or subgroup).
1122
- * Use to process or display incoming media/data.
1123
- * Informational event.
1124
- */
1125
- onDataReceived?: (data: SubgroupObject | SubgroupHeader | FetchObject | FetchHeader) => void;
1126
- /**
1127
- * Invoked after enqueuing each outbound data object/header.
1128
- * Reserved for future use.
1129
- * Informational event.
1130
- */
1131
- onDataSent?: (data: SubgroupObject | SubgroupHeader | FetchObject | FetchHeader) => void;
1132
- /**
1133
- * General-purpose error callback for surfaced exceptions not thrown to caller synchronously.
1134
- * Use to log or display errors.
1135
- * Error handler.
1136
- */
1137
- onError?: (er: unknown) => void;
1138
- /** Invoked for each decoded datagram object/status arriving. */
1139
- onDatagramReceived?: (data: Datagram) => void;
1140
- /** Invoked after enqueuing each outbound datagram object/status. */
1141
- onDatagramSent?: (data: Datagram) => void;
1142
- /** Fired when an inbound PUBLISH control message is received. */
1143
- onPeerPublish?: (msg: Publish, stream: ReadableStream<MoqtObject>) => void;
1144
- /** Fired when an inbound PUBLISH_DONE control message is received. */
1145
- onPeerPublishDone?: (msg: PublishDone) => void;
1146
- /** Fired when an inbound SUBSCRIBE_NAMESPACE control message is received. */
1147
- onPeerSubscribeNamespace?: (msg: SubscribeNamespace) => void;
1148
- /** Fired when a NAMESPACE message arrives on a SUBSCRIBE_NAMESPACE bi-stream (prefix + suffix). */
1149
- onPeerNamespace?: (prefix: Tuple, suffix: Tuple) => void;
1150
- /** Fired when a NAMESPACE_DONE message arrives on a SUBSCRIBE_NAMESPACE bi-stream (prefix + suffix). */
1151
- onPeerNamespaceDone?: (prefix: Tuple, suffix: Tuple) => void;
1152
- /**
1153
- * Stream of all received MoqtObjects from datagrams across all tracks
1154
- * Consumer should filter by fullTrackName as needed
1155
- *
1156
- * WARNING: Only one reader should be active. For multiple subscribers,
1157
- * use subscribeToTrackDatagrams() instead
1158
- */
1159
- readonly receivedDatagramObjects: ReadableStream<MoqtObject>;
1160
- /**
1161
- * Generates a safe, sequential local request ID for tracking pushed/incoming tracks.
1162
- */
1163
- allocatePseudoRequestId(): bigint;
1164
- /**
1165
- * Gets the current server setup configuration.
1166
- *
1167
- * @returns The {@link ServerSetup} instance associated with this client.
1168
- */
1169
- get serverSetup(): ServerSetup;
1170
- /**
1171
- * Returns true if datagram support is currently active
1172
- */
1173
- get isDatagramsEnabled(): boolean;
1174
- /**
1175
- * Sets the global log level for all moqtail-ts loggers.
1176
- * @param level - The minimum {@link LogLevel} to output. Use `LogLevel.NONE` to silence all logs.
1177
- */
1178
- static setLogLevel(level: LogLevel): void;
1179
- /**
1180
- * Restricts log output to the specified module names. Pass `null` to allow all modules.
1181
- * @param modules - Array of module name strings, or `null` to enable all modules.
1182
- */
1183
- static setLogEnabledModules(modules: string[] | null): void;
1184
- private constructor();
1185
- /**
1186
- * Establishes a new {@link MOQtailClient} session over WebTransport and performs the MOQT setup handshake.
1187
- *
1188
- * @param args - {@link MOQtailClientOptions}
1189
- *
1190
- * @returns Promise resolving to a ready {@link MOQtailClient} instance.
1191
- *
1192
- * @throws :{@link ProtocolViolationError} If the server sends an unexpected or invalid message during setup.
1193
- *
1194
- * @example Minimal connection
1195
- * ```ts
1196
- * const client = await MOQtailClient.new({
1197
- * url: 'https://relay.example.com/transport'
1198
- * });
1199
- * ```
1200
- *
1201
- * @example With callbacks and options
1202
- * ```ts
1203
- * const client = await MOQtailClient.new({
1204
- * url,
1205
- * setupParameters: new SetupParameters().addMaxRequestId(1000),
1206
- * transportOptions: { congestionControl: 'default' },
1207
- * dataStreamTimeoutMs: 5000,
1208
- * controlStreamTimeoutMs: 2000,
1209
- * enableDatagrams: true,
1210
- * callbacks: {
1211
- * onMessageSent: msg => console.log('Sent:', msg),
1212
- * onMessageReceived: msg => console.log('Received:', msg),
1213
- * onSessionTerminated: reason => console.warn('Session ended:', reason),
1214
- * onDatagramReceived: data => console.log('Datagram:', data),
1215
- * }
1216
- * });
1217
- * ```
1218
- */
1219
- static new(args: MOQtailClientOptions): Promise<MOQtailClient>;
1220
- /**
1221
- * Start receiving datagrams from the WebTransport connection.
1222
- * Must be called before datagrams can be received (unless enableDatagrams: true was set in options).
1223
- *
1224
- * @throws MOQtailError if client is destroyed or datagrams already started
1225
- */
1226
- startDatagrams(): Promise<void>;
1227
- /**
1228
- * Stop receiving datagrams and release resources.
1229
- * Idempotent - safe to call multiple times.
1230
- */
1231
- stopDatagrams(): Promise<void>;
1232
- /**
1233
- * Subscribe to receive datagrams for a specific track.
1234
- * Multiple tracks can have separate handlers that run concurrently.
1235
- *
1236
- * @param trackAlias - Track alias to subscribe to
1237
- * @param handler - Function called for each received MoqtObject on this track
1238
- * @returns Unsubscribe function to remove the handler
1239
- *
1240
- * @example
1241
- * ```ts
1242
- * const unsubscribe = client.subscribeToTrackDatagrams(trackAlias, (obj) => {
1243
- * console.log('Received datagram:', obj.payload);
1244
- * });
1245
- * // Later: unsubscribe();
1246
- * ```
1247
- */
1248
- subscribeToTrackDatagrams(trackAlias: bigint, handler: (obj: MoqtObject) => void): () => void;
1249
- /**
1250
- * Unsubscribe from datagram delivery for a specific track.
1251
- *
1252
- * @param trackAlias - Track alias to unsubscribe from
1253
- */
1254
- unsubscribeFromTrackDatagrams(trackAlias: bigint): void;
1255
- /**
1256
- * Create a datagram sender for a specific track.
1257
- *
1258
- * @param trackAlias - Track alias for outgoing datagrams
1259
- * @returns SendDatagramStream for writing MoqtObjects as datagrams
1260
- * @throws MOQtailError if datagram writer not initialized (call startDatagrams() first)
1261
- *
1262
- * @example
1263
- * ```ts
1264
- * const sender = client.createDatagramSender(trackAlias);
1265
- * await sender.write(moqtObject);
1266
- * ```
1267
- */
1268
- createDatagramSender(trackAlias: bigint): SendDatagramStream;
1269
- /**
1270
- * Send a single MoqtObject as a datagram.
1271
- * Convenience method for one-off datagram sends.
1272
- *
1273
- * @param trackAlias - Track alias for this object
1274
- * @param object - MoqtObject to send
1275
- * @throws MOQtailError if datagram writer not initialized
1276
- *
1277
- * @example
1278
- * ```ts
1279
- * await client.sendDatagram(trackAlias, moqtObject);
1280
- * ```
1281
- */
1282
- sendDatagram(trackAlias: bigint, object: MoqtObject): Promise<void>;
1283
- /**
1284
- * Sets (or replaces) the client-level default early discard policy for incoming subgroup streams.
1285
- *
1286
- * When set, each incoming subgroup QUIC stream is given a deadline of `subgroupReceiveTimeout` ms to
1287
- * complete. If the stream has not finished within that window it is cancelled — objects already
1288
- * delivered to the subscription are kept, but no further objects arrive from that stream.
1289
- *
1290
- * This is a client-wide default. Individual subscriptions can override it via the `earlyDiscardPolicy`
1291
- * field in {@link SubscribeOptions}, which takes precedence over this setting.
1292
- *
1293
- * The policy takes effect on the next stream accepted after this call. Passing a new config
1294
- * replaces the previous one. Pass `undefined` to remove the default.
1295
- *
1296
- * @example
1297
- * ```ts
1298
- * client.setEarlyDiscardPolicy({ subgroupReceiveTimeout: 2000 })
1299
- * ```
1300
- */
1301
- setEarlyDiscardPolicy(config: EarlyDiscardPolicyConfig | undefined): void;
1302
- /**
1303
- * Gracefully terminates this {@link MOQtailClient} session and releases underlying {@link https://developer.mozilla.org/docs/Web/API/WebTransport | WebTransport} resources.
1304
- *
1305
- * @param reason - Optional application-level reason (string or error) recorded and wrapped in an {@link InternalError}
1306
- * passed to the {@link MOQtailClient.onSessionTerminated | onSessionTerminated} callback.
1307
- *
1308
- * @returns Promise that resolves once shutdown logic completes. Subsequent calls are safe no-ops.
1309
- *
1310
- * @example Basic usage
1311
- * ```ts
1312
- * await client.disconnect();
1313
- * ```
1314
- *
1315
- * @example With reason
1316
- * ```ts
1317
- * await client.disconnect('user logout');
1318
- * ```
1319
- *
1320
- * @example Idempotent double call
1321
- * ```ts
1322
- * await client.disconnect();
1323
- * await client.disconnect(); // no error
1324
- * ```
1325
- *
1326
- * @example Page unload safety
1327
- * ```ts
1328
- * window.addEventListener('beforeunload', () => {
1329
- * client.disconnect('page unload');
1330
- * });
1331
- * ```
1332
- */
1333
- disconnect(reason?: unknown): Promise<void>;
1334
- /**
1335
- * Registers or updates a {@link Track} definition for local publishing or serving.
1336
- *
1337
- * A {@link Track} describes a logical media/data stream, identified by a unique name and namespace.
1338
- * - If `trackSource.live` is present, the track can be served to subscribers in real-time.
1339
- * - If `trackSource.past` is present, the track can be fetched for historical data.
1340
- * - If both are present, the track supports both live and historical access.
1341
- *
1342
- * @param track - The {@link Track} instance to add or update. See {@link TrackSource} for live/past source options.
1343
- * @returns void
1344
- * @throws : {@link MOQtailError} If the client has been destroyed.
1345
- *
1346
- * @example Create a live video track from getUserMedia
1347
- * ```ts
1348
- * const stream = await navigator.mediaDevices.getUserMedia({ video: true });
1349
- * const videoTrack = stream.getVideoTracks()[0];
1350
- *
1351
- * // Convert video frames to MoqtObject instances using your chosen scheme (e.g. WARP, CMAF, etc.)
1352
- * // This part is application-specific and not provided by MOQtail:
1353
- * const liveReadableStream: ReadableStream<MoqtObject> = ...
1354
- *
1355
- * // Register the track for live subscription
1356
- * client.addOrUpdateTrack({
1357
- * fullTrackName: { namespace: ["camera"], name: "main" },
1358
- * trackSource: { live: liveReadableStream },
1359
- * publisherPriority: 0 // highest priority
1360
- * });
1361
- *
1362
- * // For a hybrid track (live + past):
1363
- * import { MemoryObjectCache } from './track/object_cache';
1364
- * const cache = new MemoryObjectCache(); // Caches are not yet fully supported
1365
- * client.addOrUpdateTrack({
1366
- * fullTrackName: { namespace: ["camera"], name: "main" },
1367
- * trackSource: { live: liveReadableStream, past: cache },
1368
- * publisherPriority: 8
1369
- * });
1370
- * ```
1371
- */
1372
- addOrUpdateTrack(track: Track): void;
1373
- /**
1374
- * Removes a previously registered {@link Track} from this client's local catalog.
1375
- *
1376
- * This deletes the in-memory entry inserted via {@link MOQtailClient.addOrUpdateTrack}, so future lookups by its {@link Track.fullTrackName} will fail.
1377
- * Does **not** automatically:
1378
- * - Send an {@link PublishNamespaceDone} (call {@link MOQtailClient.publishNamespaceDone} separately if you want to inform peers)
1379
- * - Cancel active subscriptions or fetches (they continue until normal completion)
1380
- * - Affect already-sent objects.
1381
- *
1382
- * If the track was not present, the call is a silent no-op (idempotent removal).
1383
- *
1384
- * @param track - The exact {@link Track} instance (its canonical name is used as the key).
1385
- * @throws : {@link MOQtailError} If the client has been destroyed.
1386
- *
1387
- * @example
1388
- * ```ts
1389
- * // Register a track
1390
- * client.addOrUpdateTrack(track);
1391
- *
1392
- * // Later, when no longer publishing:
1393
- * client.removeTrack(track);
1394
- *
1395
- * // Optionally, inform peers that the namespace is no longer available:
1396
- * await client.publishNamespaceDone(track.fullTrackName.namespace);
1397
- * ```
1398
- */
1399
- removeTrack(track: Track): void;
1400
- /**
1401
- * Subscribes to a track and returns a stream of {@link MoqtObject}s matching the requested window and relay forwarding mode.
1402
- *
1403
- * - `forward: true` tells the relay to forward objects to this subscriber as they arrive.
1404
- * - `forward: false` means the relay subscribes upstream but buffers objects locally, not forwarding them to you.
1405
- * - `filterType: AbsoluteStart` lets you specify a start position in the future; the stream waits for that object. If the start location is \< the latest object
1406
- * observed at the publisher then it behaves as `filterType: LatestObject`
1407
- * - `filterType: AbsoluteRange` lets you specify a start and end group, both of should be in the future; the stream waits for those objects. If the start location is \< the latest object
1408
- * observed at the publisher then it behaves as `filterType: LatestObject`.
1409
- *
1410
- * The method returns either a {@link RequestError} (on refusal) or an object with the subscription `requestId` and a `ReadableStream` of {@link MoqtObject}s.
1411
- * Use the `requestId` for {@link MOQtailClient.unsubscribe} or {@link MOQtailClient.subscribeUpdate}. Use the `stream` to decode and display objects.
1412
- *
1413
- * @param args - {@link SubscribeOptions} describing the subscription window and relay forwarding behavior.
1414
- * @returns Either a {@link RequestError} or `{ requestId, stream }` for consuming objects.
1415
- * @throws : {@link MOQtailError} If the client is destroyed.
1416
- * @throws : {@link ProtocolViolationError} If required fields are missing or inconsistent.
1417
- * @throws : {@link InternalError} On transport/protocol failure (disconnect is triggered before rethrow).
1418
- *
1419
- * @example Subscribe to the latest object and receive future objects as they arrive
1420
- * ```ts
1421
- * const result = await client.subscribe({
1422
- * fullTrackName,
1423
- * filterType: FilterType.LatestObject,
1424
- * forward: true,
1425
- * groupOrder: GroupOrder.Original,
1426
- * priority: 32
1427
- * });
1428
- * if (!(result instanceof RequestError)) {
1429
- * for await (const obj of result.stream) {
1430
- * // decode and display obj
1431
- * }
1432
- * }
1433
- * ```
1434
- *
1435
- * @example Subscribe to a future range (waits for those objects to arrive)
1436
- * ```ts
1437
- * const result = await client.subscribe({
1438
- * fullTrackName,
1439
- * filterType: FilterType.AbsoluteRange,
1440
- * startLocation: futureStart,
1441
- * endGroup: futureEnd,
1442
- * forward: true,
1443
- * groupOrder: GroupOrder.Original,
1444
- * priority: 128
1445
- * });
1446
- * ```
1447
- */
1448
- subscribe(args: SubscribeOptions): Promise<RequestError | {
1449
- requestId: bigint;
1450
- stream: ReadableStream<MoqtObject>;
1451
- }>;
1452
- /**
1453
- * Stops an active subscription identified by its original SUBSCRIBE `requestId`.
1454
- *
1455
- * Sends an {@link Unsubscribe} control frame if the subscription is still active. If the id is unknown or already
1456
- * cleaned up, the call is a silent no-op (hence multiple calls are idempotent).
1457
- *
1458
- * Use this when you no longer want incoming objects for a track (e.g. user navigated away, switching quality).
1459
- * Canceling the consumer stream reader does **not** auto-unsubscribe; call this explicitly for prompt cleanup.
1460
- *
1461
- * @param requestId - The id returned from {@link MOQtailClient.subscribe}.
1462
- * @returns Promise that resolves when the unsubscribe control frame is sent.
1463
- * @throws :{@link MOQtailError} If the client is destroyed.
1464
- * @throws :{@link InternalError} Wrapped lower-level failure while attempting to send (session will be disconnected first).
1465
- *
1466
- * @remarks
1467
- * - Only targets SUBSCRIBE requests, not fetches. Passing a fetch request id is ignored (no-op).
1468
- * - Safe to call multiple times; extra calls have no effect.
1469
- *
1470
- * @example Subscribe and later unsubscribe
1471
- * ```ts
1472
- * const sub = await client.subscribe({ fullTrackName, filterType: FilterType.LatestObject, forward: true, groupOrder: GroupOrder.Original, priority: 0 });
1473
- * if (!(sub instanceof RequestError)) {
1474
- * // ...consume objects...
1475
- * await client.unsubscribe(sub.requestId);
1476
- * }
1477
- * ```
1478
- *
1479
- * @example Idempotent usage
1480
- * ```ts
1481
- * await client.unsubscribe(123n);
1482
- * await client.unsubscribe(123n); // no error
1483
- * ```
1484
- */
1485
- unsubscribe(requestId: bigint | number): Promise<void>;
1486
- /**
1487
- * Narrows or updates an active subscription window and/or relay forwarding behavior.
1488
- *
1489
- * Use this to:
1490
- * - Move the start of the subscription forward (trim history or future window).
1491
- * - Move the end group earlier (shorten the window).
1492
- * - Change relay forwarding (`forward: false` stops forwarding new objects, `true` resumes).
1493
- * - Adjust subscriber priority.
1494
- *
1495
- * Only narrowing is allowed: you cannot move the start earlier or the end group later than the original subscription.
1496
- * Forwarding and priority can be changed at any time.
1497
- *
1498
- * @param args - {@link SubscribeUpdateOptions} referencing the original subscription `requestId` and new bounds.
1499
- * @returns Promise that resolves when the update control frame is sent.
1500
- * @throws :{@link MOQtailError} If the client is destroyed.
1501
- * @throws :{@link ProtocolViolationError} If the update would widen the window (earlier start, later end group, or invalid ordering).
1502
- * @throws :{@link InternalError} On transport/control failure (disconnect is triggered before rethrow).
1503
- *
1504
- * @remarks
1505
- * - Only applies to active SUBSCRIBE requests; ignored if the request is not a subscription.
1506
- * - Omitting a parameter (e.g. `priority`) leaves the previous value unchanged.
1507
- * - Setting `forward: false` stops relay forwarding new objects after the current window drains.
1508
- * - Safe to call multiple times; extra calls with unchanged bounds have no effect.
1509
- *
1510
- * @example Trim start forward
1511
- * ```ts
1512
- * await client.subscribeUpdate({ requestId, startLocation: laterLoc, endGroup, forward: true, priority });
1513
- * ```
1514
- *
1515
- * @example Convert tailing subscription into bounded slice
1516
- * ```ts
1517
- * await client.subscribeUpdate({ requestId, startLocation: origStart, endGroup: cutoffGroup, forward: false, priority });
1518
- * ```
1519
- *
1520
- * @example Lower priority only
1521
- * ```ts
1522
- * await client.subscribeUpdate({ requestId, startLocation: currentStart, endGroup: currentEnd, forward: true, priority: 200 });
1523
- * ```
1524
- */
1525
- subscribeUpdate(args: SubscribeUpdateOptions): Promise<void>;
1526
- /**
1527
- * Switches an active subscription to a different track while retaining the same subscription parameters.
1528
- *
1529
- * Use this to change the subscribed track without tearing down and re-establishing a new subscription.
1530
- *
1531
- * @param args - {@link SwitchOptions} referencing the original subscription `requestId` and new track name.
1532
- * @returns Promise that resolves when the switch control frame is sent.
1533
- * @throws :{@link MOQtailError} If the client is destroyed.
1534
- * @throws :{@link InternalError} On transport/control failure (disconnect is triggered before rethrow).
1535
- *
1536
- * @remarks
1537
- * - Only applies to active SUBSCRIBE requests; ignored if the request is not a subscription.
1538
- * - All other subscription parameters (window, forwarding, priority) remain unchanged.
1539
- *
1540
- * @example Switch to a different track
1541
- * ```ts
1542
- * await client.switch({ subscriptionRequestId, fullTrackName: newTrackName });
1543
- * ```
1544
- */
1545
- switch(args: SwitchOptions): Promise<RequestError | {
1546
- requestId: bigint;
1547
- stream: ReadableStream<MoqtObject>;
1548
- }>;
1549
- /**
1550
- * One-shot retrieval of a bounded object span, optionally anchored to an existing subscription, returning a stream of {@link MoqtObject}s.
1551
- *
1552
- * Choose a fetch type via `typeAndProps.type`:
1553
- * - Standalone: Historical slice of a specific {@link FullTrackName} independent of active subscriptions.
1554
- * - Relative: Range relative to the JOINING subscription's current (largest) location; use when you want "N groups back" from live.
1555
- * - Absolute: Absolute group/object offsets tied to an existing subscription (stable anchor) even if that subscription keeps forwarding.
1556
- *
1557
- * Field highlights (in {@link FetchOptions}):
1558
- * - priority: 0 (highest) .. 255 (lowest); out-of-range rejected; non-integers rounded by caller expectation.
1559
- * - groupOrder: {@link GroupOrder.Original} to preserve publisher order; or reorder ascending/descending if supported by server.
1560
- * - typeAndProps: Discriminated union carrying parameters specific to each fetch mode (see examples).
1561
- * - parameters: Optional version-specific extension block.
1562
- *
1563
- * Returns either a {@link RequestError} (refusal / invalid request at protocol level) or `{ requestId, stream }` whose `stream`
1564
- * ends naturally after the bounded range completes (no explicit cancel needed for normal completion).
1565
- *
1566
- * Use cases:
1567
- * - Grab a historical window for scrubbing UI while a separate live subscription tails.
1568
- * - Late joiner fetching a short back-buffer then discarding the stream.
1569
- * - Analytics batch job pulling a fixed slice without subscribing long-term.
1570
- *
1571
- * @throws MOQtailError If client is destroyed.
1572
- * @throws ProtocolViolationError Priority out of [0-255] or missing/invalid joining subscription id for Relative/Absolute.
1573
- * @throws InternalError Transport/control failure (the client disconnects first) then rethrows original error.
1574
- *
1575
- * @remarks
1576
- * - Relative / Absolute require an existing active SUBSCRIBE `joiningRequestId`; if not found a {@link ProtocolViolationError} is thrown.
1577
- * - Result stream is finite; reader close occurs automatically when last object delivered.
1578
- * - Use {@link MOQtailClient.fetchCancel} only for early termination (not yet fully implemented: see TODO in code).
1579
- *
1580
- * @example Standalone window
1581
- * ```ts
1582
- * const r = await client.fetch({
1583
- * priority: 64,
1584
- * groupOrder: GroupOrder.Original,
1585
- * typeAndProps: {
1586
- * type: FetchType.Standalone,
1587
- * props: { fullTrackName, startLocation, endLocation }
1588
- * }
1589
- * })
1590
- * if (!(r instanceof RequestError)) {
1591
- * for await (const obj of r.stream as any) {
1592
- * // consume objects then stream ends automatically
1593
- * }
1594
- * }
1595
- * ```
1596
- *
1597
- * @example Relative to live subscription (e.g. last 5 groups)
1598
- * ```ts
1599
- * const sub = await client.subscribe({ fullTrackName, filterType: FilterType.LatestObject, forward: true, groupOrder: GroupOrder.Original, priority: 0 })
1600
- * if (!(sub instanceof RequestError)) {
1601
- * const slice = await client.fetch({
1602
- * priority: 32,
1603
- * groupOrder: GroupOrder.Original,
1604
- * typeAndProps: { type: FetchType.Relative, props: { joiningRequestId: sub.requestId, joiningStart: 0n } }
1605
- * })
1606
- * }
1607
- * ```
1608
- */
1609
- fetch(args: FetchOptions): Promise<RequestError | {
1610
- requestId: bigint;
1611
- stream: ReadableStream<MoqtObject>;
1612
- }>;
1613
- /**
1614
- * Request early termination of an in‑flight FETCH identified by its `requestId`.
1615
- *
1616
- * Use when the consumer no longer needs the remaining objects (user scrubbed away, UI panel closed, replaced by a new fetch).
1617
- * Sends a {@link FetchCancel} control frame if the id currently maps to an active fetch; otherwise silent no-op (idempotent).
1618
- *
1619
- * Parameter semantics:
1620
- * - requestId: bigint returned from {@link MOQtailClient.fetch}. Numbers auto-converted to bigint.
1621
- *
1622
- * Current behavior / limitations:
1623
- * - Data stream closure after cancel is TODO (objects may still arrive briefly).
1624
- * - Unknown / already finished request: ignored without error.
1625
- * - Only targets FETCH requests (not subscriptions).
1626
- *
1627
- * @throws MOQtailError If client is destroyed.
1628
- * @throws InternalError Failure while sending the cancel (client disconnects first).
1629
- *
1630
- * @remarks
1631
- * Follow-up improvement planned: actively close associated readable stream controller immediately upon acknowledgment.
1632
- *
1633
- * @example Cancel shortly after starting
1634
- * ```ts
1635
- * const r = await client.fetch({ priority: 32, groupOrder: GroupOrder.Original, typeAndProps: { type: FetchType.Standalone, props: { fullTrackName, startLocation, endLocation } } })
1636
- * if (!(r instanceof RequestError)) {
1637
- * // user navigated away
1638
- * await client.fetchCancel(r.requestId)
1639
- * }
1640
- * ```
1641
- *
1642
- * @example Idempotent double cancel
1643
- * ```ts
1644
- * await client.fetchCancel(456n)
1645
- * await client.fetchCancel(456n) // no error
1646
- * ```
1647
- */
1648
- fetchCancel(requestId: bigint | number): Promise<void>;
1649
- /**
1650
- * Proactively push a track to the relay/peer.
1651
- */
1652
- publish(fullTrackName: FullTrackName, forward: boolean, trackAlias: bigint, parameters?: MessageParameter[], trackExtensions?: TrackExtension[]): Promise<RequestError | {
1653
- requestId: bigint;
1654
- trackAlias: bigint;
1655
- }>;
1656
- /**
1657
- * Signals the end of a published track to the peer/relay.
1658
- * * @param publishRequestId - The original requestId used when `publish()` was called.
1659
- */
1660
- publishDone(publishRequestId: bigint | number, statusCode?: number, reasonPhrase?: string): Promise<void>;
1661
- /**
1662
- * Registers an incoming PUBLISH announcement as a valid data receiver.
1663
- * This prepares the client to ingest pushed data streams matching the published alias.
1664
- * * @param msg - The incoming Publish control message
1665
- * @returns - A stream of MoqtObjects being pushed by the publisher
1666
- */
1667
- acceptPushedTrack(msg: Publish): ReadableStream<MoqtObject>;
1668
- /**
1669
- * Declare (publish) a track namespace to the peer so subscribers using matching prefixes (via {@link MOQtailClient.subscribeNamespace})
1670
- * can discover and begin subscribing/fetching its tracks.
1671
- *
1672
- * Typical flow (publisher side):
1673
- * 1. Prepare / register one or more {@link Track} objects locally (see {@link MOQtailClient.addOrUpdateTrack}).
1674
- * 2. Call `publishNamespace(namespace)` once per namespace prefix to expose those tracks.
1675
- * 3. Later, call {@link MOQtailClient.publishNamespaceDone} when no longer publishing under that namespace.
1676
- *
1677
- * Parameter semantics:
1678
- * - trackNamespace: Tuple representing the namespace prefix (e.g. ["camera","main"]). All tracks whose full names start with this tuple are considered within the announce scope.
1679
- * - parameters: Optional {@link MessageParameters}; omitted =\> default instance.
1680
- *
1681
- * Returns: {@link RequestOk} on success (namespace added to `announcedNamespaces`) or {@link RequestError} explaining refusal.
1682
- *
1683
- * Use cases:
1684
- * - Make a camera or sensor namespace available before any objects are pushed.
1685
- * - Dynamically expose a newly created room / session namespace.
1686
- * - Re-announce after reconnect to repopulate discovery state.
1687
- *
1688
- * @throws MOQtailError If client is destroyed.
1689
- * @throws InternalError Transport/control failure while sending or awaiting response (client disconnects first).
1690
- *
1691
- * @remarks
1692
- * - Duplicate announce detection is TODO (currently a second call will still send another PUBLISH_NAMESPACE; receiver behavior may vary).
1693
- * - Successful announces are tracked in `announcedNamespaces`; manual removal occurs via {@link MOQtailClient.publishNamespaceDone}.
1694
- * - Discovery subscribers (those who issued {@link MOQtailClient.subscribeNamespace}) will receive the resulting {@link PublishNamespace} message.
1695
- *
1696
- * @example Minimal announce
1697
- * ```ts
1698
- * const res = await client.publishNamespace(["camera","main"])
1699
- * if (res instanceof RequestOk) {
1700
- * // ready to publish objects under tracks with this namespace prefix
1701
- * }
1702
- * ```
1703
- *
1704
- * @example PublishNamespace with parameters block
1705
- * ```ts
1706
- * const params = new MessageParameters().setSomeExtensionFlag(true)
1707
- * const resp = await client.publishNamespace(["room","1234"], params)
1708
- * ```
1709
- */
1710
- publishNamespace(trackNamespace: Tuple, parameters?: MessageParameter[]): Promise<RequestOk | RequestError>;
1711
- /**
1712
- * Withdraw a previously announced namespace so new subscribers no longer discover its tracks.
1713
- *
1714
- * Use when shutting down publishing for a logical scope (camera offline, room closed, session ended).
1715
- * Removes the namespace from `announcedNamespaces` locally and sends an {@link PublishNamespaceDone} control frame.
1716
- *
1717
- * Parameter semantics:
1718
- * - trackNamespace: Exact tuple used during {@link MOQtailClient.publishNamespace}. Must match to be removed from internal set.
1719
- *
1720
- * Behavior:
1721
- * - Does not delete locally registered {@link Track} objects (they remain in `trackSources`).
1722
- * - Does not forcibly end active subscriptions that were already established; peers simply stop discovering it for new ones.
1723
- * - Silent if the namespace was not currently recorded (idempotent style).
1724
- *
1725
- * @throws MOQtailError If client is destroyed before sending.
1726
- * @throws (rethrows original error) Any lower-level failure while sending results in a disconnect (unwrapped TODO: future wrap with InternalError for consistency).
1727
- *
1728
- * @remarks
1729
- * Peers that issued {@link MOQtailClient.subscribeNamespace} for a matching prefix should receive the resulting {@link PublishNamespaceDone}.
1730
- * Consider calling this before {@link MOQtailClient.disconnect} to give consumers prompt notice.
1731
- *
1732
- * @example Basic usage
1733
- * ```ts
1734
- * await client.publishNamespaceDone(["camera","main"])
1735
- * ```
1736
- *
1737
- * @example Idempotent
1738
- * ```ts
1739
- * await client.publishNamespaceDone(["camera","main"]) // first time
1740
- * await client.publishNamespaceDone(["camera","main"]) // no error, already removed
1741
- * ```
1742
- */
1743
- publishNamespaceDone(trackNamespace: Tuple): Promise<void>;
1744
- /**
1745
- * Send an {@link PublishNamespaceCancel} to abort a previously issued ANNOUNCE before (or after) the peer fully processes it.
1746
- *
1747
- * Use when an announce was sent prematurely (e.g. validation failed locally, namespace no longer needed) and you want
1748
- * to retract it without waiting for normal announce lifecycle or before publishing any objects.
1749
- *
1750
- * Parameter semantics:
1751
- * - msg: Pre-constructed {@link PublishNamespaceCancel} referencing the original announce request id / namespace (builder provided elsewhere).
1752
- *
1753
- * Behavior:
1754
- * - Simply forwards the control frame; does not modify `announcedNamespaces` (call {@link MOQtailClient.publishNamespaceDone} for local bookkeeping removal).
1755
- * - Safe to send even if the announce already succeeded; peer may ignore duplicates per spec guidance.
1756
- *
1757
- * @throws MOQtailError If client is destroyed.
1758
- * @throws InternalError Wrapped transport/control send failure (client disconnects first) then rethrows.
1759
- *
1760
- * @remarks
1761
- * Use in tandem with internal tracking if you want to prevent subsequent object publication until a new announce is issued.
1762
- *
1763
- * @example Cancel immediately after a mistaken announce
1764
- * ```ts
1765
- * const publishNamespaceResp = await client.publishNamespace(["camera","temp"]) // wrong namespace
1766
- * // Assume you kept the original announce requestId (e.g. from PublishNamespaceRequest)
1767
- * const cancelMsg = new PublishNamespaceCancel(publishNamespaceResp.requestId as bigint)
1768
- * await client.publishNamespaceCancel(cancelMsg)
1769
- * ```
1770
- */
1771
- publishNamespaceCancel(msg: PublishNamespaceCancel): Promise<void>;
1772
- subscribeNamespace(trackNamespacePrefix: Tuple, subscribeOptions?: NamespaceSubscribeOptions, parameters?: MessageParameter[]): Promise<{
1773
- response: RequestOk | RequestError;
1774
- cancel: () => Promise<void>;
1775
- }>;
1776
- unsubscribeNamespace(msg: UnsubscribeNamespace): Promise<void>;
1777
- }
1778
-
1779
- /**
1780
- * Copyright 2026 The MOQtail Authors
1781
- *
1782
- * Licensed under the Apache License, Version 2.0 (the "License");
1783
- * you may not use this file except in compliance with the License.
1784
- * You may obtain a copy of the License at
1785
- *
1786
- * http://www.apache.org/licenses/LICENSE-2.0
1787
- *
1788
- * Unless required by applicable law or agreed to in writing, software
1789
- * distributed under the License is distributed on an "AS IS" BASIS,
1790
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1791
- * See the License for the specific language governing permissions and
1792
- * limitations under the License.
1793
- */
1794
-
1795
- declare class TrackStatusRequest implements PromiseLike<RequestOk | RequestError> {
1796
- readonly requestId: bigint;
1797
- readonly message: TrackStatus;
1798
- private _resolve;
1799
- private _reject;
1800
- private promise;
1801
- constructor(msg: TrackStatus);
1802
- resolve(value: RequestOk | RequestError | PromiseLike<RequestOk | RequestError>): void;
1803
- reject(reason?: any): void;
1804
- then<TResult1 = RequestOk | RequestError, TResult2 = never>(onfulfilled?: ((value: RequestOk | RequestError) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): PromiseLike<TResult1 | TResult2>;
1805
- catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null): Promise<RequestOk | RequestError | TResult>;
1806
- finally(onfinally?: (() => void) | undefined | null): Promise<RequestOk | RequestError>;
866
+ #private;
867
+ /**
868
+ * Namespace prefixes (tuples) the peer has requested announce notifications for via SUBSCRIBE_NAMESPACE.
869
+ * Used to decide which locally issued ANNOUNCE messages should be forwarded (future optimization: prefix trie).
870
+ */
871
+ readonly peerSubscribeNamespace: Set<Tuple>;
872
+ /**
873
+ * Namespace prefixes this client has subscribed to (issued SUBSCRIBE_NAMESPACE). Enables automatic filtering
874
+ * of incoming NAMESPACE / NAMESPACE_DONE. Maintained locally; no dedupe of overlapping / shadowing prefixes yet.
875
+ */
876
+ readonly subscribedNamespaces: Set<Tuple>;
877
+ readonly subscribedTracks: Set<Tuple>;
878
+ /**
879
+ * Track namespaces this client has successfully published (received REQUEST_OK). Source of truth for
880
+ * deciding what to withdraw on teardown or targeted removal (future optimization: prefix trie).
881
+ */
882
+ readonly publishedNamespaces: Set<Tuple>;
883
+ /**
884
+ * Locally registered track definitions keyed by full track name string. Populated via addOrUpdateTrack.
885
+ * Does not imply the track has been announced or has active publications.
886
+ */
887
+ readonly trackSources: Map<string, Track>;
888
+ /**
889
+ * All in‑flight request objects keyed by requestId (SUBSCRIBE, FETCH, ANNOUNCE, etc). Facilitates lookup
890
+ * when responses / data arrive. Entries are removed on completion or error.
891
+ */
892
+ readonly requests: Map<bigint, MOQtailRequest>;
893
+ /**
894
+ * Active publications (SUBSCRIBE or FETCH) keyed by requestId to manage object stream controllers and lifecycle.
895
+ * Subset / specialization view of `requests`.
896
+ */
897
+ readonly publications: Map<bigint, SubscribePublication | FetchPublication | PublishPublication>;
898
+ /**
899
+ * Active SUBSCRIBE request wrappers keyed by track alias for rapid alias -\> subscription resolution during
900
+ * incoming unidirectional data handling.
901
+ */
902
+ readonly subscriptions: Map<bigint, any>;
903
+ /**
904
+ * Bidirectional track alias \<-\> subscription requestId mapping
905
+ */
906
+ readonly subscriptionAliasMap: Map<bigint, bigint>;
907
+ /**
908
+ * Bidirectional requestId \<-\> full track name mapping to reconstruct metadata for incoming objects.
909
+ */
910
+ readonly requestIdMap: RequestIdMap;
911
+ /**
912
+ * Maps track aliases to full track names for quick resolution during data handling.
913
+ */
914
+ readonly aliasFullTrackNameMap: Map<bigint, FullTrackName>;
915
+ /**
916
+ * Pending state updates keyed by requestId and applied once a new track alias is seen.
917
+ * Used to avoid premature state updates.
918
+ */
919
+ readonly pendingStateUpdates: Map<bigint, (newTrackAlias: bigint) => boolean>;
920
+ /** Underlying WebTransport session (set after successful construction in MOQtailClient.new). */
921
+ webTransport: WebTransport;
922
+ /** Outgoing / incoming control message stream pair. */
923
+ controlStream: ControlStream;
924
+ /** Timeout (ms) applied to reading incoming data streams; undefined =\> no explicit timeout. */
925
+ dataStreamTimeoutMs?: number;
926
+ /** Timeout (ms) for control stream read operations; undefined =\> no explicit timeout. */
927
+ controlStreamTimeoutMs?: number;
928
+ /**
929
+ * TODO: onNamespaceAnnounced may be a better name
930
+ * Fired when an PUBLISH_NAMESPACE control message is processed for a track namespace.
931
+ * Use to update UI or trigger discovery logic.
932
+ * Discovery event.
933
+ */
934
+ onNamespacePublished?: (msg: PublishNamespace) => void;
935
+ /**
936
+ * Fired on GOAWAY reception signaling graceful session wind-down.
937
+ * Use to prepare for disconnect or cleanup.
938
+ * Lifecycle handler.
939
+ */
940
+ onGoaway?: (msg: GoAway) => void;
941
+ /**
942
+ * Whether the peer has sent a GOAWAY on the control stream. Once it has, this side
943
+ * should not start new requests (§10.4); a second one closes the session with
944
+ * PROTOCOL_VIOLATION.
945
+ */
946
+ goawayReceived: boolean;
947
+ /**
948
+ * Fired if the underlying WebTransport session fails (ready -\> closed prematurely).
949
+ * Use to log or alert on transport errors.
950
+ * Lifecycle/error handler.
951
+ */
952
+ onWebTransportFail?: () => void;
953
+ /**
954
+ * Fired exactly once when the client transitions to terminated (disconnect).
955
+ * Use to clean up resources or notify user.
956
+ * Lifecycle handler.
957
+ */
958
+ onSessionTerminated?: (reason?: unknown) => void;
959
+ /**
960
+ * Invoked after each outbound control message is sent.
961
+ * Use for logging or analytics.
962
+ * Informational event.
963
+ */
964
+ onMessageSent?: (msg: ControlMessage) => void;
965
+ /**
966
+ * Invoked upon receiving each inbound control message before handling.
967
+ * Use for logging or debugging.
968
+ * Informational event.
969
+ */
970
+ onMessageReceived?: (msg: ControlMessage) => void;
971
+ /**
972
+ * Invoked for each decoded data object/header arriving on a uni stream (fetch or subgroup).
973
+ * Use to process or display incoming media/data.
974
+ * Informational event.
975
+ */
976
+ onDataReceived?: (data: SubgroupObject | SubgroupHeader | FetchObject | FetchHeader) => void;
977
+ /**
978
+ * Invoked after enqueuing each outbound data object/header.
979
+ * Reserved for future use.
980
+ * Informational event.
981
+ */
982
+ onDataSent?: (data: SubgroupObject | SubgroupHeader | FetchObject | FetchHeader) => void;
983
+ /**
984
+ * General-purpose error callback for surfaced exceptions not thrown to caller synchronously.
985
+ * Use to log or display errors.
986
+ * Error handler.
987
+ */
988
+ onError?: (er: unknown) => void;
989
+ /** Invoked for each decoded datagram object/status arriving. */
990
+ onDatagramReceived?: (data: Datagram) => void;
991
+ /** Invoked after enqueuing each outbound datagram object/status. */
992
+ onDatagramSent?: (data: Datagram) => void;
993
+ /** Fired when an inbound PUBLISH control message is received. */
994
+ onPeerPublish?: (msg: Publish, stream: ReadableStream<MoqtObject>) => void;
995
+ /**
996
+ * Fired when an inbound PUBLISH_DONE control message is received. The message names
997
+ * no request of its own, so `requestId` is the request the stream it arrived on
998
+ * opened: for a track the peer pushed, the `requestId` of the {@link Publish} handed
999
+ * to {@link MOQtailClient.onPeerPublish}. It is what says which track just ended.
1000
+ */
1001
+ onPeerPublishDone?: (msg: PublishDone, requestId: bigint) => void;
1002
+ /**
1003
+ * Fired when the peer moves the Forward State of a track this side is publishing,
1004
+ * either in its PUBLISH_OK or in a later REQUEST_UPDATE. `requestId` is the one
1005
+ * {@link MOQtailClient.publish} returned.
1006
+ *
1007
+ * A publication that declared FORWARD=0 sends nothing until this reports `true`, so
1008
+ * this is where the work behind the track starts and stops -- leaving a camera and
1009
+ * an encoder running for a track nobody is taking costs the same as publishing it.
1010
+ */
1011
+ onForwardStateChange?: (requestId: bigint, forward: boolean) => void;
1012
+ /** Fired when an inbound SUBSCRIBE_NAMESPACE control message is received. */
1013
+ onPeerSubscribeNamespace?: (msg: SubscribeNamespace) => void;
1014
+ /** Fired when an inbound SUBSCRIBE_TRACKS control message is received. */
1015
+ onPeerSubscribeTracks?: (msg: SubscribeTracks) => void;
1016
+ /**
1017
+ * Fired when a PUBLISH_BLOCKED arrives on a {@link MOQtailClient.subscribeTracks}
1018
+ * stream: the peer has a matching track but no bidi stream to send its PUBLISH on
1019
+ * until its stream limit lifts (§10.20). `prefix` is the prefix this side subscribed
1020
+ * with, which is what the message's suffix hangs off.
1021
+ */
1022
+ onPeerPublishBlocked?: (prefix: Tuple, msg: PublishBlocked) => void;
1023
+ /** Fired when a NAMESPACE message arrives on a SUBSCRIBE_NAMESPACE bi-stream (prefix + suffix). */
1024
+ onPeerNamespace?: (prefix: Tuple, suffix: Tuple) => void;
1025
+ /** Fired when a NAMESPACE_DONE message arrives on a SUBSCRIBE_NAMESPACE bi-stream (prefix + suffix). */
1026
+ onPeerNamespaceDone?: (prefix: Tuple, suffix: Tuple) => void;
1027
+ /**
1028
+ * Stream of all received MoqtObjects from datagrams across all tracks
1029
+ * Consumer should filter by fullTrackName as needed
1030
+ *
1031
+ * WARNING: Only one reader should be active. For multiple subscribers,
1032
+ * use subscribeToTrackDatagrams() instead
1033
+ */
1034
+ readonly receivedDatagramObjects: ReadableStream<MoqtObject>;
1035
+ /**
1036
+ * Generates a safe, sequential local request ID for tracking pushed/incoming tracks.
1037
+ */
1038
+ allocatePseudoRequestId(): bigint;
1039
+ /**
1040
+ * Gets the current server setup configuration.
1041
+ *
1042
+ * @returns The {@link Setup} instance the server sent back during handshake.
1043
+ */
1044
+ get serverSetup(): Setup;
1045
+ /**
1046
+ * Returns true if datagram support is currently active
1047
+ */
1048
+ get isDatagramsEnabled(): boolean;
1049
+ /**
1050
+ * Sets the global log level for all moqtail-ts loggers.
1051
+ * @param level - The minimum {@link LogLevel} to output. Use `LogLevel.NONE` to silence all logs.
1052
+ */
1053
+ static setLogLevel(level: LogLevel): void;
1054
+ /**
1055
+ * Restricts log output to the specified module names. Pass `null` to allow all modules.
1056
+ * @param modules - Array of module name strings, or `null` to enable all modules.
1057
+ */
1058
+ static setLogEnabledModules(modules: string[] | null): void;
1059
+ private constructor();
1060
+ /**
1061
+ * Establishes a new {@link MOQtailClient} session over WebTransport and performs the MOQT setup handshake.
1062
+ *
1063
+ * @param args - {@link MOQtailClientOptions}
1064
+ *
1065
+ * @returns Promise resolving to a ready {@link MOQtailClient} instance.
1066
+ *
1067
+ * @throws :{@link ProtocolViolationError} If the server sends an unexpected or invalid message during setup.
1068
+ *
1069
+ * @example Minimal connection
1070
+ * ```ts
1071
+ * const client = await MOQtailClient.new({
1072
+ * url: 'https://relay.example.com/transport'
1073
+ * });
1074
+ * ```
1075
+ *
1076
+ * @example With callbacks and options
1077
+ * ```ts
1078
+ * const client = await MOQtailClient.new({
1079
+ * url,
1080
+ * setupOptions: new SetupOptions().addPath('/live'),
1081
+ * transportOptions: { congestionControl: 'default' },
1082
+ * dataStreamTimeoutMs: 5000,
1083
+ * controlStreamTimeoutMs: 2000,
1084
+ * enableDatagrams: true,
1085
+ * callbacks: {
1086
+ * onMessageSent: msg => console.log('Sent:', msg),
1087
+ * onMessageReceived: msg => console.log('Received:', msg),
1088
+ * onSessionTerminated: reason => console.warn('Session ended:', reason),
1089
+ * onDatagramReceived: data => console.log('Datagram:', data),
1090
+ * }
1091
+ * });
1092
+ * ```
1093
+ */
1094
+ static new(args: MOQtailClientOptions): Promise<MOQtailClient>;
1095
+ /**
1096
+ * Start receiving datagrams from the WebTransport connection.
1097
+ * Must be called before datagrams can be received (unless enableDatagrams: true was set in options).
1098
+ *
1099
+ * @throws MOQtailError if client is destroyed or datagrams already started
1100
+ */
1101
+ startDatagrams(): Promise<void>;
1102
+ /**
1103
+ * Stop receiving datagrams and release resources.
1104
+ * Idempotent - safe to call multiple times.
1105
+ */
1106
+ stopDatagrams(): Promise<void>;
1107
+ /**
1108
+ * Subscribe to receive datagrams for a specific track.
1109
+ * Multiple tracks can have separate handlers that run concurrently.
1110
+ *
1111
+ * @param trackAlias - Track alias to subscribe to
1112
+ * @param handler - Function called for each received MoqtObject on this track
1113
+ * @returns Unsubscribe function to remove the handler
1114
+ *
1115
+ * @example
1116
+ * ```ts
1117
+ * const unsubscribe = client.subscribeToTrackDatagrams(trackAlias, (obj) => {
1118
+ * console.log('Received datagram:', obj.payload);
1119
+ * });
1120
+ * // Later: unsubscribe();
1121
+ * ```
1122
+ */
1123
+ subscribeToTrackDatagrams(trackAlias: bigint, handler: (obj: MoqtObject) => void): () => void;
1124
+ /**
1125
+ * Unsubscribe from datagram delivery for a specific track.
1126
+ *
1127
+ * @param trackAlias - Track alias to unsubscribe from
1128
+ */
1129
+ unsubscribeFromTrackDatagrams(trackAlias: bigint): void;
1130
+ /**
1131
+ * Create a datagram sender for a specific track.
1132
+ *
1133
+ * @param trackAlias - Track alias for outgoing datagrams
1134
+ * @returns SendDatagramStream for writing MoqtObjects as datagrams
1135
+ * @throws MOQtailError if datagram writer not initialized (call startDatagrams() first)
1136
+ *
1137
+ * @example
1138
+ * ```ts
1139
+ * const sender = client.createDatagramSender(trackAlias);
1140
+ * await sender.write(moqtObject);
1141
+ * ```
1142
+ */
1143
+ createDatagramSender(trackAlias: bigint): SendDatagramStream;
1144
+ /**
1145
+ * Send a single MoqtObject as a datagram.
1146
+ * Convenience method for one-off datagram sends.
1147
+ *
1148
+ * @param trackAlias - Track alias for this object
1149
+ * @param object - MoqtObject to send
1150
+ * @throws MOQtailError if datagram writer not initialized
1151
+ *
1152
+ * @example
1153
+ * ```ts
1154
+ * await client.sendDatagram(trackAlias, moqtObject);
1155
+ * ```
1156
+ */
1157
+ sendDatagram(trackAlias: bigint, object: MoqtObject): Promise<void>;
1158
+ /**
1159
+ * Sets (or replaces) the client-level default early discard policy for incoming subgroup streams.
1160
+ *
1161
+ * When set, each incoming subgroup QUIC stream is given a deadline of `subgroupReceiveTimeout` ms to
1162
+ * complete. If the stream has not finished within that window it is cancelled — objects already
1163
+ * delivered to the subscription are kept, but no further objects arrive from that stream.
1164
+ *
1165
+ * This is a client-wide default. Individual subscriptions can override it via the `earlyDiscardPolicy`
1166
+ * field in {@link SubscribeOptions}, which takes precedence over this setting.
1167
+ *
1168
+ * The policy takes effect on the next stream accepted after this call. Passing a new config
1169
+ * replaces the previous one. Pass `undefined` to remove the default.
1170
+ *
1171
+ * @example
1172
+ * ```ts
1173
+ * client.setEarlyDiscardPolicy({ subgroupReceiveTimeout: 2000 })
1174
+ * ```
1175
+ */
1176
+ setEarlyDiscardPolicy(config: EarlyDiscardPolicyConfig | undefined): void;
1177
+ /**
1178
+ * Gracefully terminates this {@link MOQtailClient} session and releases underlying {@link https://developer.mozilla.org/docs/Web/API/WebTransport | WebTransport} resources.
1179
+ *
1180
+ * @param reason - Optional application-level reason (string or error) recorded and wrapped in an {@link InternalError}
1181
+ * passed to the {@link MOQtailClient.onSessionTerminated | onSessionTerminated} callback.
1182
+ *
1183
+ * @returns Promise that resolves once shutdown logic completes. Subsequent calls are safe no-ops.
1184
+ *
1185
+ * @example Basic usage
1186
+ * ```ts
1187
+ * await client.disconnect();
1188
+ * ```
1189
+ *
1190
+ * @example With reason
1191
+ * ```ts
1192
+ * await client.disconnect('user logout');
1193
+ * ```
1194
+ *
1195
+ * @example Idempotent double call
1196
+ * ```ts
1197
+ * await client.disconnect();
1198
+ * await client.disconnect(); // no error
1199
+ * ```
1200
+ *
1201
+ * @example Page unload safety
1202
+ * ```ts
1203
+ * window.addEventListener('beforeunload', () => {
1204
+ * client.disconnect('page unload');
1205
+ * });
1206
+ * ```
1207
+ */
1208
+ disconnect(reason?: unknown): Promise<void>;
1209
+ /**
1210
+ * Registers or updates a {@link Track} definition for local publishing or serving.
1211
+ *
1212
+ * A {@link Track} describes a logical media/data stream, identified by a unique name and namespace.
1213
+ * - If `trackSource.live` is present, the track can be served to subscribers in real-time.
1214
+ * - If `trackSource.past` is present, the track can be fetched for historical data.
1215
+ * - If both are present, the track supports both live and historical access.
1216
+ *
1217
+ * @param track - The {@link Track} instance to add or update. See {@link TrackSource} for live/past source options.
1218
+ * @returns void
1219
+ * @throws : {@link MOQtailError} If the client has been destroyed.
1220
+ *
1221
+ * @example Create a live video track from getUserMedia
1222
+ * ```ts
1223
+ * const stream = await navigator.mediaDevices.getUserMedia({ video: true });
1224
+ * const videoTrack = stream.getVideoTracks()[0];
1225
+ *
1226
+ * // Convert video frames to MoqtObject instances using your chosen scheme (e.g. MSF, CMAF, etc.)
1227
+ * // This part is application-specific and not provided by MOQtail:
1228
+ * const liveReadableStream: ReadableStream<MoqtObject> = ...
1229
+ *
1230
+ * // Register the track for live subscription
1231
+ * client.addOrUpdateTrack({
1232
+ * fullTrackName: { namespace: ["camera"], name: "main" },
1233
+ * trackSource: { live: liveReadableStream },
1234
+ * publisherPriority: 0 // highest priority
1235
+ * });
1236
+ *
1237
+ * // For a hybrid track (live + past):
1238
+ * import { MemoryObjectCache } from './track/object_cache';
1239
+ * const cache = new MemoryObjectCache(); // Caches are not yet fully supported
1240
+ * client.addOrUpdateTrack({
1241
+ * fullTrackName: { namespace: ["camera"], name: "main" },
1242
+ * trackSource: { live: liveReadableStream, past: cache },
1243
+ * publisherPriority: 8
1244
+ * });
1245
+ * ```
1246
+ */
1247
+ addOrUpdateTrack(track: Track): void;
1248
+ /**
1249
+ * Removes a previously registered {@link Track} from this client's local catalog.
1250
+ *
1251
+ * This deletes the in-memory entry inserted via {@link MOQtailClient.addOrUpdateTrack}, so future lookups by its {@link Track.fullTrackName} will fail.
1252
+ * Does **not** automatically:
1253
+ * - Withdraw the namespace announcement (call {@link MOQtailClient.unpublishNamespace} separately if you want to inform peers)
1254
+ * - Cancel active subscriptions or fetches (they continue until normal completion)
1255
+ * - Affect already-sent objects.
1256
+ *
1257
+ * If the track was not present, the call is a silent no-op (idempotent removal).
1258
+ *
1259
+ * @param track - The exact {@link Track} instance (its canonical name is used as the key).
1260
+ * @throws : {@link MOQtailError} If the client has been destroyed.
1261
+ *
1262
+ * @example
1263
+ * ```ts
1264
+ * // Register a track
1265
+ * client.addOrUpdateTrack(track);
1266
+ *
1267
+ * // Later, when no longer publishing:
1268
+ * client.removeTrack(track);
1269
+ *
1270
+ * // Optionally, inform peers that the namespace is no longer available:
1271
+ * await client.unpublishNamespace(track.fullTrackName.namespace);
1272
+ * ```
1273
+ */
1274
+ removeTrack(track: Track): void;
1275
+ /**
1276
+ * Subscribes to a track and returns a stream of {@link MoqtObject}s matching the requested window and relay forwarding mode.
1277
+ *
1278
+ * - `forward: true` tells the relay to forward objects to this subscriber as they arrive.
1279
+ * - `forward: false` means the relay subscribes upstream but buffers objects locally, not forwarding them to you.
1280
+ * - `filterType: AbsoluteStart` lets you specify a start position in the future; the stream waits for that object. If the start location is \< the latest object
1281
+ * observed at the publisher then it behaves as `filterType: LatestObject`
1282
+ * - `filterType: AbsoluteRange` lets you specify a start and end group, both of should be in the future; the stream waits for those objects. If the start location is \< the latest object
1283
+ * observed at the publisher then it behaves as `filterType: LatestObject`.
1284
+ *
1285
+ * The method returns either a {@link RequestError} (on refusal) or an object with the subscription `requestId` and a `ReadableStream` of {@link MoqtObject}s.
1286
+ * Use the `requestId` for {@link MOQtailClient.unsubscribe} or {@link MOQtailClient.subscribeUpdate}. Use the `stream` to decode and display objects.
1287
+ *
1288
+ * @param args - {@link SubscribeOptions} describing the subscription window and relay forwarding behavior.
1289
+ * @returns Either a {@link RequestError} or `{ requestId, stream }` for consuming objects.
1290
+ * @throws : {@link MOQtailError} If the client is destroyed.
1291
+ * @throws : {@link ProtocolViolationError} If required fields are missing or inconsistent.
1292
+ * @throws : {@link InternalError} On transport/protocol failure (disconnect is triggered before rethrow).
1293
+ *
1294
+ * @example Subscribe to the latest object and receive future objects as they arrive
1295
+ * ```ts
1296
+ * const result = await client.subscribe({
1297
+ * fullTrackName,
1298
+ * filterType: FilterType.LatestObject,
1299
+ * forward: true,
1300
+ * groupOrder: GroupOrder.Original,
1301
+ * priority: 32
1302
+ * });
1303
+ * if (!(result instanceof RequestError)) {
1304
+ * for await (const obj of result.stream) {
1305
+ * // decode and display obj
1306
+ * }
1307
+ * }
1308
+ * ```
1309
+ *
1310
+ * @example Subscribe to a future range (waits for those objects to arrive)
1311
+ * ```ts
1312
+ * const result = await client.subscribe({
1313
+ * fullTrackName,
1314
+ * filterType: FilterType.AbsoluteRange,
1315
+ * startLocation: futureStart,
1316
+ * endGroup: futureEnd,
1317
+ * forward: true,
1318
+ * groupOrder: GroupOrder.Original,
1319
+ * priority: 128
1320
+ * });
1321
+ * ```
1322
+ */
1323
+ subscribe(args: SubscribeOptions): Promise<RequestError | {
1324
+ requestId: bigint;
1325
+ stream: ReadableStream<MoqtObject>;
1326
+ }>;
1327
+ /**
1328
+ * Stops an active subscription identified by its original SUBSCRIBE `requestId`.
1329
+ *
1330
+ * Resets the subscription's request stream with `CANCELLED` if it is still active. If the id is unknown or already
1331
+ * cleaned up, the call is a silent no-op (hence multiple calls are idempotent).
1332
+ *
1333
+ * Use this when you no longer want incoming objects for a track (e.g. user navigated away, switching quality).
1334
+ * Canceling the consumer stream reader does **not** auto-unsubscribe; call this explicitly for prompt cleanup.
1335
+ *
1336
+ * @param requestId - The id returned from {@link MOQtailClient.subscribe}.
1337
+ * @returns Promise that resolves once the request stream has been reset.
1338
+ * @throws :{@link MOQtailError} If the client is destroyed.
1339
+ * @throws :{@link InternalError} Wrapped lower-level failure while attempting to send (session will be disconnected first).
1340
+ *
1341
+ * @remarks
1342
+ * - Only targets SUBSCRIBE requests, not fetches. Passing a fetch request id is ignored (no-op).
1343
+ * - Safe to call multiple times; extra calls have no effect.
1344
+ *
1345
+ * @example Subscribe and later unsubscribe
1346
+ * ```ts
1347
+ * const sub = await client.subscribe({ fullTrackName, filterType: FilterType.LatestObject, forward: true, groupOrder: GroupOrder.Original, priority: 0 });
1348
+ * if (!(sub instanceof RequestError)) {
1349
+ * // ...consume objects...
1350
+ * await client.unsubscribe(sub.requestId);
1351
+ * }
1352
+ * ```
1353
+ *
1354
+ * @example Idempotent usage
1355
+ * ```ts
1356
+ * await client.unsubscribe(123n);
1357
+ * await client.unsubscribe(123n); // no error
1358
+ * ```
1359
+ */
1360
+ unsubscribe(requestId: bigint | number): Promise<void>;
1361
+ /**
1362
+ * Narrows or updates an active subscription window and/or relay forwarding behavior.
1363
+ *
1364
+ * Use this to:
1365
+ * - Move the start of the subscription forward (trim history or future window).
1366
+ * - Move the end group earlier (shorten the window).
1367
+ * - Change relay forwarding (`forward: false` stops forwarding new objects, `true` resumes).
1368
+ * - Adjust subscriber priority.
1369
+ *
1370
+ * Only narrowing is allowed: you cannot move the start earlier or the end group later than the original subscription.
1371
+ * Forwarding and priority can be changed at any time.
1372
+ *
1373
+ * @param args - {@link SubscribeUpdateOptions} referencing the original subscription `requestId` and new bounds.
1374
+ * @returns Promise that resolves when the update control frame is sent.
1375
+ * @throws :{@link MOQtailError} If the client is destroyed.
1376
+ * @throws :{@link ProtocolViolationError} If the update would widen the window (earlier start, later end group, or invalid ordering).
1377
+ * @throws :{@link InternalError} On transport/control failure (disconnect is triggered before rethrow).
1378
+ *
1379
+ * @remarks
1380
+ * - Only applies to active SUBSCRIBE requests; ignored if the request is not a subscription.
1381
+ * - Omitting a parameter (e.g. `priority`) leaves the previous value unchanged.
1382
+ * - Setting `forward: false` stops relay forwarding new objects after the current window drains.
1383
+ * - Safe to call multiple times; extra calls with unchanged bounds have no effect.
1384
+ *
1385
+ * @example Trim start forward
1386
+ * ```ts
1387
+ * await client.subscribeUpdate({ requestId, startLocation: laterLoc, endGroup, forward: true, priority });
1388
+ * ```
1389
+ *
1390
+ * @example Convert tailing subscription into bounded slice
1391
+ * ```ts
1392
+ * await client.subscribeUpdate({ requestId, startLocation: origStart, endGroup: cutoffGroup, forward: false, priority });
1393
+ * ```
1394
+ *
1395
+ * @example Lower priority only
1396
+ * ```ts
1397
+ * await client.subscribeUpdate({ requestId, startLocation: currentStart, endGroup: currentEnd, forward: true, priority: 200 });
1398
+ * ```
1399
+ */
1400
+ subscribeUpdate(args: SubscribeUpdateOptions): Promise<void>;
1401
+ /**
1402
+ * Switches an active subscription to a different track while retaining the same subscription parameters.
1403
+ *
1404
+ * Use this to change the subscribed track without tearing down and re-establishing a new subscription.
1405
+ *
1406
+ * @param args - {@link SwitchOptions} referencing the original subscription `requestId` and new track name.
1407
+ * @returns Promise that resolves when the switch control frame is sent.
1408
+ * @throws :{@link MOQtailError} If the client is destroyed.
1409
+ * @throws :{@link InternalError} On transport/control failure (disconnect is triggered before rethrow).
1410
+ *
1411
+ * @remarks
1412
+ * - Only applies to active SUBSCRIBE requests; ignored if the request is not a subscription.
1413
+ * - All other subscription parameters (window, forwarding, priority) remain unchanged.
1414
+ *
1415
+ * @example Switch to a different track
1416
+ * ```ts
1417
+ * await client.switch({ subscriptionRequestId, fullTrackName: newTrackName });
1418
+ * ```
1419
+ */
1420
+ switch(args: SwitchOptions): Promise<RequestError | {
1421
+ requestId: bigint;
1422
+ stream: ReadableStream<MoqtObject>;
1423
+ }>;
1424
+ /**
1425
+ * One-shot retrieval of a bounded object span, optionally anchored to an existing subscription, returning a stream of {@link MoqtObject}s.
1426
+ *
1427
+ * Choose a fetch type via `typeAndProps.type`:
1428
+ * - Standalone: Historical slice of a specific {@link FullTrackName} independent of active subscriptions.
1429
+ * - Relative: Range relative to the JOINING subscription's current (largest) location; use when you want "N groups back" from live.
1430
+ * - Absolute: Absolute group/object offsets tied to an existing subscription (stable anchor) even if that subscription keeps forwarding.
1431
+ *
1432
+ * Field highlights (in {@link FetchOptions}):
1433
+ * - priority: 0 (highest) .. 255 (lowest); out-of-range rejected; non-integers rounded by caller expectation.
1434
+ * - groupOrder: {@link (GroupOrder:enum).Original} to preserve publisher order; or reorder ascending/descending if supported by server.
1435
+ * - typeAndProps: Discriminated union carrying parameters specific to each fetch mode (see examples).
1436
+ * - parameters: Optional version-specific extension block.
1437
+ *
1438
+ * Returns either a {@link RequestError} (refusal / invalid request at protocol level) or `{ requestId, stream }` whose `stream`
1439
+ * ends naturally after the bounded range completes (no explicit cancel needed for normal completion).
1440
+ *
1441
+ * Use cases:
1442
+ * - Grab a historical window for scrubbing UI while a separate live subscription tails.
1443
+ * - Late joiner fetching a short back-buffer then discarding the stream.
1444
+ * - Analytics batch job pulling a fixed slice without subscribing long-term.
1445
+ *
1446
+ * @throws MOQtailError If client is destroyed.
1447
+ * @throws ProtocolViolationError Priority out of [0-255] or missing/invalid joining subscription id for Relative/Absolute.
1448
+ * @throws InternalError Transport/control failure (the client disconnects first) then rethrows original error.
1449
+ *
1450
+ * @remarks
1451
+ * - Relative / Absolute require an existing active SUBSCRIBE `joiningRequestId`; if not found a {@link ProtocolViolationError} is thrown.
1452
+ * - Result stream is finite; reader close occurs automatically when last object delivered.
1453
+ * - Use {@link MOQtailClient.fetchCancel} only for early termination (not yet fully implemented: see TODO in code).
1454
+ *
1455
+ * @example Standalone window
1456
+ * ```ts
1457
+ * const r = await client.fetch({
1458
+ * priority: 64,
1459
+ * groupOrder: GroupOrder.Original,
1460
+ * typeAndProps: {
1461
+ * type: FetchType.Standalone,
1462
+ * props: { fullTrackName, startLocation, endLocation }
1463
+ * }
1464
+ * })
1465
+ * if (!(r instanceof RequestError)) {
1466
+ * for await (const obj of r.stream as any) {
1467
+ * // consume objects then stream ends automatically
1468
+ * }
1469
+ * }
1470
+ * ```
1471
+ *
1472
+ * @example Relative to live subscription (e.g. last 5 groups)
1473
+ * ```ts
1474
+ * const sub = await client.subscribe({ fullTrackName, filterType: FilterType.LatestObject, forward: true, groupOrder: GroupOrder.Original, priority: 0 })
1475
+ * if (!(sub instanceof RequestError)) {
1476
+ * const slice = await client.fetch({
1477
+ * priority: 32,
1478
+ * groupOrder: GroupOrder.Original,
1479
+ * typeAndProps: { type: FetchType.Relative, props: { joiningRequestId: sub.requestId, joiningStart: 0n } }
1480
+ * })
1481
+ * }
1482
+ * ```
1483
+ */
1484
+ fetch(args: FetchOptions): Promise<RequestError | {
1485
+ requestId: bigint;
1486
+ stream: ReadableStream<MoqtObject>;
1487
+ }>;
1488
+ /**
1489
+ * Request early termination of an in‑flight FETCH identified by its `requestId`.
1490
+ *
1491
+ * Use when the consumer no longer needs the remaining objects (user scrubbed away, UI panel closed, replaced by a new fetch).
1492
+ * Resets the fetch's request stream with `CANCELLED` if the id currently maps to an active fetch; otherwise silent no-op (idempotent).
1493
+ *
1494
+ * Parameter semantics:
1495
+ * - requestId: bigint returned from {@link MOQtailClient.fetch}. Numbers auto-converted to bigint.
1496
+ *
1497
+ * Current behavior / limitations:
1498
+ * - Data stream closure after cancel is TODO (objects may still arrive briefly).
1499
+ * - Unknown / already finished request: ignored without error.
1500
+ * - Only targets FETCH requests (not subscriptions).
1501
+ *
1502
+ * @throws MOQtailError If client is destroyed.
1503
+ * @throws InternalError Failure while sending the cancel (client disconnects first).
1504
+ *
1505
+ * @remarks
1506
+ * Follow-up improvement planned: actively close associated readable stream controller immediately upon acknowledgment.
1507
+ *
1508
+ * @example Cancel shortly after starting
1509
+ * ```ts
1510
+ * const r = await client.fetch({ priority: 32, groupOrder: GroupOrder.Original, typeAndProps: { type: FetchType.Standalone, props: { fullTrackName, startLocation, endLocation } } })
1511
+ * if (!(r instanceof RequestError)) {
1512
+ * // user navigated away
1513
+ * await client.fetchCancel(r.requestId)
1514
+ * }
1515
+ * ```
1516
+ *
1517
+ * @example Idempotent double cancel
1518
+ * ```ts
1519
+ * await client.fetchCancel(456n)
1520
+ * await client.fetchCancel(456n) // no error
1521
+ * ```
1522
+ */
1523
+ fetchCancel(requestId: bigint | number): Promise<void>;
1524
+ /**
1525
+ * Proactively push a track to the relay/peer.
1526
+ */
1527
+ publish(fullTrackName: FullTrackName, forward: boolean, trackAlias: bigint, parameters?: MessageParameter[], trackProperties?: TrackProperty[]): Promise<RequestError | {
1528
+ requestId: bigint;
1529
+ trackAlias: bigint;
1530
+ }>;
1531
+ /**
1532
+ * Signals the end of a published track to the peer/relay.
1533
+ * * @param publishRequestId - The original requestId used when `publish()` was called.
1534
+ */
1535
+ publishDone(publishRequestId: bigint | number, statusCode?: number, reasonPhrase?: string): Promise<void>;
1536
+ /**
1537
+ * Registers an incoming PUBLISH announcement as a valid data receiver.
1538
+ * This prepares the client to ingest pushed data streams matching the published alias.
1539
+ * * @param msg - The incoming Publish control message
1540
+ * @returns - A stream of MoqtObjects being pushed by the publisher
1541
+ */
1542
+ acceptPushedTrack(msg: Publish): ReadableStream<MoqtObject>;
1543
+ /**
1544
+ * Declare (publish) a track namespace to the peer so subscribers using matching prefixes (via {@link MOQtailClient.subscribeNamespace})
1545
+ * can discover and begin subscribing/fetching its tracks.
1546
+ *
1547
+ * Typical flow (publisher side):
1548
+ * 1. Prepare / register one or more {@link Track} objects locally (see {@link MOQtailClient.addOrUpdateTrack}).
1549
+ * 2. Call `publishNamespace(namespace)` once per namespace prefix to expose those tracks.
1550
+ * 3. Later, call {@link MOQtailClient.unpublishNamespace} when no longer publishing under that namespace.
1551
+ *
1552
+ * Parameter semantics:
1553
+ * - trackNamespace: Tuple representing the namespace prefix (e.g. ["camera","main"]). All tracks whose full names start with this tuple are considered within the announce scope.
1554
+ * - parameters: Optional {@link MessageParameters}; omitted =\> default instance.
1555
+ *
1556
+ * Returns: {@link RequestOk} on success (namespace added to `publishedNamespaces`) or {@link RequestError} explaining refusal.
1557
+ *
1558
+ * Use cases:
1559
+ * - Make a camera or sensor namespace available before any objects are pushed.
1560
+ * - Dynamically expose a newly created room / session namespace.
1561
+ * - Re-announce after reconnect to repopulate discovery state.
1562
+ *
1563
+ * @throws MOQtailError If client is destroyed.
1564
+ * @throws InternalError Transport/control failure while sending or awaiting response (client disconnects first).
1565
+ *
1566
+ * @remarks
1567
+ * - Duplicate announce detection is TODO (currently a second call will still send another PUBLISH_NAMESPACE; receiver behavior may vary).
1568
+ * - Successful announces are tracked in `publishedNamespaces`; manual removal occurs via {@link MOQtailClient.unpublishNamespace}.
1569
+ * - Discovery subscribers (those who issued {@link MOQtailClient.subscribeNamespace}) will receive the resulting {@link PublishNamespace} message.
1570
+ *
1571
+ * @example Minimal announce
1572
+ * ```ts
1573
+ * const res = await client.publishNamespace(["camera","main"])
1574
+ * if (res instanceof RequestOk) {
1575
+ * // ready to publish objects under tracks with this namespace prefix
1576
+ * }
1577
+ * ```
1578
+ *
1579
+ * @example PublishNamespace with parameters block
1580
+ * ```ts
1581
+ * const params = new MessageParameters().setSomeExtensionFlag(true)
1582
+ * const resp = await client.publishNamespace(["room","1234"], params)
1583
+ * ```
1584
+ */
1585
+ publishNamespace(trackNamespace: Tuple, parameters?: MessageParameter[]): Promise<RequestOk | RequestError>;
1586
+ /**
1587
+ * Withdraw a previously announced namespace so new subscribers no longer discover its tracks.
1588
+ *
1589
+ * Use when shutting down publishing for a logical scope (camera offline, room closed, session ended).
1590
+ * Removes the namespace from `publishedNamespaces` locally and closes the stream its PUBLISH_NAMESPACE opened,
1591
+ * which is what withdraws the announcement (§3.3.2). This is also how an announce is retracted before the peer
1592
+ * has finished processing it.
1593
+ *
1594
+ * Parameter semantics:
1595
+ * - trackNamespace: Exact tuple used during {@link MOQtailClient.publishNamespace}. Must match to be removed from internal set.
1596
+ *
1597
+ * Behavior:
1598
+ * - Does not delete locally registered {@link Track} objects (they remain in `trackSources`).
1599
+ * - Does not forcibly end active subscriptions that were already established; peers simply stop discovering it for new ones.
1600
+ * - Silent if the namespace was not currently recorded (idempotent style).
1601
+ *
1602
+ * @throws MOQtailError If client is destroyed before sending.
1603
+ * @throws (rethrows original error) Any lower-level failure while sending results in a disconnect (unwrapped TODO: future wrap with InternalError for consistency).
1604
+ *
1605
+ * @remarks
1606
+ * Peers that issued {@link MOQtailClient.subscribeNamespace} for a matching prefix should receive the resulting NAMESPACE_DONE.
1607
+ * Consider calling this before {@link MOQtailClient.disconnect} to give consumers prompt notice.
1608
+ *
1609
+ * @example Basic usage
1610
+ * ```ts
1611
+ * await client.unpublishNamespace(["camera","main"])
1612
+ * ```
1613
+ *
1614
+ * @example Idempotent
1615
+ * ```ts
1616
+ * await client.unpublishNamespace(["camera","main"]) // first time
1617
+ * await client.unpublishNamespace(["camera","main"]) // no error, already removed
1618
+ * ```
1619
+ */
1620
+ unpublishNamespace(trackNamespace: Tuple): Promise<void>;
1621
+ /**
1622
+ * Subscribes to namespace announcements under a prefix (§10.18). Discovery only: the
1623
+ * peer answers NAMESPACE and NAMESPACE_DONE for matching namespaces, and nothing is
1624
+ * subscribed to. To be sent the tracks themselves, use
1625
+ * {@link MOQtailClient.subscribeTracks}.
1626
+ */
1627
+ subscribeNamespace(trackNamespacePrefix: Tuple, parameters?: MessageParameter[]): Promise<{
1628
+ response: RequestOk | RequestError;
1629
+ cancel: () => Promise<void>;
1630
+ }>;
1631
+ subscribeTracks(trackNamespacePrefix: Tuple, parameters?: MessageParameter[]): Promise<{
1632
+ response: RequestOk | RequestError;
1633
+ cancel: () => Promise<void>;
1634
+ }>;
1635
+ /**
1636
+ * Ends a prefix subscription started with {@link MOQtailClient.subscribeNamespace}.
1637
+ *
1638
+ * @param trackNamespacePrefix - The prefix that subscription was opened with.
1639
+ */
1640
+ unsubscribeNamespace(trackNamespacePrefix: Tuple): Promise<void>;
1641
+ /**
1642
+ * Asks the peer for the current status of a track.
1643
+ *
1644
+ * TRACK_STATUS is the seventh `First`-marked type: it opens its own bidi stream and
1645
+ * the REQUEST_OK answering it comes back there, after which the stream is closed.
1646
+ *
1647
+ * @param fullTrackName - The track to report on.
1648
+ * @param trackAlias - Alias to carry in the request.
1649
+ * @param parameters - Optional message parameters.
1650
+ * @returns A {@link RequestOk} on success or a {@link RequestError} on refusal.
1651
+ *
1652
+ * @example
1653
+ * ```ts
1654
+ * const status = await client.trackStatus(fullTrackName, trackAlias)
1655
+ * if (!(status instanceof RequestError)) {
1656
+ * // track exists
1657
+ * }
1658
+ * ```
1659
+ */
1660
+ trackStatus(fullTrackName: FullTrackName, trackAlias: bigint, parameters?: MessageParameter[]): Promise<RequestOk | RequestError>;
1661
+ /**
1662
+ * Re-issues one request on a fresh stream after the peer sent a GOAWAY on its request
1663
+ * stream (§10.4). Only that request moves: the session, and every other request on it,
1664
+ * are left alone.
1665
+ *
1666
+ * The re-issued request consumes a new Request ID (§10.1), so the opening message is
1667
+ * re-stamped with it. The id the caller holds keeps naming the request; only the id on
1668
+ * the wire changes.
1669
+ *
1670
+ * @returns True if the request was re-issued here. A GOAWAY naming a new session URI
1671
+ * is not: opening a session is the application's call, so it is surfaced through
1672
+ * {@link MOQtailClient.onGoaway} and the request stream is closed.
1673
+ *
1674
+ * @internal
1675
+ */
1676
+ migrateRequest(requestId: bigint, goAway: GoAway): Promise<boolean>;
1807
1677
  }
1808
-
1809
- /**
1810
- * Copyright 2025 The MOQtail Authors
1811
- *
1812
- * Licensed under the Apache License, Version 2.0 (the "License");
1813
- * you may not use this file except in compliance with the License.
1814
- * You may obtain a copy of the License at
1815
- *
1816
- * http://www.apache.org/licenses/LICENSE-2.0
1817
- *
1818
- * Unless required by applicable law or agreed to in writing, software
1819
- * distributed under the License is distributed on an "AS IS" BASIS,
1820
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1821
- * See the License for the specific language governing permissions and
1822
- * limitations under the License.
1823
- */
1824
-
1678
+ //#endregion
1679
+ //#region src/client/data_stream.d.ts
1825
1680
  declare class SendStream {
1826
- #private;
1827
- readonly header: Header;
1828
- readonly onDataSent?: (data: SubgroupObject | SubgroupHeader | FetchObject | FetchHeader) => void;
1829
- private constructor();
1830
- static new(writeStream: WritableStream<Uint8Array>, header: Header, onDataSent?: (data: SubgroupObject | SubgroupHeader | FetchObject | FetchHeader) => void): Promise<SendStream>;
1831
- write(object: FetchObject | SubgroupObject): Promise<void>;
1832
- close(): Promise<void>;
1681
+ #private;
1682
+ readonly header: Header;
1683
+ readonly onDataSent?: (data: SubgroupObject | SubgroupHeader | FetchObject | FetchHeader) => void;
1684
+ private constructor();
1685
+ static new(writeStream: WritableStream<Uint8Array>, header: Header, onDataSent?: (data: SubgroupObject | SubgroupHeader | FetchObject | FetchHeader) => void, groupOrder?: GroupOrder): Promise<SendStream>;
1686
+ write(object: FetchObject | SubgroupObject): Promise<void>;
1687
+ close(): Promise<void>;
1688
+ /** Abruptly tears the stream down, so the peer reads back `code` (§3.3.3). */
1689
+ reset(code: StreamResetCode): Promise<void>;
1833
1690
  }
1834
1691
  declare class RecvStream {
1835
- #private;
1836
- readonly header: Header;
1837
- readonly stream: ReadableStream<FetchObject | SubgroupObject>;
1838
- readonly onDataReceived?: (data: SubgroupObject | SubgroupHeader | FetchObject | FetchHeader) => void;
1839
- private constructor();
1840
- static new(readStream: ReadableStream<Uint8Array>, partialDataTimeout?: number, onDataReceived?: (data: SubgroupObject | SubgroupHeader | FetchObject | FetchHeader) => void): Promise<RecvStream>;
1692
+ #private;
1693
+ readonly header: Header;
1694
+ readonly stream: ReadableStream<FetchObject | SubgroupObject>;
1695
+ readonly onDataReceived?: (data: SubgroupObject | SubgroupHeader | FetchObject | FetchHeader) => void;
1696
+ private constructor();
1697
+ /**
1698
+ * @param resolveGroupOrder - Consulted once the FETCH header names its request, since
1699
+ * Group ID deltas on the stream are signed by the Group Order the request negotiated.
1700
+ */
1701
+ static new(readStream: ReadableStream<Uint8Array>, partialDataTimeout?: number, onDataReceived?: (data: SubgroupObject | SubgroupHeader | FetchObject | FetchHeader) => void, resolveGroupOrder?: (header: Header) => GroupOrder): Promise<RecvStream>;
1702
+ /** Asks the peer to stop sending on this stream, reporting `code` (§3.3.3). */
1703
+ stopSending(code: StreamResetCode): Promise<void>;
1841
1704
  }
1842
-
1843
- export { ControlStream, type EarlyDiscardPolicyConfig, type FetchOptions, FetchPublication, FetchRequest, HybridTrackSource, type LiveObjectSource, LiveTrackSource, MOQtailClient, type MOQtailClientOptions, type MOQtailRequest, MemoryObjectCache, type ObjectCache, type PastObjectSource, PublishNamespaceRequest, PublishPublication, PublishRequest, RecvDatagramStream, RecvStream, RingBufferObjectCache, SendDatagramStream, SendStream, StaticTrackSource, SubscribeNamespaceRequest, type SubscribeOptions, SubscribePublication, SubscribeRequest, type SubscribeUpdateOptions, type SwitchOptions, type Track, type TrackSource, TrackStatusRequest };
1705
+ //#endregion
1706
+ export { ControlRecvStream, ControlSendStream, ControlStream, EarlyDiscardPolicyConfig, FetchOptions, FetchPublication, FetchRequest, HybridTrackSource, LiveObjectSource, LiveTrackSource, MOQtailClient, MOQtailClientOptions, MOQtailRequest, MemoryObjectCache, ObjectCache, PastObjectSource, PublishNamespaceRequest, PublishPublication, PublishRequest, RecvDatagramStream, RecvStream, RequestStream, RingBufferObjectCache, SendDatagramStream, SendStream, StaticTrackSource, SubscribeNamespaceRequest, SubscribeOptions, SubscribePublication, SubscribeRequest, SubscribeUpdateOptions, SwitchOptions, Track, TrackSource, TrackStatusRequest };