moqtail 0.13.0 → 0.14.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.
@@ -329,7 +329,9 @@ var RequestStream = class RequestStream {
329
329
  #receiveBuffer;
330
330
  /** Held for the stream's lifetime once {@link next} is first called. */
331
331
  #messageReader;
332
- constructor(biStream) {
332
+ #hooks;
333
+ constructor(biStream, hooks = {}) {
334
+ this.#hooks = hooks;
333
335
  this.#receiveBuffer = new require_model.ByteBuffer();
334
336
  this.#reader = biStream.readable.getReader();
335
337
  this.#writer = biStream.writable.getWriter();
@@ -345,10 +347,10 @@ var RequestStream = class RequestStream {
345
347
  * @throws :{@link ProtocolViolationError} If `first` is not one of the seven types
346
348
  * Table 5 marks `First`; those are the only ones allowed to open a request stream.
347
349
  */
348
- static async open(webTransport, first) {
350
+ static async open(webTransport, first, hooks = {}) {
349
351
  if (!require_model.ControlMessageType.isFirst(first.getType())) throw new require_model.ProtocolViolationError("RequestStream.open", `${first.constructor.name} may not open a request stream: only First-marked types can`);
350
352
  const biStream = await webTransport.createBidirectionalStream();
351
- const requestStream = new RequestStream(biStream);
353
+ const requestStream = new RequestStream(biStream, hooks);
352
354
  requestStream.first = first;
353
355
  requestStream.openingType = first.getType();
354
356
  await requestStream.send(first);
@@ -372,6 +374,7 @@ var RequestStream = class RequestStream {
372
374
  await this.#writer.ready;
373
375
  await this.#writer.write(serialized.toUint8Array());
374
376
  require_logger.logger.debug("request_stream", `sent ${message.constructor.name}`);
377
+ this.#hooks.onMessageSent?.(message);
375
378
  } catch (error) {
376
379
  await this.close();
377
380
  const msg = error instanceof Error ? error.message : String(error);
@@ -384,8 +387,7 @@ var RequestStream = class RequestStream {
384
387
  await Promise.allSettled([this.#writer.close().catch(() => {}), this.#reader.cancel().catch(() => {})]);
385
388
  }
386
389
  /**
387
- * Cancels the request by resetting its stream with `code` (§3.3.2), which is how
388
- * draft-18 cancels a request now that the dedicated cancel messages are gone.
390
+ * Cancels the request by resetting its stream with `code`.
389
391
  */
390
392
  async reset(code) {
391
393
  require_logger.logger.debug("request_stream", `reset code=${code}`);
@@ -413,6 +415,7 @@ var RequestStream = class RequestStream {
413
415
  this.#receiveBuffer.commit();
414
416
  const msg = require_model.ControlMessage.deserialize(new require_model.FrozenByteBuffer(messageBytes));
415
417
  controller.enqueue(msg);
418
+ this.#hooks.onMessageReceived?.(msg);
416
419
  continue;
417
420
  }
418
421
  const readResult = await this.#reader.read();
@@ -446,6 +449,118 @@ var RequestStream = class RequestStream {
446
449
  }
447
450
  };
448
451
  //#endregion
452
+ //#region src/client/data_event.ts
453
+ /**
454
+ * Copyright 2026 The MOQtail Authors
455
+ *
456
+ * Licensed under the Apache License, Version 2.0 (the "License");
457
+ * you may not use this file except in compliance with the License.
458
+ * You may obtain a copy of the License at
459
+ *
460
+ * http://www.apache.org/licenses/LICENSE-2.0
461
+ *
462
+ * Unless required by applicable law or agreed to in writing, software
463
+ * distributed under the License is distributed on an "AS IS" BASIS,
464
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
465
+ * See the License for the specific language governing permissions and
466
+ * limitations under the License.
467
+ */
468
+ let lastStreamId = 0;
469
+ function locTimestampOf(properties) {
470
+ if (!properties) return void 0;
471
+ for (const pair of properties) {
472
+ const timestamp = require_model.Timestamp.fromKeyValuePair(pair);
473
+ if (timestamp) return timestamp.timestamp;
474
+ }
475
+ }
476
+ /**
477
+ * Turns one data stream's activity into {@link DataEvent}s. A throwing observer is
478
+ * logged and otherwise ignored, so it can never break the stream it watches.
479
+ */
480
+ var DataStreamReporter = class {
481
+ direction;
482
+ observer;
483
+ streamId = ++lastStreamId;
484
+ #hasEnded = false;
485
+ constructor(direction, observer) {
486
+ this.direction = direction;
487
+ this.observer = observer;
488
+ }
489
+ header(header) {
490
+ if (!this.observer) return;
491
+ const fullTrackName = this.observer.fullTrackNameOf?.(header);
492
+ const event = require_model.Header.isFetch(header) ? {
493
+ ...this.#base("header"),
494
+ stream: "fetch",
495
+ requestId: header.requestId
496
+ } : {
497
+ ...this.#base("header"),
498
+ stream: "subgroup",
499
+ trackAlias: header.trackAlias,
500
+ groupId: header.groupId,
501
+ ...header.subgroupId !== void 0 && { subgroupId: header.subgroupId }
502
+ };
503
+ if (fullTrackName) event.fullTrackName = fullTrackName;
504
+ this.#emit(event);
505
+ }
506
+ /** `header` is the stream's own: a subgroup object takes its group and subgroup from it. */
507
+ object(header, object) {
508
+ if (!this.observer) return;
509
+ let event;
510
+ if (object instanceof require_model.FetchObject) {
511
+ if (object.kind !== "object") return;
512
+ event = {
513
+ ...this.#base("object"),
514
+ groupId: object.location.group,
515
+ subgroupId: object.subgroupId,
516
+ objectId: object.location.object,
517
+ payloadLength: object.payload?.byteLength ?? 0
518
+ };
519
+ const locTimestamp = locTimestampOf(object.properties);
520
+ if (locTimestamp !== void 0) event.locTimestamp = locTimestamp;
521
+ } else {
522
+ if (require_model.Header.isFetch(header)) return;
523
+ event = {
524
+ ...this.#base("object"),
525
+ groupId: header.groupId,
526
+ objectId: object.objectId,
527
+ payloadLength: object.payload?.byteLength ?? 0,
528
+ ...header.subgroupId !== void 0 && { subgroupId: header.subgroupId },
529
+ ...object.objectStatus !== null && { objectStatus: object.objectStatus }
530
+ };
531
+ const locTimestamp = locTimestampOf(object.properties);
532
+ if (locTimestamp !== void 0) event.locTimestamp = locTimestamp;
533
+ }
534
+ this.#emit(event);
535
+ }
536
+ /** Reports how the stream ended. Only the first call counts. */
537
+ end(reason, resetCode) {
538
+ if (this.#hasEnded) return;
539
+ this.#hasEnded = true;
540
+ if (!this.observer) return;
541
+ this.#emit({
542
+ ...this.#base("end"),
543
+ reason,
544
+ ...resetCode !== void 0 && { resetCode }
545
+ });
546
+ }
547
+ #base(kind) {
548
+ return {
549
+ kind,
550
+ direction: this.direction,
551
+ streamId: this.streamId,
552
+ at: performance.now()
553
+ };
554
+ }
555
+ #emit(event) {
556
+ try {
557
+ this.observer.onDataEvent(event);
558
+ } catch (error) {
559
+ require_logger.logger.warn("data_event", "onDataEvent threw", error);
560
+ }
561
+ }
562
+ };
563
+ //#endregion
449
564
  //#region src/client/data_stream.ts
450
565
  /**
451
566
  * Copyright 2025 The MOQtail Authors
@@ -468,20 +583,25 @@ var SendStream = class SendStream {
468
583
  #fetchPrevCtx;
469
584
  #writer;
470
585
  #groupOrder;
586
+ #reporter;
471
587
  onDataSent;
472
- constructor(header, writer, onDataSent, groupOrder = 0) {
588
+ constructor(header, writer, reporter, onDataSent, groupOrder = 0) {
473
589
  this.header = header;
474
590
  if (onDataSent) this.onDataSent = onDataSent;
475
591
  this.#writer = writer;
592
+ this.#reporter = reporter;
476
593
  this.#groupOrder = groupOrder;
477
594
  }
478
- static async new(writeStream, header, onDataSent, groupOrder = 0) {
595
+ /** @param observer - Receives a {@link DataEvent} for the header, each object, and the stream's end. */
596
+ static async new(writeStream, header, onDataSent, groupOrder = 0, observer) {
479
597
  const writer = writeStream.getWriter();
480
598
  const serializedHeader = header.serialize().toUint8Array();
481
599
  await writer.write(serializedHeader);
482
600
  if (onDataSent) onDataSent(header);
601
+ const reporter = new DataStreamReporter("out", observer);
602
+ reporter.header(header);
483
603
  require_logger.logger.debug("data_stream", `SendStream opened type=${header.type}`);
484
- return new SendStream(header, writer, onDataSent, groupOrder);
604
+ return new SendStream(header, writer, reporter, onDataSent, groupOrder);
485
605
  }
486
606
  async write(object) {
487
607
  let serializedObject;
@@ -497,19 +617,27 @@ var SendStream = class SendStream {
497
617
  serializedObject = object.serialize(this.#lastObjectId).toUint8Array();
498
618
  this.#lastObjectId = object.objectId;
499
619
  }
500
- await this.#writer.write(serializedObject);
620
+ try {
621
+ await this.#writer.write(serializedObject);
622
+ } catch (error) {
623
+ this.#reporter.end("error");
624
+ throw error;
625
+ }
501
626
  if (this.onDataSent) this.onDataSent(object);
627
+ this.#reporter.object(this.header, object);
502
628
  }
503
629
  async close() {
504
630
  if (this.#writer) {
505
631
  require_logger.logger.debug("data_stream", `SendStream closed type=${this.header.type}`);
506
632
  await this.#writer.close();
633
+ this.#reporter.end("fin");
507
634
  }
508
635
  }
509
636
  /** Abruptly tears the stream down, so the peer reads back `code` (§3.3.3). */
510
637
  async reset(code) {
511
638
  require_logger.logger.debug("data_stream", `SendStream reset type=${this.header.type} code=${code}`);
512
639
  await this.#writer.abort(streamResetReason(code)).catch(() => {});
640
+ this.#reporter.end("reset", code);
513
641
  }
514
642
  };
515
643
  function withTimeout(promise, ms, errorMsg) {
@@ -527,10 +655,12 @@ var RecvStream = class RecvStream {
527
655
  #reader;
528
656
  #internalBuffer;
529
657
  #groupOrder;
658
+ #reporter;
530
659
  onDataReceived;
531
- constructor(header, reader, internalBuffer, partialDataTimeout, onDataReceived, groupOrder = 0) {
660
+ constructor(header, reader, internalBuffer, reporter, partialDataTimeout, onDataReceived, groupOrder = 0) {
532
661
  this.header = header;
533
662
  this.#reader = reader;
663
+ this.#reporter = reporter;
534
664
  this.#internalBuffer = internalBuffer;
535
665
  this.#partialDataTimeout = partialDataTimeout;
536
666
  this.#groupOrder = groupOrder;
@@ -543,8 +673,9 @@ var RecvStream = class RecvStream {
543
673
  /**
544
674
  * @param resolveGroupOrder - Consulted once the FETCH header names its request, since
545
675
  * Group ID deltas on the stream are signed by the Group Order the request negotiated.
676
+ * @param observer - Receives a {@link DataEvent} for the header, each object, and the stream's end.
546
677
  */
547
- static async new(readStream, partialDataTimeout, onDataReceived, resolveGroupOrder) {
678
+ static async new(readStream, partialDataTimeout, onDataReceived, resolveGroupOrder, observer) {
548
679
  const reader = readStream.getReader();
549
680
  const internalBuffer = new require_model.ByteBuffer();
550
681
  let headerInstance;
@@ -560,7 +691,6 @@ var RecvStream = class RecvStream {
560
691
  internalBuffer.checkpoint();
561
692
  headerInstance = require_model.Header.deserialize(internalBuffer);
562
693
  internalBuffer.commit();
563
- if (onDataReceived) onDataReceived(headerInstance);
564
694
  break;
565
695
  } catch (e) {
566
696
  if (e instanceof require_model.NotEnoughBytesError) {
@@ -575,9 +705,11 @@ var RecvStream = class RecvStream {
575
705
  throw asStreamResetError("RecvStream.new", error);
576
706
  }
577
707
  if (onDataReceived) onDataReceived(headerInstance);
708
+ const reporter = new DataStreamReporter("in", observer);
709
+ reporter.header(headerInstance);
578
710
  require_logger.logger.debug("data_stream", `RecvStream opened type=${headerInstance.type}`);
579
711
  const groupOrder = require_model.Header.isFetch(headerInstance) && resolveGroupOrder ? resolveGroupOrder(headerInstance) : 0;
580
- return new RecvStream(headerInstance, reader, internalBuffer, partialDataTimeout, onDataReceived, groupOrder);
712
+ return new RecvStream(headerInstance, reader, internalBuffer, reporter, partialDataTimeout, onDataReceived, groupOrder);
581
713
  }
582
714
  async #ingestLoop(controller) {
583
715
  try {
@@ -599,10 +731,12 @@ var RecvStream = class RecvStream {
599
731
  this.#internalBuffer.commit();
600
732
  controller.enqueue(object);
601
733
  if (this.onDataReceived) this.onDataReceived(object);
734
+ this.#reporter.object(this.header, object);
602
735
  continue;
603
736
  } catch (e) {
604
737
  if (e instanceof require_model.NotEnoughBytesError) this.#internalBuffer.restore();
605
738
  else {
739
+ this.#reporter.end("error");
606
740
  controller.error(e);
607
741
  break;
608
742
  }
@@ -614,9 +748,11 @@ var RecvStream = class RecvStream {
614
748
  if (done) {
615
749
  if (this.#internalBuffer.remaining > 0) {
616
750
  require_logger.logger.error("data_stream", `RecvStream closed with incomplete data remaining=${this.#internalBuffer.remaining}`);
751
+ this.#reporter.end("error");
617
752
  controller.error(new require_model.ProtocolViolationError("RecvStream", `Stream closed with incomplete object data. Remaining: ${this.#internalBuffer.remaining} bytes.`));
618
753
  } else {
619
754
  require_logger.logger.debug("data_stream", `RecvStream closed type=${this.header.type}`);
755
+ this.#reporter.end("fin");
620
756
  controller.close();
621
757
  }
622
758
  break;
@@ -625,9 +761,12 @@ var RecvStream = class RecvStream {
625
761
  }
626
762
  } catch (error) {
627
763
  const peerReset = streamResetCodeOf(error);
628
- if (peerReset !== void 0) require_logger.logger.debug("data_stream", `RecvStream reset by peer code=${require_model.StreamResetCode[peerReset]}`);
629
- else {
764
+ if (peerReset !== void 0) {
765
+ require_logger.logger.debug("data_stream", `RecvStream reset by peer code=${require_model.StreamResetCode[peerReset]}`);
766
+ this.#reporter.end("reset", peerReset);
767
+ } else {
630
768
  require_logger.logger.error("data_stream", "RecvStream ingest loop error", error);
769
+ this.#reporter.end("error");
631
770
  await this.#reader.cancel(streamResetReason(0)).catch(() => {});
632
771
  }
633
772
  controller.error(asStreamResetError("RecvStream", error));
@@ -820,9 +959,35 @@ var FetchRequest = class {
820
959
  }
821
960
  };
822
961
  //#endregion
962
+ //#region src/client/types.ts
963
+ /**
964
+ * Default for {@link MOQtailClientOptions.trackAliasResolutionTimeoutMs}: how long a
965
+ * data stream waits for the control message that establishes its track alias.
966
+ *
967
+ * A subscription's data streams and the SUBSCRIBE_OK naming their alias travel on
968
+ * separate streams, so nothing orders them; the data can arrive first. Waiting costs
969
+ * a stalled reader, giving up costs the whole subgroup, so the wait is generous.
970
+ */
971
+ const DEFAULT_TRACK_ALIAS_RESOLUTION_TIMEOUT_MS = 2e3;
972
+ /**
973
+ * Default for {@link MOQtailClientOptions.switchDrainTimeoutMs}: how long a track a
974
+ * soft switch handed over from may stay quiet before it is retired anyway.
975
+ *
976
+ * A soft switch leaves that track delivering up to the group the new one starts at,
977
+ * so the two meet without a hole, and a PUBLISH_DONE normally ends it. This is the
978
+ * backstop for a publisher that never sends one.
979
+ */
980
+ const DEFAULT_SWITCH_DRAIN_TIMEOUT_MS = 2e3;
981
+ /**
982
+ * @public
983
+ * The MAX_FILTER_RANGES a client advertises when its setup options set none: how
984
+ * many Range Filter ranges it applies, in total, for one subscription or fetch.
985
+ */
986
+ const DEFAULT_MAX_FILTER_RANGES = 32n;
987
+ //#endregion
823
988
  //#region src/client/request/subscribe.ts
824
989
  /**
825
- * Copyright 2025 The MOQtail Authors
990
+ * Copyright 2026 The MOQtail Authors
826
991
  *
827
992
  * Licensed under the Apache License, Version 2.0 (the "License");
828
993
  * you may not use this file except in compliance with the License.
@@ -836,6 +1001,10 @@ var FetchRequest = class {
836
1001
  * See the License for the specific language governing permissions and
837
1002
  * limitations under the License.
838
1003
  */
1004
+ /**
1005
+ * Represents an active subscription request in MOQT, implementing `PromiseLike`
1006
+ * for convenient async resolution when subscription setup succeeds or fails.
1007
+ */
839
1008
  var SubscribeRequest = class {
840
1009
  requestId;
841
1010
  fullTrackName;
@@ -847,8 +1016,17 @@ var SubscribeRequest = class {
847
1016
  subscribeParameters;
848
1017
  earlyDiscardPolicy;
849
1018
  largestLocation;
1019
+ /**
1020
+ * The publisher's Largest Object as of the last SUBSCRIBE_OK or REQUEST_UPDATE_OK,
1021
+ * which is where a fill fetch stream stops.
1022
+ */
1023
+ fillBoundary;
1024
+ /** EXPIRES from the last SUBSCRIBE_OK or REQUEST_UPDATE_OK, in milliseconds. */
1025
+ expires;
850
1026
  streamsAccepted = 0n;
851
1027
  expectedStreams;
1028
+ /** The Subscription managing this request's output stream once switching is involved. */
1029
+ manager;
852
1030
  controller;
853
1031
  stream;
854
1032
  #promise;
@@ -857,9 +1035,9 @@ var SubscribeRequest = class {
857
1035
  constructor(msg) {
858
1036
  this.requestId = msg.requestId;
859
1037
  this.fullTrackName = msg.fullTrackName;
860
- const filter = msg.parameters.find(require_model.MessageParameter.isSubscriptionFilter);
861
- this.startLocation = filter?.startLocation;
862
- this.endGroup = filter?.endGroup;
1038
+ const filter = msg.parameters.find(require_model.MessageParameter.isLocationFilter);
1039
+ this.startLocation = filter?.absoluteStart;
1040
+ this.endGroup = filter?.endLocation()?.group;
863
1041
  const subPriority = msg.parameters.find(require_model.MessageParameter.isSubscriberPriority);
864
1042
  this.priority = subPriority?.priority ?? 128;
865
1043
  const fwd = msg.parameters.find(require_model.MessageParameter.isForward);
@@ -874,30 +1052,36 @@ var SubscribeRequest = class {
874
1052
  });
875
1053
  require_logger.logger.debug("request/subscribe", `created requestId=${this.requestId} ftn="${this.fullTrackName}" priority=${this.priority} forward=${this.forward}`);
876
1054
  }
1055
+ /**
1056
+ * Updates subscription parameters in-place when a `RequestUpdate` message is received.
1057
+ */
877
1058
  update(msg) {
878
- const filter = msg.parameters.find(require_model.MessageParameter.isSubscriptionFilter);
879
- if (filter?.startLocation !== void 0) this.startLocation = filter.startLocation;
880
- if (filter?.endGroup !== void 0) this.endGroup = filter.endGroup;
1059
+ const filter = msg.parameters.find(require_model.MessageParameter.isLocationFilter);
1060
+ if (filter) {
1061
+ this.startLocation = filter.absoluteStart;
1062
+ this.endGroup = filter.endLocation()?.group;
1063
+ }
881
1064
  for (const param of msg.parameters) if (require_model.MessageParameter.isSubscriberPriority?.(param)) this.priority = param.priority;
882
1065
  else if (require_model.MessageParameter.isForward?.(param)) this.forward = param.forward;
883
1066
  if (typeof require_model.applyMessageParameterUpdate === "function") require_model.applyMessageParameterUpdate(this.subscribeParameters, msg.parameters);
884
1067
  }
885
- switch(newTrackName, newParameters) {
886
- this.fullTrackName = newTrackName;
887
- this.subscribeParameters = newParameters;
888
- this.#promise = new Promise((resolve, reject) => {
889
- this.#resolve = resolve;
890
- this.#reject = reject;
891
- });
892
- }
1068
+ /**
1069
+ * Marks this subscription request as canceled.
1070
+ */
893
1071
  unsubscribe() {
894
1072
  this.isCanceled = true;
895
1073
  }
1074
+ /**
1075
+ * Resolves the internal promise with a `SubscribeOk` or `RequestError`.
1076
+ */
896
1077
  resolve(value) {
897
1078
  if (value instanceof require_model.RequestError) require_logger.logger.error("request/subscribe", `resolved with error requestId=${this.requestId} code=${value.errorCode} reason="${value.reasonPhrase.phrase}"`);
898
1079
  else if (value instanceof require_model.SubscribeOk) require_logger.logger.debug("request/subscribe", `resolved with OK requestId=${this.requestId} trackAlias=${value.trackAlias}`);
899
1080
  this.#resolve(value);
900
1081
  }
1082
+ /**
1083
+ * Rejects the internal promise with an error/reason.
1084
+ */
901
1085
  reject(reason) {
902
1086
  require_logger.logger.error("request/subscribe", `rejected requestId=${this.requestId}`, reason);
903
1087
  this.#reject(reason);
@@ -912,6 +1096,122 @@ var SubscribeRequest = class {
912
1096
  return this.#promise.finally(onfinally);
913
1097
  }
914
1098
  };
1099
+ /**
1100
+ * Owns the single consumer-facing stream for a SUBSCRIBE that may be switched to a
1101
+ * new track one or more times. A soft switch can keep producing from the old track
1102
+ * for an unknown time after SUBSCRIBE_OK, and a second switch may be issued before the
1103
+ * first target ever delivers anything, so only the first object actually delivered by
1104
+ * the newest tracked request is the guarantee that nothing older will send again.
1105
+ *
1106
+ * That first delivery is the handover, not the end of the old track: a soft switch
1107
+ * leaves it delivering up to the group the new one starts at, so the two meet without
1108
+ * a hole. Those objects keep coming through here until the publisher says the
1109
+ * subscription is done, or until it has been quiet long enough to say so itself.
1110
+ */
1111
+ var Subscription = class {
1112
+ controller;
1113
+ stream;
1114
+ /** Oldest first; the last entry is the newest switch target still racing to produce data. */
1115
+ #requests;
1116
+ /**
1117
+ * Requests a soft switch handed over from, still delivering the tail of what they
1118
+ * were told to finish, each with the timer that retires it if it goes quiet.
1119
+ */
1120
+ #draining = /* @__PURE__ */ new Map();
1121
+ /** Switch targets whose handover drains what it supersedes rather than cutting it. */
1122
+ #drainsSuperseded = /* @__PURE__ */ new WeakSet();
1123
+ /** Set once by `MOQtailClient.switch`; invoked with everything older on cutover. */
1124
+ onSuperseded;
1125
+ /** Set by the client to decide whether draining a request should continue. */
1126
+ onDrainDecision = () => true;
1127
+ /**
1128
+ * How long a drained request may stay quiet before it is retired anyway, in
1129
+ * milliseconds. The publisher normally ends the drain with a PUBLISH_DONE; this is
1130
+ * what keeps a request that never gets one from being tracked forever.
1131
+ */
1132
+ drainTimeoutMs = DEFAULT_SWITCH_DRAIN_TIMEOUT_MS;
1133
+ constructor(initial) {
1134
+ this.stream = initial.stream;
1135
+ this.controller = initial.controller;
1136
+ initial.manager = this;
1137
+ this.#requests = [initial];
1138
+ }
1139
+ /** Requests still tracked, oldest first, draining ones last. */
1140
+ get requests() {
1141
+ return [...this.#requests, ...this.#draining.keys()];
1142
+ }
1143
+ /** The request most recently switched to; must deliver data to win the handover. */
1144
+ get newest() {
1145
+ return this.#requests[this.#requests.length - 1];
1146
+ }
1147
+ /**
1148
+ * Track a newly issued switch target alongside whatever is still delivering.
1149
+ *
1150
+ * `drainSuperseded` says what its handover does to the requests it takes over from:
1151
+ * a soft switch leaves them delivering to the end of what the publisher was told to
1152
+ * finish, a hard one retires them on the spot.
1153
+ */
1154
+ addSwitchTarget(request, drainSuperseded = false) {
1155
+ request.manager = this;
1156
+ if (drainSuperseded) this.#drainsSuperseded.add(request);
1157
+ this.#requests.push(request);
1158
+ }
1159
+ /** Stop tracking `request` (e.g. it naturally completed without ever losing/winning a handover). */
1160
+ drop(request) {
1161
+ this.#clearDrain(request);
1162
+ this.#requests = this.#requests.filter((r) => r !== request);
1163
+ }
1164
+ /** Stop tracking everything (used when the whole switch chain is torn down at once). */
1165
+ clear() {
1166
+ for (const request of [...this.#draining.keys()]) this.#clearDrain(request);
1167
+ this.#requests = [];
1168
+ }
1169
+ /** Starts, or on each further object restarts, the quiet period that ends a drain. */
1170
+ #keepDraining(request) {
1171
+ this.#clearDrain(request);
1172
+ this.#draining.set(request, setTimeout(() => {
1173
+ this.#draining.delete(request);
1174
+ require_logger.logger.debug("Subscription", `drain of request ${request.requestId} ended on silence`);
1175
+ this.onSuperseded?.([request]);
1176
+ }, this.drainTimeoutMs));
1177
+ }
1178
+ #clearDrain(request) {
1179
+ const timeout = this.#draining.get(request);
1180
+ if (timeout === void 0) return;
1181
+ clearTimeout(timeout);
1182
+ this.#draining.delete(request);
1183
+ }
1184
+ /**
1185
+ * Delivers an object received for `request`. The first object delivered by the
1186
+ * newest tracked request retires everything older — only then is it guaranteed no
1187
+ * more data is coming from them.
1188
+ *
1189
+ * Returns `true` if the object was delivered to the caller,
1190
+ * `false` if it was not consumed, and client should cancel the stream.
1191
+ */
1192
+ deliver(request, obj) {
1193
+ if (this.#draining.has(request)) {
1194
+ if (this.onDrainDecision?.(request)) {
1195
+ this.#keepDraining(request);
1196
+ this.controller.enqueue(obj);
1197
+ return true;
1198
+ }
1199
+ return false;
1200
+ }
1201
+ if (!this.#requests.includes(request)) {
1202
+ require_logger.logger.warn("Subscription", `discarding object from superseded request ${request.requestId}`);
1203
+ return false;
1204
+ }
1205
+ if (request === this.newest && this.#requests.length > 1) {
1206
+ const superseded = this.#requests.slice(0, -1);
1207
+ this.#requests = [request];
1208
+ if (this.#drainsSuperseded.has(request)) for (const old of superseded) this.#keepDraining(old);
1209
+ else this.onSuperseded?.(superseded);
1210
+ }
1211
+ this.controller.enqueue(obj);
1212
+ return true;
1213
+ }
1214
+ };
915
1215
  //#endregion
916
1216
  //#region src/client/request/publish.ts
917
1217
  /**
@@ -1052,7 +1352,29 @@ const handlerPublish = async (client, msg, stream) => {
1052
1352
  await stream.send(new require_model.RequestOk());
1053
1353
  };
1054
1354
  //#endregion
1055
- //#region src/client/handler/publish_blocked.ts
1355
+ //#region src/client/handler/publish_namespace.ts
1356
+ /**
1357
+ * Copyright 2025 The MOQtail Authors
1358
+ *
1359
+ * Licensed under the Apache License, Version 2.0 (the "License");
1360
+ * you may not use this file except in compliance with the License.
1361
+ * You may obtain a copy of the License at
1362
+ *
1363
+ * http://www.apache.org/licenses/LICENSE-2.0
1364
+ *
1365
+ * Unless required by applicable law or agreed to in writing, software
1366
+ * distributed under the License is distributed on an "AS IS" BASIS,
1367
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1368
+ * See the License for the specific language governing permissions and
1369
+ * limitations under the License.
1370
+ */
1371
+ const handlerPublishNamespace = async (client, msg, stream) => {
1372
+ require_logger.logger.log("handler/publish_namespace", "namespace", msg.trackNamespace.toUtf8Path());
1373
+ if (client.onNamespacePublished) client.onNamespacePublished(msg);
1374
+ await stream.send(new require_model.RequestOk());
1375
+ };
1376
+ //#endregion
1377
+ //#region src/client/handler/publish_skipped.ts
1056
1378
  /**
1057
1379
  * Copyright 2026 The MOQtail Authors
1058
1380
  *
@@ -1068,14 +1390,77 @@ const handlerPublish = async (client, msg, stream) => {
1068
1390
  * See the License for the specific language governing permissions and
1069
1391
  * limitations under the License.
1070
1392
  */
1071
- const handlerPublishBlocked = async (client, msg, stream) => {
1393
+ const handlerPublishSkipped = async (client, msg, stream) => {
1072
1394
  const first = stream.first;
1073
- if (!(first instanceof require_model.SubscribeTracks)) throw new require_model.ProtocolViolationError("handlerPublishBlocked", "PUBLISH_BLOCKED on a stream this side did not open with SUBSCRIBE_TRACKS");
1074
- require_logger.logger.log("handler/publish_blocked", "prefix", first.trackNamespacePrefix.toUtf8Path(), "suffix", msg.trackNamespaceSuffix.toUtf8Path());
1075
- client.onPeerPublishBlocked?.(first.trackNamespacePrefix, msg);
1395
+ if (!(first instanceof require_model.SubscribeTracks)) throw new require_model.ProtocolViolationError("handlerPublishSkipped", "PUBLISH_SKIPPED on a stream this side did not open with SUBSCRIBE_TRACKS");
1396
+ require_logger.logger.log("handler/publish_skipped", "prefix", first.trackNamespacePrefix.toUtf8Path(), "suffix", msg.trackNamespaceSuffix.toUtf8Path());
1397
+ client.onPeerPublishSkipped?.(first.trackNamespacePrefix, msg);
1076
1398
  };
1077
1399
  //#endregion
1078
- //#region src/client/handler/publish_namespace.ts
1400
+ //#region src/client/publication/subgroup.ts
1401
+ /**
1402
+ * Copyright 2026 The MOQtail Authors
1403
+ *
1404
+ * Licensed under the Apache License, Version 2.0 (the "License");
1405
+ * you may not use this file except in compliance with the License.
1406
+ * You may obtain a copy of the License at
1407
+ *
1408
+ * http://www.apache.org/licenses/LICENSE-2.0
1409
+ *
1410
+ * Unless required by applicable law or agreed to in writing, software
1411
+ * distributed under the License is distributed on an "AS IS" BASIS,
1412
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1413
+ * See the License for the specific language governing permissions and
1414
+ * limitations under the License.
1415
+ */
1416
+ /** Groups kept behind the newest in {@link SubgroupIds}, for objects that arrive late. */
1417
+ const GROUPS_KEPT = 4n;
1418
+ /**
1419
+ * Resolves the Subgroup ID of Objects that leave it to their subgroup's first Object
1420
+ * ID (a `null` {@link MoqtObject.subgroupId}). An Object cannot tell that on its own
1421
+ * once the first one has gone by, so the first Object ID of each group is noted as
1422
+ * the Objects arrive, whether or not they are then sent.
1423
+ *
1424
+ * This assumes one subgroup per group, which is how this client publishes.
1425
+ */
1426
+ var SubgroupIds = class {
1427
+ #firstObject = /* @__PURE__ */ new Map();
1428
+ /** Notes `obj`. Call it for every Object the track produces, sent or not. */
1429
+ note(obj) {
1430
+ const group = obj.location.group;
1431
+ const first = this.#firstObject.get(group);
1432
+ if (first !== void 0 && first <= obj.location.object) return;
1433
+ this.#firstObject.set(group, obj.location.object);
1434
+ for (const old of this.#firstObject.keys()) if (old + GROUPS_KEPT < group) this.#firstObject.delete(old);
1435
+ }
1436
+ /**
1437
+ * The Subgroup ID `obj` travels in, or `null` for a datagram. An Object whose
1438
+ * group was never noted is taken to be its subgroup's first.
1439
+ */
1440
+ of(obj) {
1441
+ if (obj.isDatagram()) return null;
1442
+ return obj.subgroupId ?? this.#firstObject.get(obj.location.group) ?? obj.location.object;
1443
+ }
1444
+ };
1445
+ /**
1446
+ * The header for a subgroup stream that starts with `obj`.
1447
+ *
1448
+ * An Object that leaves its Subgroup ID to the first Object ID only gets that header
1449
+ * when it is the first: a stream that starts later — a filter dropped the Objects
1450
+ * before it, or the subscription joined mid-group — states the ID, or a receiver
1451
+ * would read the wrong one off it.
1452
+ */
1453
+ function subgroupHeaderFor(obj, subgroupId, trackAlias, publisherPriority, firstObject) {
1454
+ let headerType = obj.getSubgroupHeaderType(true, false, firstObject);
1455
+ if (obj.subgroupId === null && subgroupId !== obj.location.object) {
1456
+ const hasProperties = !!obj.properties && obj.properties.length > 0;
1457
+ headerType = require_model.SubgroupHeaderType.fromProperties(hasProperties, 2, true, false, firstObject);
1458
+ }
1459
+ const explicit = require_model.SubgroupHeaderType.hasExplicitSubgroupId(headerType) ? subgroupId : void 0;
1460
+ return new require_model.SubgroupHeader(headerType, trackAlias, obj.location.group, explicit, publisherPriority);
1461
+ }
1462
+ //#endregion
1463
+ //#region src/client/publication/fetch.ts
1079
1464
  /**
1080
1465
  * Copyright 2025 The MOQtail Authors
1081
1466
  *
@@ -1091,10 +1476,237 @@ const handlerPublishBlocked = async (client, msg, stream) => {
1091
1476
  * See the License for the specific language governing permissions and
1092
1477
  * limitations under the License.
1093
1478
  */
1094
- const handlerPublishNamespace = async (client, msg, stream) => {
1095
- require_logger.logger.log("handler/publish_namespace", "namespace", msg.trackNamespace.toUtf8Path());
1096
- if (client.onNamespacePublished) client.onNamespacePublished(msg);
1097
- await stream.send(new require_model.RequestOk());
1479
+ var FetchPublication = class {
1480
+ #requestId;
1481
+ #track;
1482
+ #startLocation;
1483
+ /** The last Location to send, inclusive. */
1484
+ #endLocation;
1485
+ #msg;
1486
+ #client;
1487
+ /** What the FETCH's Range Filters let through. */
1488
+ #filter;
1489
+ #sendStream;
1490
+ #objects;
1491
+ #isCanceled = false;
1492
+ /** `start` and `end` are the FETCH's range resolved against the Largest Object, inclusive. */
1493
+ constructor(client, track, fetchRequest, start, end) {
1494
+ this.#client = client;
1495
+ this.#requestId = fetchRequest.requestId;
1496
+ this.#track = track;
1497
+ this.#msg = fetchRequest;
1498
+ this.#startLocation = start;
1499
+ this.#endLocation = end;
1500
+ this.#filter = new require_model.CombinedFilter(fetchRequest.parameters);
1501
+ require_logger.logger.debug("publication/fetch", `created requestId=${this.#requestId}`);
1502
+ this.publish();
1503
+ }
1504
+ cancel() {
1505
+ require_logger.logger.debug("publication/fetch", `canceled requestId=${this.#requestId}`);
1506
+ this.#isCanceled = true;
1507
+ }
1508
+ /**
1509
+ * Resets the data stream this fetch is being delivered on, which §10.9.1 requires when
1510
+ * a REQUEST_UPDATE for a FETCH fails.
1511
+ */
1512
+ async resetDataStream(code) {
1513
+ require_logger.logger.debug("publication/fetch", `reset data stream requestId=${this.#requestId} code=${code}`);
1514
+ this.#isCanceled = true;
1515
+ await this.#sendStream?.reset(code);
1516
+ }
1517
+ async publish() {
1518
+ if (this.#isCanceled) return;
1519
+ if (!this.#track.trackSource.past) throw new require_model.MOQtailError("FetchPublication.publish, Track does not support fetch");
1520
+ require_logger.logger.debug("publication/fetch", `publishing requestId=${this.#requestId} start=${this.#startLocation} end=${this.#endLocation}`);
1521
+ try {
1522
+ const objects = await this.#track.trackSource.past.getRange(this.#startLocation);
1523
+ this.#objects = objects.filter((obj) => obj.location.compare(this.#endLocation) <= 0);
1524
+ const writeStream = await this.#client.webTransport.createUnidirectionalStream();
1525
+ const header = new require_model.FetchHeader(5, this.#requestId);
1526
+ this.#sendStream = await SendStream.new(writeStream, header, this.#client.onDataSent, require_model.MessageParameter.groupOrderOf(this.#msg.parameters), this.#client.dataStreamObserver(() => this.#track.fullTrackName));
1527
+ const subgroupIds = new SubgroupIds();
1528
+ let sent = 0;
1529
+ for (const obj of this.#objects) {
1530
+ subgroupIds.note(obj);
1531
+ if (!this.#filter.matches(obj, subgroupIds.of(obj))) continue;
1532
+ if (this.#isCanceled) {
1533
+ require_logger.logger.debug("publication/fetch", `aborted during publish requestId=${this.#requestId}`);
1534
+ await this.#sendStream.reset(1);
1535
+ this.#client.publications.delete(this.#requestId);
1536
+ return;
1537
+ }
1538
+ await this.#sendStream.write(obj.tryIntoFetchObject());
1539
+ sent++;
1540
+ }
1541
+ await this.#sendStream.close();
1542
+ require_logger.logger.debug("publication/fetch", `published requestId=${this.#requestId} objects=${sent} of ${this.#objects.length}`);
1543
+ this.#client.publications.delete(this.#requestId);
1544
+ } catch (error) {
1545
+ if (this.#isCanceled) return;
1546
+ await this.#sendStream?.reset(0);
1547
+ const message = error instanceof Error ? error.message : String(error);
1548
+ require_logger.logger.error("publication/fetch", `publish failed requestId=${this.#requestId}`, message);
1549
+ throw new require_model.InternalError("FetchPublication.publish", `Failed to publish: ${message}`);
1550
+ }
1551
+ }
1552
+ };
1553
+ //#endregion
1554
+ //#region src/client/util/validators.ts
1555
+ /**
1556
+ * Copyright 2026 The MOQtail Authors
1557
+ *
1558
+ * Licensed under the Apache License, Version 2.0 (the "License");
1559
+ * you may not use this file except in compliance with the License.
1560
+ * You may obtain a copy of the License at
1561
+ *
1562
+ * http://www.apache.org/licenses/LICENSE-2.0
1563
+ *
1564
+ * Unless required by applicable law or agreed to in writing, software
1565
+ * distributed under the License is distributed on an "AS IS" BASIS,
1566
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1567
+ * See the License for the specific language governing permissions and
1568
+ * limitations under the License.
1569
+ */
1570
+ /** Returns true when `trackAlias` is a valid (non-negative) track alias. Zero is a legal value. */
1571
+ function isValidTrackAlias(trackAlias) {
1572
+ return trackAlias !== void 0 && trackAlias >= 0n;
1573
+ }
1574
+ /**
1575
+ * The REQUEST_ERROR INVALID_FILTER for a request whose Range Filters this client
1576
+ * cannot take: more ranges than the `limit` it advertised (with a limit of 0, any
1577
+ * filter at all), or a filter that cannot be applied. `undefined` when they are
1578
+ * fine, which includes carrying none.
1579
+ */
1580
+ function rangeFilterRejection(params, limit) {
1581
+ try {
1582
+ assertWithinFilterRangeLimit(params, limit, "request");
1583
+ new require_model.CombinedFilter(params);
1584
+ for (const fill of params.filter(require_model.MessageParameter.isFillParameters)) new require_model.CombinedFilter(fill.parameters);
1585
+ return;
1586
+ } catch (error) {
1587
+ if (!(error instanceof require_model.InvalidFilterError)) throw error;
1588
+ return new require_model.RequestError(54, 0n, new require_model.ReasonPhrase(error.details));
1589
+ }
1590
+ }
1591
+ /**
1592
+ * Throws unless `params` stay within a MAX_FILTER_RANGES of `limit`: the peer's,
1593
+ * so a request it would have to refuse is never sent, or this client's own, for
1594
+ * a request it received.
1595
+ *
1596
+ * A limit of 0 allows no Range Filter parameter at all, not even a
1597
+ * zero-length removal. Otherwise the Ranges of every filter in the request count
1598
+ * against the limit together. FILL_PARAMETERS describes a separate fill fetch
1599
+ * stream, so the filters inside it count against a limit of their own.
1600
+ *
1601
+ * @throws :{@link InvalidFilterError} When the limit is exceeded.
1602
+ */
1603
+ function assertWithinFilterRangeLimit(params, limit, context) {
1604
+ const filters = params.filter(require_model.MessageParameter.isRangeFilter);
1605
+ if (filters.length > 0) {
1606
+ if (limit === 0n) throw new require_model.InvalidFilterError(context, "no range filters are allowed (MAX_FILTER_RANGES is 0)");
1607
+ const count = BigInt(filters.reduce((sum, f) => sum + f.rangeCount, 0));
1608
+ if (count > limit) throw new require_model.InvalidFilterError(context, `${count} filter ranges exceed MAX_FILTER_RANGES of ${limit}`);
1609
+ }
1610
+ for (const fill of params.filter(require_model.MessageParameter.isFillParameters)) assertWithinFilterRangeLimit(fill.parameters, limit, `${context} (FILL_PARAMETERS)`);
1611
+ }
1612
+ //#endregion
1613
+ //#region src/client/handler/fetch.ts
1614
+ /**
1615
+ * Copyright 2025 The MOQtail Authors
1616
+ *
1617
+ * Licensed under the Apache License, Version 2.0 (the "License");
1618
+ * you may not use this file except in compliance with the License.
1619
+ * You may obtain a copy of the License at
1620
+ *
1621
+ * http://www.apache.org/licenses/LICENSE-2.0
1622
+ *
1623
+ * Unless required by applicable law or agreed to in writing, software
1624
+ * distributed under the License is distributed on an "AS IS" BASIS,
1625
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1626
+ * See the License for the specific language governing permissions and
1627
+ * limitations under the License.
1628
+ */
1629
+ const handlerFetch = async (client, msg, stream) => {
1630
+ require_logger.logger.log("handler/fetch", "requestId", msg.requestId);
1631
+ const filterRejection = rangeFilterRejection(msg.parameters, client.maxFilterRanges);
1632
+ if (filterRejection) {
1633
+ require_logger.logger.warn("handler/fetch", `requestId=${msg.requestId} has filters this client cannot take: ${filterRejection.reasonPhrase.phrase}`);
1634
+ await stream.send(filterRejection);
1635
+ return;
1636
+ }
1637
+ const fullTrackName = msg.fullTrackName;
1638
+ const track = client.trackSources.get(fullTrackName.toString());
1639
+ if (!track) {
1640
+ const response = new require_model.RequestError(16, 0n, new require_model.ReasonPhrase("Track does not exists"));
1641
+ await stream.send(response);
1642
+ return;
1643
+ }
1644
+ if (!track.trackSource.past) {
1645
+ const response = new require_model.RequestError(3, 0n, new require_model.ReasonPhrase("Requested track does not support fetch"));
1646
+ await stream.send(response);
1647
+ return;
1648
+ }
1649
+ const largest = track.trackSource.live?.largestLocation ?? (await track.trackSource.past.getRange()).at(-1)?.location;
1650
+ const range = msg.locationFilter.fetchRange(largest);
1651
+ if (!range) {
1652
+ require_logger.logger.warn("handler/fetch", `requestId=${msg.requestId} selects nothing published (largest=${largest})`);
1653
+ const response = new require_model.RequestError(17, 0n, new require_model.ReasonPhrase("Nothing published in the requested range"));
1654
+ await stream.send(response);
1655
+ return;
1656
+ }
1657
+ const publication = new FetchPublication(client, track, msg, range.start, range.end);
1658
+ client.publications.set(msg.requestId, publication);
1659
+ const trackProperties = require_model.MessageParameter.includesProperties(msg.parameters) ? track.trackProperties ?? [] : [];
1660
+ const response = new require_model.FetchOk(false, range.end, [], trackProperties);
1661
+ await stream.send(response);
1662
+ };
1663
+ //#endregion
1664
+ //#region src/client/handler/fetch_ok.ts
1665
+ /**
1666
+ * Copyright 2025 The MOQtail Authors
1667
+ *
1668
+ * Licensed under the Apache License, Version 2.0 (the "License");
1669
+ * you may not use this file except in compliance with the License.
1670
+ * You may obtain a copy of the License at
1671
+ *
1672
+ * http://www.apache.org/licenses/LICENSE-2.0
1673
+ *
1674
+ * Unless required by applicable law or agreed to in writing, software
1675
+ * distributed under the License is distributed on an "AS IS" BASIS,
1676
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1677
+ * See the License for the specific language governing permissions and
1678
+ * limitations under the License.
1679
+ */
1680
+ const handlerFetchOk = async (client, msg, _stream, requestId) => {
1681
+ require_logger.logger.log("handler/fetch_ok", "requestId", requestId);
1682
+ const request = client.requests.get(requestId);
1683
+ if (request instanceof FetchRequest) {
1684
+ if (msg.trackProperties.length > 0) {
1685
+ const track = client.trackSources.get(request.message.fullTrackName.toString());
1686
+ if (track !== void 0) track.trackProperties = msg.trackProperties;
1687
+ }
1688
+ request.resolve(msg);
1689
+ } else throw new require_model.ProtocolViolationError("handlerFetchOk", `FETCH_OK on a stream with no pending fetch request (request id ${requestId})`);
1690
+ };
1691
+ //#endregion
1692
+ //#region src/client/handler/goaway.ts
1693
+ const handlerGoAway = async (client, msg) => {
1694
+ require_logger.logger.log("handler/goaway", "newSessionUri", msg.newSessionUri, "timeout", msg.timeout);
1695
+ if (client.goawayReceived) {
1696
+ await client.disconnect(new require_model.ProtocolViolationError("handler/goaway", "A second GOAWAY arrived on the control stream"));
1697
+ return;
1698
+ }
1699
+ client.goawayReceived = true;
1700
+ if (client.onGoaway) client.onGoaway(msg);
1701
+ };
1702
+ /**
1703
+ * GOAWAY on a request stream: the peer is migrating that one request (§10.4). The
1704
+ * request is re-issued on a fresh stream and the session, along with every other request
1705
+ * on it, carries on.
1706
+ */
1707
+ const handlerGoAwayOnRequestStream = async (client, msg, _stream, requestId) => {
1708
+ require_logger.logger.log("handler/goaway", `GOAWAY migrating request ${requestId}`, "timeout", msg.timeout);
1709
+ await client.migrateRequest(requestId, msg);
1098
1710
  };
1099
1711
  //#endregion
1100
1712
  //#region src/util/simple_lock.ts
@@ -1188,9 +1800,9 @@ var SubscribePublication = class {
1188
1800
  */
1189
1801
  #startLocation;
1190
1802
  /**
1191
- * The end group for AbsoluteRange subscriptions, if specified.
1803
+ * The last Location delivered, inclusive, when the Location Filter has an end.
1192
1804
  */
1193
- #endGroup;
1805
+ #endLocation;
1194
1806
  /**
1195
1807
  * The priority of the subscriber.
1196
1808
  */
@@ -1208,6 +1820,14 @@ var SubscribePublication = class {
1208
1820
  */
1209
1821
  #parameters;
1210
1822
  /**
1823
+ * What the subscription's Range Filters let through.
1824
+ */
1825
+ #filter;
1826
+ /**
1827
+ * The Subgroup ID of each Object, which the filter and the stream header need.
1828
+ */
1829
+ #subgroupIds = new SubgroupIds();
1830
+ /**
1211
1831
  * The number of streams opened for this subscription.
1212
1832
  */
1213
1833
  #streamsOpened = 0n;
@@ -1259,28 +1879,13 @@ var SubscribePublication = class {
1259
1879
  this.#publisherPriority = track.publisherPriority;
1260
1880
  const subPriority = subscribeMsg.parameters.find(require_model.MessageParameter.isSubscriberPriority);
1261
1881
  const fwd = subscribeMsg.parameters.find(require_model.MessageParameter.isForward);
1262
- const filter = subscribeMsg.parameters.find(require_model.MessageParameter.isSubscriptionFilter);
1882
+ const filter = subscribeMsg.parameters.find(require_model.MessageParameter.isLocationFilter);
1263
1883
  this.#subscriberPriority = subPriority?.priority ?? 128;
1264
1884
  this.#forward = fwd?.forward ?? true;
1265
1885
  this.#parameters = [...subscribeMsg.parameters];
1266
- this.#startLocation = new require_model.Location(0n, 0n);
1267
- switch (filter?.filterType ?? 2) {
1268
- case 2:
1269
- if (largestLocation) this.#startLocation = new require_model.Location(largestLocation.group, largestLocation.object + 1n);
1270
- else this.#startLocation = new require_model.Location(0n, 0n);
1271
- break;
1272
- case 1:
1273
- if (largestLocation) this.#startLocation = new require_model.Location(largestLocation.group + 1n, 0n);
1274
- else this.#startLocation = new require_model.Location(0n, 0n);
1275
- break;
1276
- case 3:
1277
- this.#startLocation = filter?.startLocation ?? new require_model.Location(0n, 0n);
1278
- break;
1279
- case 4:
1280
- this.#startLocation = filter?.startLocation ?? new require_model.Location(0n, 0n);
1281
- this.#endGroup = filter?.endGroup;
1282
- break;
1283
- }
1886
+ this.#filter = new require_model.CombinedFilter(this.#parameters);
1887
+ this.#startLocation = filter?.startLocation(largestLocation) ?? new require_model.Location(0n, 0n);
1888
+ this.#endLocation = filter?.endLocation();
1284
1889
  this.publish();
1285
1890
  }
1286
1891
  /**
@@ -1313,14 +1918,39 @@ var SubscribePublication = class {
1313
1918
  /**
1314
1919
  * Updates the subscription parameters and locations based on a RequestUpdate message.
1315
1920
  * @param msg - The update message containing new request details.
1921
+ * @throws :{@link InvalidFilterError} If the Range Filters the subscription would be
1922
+ * left with cannot be applied; nothing is updated.
1316
1923
  */
1317
1924
  update(msg) {
1318
- const filter = msg.parameters.find(require_model.MessageParameter.isSubscriptionFilter);
1319
- if (filter?.startLocation !== void 0) this.#startLocation = filter.startLocation;
1320
- if (filter?.endGroup !== void 0) this.#endGroup = filter.endGroup;
1925
+ const parameters = [...this.#parameters];
1926
+ require_model.applyMessageParameterUpdate(parameters, msg.parameters);
1927
+ assertWithinFilterRangeLimit(parameters, this.client.maxFilterRanges, "REQUEST_UPDATE");
1928
+ this.#filter = new require_model.CombinedFilter(parameters);
1929
+ const filter = msg.parameters.find(require_model.MessageParameter.isLocationFilter);
1930
+ if (filter) {
1931
+ this.#startLocation = filter.startLocation(this.latestLocation) ?? new require_model.Location(0n, 0n);
1932
+ this.#endLocation = filter.endLocation();
1933
+ }
1321
1934
  for (const param of msg.parameters) if (require_model.MessageParameter.isSubscriberPriority?.(param)) this.#subscriberPriority = param.priority;
1322
1935
  else if (require_model.MessageParameter.isForward?.(param)) this.#forward = param.forward;
1323
- require_model.applyMessageParameterUpdate(this.#parameters, msg.parameters);
1936
+ this.#parameters = parameters;
1937
+ }
1938
+ /**
1939
+ * Closes the stream carrying `group`, if one is open.
1940
+ */
1941
+ async #closeGroupStream(group) {
1942
+ await this.#lock.acquire();
1943
+ try {
1944
+ const stream = this.#streams.get(group);
1945
+ if (stream) {
1946
+ this.#streams.delete(group);
1947
+ await stream.close();
1948
+ }
1949
+ } catch (err) {
1950
+ require_logger.logger.warn("publication/subscribe", "error in closing stream: id, group, err", this.#id, group, err);
1951
+ } finally {
1952
+ await this.#lock.release();
1953
+ }
1324
1954
  }
1325
1955
  #markGroupSeen(group) {
1326
1956
  if (this.#highestGroupSeen === void 0 || group > this.#highestGroupSeen) this.#highestGroupSeen = group;
@@ -1338,305 +1968,56 @@ var SubscribePublication = class {
1338
1968
  this.#highestGroupSeen = this.track.trackSource.live.largestLocation?.group;
1339
1969
  this.#cancelPublishing = this.track.trackSource.live.onNewObject(async (obj) => {
1340
1970
  if (this.#isCompleted) return;
1971
+ this.#subgroupIds.note(obj);
1341
1972
  if (!this.#forward) {
1342
1973
  this.#markGroupSeen(obj.location.group);
1343
1974
  return;
1344
1975
  }
1345
- if (!this.#isStarted && this.#startLocation.compare(obj.location) <= 0) this.#isStarted = true;
1346
- if (!this.#isStarted) this.#markGroupSeen(obj.location.group);
1347
- if (this.#isStarted) try {
1348
- if (!this.#streams.has(obj.location.group)) {
1349
- await this.#lock.acquire();
1350
- if (!this.#streams.has(obj.location.group)) {
1351
- const writeStream = await this.client.webTransport.createUnidirectionalStream({ sendOrder: this.#streamPriority });
1352
- const firstObject = this.#highestGroupSeen === void 0 || obj.location.group > this.#highestGroupSeen;
1353
- const headerType = obj.getSubgroupHeaderType(true, false, firstObject);
1354
- let subgroupId;
1355
- if (require_model.SubgroupHeaderType.hasExplicitSubgroupId(headerType)) subgroupId = obj.subgroupId;
1356
- const header = new require_model.SubgroupHeader(headerType, this.#trackAlias, obj.location.group, subgroupId, this.#publisherPriority);
1357
- const sendStream = await SendStream.new(writeStream, header);
1358
- this.#streams.set(obj.location.group, sendStream);
1359
- this.#streamsOpened++;
1360
- this.#markGroupSeen(obj.location.group);
1361
- }
1362
- await this.#lock.release();
1363
- }
1364
- const sendStream = this.#streams.get(obj.location.group);
1365
- await this.#lock.acquire();
1366
- await sendStream.write(obj.tryIntoSubgroupObject());
1367
- await this.#lock.release();
1368
- if (this.#endGroup && obj.location.group === this.#endGroup) {
1369
- try {
1370
- await this.#lock.acquire();
1371
- if (this.#streams.has(obj.location.group)) {
1372
- await sendStream.close();
1373
- this.#streams.delete(obj.location.group);
1374
- }
1375
- await this.#lock.release();
1376
- } catch (err) {
1377
- require_logger.logger.warn("publication/subscribe", "error in closing stream: id, endGroup, err", this.#id, this.#endGroup, err);
1378
- }
1379
- await this.done(3);
1380
- this.cancel();
1381
- } else if (this.latestLocation && this.latestLocation.group !== obj.location.group) {
1382
- const prevGroup = this.latestLocation.group;
1383
- try {
1384
- await this.#lock.acquire();
1385
- const prevStream = this.#streams.get(prevGroup);
1386
- if (prevStream) {
1387
- try {
1388
- await prevStream.close();
1389
- } catch (err) {
1390
- require_logger.logger.warn("publication/subscribe", "error in closing stream", prevGroup, err);
1391
- }
1392
- this.#streams.delete(prevGroup);
1393
- }
1394
- await this.#lock.release();
1395
- } catch (err) {
1396
- require_logger.logger.warn("publication/subscribe", "error in closing stream: id, latestLocation.group, err", this.#id, this.latestLocation.group, err);
1397
- }
1398
- }
1399
- await this.#lock.acquire();
1400
- this.latestLocation = obj.location;
1401
- await this.#lock.release();
1402
- } catch (err) {
1403
- this.cancel();
1404
- throw err;
1405
- }
1406
- });
1407
- }
1408
- };
1409
- //#endregion
1410
- //#region src/client/publication/fetch.ts
1411
- /**
1412
- * Copyright 2025 The MOQtail Authors
1413
- *
1414
- * Licensed under the Apache License, Version 2.0 (the "License");
1415
- * you may not use this file except in compliance with the License.
1416
- * You may obtain a copy of the License at
1417
- *
1418
- * http://www.apache.org/licenses/LICENSE-2.0
1419
- *
1420
- * Unless required by applicable law or agreed to in writing, software
1421
- * distributed under the License is distributed on an "AS IS" BASIS,
1422
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1423
- * See the License for the specific language governing permissions and
1424
- * limitations under the License.
1425
- */
1426
- var FetchPublication = class {
1427
- #requestId;
1428
- #track;
1429
- #startLocation;
1430
- #endLocation;
1431
- #msg;
1432
- #client;
1433
- #stream;
1434
- #writer;
1435
- #objects;
1436
- #isCanceled = false;
1437
- constructor(client, track, fetchRequest) {
1438
- this.#client = client;
1439
- this.#requestId = fetchRequest.requestId;
1440
- this.#track = track;
1441
- this.#msg = fetchRequest;
1442
- let joiningRequest;
1443
- switch (this.#msg.typeAndProps.type) {
1444
- case 1:
1445
- this.#startLocation = this.#msg.typeAndProps.props.startLocation;
1446
- this.#endLocation = this.#msg.typeAndProps.props.endLocation;
1447
- break;
1448
- case 2:
1449
- joiningRequest = client.publications.get(this.#msg.typeAndProps.props.joiningRequestId);
1450
- if (!(joiningRequest instanceof SubscribePublication)) throw new require_model.InternalError("FetchPublication.constructor", "No subscription for the joining request id");
1451
- if (!joiningRequest.latestLocation) throw new require_model.InternalError("FetchPublication.constructor", "joiningRequest.largestLocation does not exist");
1452
- this.#startLocation = new require_model.Location(joiningRequest.latestLocation.group - this.#msg.typeAndProps.props.joiningStart, 0n);
1453
- this.#endLocation = joiningRequest.latestLocation;
1454
- break;
1455
- case 3:
1456
- joiningRequest = client.publications.get(this.#msg.typeAndProps.props.joiningRequestId);
1457
- if (!(joiningRequest instanceof SubscribePublication)) throw new require_model.InternalError("FetchPublication.constructor", "No subscription for the joining request id");
1458
- if (!joiningRequest.latestLocation) throw new require_model.InternalError("FetchPublication.constructor", "joiningRequest.largestLocation does not exist");
1459
- this.#startLocation = new require_model.Location(this.#msg.typeAndProps.props.joiningStart, 0n);
1460
- this.#endLocation = joiningRequest.latestLocation;
1461
- break;
1462
- }
1463
- require_logger.logger.debug("publication/fetch", `created requestId=${this.#requestId} type=${this.#msg.typeAndProps.type}`);
1464
- this.publish();
1465
- }
1466
- cancel() {
1467
- require_logger.logger.debug("publication/fetch", `canceled requestId=${this.#requestId}`);
1468
- this.#isCanceled = true;
1469
- }
1470
- /**
1471
- * Resets the data stream this fetch is being delivered on, which §10.9.1 requires when
1472
- * a REQUEST_UPDATE for a FETCH fails.
1473
- */
1474
- async resetDataStream(code) {
1475
- require_logger.logger.debug("publication/fetch", `reset data stream requestId=${this.#requestId} code=${code}`);
1476
- this.#isCanceled = true;
1477
- await this.#writer?.abort(streamResetReason(code)).catch(() => {});
1478
- }
1479
- async publish() {
1480
- if (this.#isCanceled) return;
1481
- if (!this.#track.trackSource.past) throw new require_model.MOQtailError("FetchPublication.publish, Track does not support fetch");
1482
- require_logger.logger.debug("publication/fetch", `publishing requestId=${this.#requestId} start=${this.#startLocation} end=${this.#endLocation}`);
1483
- try {
1484
- this.#objects = await this.#track.trackSource.past.getRange(this.#startLocation, this.#endLocation);
1485
- this.#stream = await this.#client.webTransport.createUnidirectionalStream();
1486
- this.#writer = this.#stream.getWriter();
1487
- const header = new require_model.FetchHeader(5, this.#requestId);
1488
- await this.#writer.write(header);
1489
- const groupOrder = require_model.MessageParameter.groupOrderOf(this.#msg.parameters);
1490
- let fetchPrevCtx = void 0;
1491
- for (const obj of this.#objects) {
1492
- if (this.#isCanceled) {
1493
- require_logger.logger.debug("publication/fetch", `aborted during publish requestId=${this.#requestId}`);
1494
- await this.#writer.abort(streamResetReason(1));
1495
- this.#client.publications.delete(this.#requestId);
1496
- return;
1497
- }
1498
- const fetchObj = obj.tryIntoFetchObject();
1499
- await this.#writer.write(fetchObj.serialize(fetchPrevCtx, groupOrder).toUint8Array());
1500
- const newCtx = fetchObj.toContext();
1501
- if (newCtx) fetchPrevCtx = newCtx;
1502
- }
1503
- await this.#writer.close();
1504
- require_logger.logger.debug("publication/fetch", `published requestId=${this.#requestId} objects=${this.#objects.length}`);
1505
- this.#client.publications.delete(this.#requestId);
1506
- } catch (error) {
1507
- if (this.#isCanceled) return;
1508
- await this.#writer?.abort(streamResetReason(0));
1509
- const message = error instanceof Error ? error.message : String(error);
1510
- require_logger.logger.error("publication/fetch", `publish failed requestId=${this.#requestId}`, message);
1511
- throw new require_model.InternalError("FetchPublication.publish", `Failed to publish: ${message}`);
1512
- }
1513
- }
1514
- };
1515
- //#endregion
1516
- //#region src/client/handler/fetch.ts
1517
- /**
1518
- * Copyright 2025 The MOQtail Authors
1519
- *
1520
- * Licensed under the Apache License, Version 2.0 (the "License");
1521
- * you may not use this file except in compliance with the License.
1522
- * You may obtain a copy of the License at
1523
- *
1524
- * http://www.apache.org/licenses/LICENSE-2.0
1525
- *
1526
- * Unless required by applicable law or agreed to in writing, software
1527
- * distributed under the License is distributed on an "AS IS" BASIS,
1528
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1529
- * See the License for the specific language governing permissions and
1530
- * limitations under the License.
1531
- */
1532
- const handlerFetch = async (client, msg, stream) => {
1533
- require_logger.logger.log("handler/fetch", "requestId, type", msg.requestId, msg.typeAndProps.type);
1534
- let fullTrackName;
1535
- let joiningRequest;
1536
- switch (msg.typeAndProps.type) {
1537
- case 1:
1538
- fullTrackName = msg.typeAndProps.props.fullTrackName;
1539
- break;
1540
- case 2:
1541
- case 3:
1542
- joiningRequest = client.publications.get(msg.typeAndProps.props.joiningRequestId);
1543
- if (!(joiningRequest instanceof SubscribePublication)) throw new require_model.InternalError("handlerFetch", "No subscription for the joining request id");
1544
- fullTrackName = joiningRequest.track.fullTrackName;
1545
- break;
1546
- }
1547
- const track = client.trackSources.get(fullTrackName.toString());
1548
- if (!track) {
1549
- const response = new require_model.RequestError(16, 0n, new require_model.ReasonPhrase("Track does not exists"));
1550
- await stream.send(response);
1551
- return;
1552
- }
1553
- if (!track.trackSource.past) {
1554
- const response = new require_model.RequestError(3, 0n, new require_model.ReasonPhrase("Requested track does not support fetch"));
1555
- await stream.send(response);
1556
- return;
1557
- }
1558
- const publication = new FetchPublication(client, track, msg);
1559
- client.publications.set(msg.requestId, publication);
1560
- const response = new require_model.FetchOk(false, new require_model.Location(0n, 0n), msg.parameters, track.trackProperties ?? []);
1561
- await stream.send(response);
1562
- };
1563
- //#endregion
1564
- //#region src/client/handler/fetch_ok.ts
1565
- /**
1566
- * Copyright 2025 The MOQtail Authors
1567
- *
1568
- * Licensed under the Apache License, Version 2.0 (the "License");
1569
- * you may not use this file except in compliance with the License.
1570
- * You may obtain a copy of the License at
1571
- *
1572
- * http://www.apache.org/licenses/LICENSE-2.0
1573
- *
1574
- * Unless required by applicable law or agreed to in writing, software
1575
- * distributed under the License is distributed on an "AS IS" BASIS,
1576
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1577
- * See the License for the specific language governing permissions and
1578
- * limitations under the License.
1579
- */
1580
- const handlerFetchOk = async (client, msg, _stream, requestId) => {
1581
- require_logger.logger.log("handler/fetch_ok", "requestId", requestId);
1582
- const request = client.requests.get(requestId);
1583
- if (request instanceof FetchRequest) {
1584
- if (msg.trackProperties.length > 0) {
1585
- const fetchMsg = request.message;
1586
- let fullTrackName = fetchMsg.typeAndProps.type === 1 ? fetchMsg.typeAndProps.props.fullTrackName : (() => {
1587
- const joiningReq = client.requests.get(fetchMsg.typeAndProps.props.joiningRequestId);
1588
- return joiningReq instanceof SubscribeRequest ? joiningReq.fullTrackName : void 0;
1589
- })();
1590
- if (fullTrackName !== void 0) {
1591
- const track = client.trackSources.get(fullTrackName.toString());
1592
- if (track !== void 0) track.trackProperties = msg.trackProperties;
1593
- }
1594
- }
1595
- request.resolve(msg);
1596
- } else throw new require_model.ProtocolViolationError("handlerFetchOk", `FETCH_OK on a stream with no pending fetch request (request id ${requestId})`);
1597
- };
1598
- //#endregion
1599
- //#region src/client/handler/goaway.ts
1600
- const handlerGoAway = async (client, msg) => {
1601
- require_logger.logger.log("handler/goaway", "newSessionUri", msg.newSessionUri, "timeout", msg.timeout, "requestId", msg.requestId);
1602
- if (client.goawayReceived) {
1603
- await client.disconnect(new require_model.ProtocolViolationError("handler/goaway", "A second GOAWAY arrived on the control stream"));
1604
- return;
1976
+ if (!this.#isStarted && this.#startLocation.compare(obj.location) <= 0) this.#isStarted = true;
1977
+ if (!this.#isStarted) this.#markGroupSeen(obj.location.group);
1978
+ if (this.#isStarted && this.#endLocation && obj.location.compare(this.#endLocation) > 0) {
1979
+ this.#markGroupSeen(obj.location.group);
1980
+ if (this.latestLocation) await this.#closeGroupStream(this.latestLocation.group);
1981
+ return;
1982
+ }
1983
+ if (!this.#isStarted) return;
1984
+ const subgroupId = this.#subgroupIds.of(obj);
1985
+ if (!this.#filter.matches(obj, subgroupId)) {
1986
+ this.#markGroupSeen(obj.location.group);
1987
+ if (this.latestLocation && this.latestLocation.group !== obj.location.group) await this.#closeGroupStream(this.latestLocation.group);
1988
+ return;
1989
+ }
1990
+ try {
1991
+ if (!this.#streams.has(obj.location.group)) {
1992
+ await this.#lock.acquire();
1993
+ if (!this.#streams.has(obj.location.group)) {
1994
+ const writeStream = await this.client.webTransport.createUnidirectionalStream({ sendOrder: this.#streamPriority });
1995
+ const firstObject = this.#highestGroupSeen === void 0 || obj.location.group > this.#highestGroupSeen;
1996
+ const header = subgroupHeaderFor(obj, subgroupId ?? obj.location.object, this.#trackAlias, this.#publisherPriority, firstObject);
1997
+ const sendStream = await SendStream.new(writeStream, header, this.client.onDataSent, void 0, this.client.dataStreamObserver(() => this.track.fullTrackName));
1998
+ this.#streams.set(obj.location.group, sendStream);
1999
+ this.#streamsOpened++;
2000
+ this.#markGroupSeen(obj.location.group);
2001
+ }
2002
+ await this.#lock.release();
2003
+ }
2004
+ const sendStream = this.#streams.get(obj.location.group);
2005
+ await this.#lock.acquire();
2006
+ await sendStream.write(obj.tryIntoSubgroupObject());
2007
+ await this.#lock.release();
2008
+ if (this.#endLocation && obj.location.equals(this.#endLocation)) await this.#closeGroupStream(obj.location.group);
2009
+ else if (this.latestLocation && this.latestLocation.group !== obj.location.group) await this.#closeGroupStream(this.latestLocation.group);
2010
+ await this.#lock.acquire();
2011
+ this.latestLocation = obj.location;
2012
+ await this.#lock.release();
2013
+ } catch (err) {
2014
+ this.cancel();
2015
+ throw err;
2016
+ }
2017
+ });
1605
2018
  }
1606
- client.goawayReceived = true;
1607
- if (client.onGoaway) client.onGoaway(msg);
1608
- };
1609
- /**
1610
- * GOAWAY on a request stream: the peer is migrating that one request (§10.4). The
1611
- * request is re-issued on a fresh stream and the session, along with every other request
1612
- * on it, carries on.
1613
- */
1614
- const handlerGoAwayOnRequestStream = async (client, msg, _stream, requestId) => {
1615
- require_logger.logger.log("handler/goaway", `GOAWAY migrating request ${requestId}`, "timeout", msg.timeout);
1616
- await client.migrateRequest(requestId, msg);
1617
2019
  };
1618
2020
  //#endregion
1619
- //#region src/client/util/validators.ts
1620
- /**
1621
- * Copyright 2026 The MOQtail Authors
1622
- *
1623
- * Licensed under the Apache License, Version 2.0 (the "License");
1624
- * you may not use this file except in compliance with the License.
1625
- * You may obtain a copy of the License at
1626
- *
1627
- * http://www.apache.org/licenses/LICENSE-2.0
1628
- *
1629
- * Unless required by applicable law or agreed to in writing, software
1630
- * distributed under the License is distributed on an "AS IS" BASIS,
1631
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1632
- * See the License for the specific language governing permissions and
1633
- * limitations under the License.
1634
- */
1635
- /** Returns true when `trackAlias` is a valid (non-negative) track alias. Zero is a legal value. */
1636
- function isValidTrackAlias(trackAlias) {
1637
- return trackAlias !== void 0 && trackAlias >= 0n;
1638
- }
1639
- //#endregion
1640
2021
  //#region src/client/handler/subscribe.ts
1641
2022
  /**
1642
2023
  * Copyright 2025 The MOQtail Authors
@@ -1655,6 +2036,12 @@ function isValidTrackAlias(trackAlias) {
1655
2036
  */
1656
2037
  const handlerSubscribe = async (client, msg, stream) => {
1657
2038
  require_logger.logger.debug("handler/subscribe", `received requestId=${msg.requestId} ftn="${msg.fullTrackName}"`);
2039
+ const filterRejection = rangeFilterRejection(msg.parameters, client.maxFilterRanges);
2040
+ if (filterRejection) {
2041
+ require_logger.logger.warn("handler/subscribe", `requestId=${msg.requestId} has filters this client cannot take: ${filterRejection.reasonPhrase.phrase}`);
2042
+ await stream.send(filterRejection);
2043
+ return;
2044
+ }
1658
2045
  const track = client.trackSources.get(msg.fullTrackName.toString());
1659
2046
  if (!track) {
1660
2047
  require_logger.logger.error("handler/subscribe", `requestId=${msg.requestId} ftn="${msg.fullTrackName}" — track not found, sending REQUEST_ERROR`);
@@ -1670,10 +2057,10 @@ const handlerSubscribe = async (client, msg, stream) => {
1670
2057
  }
1671
2058
  if (!isValidTrackAlias(track.trackAlias)) throw new Error("Expected track alias to be set");
1672
2059
  const largestLocation = track.trackSource.live.largestLocation;
1673
- const parameters = [...msg.parameters];
1674
- if (largestLocation) parameters.push(new require_model.LargestObject(largestLocation));
2060
+ const parameters = largestLocation ? [new require_model.LargestObject(largestLocation)] : [];
2061
+ const trackProperties = require_model.MessageParameter.includesProperties(msg.parameters) ? track.trackProperties ?? [] : [];
1675
2062
  require_logger.logger.debug("handler/subscribe", `requestId=${msg.requestId} ftn="${msg.fullTrackName}" trackAlias=${track.trackAlias} largestLocation=${largestLocation ? `${largestLocation.group}:${largestLocation.object}` : "none"} — sending SUBSCRIBE_OK`);
1676
- const subscribeOk = require_model.SubscribeOk.create(track.trackAlias, parameters, track.trackProperties ?? []);
2063
+ const subscribeOk = require_model.SubscribeOk.create(track.trackAlias, parameters, trackProperties);
1677
2064
  const publication = new SubscribePublication(client, track, msg, stream, largestLocation);
1678
2065
  client.publications.set(msg.requestId, publication);
1679
2066
  await stream.send(subscribeOk);
@@ -1720,6 +2107,20 @@ const handlerSubscribeNamespace = async (client, msg, stream) => {
1720
2107
  */
1721
2108
  const handlerSubscribeTracks = async (client, msg, stream) => {
1722
2109
  require_logger.logger.log("handler/subscribe_tracks", "prefix", msg.trackNamespacePrefix.toUtf8Path());
2110
+ if (require_model.MessageParameter.carriesRangeFilter(msg.parameters)) {
2111
+ let code = 3;
2112
+ let reason = "Range filters on SUBSCRIBE_TRACKS are not supported";
2113
+ try {
2114
+ assertWithinFilterRangeLimit(msg.parameters, client.maxFilterRanges, "SUBSCRIBE_TRACKS");
2115
+ } catch (error) {
2116
+ if (!(error instanceof require_model.InvalidFilterError)) throw error;
2117
+ code = 54;
2118
+ reason = error.details;
2119
+ }
2120
+ require_logger.logger.warn("handler/subscribe_tracks", `requestId=${msg.requestId} refused: ${reason}`);
2121
+ await stream.send(new require_model.RequestError(code, 0n, new require_model.ReasonPhrase(reason)));
2122
+ return;
2123
+ }
1723
2124
  if (client.onPeerSubscribeTracks) client.onPeerSubscribeTracks(msg);
1724
2125
  await stream.send(new require_model.RequestOk());
1725
2126
  };
@@ -1833,6 +2234,15 @@ var PublishPublication = class {
1833
2234
  */
1834
2235
  #parameters;
1835
2236
  /**
2237
+ * What the subscriber's Range Filters let through. A PUBLISH carries none, so this
2238
+ * passes everything until a REQUEST_UPDATE says otherwise.
2239
+ */
2240
+ #filter = new require_model.CombinedFilter([]);
2241
+ /**
2242
+ * The Subgroup ID of each Object, which the filter and the stream header need.
2243
+ */
2244
+ #subgroupIds = new SubgroupIds();
2245
+ /**
1836
2246
  * Highest group this publication has already opened a stream for or skipped objects of.
1837
2247
  * A stream for a group at or below it reopens a subgroup, so it cannot claim FIRST_OBJECT.
1838
2248
  */
@@ -1879,14 +2289,20 @@ var PublishPublication = class {
1879
2289
  this.client.onForwardStateChange?.(this.publishMsg.requestId, forward);
1880
2290
  }
1881
2291
  /**
1882
- * Applies a REQUEST_UPDATE the peer sent on this publication's request stream. The
1883
- * Forward State is the one thing it can move; what a publisher sends, and when,
1884
- * is otherwise its own to decide.
2292
+ * Applies a REQUEST_UPDATE the peer sent on this publication's request stream. It
2293
+ * can move the Forward State and the Range Filters; what a publisher sends, and
2294
+ * when, is otherwise its own to decide.
2295
+ * @throws :{@link InvalidFilterError} If the Range Filters the publication would be
2296
+ * left with cannot be applied; nothing is updated.
1885
2297
  */
1886
2298
  update(msg) {
2299
+ const parameters = [...this.#parameters];
2300
+ require_model.applyMessageParameterUpdate(parameters, msg.parameters);
2301
+ assertWithinFilterRangeLimit(parameters, this.client.maxFilterRanges, "REQUEST_UPDATE");
2302
+ this.#filter = new require_model.CombinedFilter(parameters);
2303
+ this.#parameters = parameters;
1887
2304
  const forward = msg.parameters.find(require_model.MessageParameter.isForward);
1888
2305
  if (forward) this.setForwardState(forward.forward);
1889
- require_model.applyMessageParameterUpdate(this.#parameters, msg.parameters);
1890
2306
  }
1891
2307
  /**
1892
2308
  * Calculates the stream priority based on publisher priority.
@@ -1927,21 +2343,24 @@ var PublishPublication = class {
1927
2343
  this.#highestGroupSeen = this.track.trackSource.live.largestLocation?.group;
1928
2344
  this.#cancelPublishing = this.track.trackSource.live.onNewObject(async (obj) => {
1929
2345
  if (this.#isCompleted) return;
2346
+ this.#subgroupIds.note(obj);
1930
2347
  if (!this.#forward) {
1931
2348
  this.#markGroupSeen(obj.location.group);
1932
2349
  return;
1933
2350
  }
2351
+ const subgroupId = this.#subgroupIds.of(obj);
2352
+ if (!this.#filter.matches(obj, subgroupId)) {
2353
+ this.#markGroupSeen(obj.location.group);
2354
+ return;
2355
+ }
1934
2356
  try {
1935
2357
  if (!this.#streams.has(obj.location.group)) {
1936
2358
  await this.#lock.acquire();
1937
2359
  if (!this.#streams.has(obj.location.group)) {
1938
2360
  const writeStream = await this.client.webTransport.createUnidirectionalStream({ sendOrder: this.#streamPriority });
1939
2361
  const firstObject = this.#highestGroupSeen === void 0 || obj.location.group > this.#highestGroupSeen;
1940
- const headerType = obj.getSubgroupHeaderType(true, false, firstObject);
1941
- let subgroupId;
1942
- if (require_model.SubgroupHeaderType.hasExplicitSubgroupId(headerType)) subgroupId = obj.subgroupId;
1943
- const header = new require_model.SubgroupHeader(headerType, this.#trackAlias, obj.location.group, subgroupId, this.#publisherPriority);
1944
- const sendStream = await SendStream.new(writeStream, header);
2362
+ const header = subgroupHeaderFor(obj, subgroupId ?? obj.location.object, this.#trackAlias, this.#publisherPriority, firstObject);
2363
+ const sendStream = await SendStream.new(writeStream, header, this.client.onDataSent, void 0, this.client.dataStreamObserver(() => this.track.fullTrackName));
1945
2364
  this.#streams.set(obj.location.group, sendStream);
1946
2365
  this.#streamsOpened++;
1947
2366
  this.#markGroupSeen(obj.location.group);
@@ -1981,6 +2400,44 @@ var PublishPublication = class {
1981
2400
  }
1982
2401
  };
1983
2402
  //#endregion
2403
+ //#region src/client/handler/subscription_response.ts
2404
+ /**
2405
+ * Copyright 2026 The MOQtail Authors
2406
+ *
2407
+ * Licensed under the Apache License, Version 2.0 (the "License");
2408
+ * you may not use this file except in compliance with the License.
2409
+ * You may obtain a copy of the License at
2410
+ *
2411
+ * http://www.apache.org/licenses/LICENSE-2.0
2412
+ *
2413
+ * Unless required by applicable law or agreed to in writing, software
2414
+ * distributed under the License is distributed on an "AS IS" BASIS,
2415
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2416
+ * See the License for the specific language governing permissions and
2417
+ * limitations under the License.
2418
+ */
2419
+ /**
2420
+ * Records what a SUBSCRIBE_OK or REQUEST_UPDATE_OK says about a subscription.
2421
+ * Both carry the same things, so both are read the same way.
2422
+ *
2423
+ * LARGEST_OBJECT is where a fill fetch stream stops, which is how a subscriber
2424
+ * tells a fill that finished from one that was cut short. Track properties, such
2425
+ * as whether the track supports dynamic groups, belong to the track rather than
2426
+ * to this subscription and are recorded there. EXPIRES is kept for callers to
2427
+ * read but nothing acts on it: no subscription expires on a timer here yet.
2428
+ */
2429
+ function applySubscriptionResponse(client, request, parameters, trackProperties) {
2430
+ const largest = parameters.find(require_model.MessageParameter.isLargestObject);
2431
+ if (largest) request.fillBoundary = largest.location;
2432
+ const expires = parameters.find(require_model.MessageParameter.isExpires);
2433
+ if (expires) request.expires = expires.expires;
2434
+ if (trackProperties.length > 0) {
2435
+ require_logger.logger.debug("handler/subscription_response", `requestId=${request.requestId} — applying ${trackProperties.length} track propert(ies)`);
2436
+ const track = client.trackSources.get(request.fullTrackName.toString());
2437
+ if (track !== void 0) track.trackProperties = trackProperties;
2438
+ }
2439
+ }
2440
+ //#endregion
1984
2441
  //#region src/client/handler/request_ok.ts
1985
2442
  const handlerRequestOk = async (client, msg, _stream, requestId) => {
1986
2443
  require_logger.logger.log("handler/request_ok", "received RequestOk for requestId:", requestId);
@@ -2002,10 +2459,11 @@ const handlerRequestOk = async (client, msg, _stream, requestId) => {
2002
2459
  require_logger.logger.warn("handler/request_ok", `Live track source not found for ${fullTrackName.toString()}`);
2003
2460
  return;
2004
2461
  }
2005
- const publication = new PublishPublication(client, track, request.message);
2006
- client.publications.set(requestId, publication);
2007
- const forward = msg.parameters.find(require_model.MessageParameter.isForward);
2008
- if (forward) publication.setForwardState(forward.forward);
2462
+ client.publications.set(requestId, new PublishPublication(client, track, request.message));
2463
+ return;
2464
+ }
2465
+ if (request instanceof SubscribeRequest) {
2466
+ applySubscriptionResponse(client, request, msg.parameters, msg.trackProperties);
2009
2467
  return;
2010
2468
  }
2011
2469
  if (request instanceof PublishNamespaceRequest || request instanceof SubscribeNamespaceRequest || request instanceof TrackStatusRequest) {
@@ -2033,7 +2491,10 @@ const handlerRequestError = async (client, msg, _stream, requestId) => {
2033
2491
  const handlerPublishDone = async (client, msg, _stream, openingRequestId) => {
2034
2492
  if (client.onPeerPublishDone) client.onPeerPublishDone(msg, openingRequestId);
2035
2493
  const request = client.requests.get(openingRequestId);
2036
- if (request instanceof SubscribeRequest) request.expectedStreams = msg.streamCount;
2494
+ if (request instanceof SubscribeRequest) {
2495
+ request.expectedStreams = msg.streamCount;
2496
+ client.completeSubscription(request);
2497
+ }
2037
2498
  };
2038
2499
  //#endregion
2039
2500
  //#region src/client/handler/subscribe_ok.ts
@@ -2056,11 +2517,7 @@ const handlerSubscribeOk = async (client, msg, _stream, requestId) => {
2056
2517
  require_logger.logger.debug("handler/subscribe_ok", `received requestId=${requestId} trackAlias=${msg.trackAlias}`);
2057
2518
  const request = client.requests.get(requestId);
2058
2519
  if (request instanceof SubscribeRequest) {
2059
- if (msg.trackProperties.length > 0) {
2060
- require_logger.logger.debug("handler/subscribe_ok", `requestId=${requestId} — applying ${msg.trackProperties.length} track propert(ies)`);
2061
- const track = client.trackSources.get(request.fullTrackName.toString());
2062
- if (track !== void 0) track.trackProperties = msg.trackProperties;
2063
- }
2520
+ applySubscriptionResponse(client, request, msg.parameters, msg.trackProperties);
2064
2521
  require_logger.logger.debug("handler/subscribe_ok", `requestId=${requestId} — resolving SubscribeRequest ftn="${request.fullTrackName}"`);
2065
2522
  request.resolve(msg);
2066
2523
  } else {
@@ -2087,37 +2544,54 @@ const handlerSubscribeOk = async (client, msg, _stream, requestId) => {
2087
2544
  */
2088
2545
  /**
2089
2546
  * A REQUEST_UPDATE modifies the request whose stream it arrived on, and §10.9 requires
2090
- * exactly one REQUEST_OK or REQUEST_ERROR back on that stream. TRACK_STATUS is no longer
2091
- * one of the updatable request types, so an update naming one is refused.
2547
+ * exactly one REQUEST_OK or REQUEST_ERROR back on that stream. Only the sender of a
2548
+ * request may update it, plus a subscriber on a PUBLISH it was offered. An update
2549
+ * arriving anywhere else, a TRACK_STATUS among them, closes the session.
2092
2550
  */
2093
2551
  const handlerRequestUpdate = async (client, msg, stream, requestId) => {
2094
2552
  require_logger.logger.log("handler/request_update", "requestId", requestId);
2095
- const openingType = stream.openingType;
2096
- if (openingType !== void 0 && !require_model.ControlMessageType.isUpdatable(openingType)) {
2097
- await stream.send(new require_model.RequestError(3, 0n, new require_model.ReasonPhrase("request does not support REQUEST_UPDATE")));
2553
+ if (!isExpectedUpdate(stream)) {
2554
+ await client.disconnect(new require_model.ProtocolViolationError("handler/request_update", `Unexpected REQUEST_UPDATE on a ${stream.first ? "locally" : "peer"} opened ${describe(stream.openingType)} stream`));
2555
+ return;
2556
+ }
2557
+ const filterRejection = rangeFilterRejection(msg.parameters, client.maxFilterRanges);
2558
+ if (filterRejection) {
2559
+ const reason = filterRejection.reasonPhrase.phrase;
2560
+ require_logger.logger.warn("handler/request_update", `requestId=${requestId} has filters this client cannot take: ${reason}`);
2561
+ await failUpdate(client, stream, requestId, 54, reason);
2098
2562
  return;
2099
2563
  }
2100
2564
  const publication = client.publications.get(requestId);
2101
- if (publication instanceof SubscribePublication) {
2565
+ if (publication instanceof SubscribePublication || publication instanceof PublishPublication) {
2102
2566
  try {
2103
2567
  publication.update(msg);
2104
2568
  } catch (error) {
2569
+ const invalid = error instanceof require_model.InvalidFilterError;
2105
2570
  require_logger.logger.error("handler/request_update", `update failed for requestId=${requestId}`, error);
2106
- await failUpdate(client, stream, requestId, 0, "REQUEST_UPDATE failed");
2571
+ await failUpdate(client, stream, requestId, invalid ? 54 : 0, invalid ? error.details : "REQUEST_UPDATE failed");
2107
2572
  return;
2108
2573
  }
2109
2574
  await stream.send(new require_model.RequestOk());
2110
2575
  return;
2111
2576
  }
2112
- if (publication instanceof PublishPublication) {
2113
- publication.update(msg);
2114
- await stream.send(new require_model.RequestOk());
2115
- return;
2116
- }
2117
2577
  require_logger.logger.warn("handler/request_update", `no updatable request for requestId=${requestId}`);
2118
2578
  await failUpdate(client, stream, requestId, 3, "REQUEST_UPDATE cannot be applied");
2119
2579
  };
2120
2580
  /**
2581
+ * Whether the peer may send a REQUEST_UPDATE on this stream. On a stream the peer
2582
+ * opened, it is the requester and may update any of the updatable request types. On a
2583
+ * stream this side opened, it may only update a PUBLISH, as that PUBLISH's subscriber.
2584
+ */
2585
+ function isExpectedUpdate(stream) {
2586
+ const openingType = stream.openingType;
2587
+ if (openingType === void 0) return false;
2588
+ if (stream.first) return openingType === 29;
2589
+ return require_model.ControlMessageType.isUpdatable(openingType);
2590
+ }
2591
+ function describe(openingType) {
2592
+ return openingType === void 0 ? "unknown" : require_model.ControlMessageType[openingType];
2593
+ }
2594
+ /**
2121
2595
  * Refuses the update, then ends the request the way §10.9.1 requires for its type: a
2122
2596
  * subscription is terminated with PUBLISH_DONE(UPDATE_FAILED), a FETCH has its data
2123
2597
  * stream reset, and a namespace request has its bidi stream closed.
@@ -2186,7 +2660,7 @@ const handlerTrackStatus = async (_client, msg, stream) => {
2186
2660
  * limitations under the License.
2187
2661
  */
2188
2662
  /**
2189
- * Draft-18 §3.3: the control stream carries SETUP and GOAWAY, nothing else. SETUP is
2663
+ * The control stream carries SETUP and GOAWAY, nothing else. SETUP is
2190
2664
  * consumed by the handshake in {@link MOQtailClient.new}, so GOAWAY is all that reaches
2191
2665
  * the read loop. Every request type has moved to its own bidi stream — see
2192
2666
  * {@link getHandlerForRequestStreamMessage}.
@@ -2214,7 +2688,7 @@ function getHandlerForRequestStreamMessage(msg) {
2214
2688
  if (msg instanceof require_model.GoAway) return handlerGoAwayOnRequestStream;
2215
2689
  if (msg instanceof require_model.RequestUpdate) return handlerRequestUpdate;
2216
2690
  if (msg instanceof require_model.PublishDone) return handlerPublishDone;
2217
- if (msg instanceof require_model.PublishBlocked) return handlerPublishBlocked;
2691
+ if (msg instanceof require_model.PublishSkipped) return handlerPublishSkipped;
2218
2692
  }
2219
2693
  //#endregion
2220
2694
  //#region src/client/util/random_id.ts
@@ -2450,7 +2924,7 @@ var RecvDatagramStream = class RecvDatagramStream {
2450
2924
  * const client = await MOQtailClient.new({ url });
2451
2925
  * const result = await client.subscribe({
2452
2926
  * fullTrackName,
2453
- * filterType: FilterType.LatestObject,
2927
+ * locationFilter: new LocationFilter(LocationFilterType.NextObject),
2454
2928
  * forward: true,
2455
2929
  * groupOrder: GroupOrder.Original,
2456
2930
  * priority: 0
@@ -2526,23 +3000,17 @@ var MOQtailClient = class MOQtailClient {
2526
3000
  */
2527
3001
  aliasFullTrackNameMap = /* @__PURE__ */ new Map();
2528
3002
  /**
2529
- * Pending state updates keyed by requestId and applied once a new track alias is seen.
2530
- * Used to avoid premature state updates.
2531
- */
2532
- pendingStateUpdates = /* @__PURE__ */ new Map();
2533
- /**
2534
3003
  * The bidirectional request stream each locally issued request runs on, keyed by the
2535
- * requestId of the message that opened it (draft-18 §3.3.2). The stream stays open for
3004
+ * requestId of the message that opened it. The stream stays open for
2536
3005
  * the request's lifetime: responses and follow-ups arrive on it, updates are written to
2537
3006
  * it, and closing it is how the request is cancelled.
2538
3007
  */
2539
3008
  #requestStreams = /* @__PURE__ */ new Map();
2540
3009
  /**
2541
- * Request ids of requests re-issued after a per-request GOAWAY (§10.4), which consumes
3010
+ * Request ids of requests re-issued after a per-request GOAWAY, which consumes
2542
3011
  * a fresh Request ID each time (§10.1). The id the caller was given stays the client's
2543
3012
  * key for the request; these two maps translate it to and from the id now on the wire.
2544
3013
  */
2545
- #wireRequestIds = /* @__PURE__ */ new Map();
2546
3014
  #clientRequestIds = /* @__PURE__ */ new Map();
2547
3015
  /**
2548
3016
  * Namespace path -\> the requestId that announced or subscribed to it, so the
@@ -2554,6 +3022,8 @@ var MOQtailClient = class MOQtailClient {
2554
3022
  webTransport;
2555
3023
  /** Validated Setup message the server sent back during handshake (protocol parameters negotiated). */
2556
3024
  #serverSetup;
3025
+ /** How many filter ranges this client allows the server per request, as advertised in SETUP. */
3026
+ #maxFilterRanges = 0n;
2557
3027
  /** Outgoing / incoming control message stream pair. */
2558
3028
  controlStream;
2559
3029
  /** Reader over incoming uni streams: the control recv half first, data streams after. */
@@ -2562,6 +3032,21 @@ var MOQtailClient = class MOQtailClient {
2562
3032
  dataStreamTimeoutMs;
2563
3033
  /** Timeout (ms) for control stream read operations; undefined =\> no explicit timeout. */
2564
3034
  controlStreamTimeoutMs;
3035
+ /**
3036
+ * How long (ms) an incoming data stream waits for the control message that establishes
3037
+ * its track alias before the stream is abandoned.
3038
+ */
3039
+ trackAliasResolutionTimeoutMs = DEFAULT_TRACK_ALIAS_RESOLUTION_TIMEOUT_MS;
3040
+ /**
3041
+ * How long (ms) a track a soft switch handed over from may stay quiet before it is
3042
+ * retired anyway, if no PUBLISH_DONE ends its drain first.
3043
+ */
3044
+ switchDrainTimeoutMs = DEFAULT_SWITCH_DRAIN_TIMEOUT_MS;
3045
+ /**
3046
+ * Callbacks waiting for a track alias to be registered, keyed by alias. Each entry
3047
+ * belongs to a data stream that arrived before the control message naming its alias.
3048
+ */
3049
+ #aliasWaiters = /* @__PURE__ */ new Map();
2565
3050
  /** Flag indicating the client has been disconnected/destroyed and cannot accept further API calls. */
2566
3051
  #isDestroyed = false;
2567
3052
  /** Internal monotonically increasing client-assigned request id counter (even/odd parity scheme advances by 2). */
@@ -2583,7 +3068,7 @@ var MOQtailClient = class MOQtailClient {
2583
3068
  onGoaway;
2584
3069
  /**
2585
3070
  * Whether the peer has sent a GOAWAY on the control stream. Once it has, this side
2586
- * should not start new requests (§10.4); a second one closes the session with
3071
+ * should not start new requests; a second one closes the session with
2587
3072
  * PROTOCOL_VIOLATION.
2588
3073
  */
2589
3074
  goawayReceived = false;
@@ -2624,6 +3109,13 @@ var MOQtailClient = class MOQtailClient {
2624
3109
  */
2625
3110
  onDataSent;
2626
3111
  /**
3112
+ * Invoked for every data stream this client opens or accepts: once for its header, once
3113
+ * per object (identity and payload length only), and once when the stream ends.
3114
+ * Use for counters and diagnostics.
3115
+ * Informational event.
3116
+ */
3117
+ onDataEvent;
3118
+ /**
2627
3119
  * General-purpose error callback for surfaced exceptions not thrown to caller synchronously.
2628
3120
  * Use to log or display errors.
2629
3121
  * Error handler.
@@ -2654,15 +3146,28 @@ var MOQtailClient = class MOQtailClient {
2654
3146
  onForwardStateChange;
2655
3147
  /** Fired when an inbound SUBSCRIBE_NAMESPACE control message is received. */
2656
3148
  onPeerSubscribeNamespace;
2657
- /** Fired when an inbound SUBSCRIBE_TRACKS control message is received. */
3149
+ /**
3150
+ * Fired when an inbound SUBSCRIBE_TRACKS control message is received. The PUBLISH
3151
+ * sent for each matching track:
3152
+ * - states the request's settings as its parameters, from
3153
+ * `MessageParameter.publishParametersFor(msg.parameters)`: FORWARD, GROUP_ORDER and
3154
+ * the LOCATION_FILTER the subscription starts from, but never the request's
3155
+ * AUTHORIZATION_TOKEN;
3156
+ * - goes without Track Properties when
3157
+ * `MessageParameter.includesProperties(msg.parameters)` is false.
3158
+ *
3159
+ * A request carrying FILL_PARAMETERS also asks for a fill of what each track has
3160
+ * already published. This client cannot open a fill for a pushed track, so such a
3161
+ * subscriber gets only the live Objects.
3162
+ */
2658
3163
  onPeerSubscribeTracks;
2659
3164
  /**
2660
- * Fired when a PUBLISH_BLOCKED arrives on a {@link MOQtailClient.subscribeTracks}
3165
+ * Fired when a PUBLISH_SKIPPED arrives on a {@link MOQtailClient.subscribeTracks}
2661
3166
  * stream: the peer has a matching track but no bidi stream to send its PUBLISH on
2662
3167
  * until its stream limit lifts (§10.20). `prefix` is the prefix this side subscribed
2663
3168
  * with, which is what the message's suffix hangs off.
2664
3169
  */
2665
- onPeerPublishBlocked;
3170
+ onPeerPublishSkipped;
2666
3171
  /** Fired when a NAMESPACE message arrives on a SUBSCRIBE_NAMESPACE bi-stream (prefix + suffix). */
2667
3172
  onPeerNamespace;
2668
3173
  /** Fired when a NAMESPACE_DONE message arrives on a SUBSCRIBE_NAMESPACE bi-stream (prefix + suffix). */
@@ -2709,6 +3214,29 @@ var MOQtailClient = class MOQtailClient {
2709
3214
  return this.#serverSetup;
2710
3215
  }
2711
3216
  /**
3217
+ * How many filter ranges the server allows in one request: its MAX_FILTER_RANGES,
3218
+ * or 0 when it sent none, which allows no Range Filter at all.
3219
+ */
3220
+ /**
3221
+ * How many filter ranges this client allows the server in one request: the
3222
+ * MAX_FILTER_RANGES it advertised, {@link DEFAULT_MAX_FILTER_RANGES} unless the
3223
+ * caller's setup options set one.
3224
+ */
3225
+ get maxFilterRanges() {
3226
+ return this.#maxFilterRanges;
3227
+ }
3228
+ /**
3229
+ * How many filter ranges the server allows in one request: its MAX_FILTER_RANGES,
3230
+ * or 0 when it sent none, which allows no Range Filter at all.
3231
+ */
3232
+ get peerMaxFilterRanges() {
3233
+ for (const pair of this.#serverSetup?.setupOptions ?? []) {
3234
+ const option = require_model.MaxFilterRanges.fromKeyValuePair(pair);
3235
+ if (option) return option.value;
3236
+ }
3237
+ return 0n;
3238
+ }
3239
+ /**
2712
3240
  * Returns true if datagram support is currently active
2713
3241
  */
2714
3242
  get isDatagramsEnabled() {
@@ -2768,6 +3296,7 @@ var MOQtailClient = class MOQtailClient {
2768
3296
  * transportOptions: { congestionControl: 'default' },
2769
3297
  * dataStreamTimeoutMs: 5000,
2770
3298
  * controlStreamTimeoutMs: 2000,
3299
+ * trackAliasResolutionTimeoutMs: 2000,
2771
3300
  * enableDatagrams: true,
2772
3301
  * callbacks: {
2773
3302
  * onMessageSent: msg => console.log('Sent:', msg),
@@ -2779,7 +3308,7 @@ var MOQtailClient = class MOQtailClient {
2779
3308
  * ```
2780
3309
  */
2781
3310
  static async new(args) {
2782
- let { url, setupOptions, transportOptions, dataStreamTimeoutMs, controlStreamTimeoutMs, enableDatagrams, callbacks } = args;
3311
+ let { url, setupOptions, transportOptions, dataStreamTimeoutMs, controlStreamTimeoutMs, trackAliasResolutionTimeoutMs, switchDrainTimeoutMs, enableDatagrams, callbacks } = args;
2783
3312
  const client = new MOQtailClient();
2784
3313
  if (!transportOptions) transportOptions = { protocols: [] };
2785
3314
  if (!transportOptions.protocols) transportOptions = {
@@ -2801,10 +3330,19 @@ var MOQtailClient = class MOQtailClient {
2801
3330
  if (callbacks?.onSessionTerminated) client.onSessionTerminated = callbacks.onSessionTerminated;
2802
3331
  if (callbacks?.onDatagramReceived) client.onDatagramReceived = callbacks.onDatagramReceived;
2803
3332
  if (callbacks?.onDatagramSent) client.onDatagramSent = callbacks.onDatagramSent;
3333
+ if (callbacks?.onDataEvent) client.onDataEvent = callbacks.onDataEvent;
2804
3334
  if (dataStreamTimeoutMs) client.dataStreamTimeoutMs = dataStreamTimeoutMs;
2805
3335
  if (controlStreamTimeoutMs) client.controlStreamTimeoutMs = controlStreamTimeoutMs;
3336
+ if (trackAliasResolutionTimeoutMs !== void 0) client.trackAliasResolutionTimeoutMs = trackAliasResolutionTimeoutMs;
3337
+ if (switchDrainTimeoutMs !== void 0) client.switchDrainTimeoutMs = switchDrainTimeoutMs;
2806
3338
  const sendHalf = new ControlSendStream(await client.webTransport.createUnidirectionalStream({ sendOrder: Number.MAX_SAFE_INTEGER }), client.onMessageSent);
2807
3339
  const params = setupOptions ? setupOptions.build() : new require_model.SetupOptions().build();
3340
+ let maxFilterRanges = params.map((p) => require_model.MaxFilterRanges.fromKeyValuePair(p)).find((o) => o !== void 0);
3341
+ if (!maxFilterRanges) {
3342
+ maxFilterRanges = new require_model.MaxFilterRanges(DEFAULT_MAX_FILTER_RANGES);
3343
+ params.push(maxFilterRanges.toKeyValuePair());
3344
+ }
3345
+ client.#maxFilterRanges = maxFilterRanges.value;
2808
3346
  require_model.assertNoAuthorityOverWebTransport(params);
2809
3347
  await sendHalf.send(new require_model.Setup(params));
2810
3348
  client.#incomingUniStreams = client.webTransport.incomingUnidirectionalStreams.getReader();
@@ -2989,17 +3527,11 @@ var MOQtailClient = class MOQtailClient {
2989
3527
  }
2990
3528
  }
2991
3529
  /**
2992
- * Resolve track alias to full track name using client's request ID map.
2993
- * Falls back to a placeholder if not found.
3530
+ * Resolve track alias to the full track name it was claimed for.
3531
+ * Falls back to a placeholder if no request holds the alias.
2994
3532
  */
2995
3533
  #resolveTrackAlias(trackAlias) {
2996
- try {
2997
- const requestId = this.subscriptionAliasMap.get(trackAlias);
2998
- if (requestId !== void 0) return this.requestIdMap.getNameByRequestId(requestId);
2999
- return require_model.FullTrackName.tryNew("unknown", `track-${trackAlias}`);
3000
- } catch {
3001
- return require_model.FullTrackName.tryNew("unknown", `track-${trackAlias}`);
3002
- }
3534
+ return this.aliasFullTrackNameMap.get(trackAlias) ?? require_model.FullTrackName.tryNew("unknown", `track-${trackAlias}`);
3003
3535
  }
3004
3536
  /**
3005
3537
  * Sets (or replaces) the client-level default early discard policy for incoming subgroup streams.
@@ -3063,7 +3595,7 @@ var MOQtailClient = class MOQtailClient {
3063
3595
  this.#requestStreams.clear();
3064
3596
  this.#namespaceRequestIds.clear();
3065
3597
  await Promise.allSettled(openStreams.map((requestStream) => requestStream.close()));
3066
- if (!this.webTransport.closed) this.webTransport.close();
3598
+ this.webTransport.close();
3067
3599
  if (this.onSessionTerminated) this.onSessionTerminated(new require_model.InternalError("MOQtailClient.disconnect", reason instanceof Error ? reason.message : String(reason)));
3068
3600
  }
3069
3601
  /**
@@ -3144,25 +3676,25 @@ var MOQtailClient = class MOQtailClient {
3144
3676
  *
3145
3677
  * - `forward: true` tells the relay to forward objects to this subscriber as they arrive.
3146
3678
  * - `forward: false` means the relay subscribes upstream but buffers objects locally, not forwarding them to you.
3147
- * - `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
3148
- * observed at the publisher then it behaves as `filterType: LatestObject`
3149
- * - `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
3150
- * observed at the publisher then it behaves as `filterType: LatestObject`.
3679
+ * - `locationFilter` selects which Objects are delivered; omitted, the subscription is unfiltered. An absolute start in the
3680
+ * future waits for that object.
3681
+ * - A {@link FillParameters} in `parameters` also retrieves Objects already published, on a fill fetch stream.
3151
3682
  *
3152
- * The method returns either a {@link RequestError} (on refusal) or an object with the subscription `requestId` and a `ReadableStream` of {@link MoqtObject}s.
3683
+ * The method returns either a {@link RequestError} (on refusal) or an object with the subscription `requestId`, the `trackAlias` and a `ReadableStream` of {@link MoqtObject}s.
3153
3684
  * Use the `requestId` for {@link MOQtailClient.unsubscribe} or {@link MOQtailClient.subscribeUpdate}. Use the `stream` to decode and display objects.
3154
3685
  *
3155
3686
  * @param args - {@link SubscribeOptions} describing the subscription window and relay forwarding behavior.
3156
- * @returns Either a {@link RequestError} or `{ requestId, stream }` for consuming objects.
3687
+ * @returns Either a {@link RequestError} or `{ requestId, trackAlias, stream }` for consuming objects.
3157
3688
  * @throws : {@link MOQtailError} If the client is destroyed.
3158
3689
  * @throws : {@link ProtocolViolationError} If required fields are missing or inconsistent.
3690
+ * @throws : {@link InvalidFilterError} If the Range Filters exceed the server's MAX_FILTER_RANGES; nothing is sent.
3159
3691
  * @throws : {@link InternalError} On transport/protocol failure (disconnect is triggered before rethrow).
3160
3692
  *
3161
3693
  * @example Subscribe to the latest object and receive future objects as they arrive
3162
3694
  * ```ts
3163
3695
  * const result = await client.subscribe({
3164
3696
  * fullTrackName,
3165
- * filterType: FilterType.LatestObject,
3697
+ * locationFilter: new LocationFilter(LocationFilterType.NextObject),
3166
3698
  * forward: true,
3167
3699
  * groupOrder: GroupOrder.Original,
3168
3700
  * priority: 32
@@ -3174,13 +3706,11 @@ var MOQtailClient = class MOQtailClient {
3174
3706
  * }
3175
3707
  * ```
3176
3708
  *
3177
- * @example Subscribe to a future range (waits for those objects to arrive)
3709
+ * @example Subscribe to a future range of groups (waits for those objects to arrive)
3178
3710
  * ```ts
3179
3711
  * const result = await client.subscribe({
3180
3712
  * fullTrackName,
3181
- * filterType: FilterType.AbsoluteRange,
3182
- * startLocation: futureStart,
3183
- * endGroup: futureEnd,
3713
+ * locationFilter: new LocationFilter(LocationFilterType.AbsoluteStartGroupEnd, startGroup, 0n, endGroup),
3184
3714
  * forward: true,
3185
3715
  * groupOrder: GroupOrder.Original,
3186
3716
  * priority: 128
@@ -3189,35 +3719,19 @@ var MOQtailClient = class MOQtailClient {
3189
3719
  */
3190
3720
  async subscribe(args) {
3191
3721
  this.#ensureActive();
3722
+ assertWithinFilterRangeLimit(args.parameters ?? [], this.peerMaxFilterRanges, "MOQtailClient.subscribe");
3192
3723
  try {
3193
- let { fullTrackName, priority, groupOrder, forward, filterType, parameters, startLocation, endGroup } = args;
3194
- require_logger.logger.debug("MOQtailClient", `subscribe: ftn="${fullTrackName}" filterType=${filterType} priority=${priority} forward=${forward} groupOrder=${groupOrder}`);
3195
- let msg;
3196
- if (typeof endGroup === "number") endGroup = BigInt(endGroup);
3197
- const baseParams = [
3724
+ const { fullTrackName, priority, groupOrder, forward, locationFilter, parameters } = args;
3725
+ require_logger.logger.debug("MOQtailClient", `subscribe: ftn="${fullTrackName}" locationFilter=${locationFilter?.filterType} priority=${priority} forward=${forward} groupOrder=${groupOrder}`);
3726
+ const msg = new require_model.Subscribe(this.#nextClientRequestId, fullTrackName, [
3198
3727
  new require_model.SubscriberPriority(priority),
3199
- new require_model.Forward(forward),
3728
+ ...forward !== void 0 ? [new require_model.Forward(forward)] : [],
3200
3729
  ...groupOrder !== 0 ? [new require_model.GroupOrderParam(groupOrder)] : [],
3730
+ ...locationFilter ? [locationFilter] : [],
3201
3731
  ...parameters ?? []
3202
- ];
3203
- switch (filterType) {
3204
- case 2:
3205
- msg = require_model.Subscribe.newLatestObject(this.#nextClientRequestId, fullTrackName, baseParams);
3206
- break;
3207
- case 1:
3208
- msg = require_model.Subscribe.newNextGroupStart(this.#nextClientRequestId, fullTrackName, baseParams);
3209
- break;
3210
- case 3:
3211
- if (!startLocation) throw new require_model.ProtocolViolationError("MOQtailClient.subscribe", "FilterType.AbsoluteStart must have a start location");
3212
- msg = require_model.Subscribe.newAbsoluteStart(this.#nextClientRequestId, fullTrackName, startLocation, baseParams);
3213
- break;
3214
- case 4:
3215
- if (startLocation === void 0 || endGroup === void 0) throw new require_model.ProtocolViolationError("MOQtailClient.subscribe", "FilterType.AbsoluteRange must have a start location and an end group");
3216
- if (endGroup > 0 && startLocation.group >= endGroup) throw new require_model.ProtocolViolationError("MOQtailClient.subscribe", "End group must be greater than start group");
3217
- msg = require_model.Subscribe.newAbsoluteRange(this.#nextClientRequestId, fullTrackName, startLocation, endGroup, baseParams);
3218
- break;
3219
- }
3732
+ ]);
3220
3733
  const request = new SubscribeRequest(msg);
3734
+ request.manager = new Subscription(request);
3221
3735
  request.earlyDiscardPolicy = args.earlyDiscardPolicy;
3222
3736
  this.requests.set(request.requestId, request);
3223
3737
  this.requestIdMap.addMapping(request.requestId, request.fullTrackName);
@@ -3232,11 +3746,10 @@ var MOQtailClient = class MOQtailClient {
3232
3746
  return response;
3233
3747
  } else {
3234
3748
  require_logger.logger.debug("MOQtailClient", `subscribe: SUBSCRIBE_OK requestId=${request.requestId} trackAlias=${response.trackAlias}`);
3235
- this.subscriptions.set(response.trackAlias, request);
3236
- this.subscriptionAliasMap.set(request.requestId, response.trackAlias);
3237
- this.aliasFullTrackNameMap.set(response.trackAlias, fullTrackName);
3749
+ this.#claimTrackAlias(response.trackAlias, request);
3238
3750
  return {
3239
3751
  requestId: msg.requestId,
3752
+ trackAlias: response.trackAlias,
3240
3753
  stream: request.stream
3241
3754
  };
3242
3755
  }
@@ -3266,7 +3779,7 @@ var MOQtailClient = class MOQtailClient {
3266
3779
  *
3267
3780
  * @example Subscribe and later unsubscribe
3268
3781
  * ```ts
3269
- * const sub = await client.subscribe({ fullTrackName, filterType: FilterType.LatestObject, forward: true, groupOrder: GroupOrder.Original, priority: 0 });
3782
+ * const sub = await client.subscribe({ fullTrackName, locationFilter: new LocationFilter(LocationFilterType.NextObject), forward: true, groupOrder: GroupOrder.Original, priority: 0 });
3270
3783
  * if (!(sub instanceof RequestError)) {
3271
3784
  * // ...consume objects...
3272
3785
  * await client.unsubscribe(sub.requestId);
@@ -3282,31 +3795,25 @@ var MOQtailClient = class MOQtailClient {
3282
3795
  async unsubscribe(requestId) {
3283
3796
  this.#ensureActive();
3284
3797
  if (typeof requestId === "number") requestId = BigInt(requestId);
3285
- let cleanupData = null;
3798
+ const subscription = this.requests.get(requestId);
3799
+ if (!(subscription instanceof SubscribeRequest)) return;
3800
+ const owner = subscription.manager;
3801
+ const targets = owner ? owner.requests.slice() : [subscription];
3286
3802
  try {
3287
- if (this.requests.has(requestId)) {
3288
- const subscription = this.requests.get(requestId);
3289
- if (subscription instanceof SubscribeRequest) {
3290
- const trackAlias = this.subscriptionAliasMap.get(requestId);
3291
- cleanupData = {
3292
- requestId,
3293
- trackAlias,
3294
- subscription
3295
- };
3296
- await this.#resetRequestStream(requestId, 1);
3297
- subscription.unsubscribe();
3298
- }
3803
+ for (const target of targets) {
3804
+ await this.#resetRequestStream(target.requestId, 1);
3805
+ target.unsubscribe();
3299
3806
  }
3300
3807
  } catch (error) {
3301
3808
  await this.disconnect(new require_model.InternalError("MOQtailClient.unsubscribe", error instanceof Error ? error.message : String(error)));
3302
3809
  throw error;
3303
3810
  } finally {
3304
- if (cleanupData) {
3305
- this.requests.delete(cleanupData.requestId);
3306
- this.subscriptions.delete(cleanupData.trackAlias);
3307
- this.aliasFullTrackNameMap.delete(cleanupData.trackAlias);
3308
- this.requestIdMap.removeMappingByRequestId(cleanupData.requestId);
3811
+ for (const target of targets) {
3812
+ this.requests.delete(target.requestId);
3813
+ this.requestIdMap.removeMappingByRequestId(target.requestId);
3814
+ this.#releaseTrackAlias(target);
3309
3815
  }
3816
+ owner?.clear();
3310
3817
  }
3311
3818
  }
3312
3819
  /**
@@ -3335,23 +3842,30 @@ var MOQtailClient = class MOQtailClient {
3335
3842
  *
3336
3843
  * @example Trim start forward
3337
3844
  * ```ts
3338
- * await client.subscribeUpdate({ requestId, startLocation: laterLoc, endGroup, forward: true, priority });
3845
+ * await client.subscribeUpdate({ subscriptionRequestId, locationFilter: new LocationFilter(LocationFilterType.AbsoluteStart, laterGroup, 0n), forward: true, priority });
3339
3846
  * ```
3340
3847
  *
3341
3848
  * @example Convert tailing subscription into bounded slice
3342
3849
  * ```ts
3343
- * await client.subscribeUpdate({ requestId, startLocation: origStart, endGroup: cutoffGroup, forward: false, priority });
3850
+ * await client.subscribeUpdate({ subscriptionRequestId, locationFilter: new LocationFilter(LocationFilterType.AbsoluteStartGroupEnd, startGroup, 0n, cutoffGroup), forward: false, priority });
3344
3851
  * ```
3345
3852
  *
3346
3853
  * @example Lower priority only
3347
3854
  * ```ts
3348
- * await client.subscribeUpdate({ requestId, startLocation: currentStart, endGroup: currentEnd, forward: true, priority: 200 });
3855
+ * await client.subscribeUpdate({ subscriptionRequestId, forward: true, priority: 200 });
3349
3856
  * ```
3350
3857
  */
3351
3858
  async subscribeUpdate(args) {
3352
3859
  this.#ensureActive();
3353
- let { subscriptionRequestId, priority, forward, parameters, startLocation, endGroup } = args;
3354
- if (endGroup && startLocation.group >= endGroup) throw new require_model.ProtocolViolationError("MOQtailClient.subscribeUpdate", "End group must be greater than start group");
3860
+ const { subscriptionRequestId, priority, forward, parameters, locationFilter } = args;
3861
+ const limit = this.peerMaxFilterRanges;
3862
+ assertWithinFilterRangeLimit(parameters ?? [], limit, "MOQtailClient.subscribeUpdate");
3863
+ const current = this.requests.get(subscriptionRequestId);
3864
+ if (current instanceof SubscribeRequest) {
3865
+ const resulting = [...current.subscribeParameters];
3866
+ require_model.applyMessageParameterUpdate(resulting, parameters ?? []);
3867
+ assertWithinFilterRangeLimit(resulting, limit, "MOQtailClient.subscribeUpdate");
3868
+ }
3355
3869
  try {
3356
3870
  if (this.requests.has(subscriptionRequestId)) {
3357
3871
  if (this.requests.get(subscriptionRequestId) instanceof SubscribeRequest) {
@@ -3363,7 +3877,7 @@ var MOQtailClient = class MOQtailClient {
3363
3877
  const msg = new require_model.RequestUpdate(requestId, [
3364
3878
  new require_model.SubscriberPriority(priority),
3365
3879
  new require_model.Forward(forward),
3366
- new require_model.SubscriptionFilter(4, startLocation, endGroup),
3880
+ ...locationFilter ? [locationFilter] : [],
3367
3881
  ...parameters ?? []
3368
3882
  ]);
3369
3883
  subscription.update(msg);
@@ -3376,70 +3890,153 @@ var MOQtailClient = class MOQtailClient {
3376
3890
  }
3377
3891
  }
3378
3892
  /**
3379
- * Switches an active subscription to a different track while retaining the same subscription parameters.
3893
+ * Switches an active subscription to a different track while retaining the same subscription's
3894
+ * output stream.
3380
3895
  *
3381
- * Use this to change the subscribed track without tearing down and re-establishing a new subscription.
3896
+ * Sends a fresh SUBSCRIBE carrying a SwitchFrom parameter referencing `switchFromRequestId`. A soft
3897
+ * switch may keep delivering objects from the old track for a while after SUBSCRIBE_OK, and this can
3898
+ * be called again before the previous target has produced anything; only the first object actually
3899
+ * delivered by the newest switch target retires everything older.
3382
3900
  *
3383
- * @param args - {@link SwitchOptions} referencing the original subscription `requestId` and new track name.
3384
- * @returns Promise that resolves when the switch control frame is sent.
3901
+ * @param args - {@link SwitchOptions} referencing the subscription to switch from and the new subscription options.
3902
+ * @returns Either a {@link RequestError} (refusal) or `{ requestId, stream }`, where `stream` is the
3903
+ * same {@link https://developer.mozilla.org/docs/Web/API/ReadableStream | ReadableStream} object returned by the original `subscribe()` call.
3385
3904
  * @throws :{@link MOQtailError} If the client is destroyed.
3905
+ * @throws :{@link ProtocolViolationError} If `switchFromRequestId` does not name an active subscription.
3386
3906
  * @throws :{@link InternalError} On transport/control failure (disconnect is triggered before rethrow).
3387
3907
  *
3388
- * @remarks
3389
- * - Only applies to active SUBSCRIBE requests; ignored if the request is not a subscription.
3390
- * - All other subscription parameters (window, forwarding, priority) remain unchanged.
3391
- *
3392
3908
  * @example Switch to a different track
3393
3909
  * ```ts
3394
- * await client.switch({ subscriptionRequestId, fullTrackName: newTrackName });
3910
+ * await client.switch({
3911
+ * switchFromRequestId,
3912
+ * switchMode: SwitchMode.Soft,
3913
+ * newSubscribeOptions: { fullTrackName: newTrackName, priority: 0, groupOrder: GroupOrder.Original, forward: true, locationFilter: new LocationFilter(LocationFilterType.NextObject) },
3914
+ * onDrainDecision: (request) => true
3915
+ * });
3395
3916
  * ```
3396
3917
  */
3397
3918
  async switch(args) {
3398
3919
  this.#ensureActive();
3399
- let { fullTrackName, subscriptionRequestId, parameters } = args;
3920
+ const { switchFromRequestId, switchMode, newSubscribeOptions, onDrainDecision } = args;
3921
+ assertWithinFilterRangeLimit(newSubscribeOptions.parameters ?? [], this.peerMaxFilterRanges, "MOQtailClient.switch");
3400
3922
  try {
3401
- if (!this.requests.has(subscriptionRequestId)) throw new require_model.ProtocolViolationError("MOQtailClient.switch", "Unknown subscription request id");
3402
- if (!(this.requests.get(subscriptionRequestId) instanceof SubscribeRequest)) throw new require_model.ProtocolViolationError("MOQtailClient.switch", "Request id is not a subscription");
3403
- const trackAlias = this.subscriptionAliasMap.get(subscriptionRequestId);
3404
- if (!isValidTrackAlias(trackAlias)) throw new require_model.InternalError("MOQtailClient.switch", "Request exists but track alias mapping does not");
3405
- const subscription = this.subscriptions.get(trackAlias);
3406
- if (!subscription) throw new require_model.InternalError("MOQtailClient.switch", "Request exists but subscription does not");
3407
- const requestId = this.#nextClientRequestId;
3408
- this.requests.set(requestId, subscription);
3409
- const switchParams = parameters ?? [];
3410
- const msg = new require_model.Switch(requestId, fullTrackName, subscriptionRequestId, switchParams.map((p) => p.toKeyValuePair()));
3411
- subscription.switch(fullTrackName, switchParams);
3412
- const requestStream = this.#requestStreamFor(subscriptionRequestId, "MOQtailClient.switch");
3413
- await requestStream.send(msg);
3414
- this.#requestStreams.set(requestId, requestStream);
3415
- const response = await subscription;
3416
- if (response instanceof require_model.SubscribeOk) {
3417
- this.aliasFullTrackNameMap.set(response.trackAlias, fullTrackName);
3418
- this.pendingStateUpdates.set(subscriptionRequestId, (newTrackAlias) => {
3419
- if (newTrackAlias !== response.trackAlias) return false;
3420
- this.subscriptions.set(response.trackAlias, subscription);
3421
- this.subscriptionAliasMap.set(requestId, response.trackAlias);
3422
- subscription.requestId = requestId;
3423
- this.requestIdMap.removeMappingByRequestId(subscriptionRequestId);
3424
- this.requestIdMap.addMapping(subscriptionRequestId, fullTrackName);
3425
- this.subscriptions.delete(trackAlias);
3426
- return true;
3427
- });
3428
- return {
3429
- requestId,
3430
- stream: subscription.stream
3431
- };
3432
- } else {
3433
- this.requestIdMap.removeMappingByRequestId(requestId);
3434
- this.requests.delete(requestId);
3435
- return response;
3436
- }
3923
+ const fromRequest = this.requests.get(switchFromRequestId);
3924
+ if (!(fromRequest instanceof SubscribeRequest) || !fromRequest.manager) throw new require_model.ProtocolViolationError("MOQtailClient.switch", "switchFromRequestId is not an active subscription");
3925
+ const subscription = fromRequest.manager;
3926
+ subscription.onSuperseded ??= (superseded) => {
3927
+ for (const request of superseded) this.#retireSwitchedRequest(request);
3928
+ };
3929
+ subscription.drainTimeoutMs = this.switchDrainTimeoutMs;
3930
+ if (onDrainDecision) subscription.onDrainDecision = onDrainDecision;
3931
+ const drains = switchMode === 1;
3932
+ if (newSubscribeOptions.parameters?.find(require_model.MessageParameter.isSwitchFrom)) require_logger.logger.warn("MOQtailClient", `switch: overwriting existing SwitchFrom parameter for requestId=${switchFromRequestId}`);
3933
+ const parameters = [...newSubscribeOptions.parameters?.filter((p) => !require_model.MessageParameter.isSwitchFrom(p)) ?? [], new require_model.SwitchFrom(switchFromRequestId, switchMode, drains)];
3934
+ const result = await this.subscribe({
3935
+ ...newSubscribeOptions,
3936
+ parameters
3937
+ });
3938
+ if (result instanceof require_model.RequestError) return result;
3939
+ const newRequest = this.requests.get(result.requestId);
3940
+ subscription.addSwitchTarget(newRequest, drains);
3941
+ return {
3942
+ requestId: result.requestId,
3943
+ stream: subscription.stream
3944
+ };
3437
3945
  } catch (error) {
3438
3946
  await this.disconnect(new require_model.InternalError("MOQtailClient.switch", error instanceof Error ? error.message : String(error)));
3439
3947
  throw error;
3440
3948
  }
3441
3949
  }
3442
3950
  /**
3951
+ * Ends a subscription whose publisher has said how many streams it opened and has
3952
+ * now delivered all of them, and reports whether that happened.
3953
+ *
3954
+ * Both halves of that arrive on their own: a PUBLISH_DONE carries the count, and
3955
+ * the streams finish whenever they finish. Either can be last, so this is checked
3956
+ * from both -- a drained switch target has usually finished its streams well
3957
+ * before the PUBLISH_DONE that ends it.
3958
+ */
3959
+ completeSubscription(request, force = false) {
3960
+ if (!force && (!request.expectedStreams || request.streamsAccepted < request.expectedStreams)) return false;
3961
+ const owner = request.manager;
3962
+ if (owner) {
3963
+ owner.drop(request);
3964
+ if (owner.requests.length === 0) owner.controller.close();
3965
+ } else request.controller?.close();
3966
+ this.#releaseTrackAlias(request);
3967
+ this.requests.delete(request.requestId);
3968
+ this.requestIdMap.removeMappingByRequestId(request.requestId);
3969
+ this.#closeRequestStream(request.requestId);
3970
+ require_logger.logger.debug("MOQtailClient", `subscription for request ${request.requestId} completed`);
3971
+ return true;
3972
+ }
3973
+ /**
3974
+ * Records the alias a publisher just named for `request`, releasing any data stream
3975
+ * that arrived before the control message carrying it.
3976
+ */
3977
+ #claimTrackAlias(trackAlias, holder) {
3978
+ this.subscriptions.set(trackAlias, holder);
3979
+ this.subscriptionAliasMap.set(holder.requestId, trackAlias);
3980
+ this.aliasFullTrackNameMap.set(trackAlias, holder.fullTrackName);
3981
+ const waiters = this.#aliasWaiters.get(trackAlias);
3982
+ if (!waiters) return;
3983
+ this.#aliasWaiters.delete(trackAlias);
3984
+ for (const waiter of waiters) waiter();
3985
+ }
3986
+ /**
3987
+ * Waits out the race between a subscription's data streams and the control message
3988
+ * that names their track alias. The two travel on separate streams, so nothing
3989
+ * orders them and the data can arrive first; giving up on it immediately would drop
3990
+ * a whole subgroup, which is a visible gap in the media.
3991
+ *
3992
+ * Returns once the alias is claimed, or once
3993
+ * {@link MOQtailClient.trackAliasResolutionTimeoutMs} elapses with it still unclaimed.
3994
+ */
3995
+ async #waitForTrackAlias(trackAlias) {
3996
+ require_logger.logger.debug("MOQtailClient", `data stream waiting for the track alias ${trackAlias} to be named`);
3997
+ return new Promise((resolve) => {
3998
+ let waiters = this.#aliasWaiters.get(trackAlias);
3999
+ if (!waiters) {
4000
+ waiters = /* @__PURE__ */ new Set();
4001
+ this.#aliasWaiters.set(trackAlias, waiters);
4002
+ }
4003
+ const claimed = () => {
4004
+ clearTimeout(timeoutId);
4005
+ resolve();
4006
+ };
4007
+ const timeoutId = setTimeout(() => {
4008
+ waiters.delete(claimed);
4009
+ if (waiters.size === 0) this.#aliasWaiters.delete(trackAlias);
4010
+ resolve();
4011
+ }, this.trackAliasResolutionTimeoutMs);
4012
+ waiters.add(claimed);
4013
+ });
4014
+ }
4015
+ /**
4016
+ * Drops `request`'s hold on its track alias.
4017
+ *
4018
+ * An alias names a track, not a subscription, so two requests for the same track
4019
+ * carry the same one -- a switch back to a track whose earlier request has not
4020
+ * been retired yet is exactly that. The alias-keyed maps can only describe the
4021
+ * request that holds the alias now, so the other one clears its own row and leaves
4022
+ * theirs alone.
4023
+ */
4024
+ #releaseTrackAlias(holder) {
4025
+ const trackAlias = this.subscriptionAliasMap.get(holder.requestId);
4026
+ this.subscriptionAliasMap.delete(holder.requestId);
4027
+ if (trackAlias === void 0) return;
4028
+ if (this.subscriptions.get(trackAlias) !== holder) return;
4029
+ this.subscriptions.delete(trackAlias);
4030
+ this.aliasFullTrackNameMap.delete(trackAlias);
4031
+ }
4032
+ /** Tears down a switch target that lost the handover race to a newer one. */
4033
+ async #retireSwitchedRequest(request) {
4034
+ this.requests.delete(request.requestId);
4035
+ this.requestIdMap.removeMappingByRequestId(request.requestId);
4036
+ this.#releaseTrackAlias(request);
4037
+ await this.#resetRequestStream(request.requestId, 1);
4038
+ }
4039
+ /**
3443
4040
  * One-shot retrieval of a bounded object span, optionally anchored to an existing subscription, returning a stream of {@link MoqtObject}s.
3444
4041
  *
3445
4042
  * Choose a fetch type via `typeAndProps.type`:
@@ -3470,15 +4067,13 @@ var MOQtailClient = class MOQtailClient {
3470
4067
  * - Result stream is finite; reader close occurs automatically when last object delivered.
3471
4068
  * - Use {@link MOQtailClient.fetchCancel} only for early termination (not yet fully implemented: see TODO in code).
3472
4069
  *
3473
- * @example Standalone window
4070
+ * @example Groups 10 through 12, inclusive
3474
4071
  * ```ts
3475
4072
  * const r = await client.fetch({
4073
+ * fullTrackName,
3476
4074
  * priority: 64,
3477
4075
  * groupOrder: GroupOrder.Original,
3478
- * typeAndProps: {
3479
- * type: FetchType.Standalone,
3480
- * props: { fullTrackName, startLocation, endLocation }
3481
- * }
4076
+ * locationFilter: new LocationFilter(LocationFilterType.AbsoluteStartGroupEnd, 10n, 0n, 12n)
3482
4077
  * })
3483
4078
  * if (!(r instanceof RequestError)) {
3484
4079
  * for await (const obj of r.stream as any) {
@@ -3487,68 +4082,35 @@ var MOQtailClient = class MOQtailClient {
3487
4082
  * }
3488
4083
  * ```
3489
4084
  *
3490
- * @example Relative to live subscription (e.g. last 5 groups)
4085
+ * @example The last 5 groups, counting the current one
3491
4086
  * ```ts
3492
- * const sub = await client.subscribe({ fullTrackName, filterType: FilterType.LatestObject, forward: true, groupOrder: GroupOrder.Original, priority: 0 })
3493
- * if (!(sub instanceof RequestError)) {
3494
- * const slice = await client.fetch({
3495
- * priority: 32,
3496
- * groupOrder: GroupOrder.Original,
3497
- * typeAndProps: { type: FetchType.Relative, props: { joiningRequestId: sub.requestId, joiningStart: 0n } }
3498
- * })
3499
- * }
4087
+ * const slice = await client.fetch({
4088
+ * fullTrackName,
4089
+ * priority: 32,
4090
+ * groupOrder: GroupOrder.Original,
4091
+ * locationFilter: new LocationFilter(LocationFilterType.RelativeStart, 5n)
4092
+ * })
3500
4093
  * ```
3501
4094
  */
3502
4095
  async fetch(args) {
3503
4096
  this.#ensureActive();
4097
+ assertWithinFilterRangeLimit(args.parameters ?? [], this.peerMaxFilterRanges, "MOQtailClient.fetch");
3504
4098
  try {
3505
- const { priority, groupOrder, typeAndProps, parameters } = args;
4099
+ const { priority, groupOrder, fullTrackName, locationFilter, parameters } = args;
3506
4100
  if (priority < 0 || priority > 255) throw new require_model.ProtocolViolationError("MOQtailClient.fetch", `subscriberPriority: ${priority} must be in range of [0-255]`);
3507
4101
  const params = [
3508
4102
  new require_model.SubscriberPriority(priority),
4103
+ ...locationFilter ? [locationFilter] : [],
3509
4104
  ...groupOrder !== 0 ? [new require_model.GroupOrderParam(groupOrder)] : [],
3510
4105
  ...parameters ?? []
3511
4106
  ];
3512
- let msg;
3513
- let joiningRequest;
3514
4107
  const requestId = this.#nextClientRequestId;
3515
- require_logger.logger.log("MOQtailClient", "fetch: generated requestId:", requestId, "for fetch type:", typeAndProps.type, "current #dontUseRequestId:", this.#dontUseRequestId);
3516
- switch (typeAndProps.type) {
3517
- case 1:
3518
- msg = new require_model.Fetch(requestId, {
3519
- type: typeAndProps.type,
3520
- props: typeAndProps.props
3521
- }, params);
3522
- break;
3523
- case 2:
3524
- joiningRequest = this.requests.get(typeAndProps.props.joiningRequestId);
3525
- if (!(joiningRequest instanceof SubscribeRequest)) throw new require_model.ProtocolViolationError("MOQtailClient.fetch", `No subscribe request for the given joiningRequestId: ${typeAndProps.props.joiningRequestId}`);
3526
- msg = new require_model.Fetch(requestId, {
3527
- type: typeAndProps.type,
3528
- props: {
3529
- ...typeAndProps.props,
3530
- joiningRequestId: this.#wireRequestId(typeAndProps.props.joiningRequestId)
3531
- }
3532
- }, params);
3533
- break;
3534
- case 3:
3535
- joiningRequest = this.requests.get(typeAndProps.props.joiningRequestId);
3536
- if (!(joiningRequest instanceof SubscribeRequest)) throw new require_model.ProtocolViolationError("MOQtailClient.fetch", `No subscribe request for the given joiningRequestId: ${typeAndProps.props.joiningRequestId}`);
3537
- msg = new require_model.Fetch(requestId, {
3538
- type: typeAndProps.type,
3539
- props: {
3540
- ...typeAndProps.props,
3541
- joiningRequestId: this.#wireRequestId(typeAndProps.props.joiningRequestId)
3542
- }
3543
- }, params);
3544
- break;
3545
- }
4108
+ require_logger.logger.log("MOQtailClient", "fetch: generated requestId:", requestId, "current #dontUseRequestId:", this.#dontUseRequestId);
4109
+ const msg = new require_model.Fetch(requestId, fullTrackName, params);
3546
4110
  const request = new FetchRequest(msg);
3547
- require_logger.logger.log("MOQtailClient", "fetch: storing FetchRequest with requestId:", msg.requestId, "for fetch type:", typeAndProps.type);
3548
4111
  require_logger.logger.log("MOQtailClient", "fetch: full fetch message:", {
3549
4112
  requestId: msg.requestId,
3550
- fetchType: typeAndProps.type,
3551
- joiningRequestId: typeAndProps.type !== 1 ? typeAndProps.props.joiningRequestId : "N/A"
4113
+ fullTrackName: `${fullTrackName}`
3552
4114
  });
3553
4115
  this.requests.set(msg.requestId, request);
3554
4116
  require_logger.logger.log("MOQtailClient", "fetch: about to send fetch message to server");
@@ -3592,7 +4154,7 @@ var MOQtailClient = class MOQtailClient {
3592
4154
  *
3593
4155
  * @example Cancel shortly after starting
3594
4156
  * ```ts
3595
- * const r = await client.fetch({ priority: 32, groupOrder: GroupOrder.Original, typeAndProps: { type: FetchType.Standalone, props: { fullTrackName, startLocation, endLocation } } })
4157
+ * const r = await client.fetch({ fullTrackName, priority: 32, groupOrder: GroupOrder.Original, locationFilter })
3596
4158
  * if (!(r instanceof RequestError)) {
3597
4159
  * // user navigated away
3598
4160
  * await client.fetchCancel(r.requestId)
@@ -3651,7 +4213,8 @@ var MOQtailClient = class MOQtailClient {
3651
4213
  this.#ensureActive();
3652
4214
  try {
3653
4215
  if (typeof publishRequestId === "number") publishRequestId = BigInt(publishRequestId);
3654
- const msg = new require_model.PublishDone(statusCode, 0n, new require_model.ReasonPhrase(reasonPhrase));
4216
+ const publication = this.publications.get(publishRequestId);
4217
+ const msg = new require_model.PublishDone(statusCode, publication instanceof PublishPublication ? publication.streamsOpened : require_model.PublishDone.UNKNOWN_STREAM_COUNT, new require_model.ReasonPhrase(reasonPhrase));
3655
4218
  const requestStream = this.#requestStreams.get(publishRequestId);
3656
4219
  if (requestStream) {
3657
4220
  await requestStream.send(msg);
@@ -3678,15 +4241,14 @@ var MOQtailClient = class MOQtailClient {
3678
4241
  streamController = c;
3679
4242
  } });
3680
4243
  this.requestIdMap.addMapping(msg.requestId, msg.fullTrackName);
3681
- this.subscriptionAliasMap.set(msg.requestId, msg.trackAlias);
3682
- this.aliasFullTrackNameMap.set(msg.trackAlias, msg.fullTrackName);
3683
4244
  const receiver = {
3684
4245
  requestId: msg.requestId,
4246
+ fullTrackName: msg.fullTrackName,
3685
4247
  streamsAccepted: 0,
3686
4248
  largestLocation: void 0,
3687
4249
  controller: streamController
3688
4250
  };
3689
- this.subscriptions.set(msg.trackAlias, receiver);
4251
+ this.#claimTrackAlias(msg.trackAlias, receiver);
3690
4252
  return stream;
3691
4253
  }
3692
4254
  /**
@@ -3806,7 +4368,7 @@ var MOQtailClient = class MOQtailClient {
3806
4368
  try {
3807
4369
  const params = parameters ?? [];
3808
4370
  const msg = new require_model.SubscribeNamespace(this.#nextClientRequestId, trackNamespacePrefix, params);
3809
- const requestStream = await RequestStream.open(this.webTransport, msg);
4371
+ const requestStream = await RequestStream.open(this.webTransport, msg, this.#requestStreamHooks);
3810
4372
  this.#requestStreams.set(msg.requestId, requestStream);
3811
4373
  require_logger.logger.log("MOQtailClient", "subscribeNamespace | sent msg", msg, msg.trackNamespacePrefix.toUtf8Path(), msg.requestId);
3812
4374
  const response = await requestStream.next();
@@ -3833,9 +4395,10 @@ var MOQtailClient = class MOQtailClient {
3833
4395
  }
3834
4396
  async subscribeTracks(trackNamespacePrefix, parameters) {
3835
4397
  this.#ensureActive();
4398
+ assertWithinFilterRangeLimit(parameters ?? [], this.peerMaxFilterRanges, "MOQtailClient.subscribeTracks");
3836
4399
  try {
3837
4400
  const msg = new require_model.SubscribeTracks(this.#nextClientRequestId, trackNamespacePrefix, parameters ?? []);
3838
- const requestStream = await RequestStream.open(this.webTransport, msg);
4401
+ const requestStream = await RequestStream.open(this.webTransport, msg, this.#requestStreamHooks);
3839
4402
  this.#requestStreams.set(msg.requestId, requestStream);
3840
4403
  const response = await requestStream.next();
3841
4404
  if (!response) throw new require_model.InternalError("MOQtailClient.subscribeTracks", "Stream closed before response");
@@ -3906,7 +4469,7 @@ var MOQtailClient = class MOQtailClient {
3906
4469
  async trackStatus(fullTrackName, trackAlias, parameters) {
3907
4470
  this.#ensureActive();
3908
4471
  try {
3909
- const msg = require_model.TrackStatus.newLatestObject(this.#nextClientRequestId, trackAlias, fullTrackName, 128, 0, false, parameters ?? []);
4472
+ const msg = new require_model.TrackStatus(this.#nextClientRequestId, trackAlias, fullTrackName, 128, 0, false, new require_model.LocationFilter(5), parameters ?? []);
3910
4473
  const request = new TrackStatusRequest(msg);
3911
4474
  this.requests.set(msg.requestId, request);
3912
4475
  await this.#openRequestStream(msg.requestId, msg);
@@ -3924,8 +4487,28 @@ var MOQtailClient = class MOQtailClient {
3924
4487
  *
3925
4488
  * @param requestId - The requestId carried by `first`; the key the stream is filed under.
3926
4489
  */
4490
+ /**
4491
+ * Hands a data stream {@link MOQtailClient.onDataEvent}, read at call time so an observer assigned
4492
+ * after connecting still sees streams that are already open.
4493
+ *
4494
+ * @internal
4495
+ */
4496
+ dataStreamObserver(fullTrackNameOf) {
4497
+ return {
4498
+ onDataEvent: (event) => this.onDataEvent?.(event),
4499
+ ...fullTrackNameOf && { fullTrackNameOf }
4500
+ };
4501
+ }
4502
+ /**
4503
+ * Forwards request-stream traffic to {@link onMessageSent} and {@link onMessageReceived},
4504
+ * read at call time so callbacks assigned after connecting still see it.
4505
+ */
4506
+ #requestStreamHooks = {
4507
+ onMessageSent: (msg) => this.onMessageSent?.(msg),
4508
+ onMessageReceived: (msg) => this.onMessageReceived?.(msg)
4509
+ };
3927
4510
  async #openRequestStream(requestId, first) {
3928
- const requestStream = await RequestStream.open(this.webTransport, first);
4511
+ const requestStream = await RequestStream.open(this.webTransport, first, this.#requestStreamHooks);
3929
4512
  this.#requestStreams.set(requestId, requestStream);
3930
4513
  this.#pumpRequestStream(requestId, requestStream);
3931
4514
  return requestStream;
@@ -3961,7 +4544,6 @@ var MOQtailClient = class MOQtailClient {
3961
4544
  const wireRequestId = this.#nextClientRequestId;
3962
4545
  const reissued = require_model.ControlMessage.deserialize(require_model.ControlMessage.serialize(first));
3963
4546
  reissued.requestId = wireRequestId;
3964
- this.#wireRequestIds.set(requestId, wireRequestId);
3965
4547
  this.#clientRequestIds.set(wireRequestId, requestId);
3966
4548
  oldStream.migrated = true;
3967
4549
  await oldStream.close();
@@ -3969,10 +4551,6 @@ var MOQtailClient = class MOQtailClient {
3969
4551
  require_logger.logger.log("MOQtailClient", `re-issued request ${requestId} as request id ${wireRequestId}`);
3970
4552
  return true;
3971
4553
  }
3972
- /** The Request ID `requestId` currently travels under, which a migration has moved on. */
3973
- #wireRequestId(requestId) {
3974
- return this.#wireRequestIds.get(requestId) ?? requestId;
3975
- }
3976
4554
  /** The request a peer-supplied Request ID belongs to, undoing any migration. */
3977
4555
  #clientRequestId(wireRequestId) {
3978
4556
  return this.#clientRequestIds.get(wireRequestId) ?? wireRequestId;
@@ -4023,8 +4601,6 @@ var MOQtailClient = class MOQtailClient {
4023
4601
  }
4024
4602
  /**
4025
4603
  * Resets the request stream filed under `requestId` with `code`, if it is still open.
4026
- * §3.3.2: this is how draft-18 cancels a request now that the cancel messages are
4027
- * gone — the peer reads the code back off the RESET_STREAM.
4028
4604
  */
4029
4605
  async #resetRequestStream(requestId, code) {
4030
4606
  const requestStream = this.#requestStreams.get(requestId);
@@ -4041,9 +4617,7 @@ var MOQtailClient = class MOQtailClient {
4041
4617
  await this.#closeRequestStream(requestId);
4042
4618
  }
4043
4619
  /**
4044
- * Reads the shared control stream, which after draft-18 §3.3 carries only SETUP and
4045
- * GOAWAY. SETUP is consumed by the handshake, so GOAWAY is all that is handled here;
4046
- * every request type has its own bidi stream.
4620
+ * Reads the shared control stream, every request type has its own bidi stream.
4047
4621
  */
4048
4622
  async #handleIncomingControlMessages() {
4049
4623
  this.#ensureActive();
@@ -4054,7 +4628,7 @@ var MOQtailClient = class MOQtailClient {
4054
4628
  if (done) throw new require_model.MOQtailError("WebTransport session is terminated");
4055
4629
  const handler = getHandlerForControlMessage(msg);
4056
4630
  if (!handler) {
4057
- require_logger.logger.warn("MOQtailClient", `${msg.constructor.name} on the control stream; draft-18 allows only SETUP and GOAWAY there`);
4631
+ require_logger.logger.warn("MOQtailClient", `${msg.constructor.name} on the control stream`);
4058
4632
  continue;
4059
4633
  }
4060
4634
  await handler(this, msg);
@@ -4092,7 +4666,7 @@ var MOQtailClient = class MOQtailClient {
4092
4666
  while (true) {
4093
4667
  const { value: biStream, done } = await reader.read();
4094
4668
  if (done) break;
4095
- this.#dispatchIncomingRequestStream(new RequestStream(biStream));
4669
+ this.#dispatchIncomingRequestStream(new RequestStream(biStream, this.#requestStreamHooks));
4096
4670
  }
4097
4671
  })();
4098
4672
  }
@@ -4139,28 +4713,14 @@ var MOQtailClient = class MOQtailClient {
4139
4713
  const request = this.requests.get(this.#clientRequestId(header.requestId));
4140
4714
  if (!(request instanceof FetchRequest)) return 0;
4141
4715
  return require_model.MessageParameter.groupOrderOf(request.message.parameters);
4142
- });
4716
+ }, this.dataStreamObserver((header) => header instanceof require_model.SubgroupHeader ? this.aliasFullTrackNameMap.get(header.trackAlias) : void 0));
4143
4717
  const header = recvStream.header;
4144
4718
  const reader = recvStream.stream.getReader();
4719
+ let forceComplete = false;
4145
4720
  if (header instanceof require_model.FetchHeader) {
4146
4721
  const request = this.requests.get(this.#clientRequestId(header.requestId));
4147
4722
  if (request && request instanceof FetchRequest) {
4148
- let fullTrackName;
4149
- switch (request.message.typeAndProps.type) {
4150
- case 1:
4151
- fullTrackName = request.message.typeAndProps.props.fullTrackName;
4152
- break;
4153
- case 2:
4154
- case 3: {
4155
- const joiningSubscription = this.requests.get(request.message.typeAndProps.props.joiningRequestId);
4156
- if (joiningSubscription instanceof SubscribeRequest) {
4157
- fullTrackName = joiningSubscription.fullTrackName;
4158
- break;
4159
- }
4160
- throw new require_model.ProtocolViolationError("_handleRecvStreams", "No active subscription for given joining request id");
4161
- }
4162
- default: throw new require_model.ProtocolViolationError("_handleRecvStreams", "Unknown fetchType");
4163
- }
4723
+ const fullTrackName = request.message.fullTrackName;
4164
4724
  try {
4165
4725
  while (true) {
4166
4726
  const { done, value: nextObject } = await reader.read();
@@ -4183,18 +4743,40 @@ var MOQtailClient = class MOQtailClient {
4183
4743
  }
4184
4744
  return;
4185
4745
  }
4746
+ if (request instanceof SubscribeRequest) {
4747
+ request.streamsAccepted++;
4748
+ try {
4749
+ while (true) {
4750
+ const { done, value: nextObject } = await reader.read();
4751
+ if (done) break;
4752
+ if (!nextObject) continue;
4753
+ if (!(nextObject instanceof require_model.FetchObject)) throw new require_model.ProtocolViolationError("MOQtailClient", "Received subgroup object after fetch header");
4754
+ if (nextObject.kind === "end_of_range") continue;
4755
+ const moqtObject = require_model.MoqtObject.fromFetchObject(nextObject, request.fullTrackName);
4756
+ if (request.manager) {
4757
+ if (!request.manager.deliver(request, moqtObject)) {
4758
+ await recvStream.stopSending(1);
4759
+ forceComplete = true;
4760
+ break;
4761
+ }
4762
+ } else request.controller?.enqueue(moqtObject);
4763
+ }
4764
+ } finally {
4765
+ reader.releaseLock();
4766
+ }
4767
+ this.completeSubscription(request, forceComplete);
4768
+ return;
4769
+ }
4186
4770
  throw new require_model.ProtocolViolationError("MOQtailClient", "No request for received request id");
4187
4771
  } else {
4188
4772
  let subscription = this.subscriptions.get(header.trackAlias);
4189
4773
  if (!subscription) {
4190
- for (const [subscriptionId, callback] of this.pendingStateUpdates) if (callback(header.trackAlias)) {
4191
- subscription = this.subscriptions.get(header.trackAlias);
4192
- this.pendingStateUpdates.delete(subscriptionId);
4193
- break;
4194
- }
4774
+ await this.#waitForTrackAlias(header.trackAlias);
4775
+ subscription = this.subscriptions.get(header.trackAlias);
4195
4776
  }
4196
4777
  if (subscription) {
4197
4778
  subscription.streamsAccepted++;
4779
+ const fullTrackName = subscription.fullTrackName;
4198
4780
  let firstObjectId = null;
4199
4781
  let subgroupTimeoutId;
4200
4782
  const effectiveDiscardPolicy = subscription.earlyDiscardPolicy ?? this.#earlyDiscardPolicy;
@@ -4212,12 +4794,16 @@ var MOQtailClient = class MOQtailClient {
4212
4794
  if (require_model.SubgroupHeaderType.isSubgroupIdZero(header.type)) subgroupId = 0n;
4213
4795
  else if (require_model.SubgroupHeaderType.isSubgroupIdFirstObjectId(header.type)) subgroupId = firstObjectId ?? null;
4214
4796
  else if (require_model.SubgroupHeaderType.hasExplicitSubgroupId(header.type)) subgroupId = header.subgroupId ?? null;
4215
- const fullTrackName = this.aliasFullTrackNameMap.get(header.trackAlias);
4216
- if (!fullTrackName) throw new require_model.ProtocolViolationError("MOQtailClient", "No full track name for received track alias");
4217
4797
  const moqtObject = require_model.MoqtObject.fromSubgroupObject(nextObject, header.groupId, header.publisherPriority, subgroupId, fullTrackName);
4218
4798
  if (!subscription.largestLocation) subscription.largestLocation = moqtObject.location;
4219
4799
  if (subscription.largestLocation.compare(moqtObject.location) == -1) subscription.largestLocation = moqtObject.location;
4220
- subscription.controller?.enqueue(moqtObject);
4800
+ if (subscription.manager) {
4801
+ if (!subscription.manager.deliver(subscription, moqtObject)) {
4802
+ forceComplete = true;
4803
+ await recvStream.stopSending(1);
4804
+ break;
4805
+ }
4806
+ } else subscription.controller?.enqueue(moqtObject);
4221
4807
  continue;
4222
4808
  }
4223
4809
  throw new require_model.ProtocolViolationError("MOQtailClient", "Received fetch object after subgroup header");
@@ -4226,11 +4812,7 @@ var MOQtailClient = class MOQtailClient {
4226
4812
  } finally {
4227
4813
  if (subgroupTimeoutId !== void 0) clearTimeout(subgroupTimeoutId);
4228
4814
  }
4229
- if (subscription.expectedStreams && subscription.expectedStreams === subscription.streamsAccepted) {
4230
- subscription.controller?.close();
4231
- this.subscriptions.delete(header.trackAlias);
4232
- this.requests.delete(subscription.requestId);
4233
- }
4815
+ this.completeSubscription(subscription, forceComplete);
4234
4816
  return;
4235
4817
  }
4236
4818
  throw new require_model.ProtocolViolationError("MOQtailClient", "No subscription for received track alias");
@@ -4374,6 +4956,30 @@ Object.defineProperty(exports, "ControlStream", {
4374
4956
  return ControlStream;
4375
4957
  }
4376
4958
  });
4959
+ Object.defineProperty(exports, "DEFAULT_MAX_FILTER_RANGES", {
4960
+ enumerable: true,
4961
+ get: function() {
4962
+ return DEFAULT_MAX_FILTER_RANGES;
4963
+ }
4964
+ });
4965
+ Object.defineProperty(exports, "DEFAULT_SWITCH_DRAIN_TIMEOUT_MS", {
4966
+ enumerable: true,
4967
+ get: function() {
4968
+ return DEFAULT_SWITCH_DRAIN_TIMEOUT_MS;
4969
+ }
4970
+ });
4971
+ Object.defineProperty(exports, "DEFAULT_TRACK_ALIAS_RESOLUTION_TIMEOUT_MS", {
4972
+ enumerable: true,
4973
+ get: function() {
4974
+ return DEFAULT_TRACK_ALIAS_RESOLUTION_TIMEOUT_MS;
4975
+ }
4976
+ });
4977
+ Object.defineProperty(exports, "DataStreamReporter", {
4978
+ enumerable: true,
4979
+ get: function() {
4980
+ return DataStreamReporter;
4981
+ }
4982
+ });
4377
4983
  Object.defineProperty(exports, "FetchPublication", {
4378
4984
  enumerable: true,
4379
4985
  get: function() {
@@ -4488,6 +5094,12 @@ Object.defineProperty(exports, "SubscribeRequest", {
4488
5094
  return SubscribeRequest;
4489
5095
  }
4490
5096
  });
5097
+ Object.defineProperty(exports, "Subscription", {
5098
+ enumerable: true,
5099
+ get: function() {
5100
+ return Subscription;
5101
+ }
5102
+ });
4491
5103
  Object.defineProperty(exports, "TrackStatusRequest", {
4492
5104
  enumerable: true,
4493
5105
  get: function() {