@moq/net 0.4.3 → 0.4.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/connection/connect.d.ts.map +1 -1
- package/connection/connect.js +7 -3
- package/connection/connect.js.map +1 -1
- package/lite/subscriber.d.ts +1 -0
- package/lite/subscriber.d.ts.map +1 -1
- package/lite/subscriber.js +4 -4
- package/lite/subscriber.js.map +1 -1
- package/package.json +2 -2
- package/path.d.ts.map +1 -1
- package/path.js +6 -2
- package/path.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"connect.d.ts","sourceRoot":"","sources":["../../src/connection/connect.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,QAAQ,IAAI,cAAc,EAAE,QAAQ,IAAI,cAAc,EAAE,MAAM,cAAc,CAAC;AAE3F,OAAO,KAAK,IAAI,MAAM,YAAY,CAAC;AAInC,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAWpD,yGAAyG;AACzG,MAAM,WAAW,cAAc;IAC9B,yDAAyD;IACzD,OAAO,CAAC,EAAE,OAAO,CAAC;IAElB,mGAAmG;IACnG,GAAG,CAAC,EAAE,GAAG,CAAC;IAEV;;;OAGG;IACH,KAAK,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC;CACnB;AAED;;;;GAIG;AACH,MAAM,WAAW,eAAe;IAC/B,4EAA4E;IAC5E,SAAS,CAAC,EAAE,SAAS,CAAC;IACtB,uDAAuD;IACvD,KAAK,EAAE,YAAY,GAAG,MAAM,CAAC;CAC7B;AAED,2GAA2G;AAC3G,MAAM,WAAW,iBAAkB,SAAQ,IAAI,CAAC,mBAAmB,EAAE,yBAAyB,CAAC;IAC9F;;;OAGG;IACH,uBAAuB,CAAC,EAAE,eAAe,EAAE,CAAC;IAE5C;;;;OAIG;IACH,iBAAiB,CAAC,EAAE,MAAM,GAAG,YAAY,CAAC;CAC1C;AAED,mCAAmC;AACnC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AAM,WAAW,iBAAkB,SAAQ,IAAI,CAAC,mBAAmB,EAAE,yBAAyB,CAAC;IAC9F;;;OAGG;IACH,uBAAuB,CAAC,EAAE,eAAe,EAAE,CAAC;IAE5C;;;;OAIG;IACH,iBAAiB,CAAC,EAAE,MAAM,GAAG,YAAY,CAAC;CAC1C;AAED,mCAAmC;AACnC,MAAM,WAAW,YAAY;IAC5B,qBAAqB;IACrB,GAAG,EAAE,GAAG,CAAC;IAET,4BAA4B;IAC5B,YAAY,CAAC,EAAE,iBAAiB,CAAC;IAEjC,oCAAoC;IACpC,SAAS,CAAC,EAAE,cAAc,CAAC;IAE3B;;;;;;OAMG;IACH,SAAS,CAAC,EAAE,YAAY,CAAC;IAEzB;;;OAGG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC;IAEpB;;;;;;;OAOG;IACH,OAAO,CAAC,EAAE,cAAc,CAAC;IAEzB;;;;;;;;;OASG;IACH,OAAO,CAAC,EAAE,cAAc,CAAC;IAEzB;;;;OAIG;IACH,MAAM,CAAC,EAAE,WAAW,CAAC;CACrB;AAcD;;;;;;GAMG;AACH,wBAAsB,OAAO,CAAC,EAAE,GAAG,EAAE,GAAG,KAAK,EAAE,EAAE,YAAY,GAAG,OAAO,CAAC,WAAW,CAAC,CAwBnF;AAiPD;;;;GAIG;AACH,wBAAsB,eAAe,CAAC,IAAI,EAAE,MAAM,GAAG,YAAY,GAAG,OAAO,CAAC,UAAU,CAAC,WAAW,CAAC,CAAC,CAInG"}
|
package/connection/connect.js
CHANGED
|
@@ -250,11 +250,15 @@ async function handshakeAlpn(url, session, version, wiring) {
|
|
|
250
250
|
}
|
|
251
251
|
// Strip PEM armor and base64-decode to the raw DER bytes.
|
|
252
252
|
function pemToDer(pem) {
|
|
253
|
-
|
|
254
|
-
|
|
253
|
+
// indexOf rather than a lazy regex, which goes quadratic on repeated BEGIN lines without an END.
|
|
254
|
+
const begin = "-----BEGIN CERTIFICATE-----";
|
|
255
|
+
const start = pem.indexOf(begin);
|
|
256
|
+
const end = start < 0 ? -1 : pem.indexOf("-----END CERTIFICATE-----", start + begin.length);
|
|
257
|
+
const body = end < 0 ? "" : pem.slice(start + begin.length, end).replace(/\s+/g, "");
|
|
258
|
+
if (!body) {
|
|
255
259
|
throw new Error("invalid PEM certificate: missing -----BEGIN/END CERTIFICATE----- armor");
|
|
256
260
|
}
|
|
257
|
-
const binary = atob(
|
|
261
|
+
const binary = atob(body);
|
|
258
262
|
const der = new Uint8Array(binary.length);
|
|
259
263
|
for (let i = 0; i < binary.length; i++) {
|
|
260
264
|
der[i] = binary.charCodeAt(i);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"connect.js","sourceRoot":"","sources":["../../src/connection/connect.ts"],"names":[],"mappings":"AAAA,OAAO,OAAwC,MAAM,WAAW,CAAC;AACjE,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,KAAK,IAAI,MAAM,kBAAkB,CAAC;AACzC,OAAO,KAAK,IAAI,MAAM,kBAAkB,CAAC;AAEzC,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AACtC,OAAO,KAAK,IAAI,MAAM,YAAY,CAAC;AACnC,OAAO,KAAK,GAAG,MAAM,gBAAgB,CAAC;AACtC,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,EAAE,uBAAuB,EAAE,MAAM,cAAc,CAAC;AAEvD,OAAO,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAChD,OAAO,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAE/C,gFAAgF;AAChF,MAAM,0BAA0B,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;AAEnD,0FAA0F;AAC1F,gGAAgG;AAChG,MAAM,oBAAoB,GAAG,GAAG,CAAC;AA2GjC,qFAAqF;AACrF,MAAM,YAAY,GAAG,IAAI,GAAG,EAAU,CAAC;AAEvC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AAI,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,IAAI;QAC1B,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,IAAI;KAC4C,CAAC;IAExE,yEAAyE;IACzE,0EAA0E;IAC1E,kEAAkE;IAClE,mBAAmB;IACnB,MAAM,IAAI,GAAG,IAAI,OAAO,CAAC,GAAG,EAAE;QAC7B,SAAS,EAAE,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC;QAChC,QAAQ;KACR,CAAC,CAAC;IAEH,2EAA2E;IAC3E,kFAAkF;IAClF,4EAA4E;IAC5E,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACzE,IAAI,CAAC,MAAM,EAAE,CAAC;QACb,IAAI,CAAC,KAAK,EAAE,CAAC;QACb,OAAO,SAAS,CAAC;IAClB,CAAC;IAED,OAAO,IAAI,CAAC;AACb,CAAC","sourcesContent":["import Session, { type Version as QmuxVersion } from \"@moq/qmux\";\nimport { error, fromClose } from \"../error.ts\";\nimport * as Ietf from \"../ietf/index.ts\";\nimport * as Lite from \"../lite/index.ts\";\nimport type { Consumer as OriginConsumer, Producer as OriginProducer } from \"../origin.ts\";\nimport { Stream } from \"../stream.ts\";\nimport * as Time from \"../time.ts\";\nimport * as Hex from \"../util/hex.ts\";\nimport { dev, redact } from \"../util/log.ts\";\nimport { isWebTransportSupported } from \"./browser.ts\";\nimport type { Established } from \"./established.ts\";\nimport { forwardAnnounced } from \"./forward.ts\";\nimport { exchangeSetup } from \"./handshake.ts\";\n\n// Default head start for WebTransport before attempting the WebSocket fallback.\nconst DEFAULT_WEBSOCKET_DELAY_MS = Time.Milli(500);\n\n// RESET_STREAM and CONNECTION_CLOSE are separate transport notifications. Give the latter\n// time to surface its authoritative code without letting a reset-only peer stall SETUP forever.\nconst SETUP_CLOSE_GRACE_MS = 100;\n\n/** Tuning for the WebSocket fallback used when WebTransport is unavailable or loses the connect race. */\nexport interface WebSocketProps {\n\t/** Enable the WebSocket fallback. Defaults to `true`. */\n\tenabled?: boolean;\n\n\t/** Use a different URL than WebTransport. By default, `https` maps to `wss` and `http` to `ws`. */\n\turl?: URL;\n\n\t/**\n\t * The delay in milliseconds before attempting the WebSocket fallback (default: 500).\n\t * If WebSocket won the previous race for a given URL, this is 0.\n\t */\n\tdelay?: Time.Milli;\n}\n\n/**\n * A server certificate hash used to pin a self-signed server, one entry of\n * `serverCertificateHashes`. Unlike the DOM type, `value` also accepts a hex string (the\n * format moq servers report via their certificate fingerprints), decoded automatically.\n */\nexport interface CertificateHash {\n\t/** The hash algorithm. Defaults to `sha-256` (the only supported value). */\n\talgorithm?: \"sha-256\";\n\t/** The certificate hash: raw bytes or a hex string. */\n\tvalue: BufferSource | string;\n}\n\n/** WebTransport options extended with friendlier certificate pinning (hex hashes or a raw certificate). */\nexport interface WebTransportProps extends Omit<WebTransportOptions, \"serverCertificateHashes\"> {\n\t/**\n\t * Pin the server to one or more certificate hashes. Each `value` may be raw\n\t * bytes or a hex string; the algorithm defaults to `sha-256`.\n\t */\n\tserverCertificateHashes?: CertificateHash[];\n\n\t/**\n\t * Pin the server by supplying its certificate directly; the SHA-256 hash is\n\t * computed for you. Accepts a PEM string or raw DER bytes. Use this when you\n\t * have the certificate but not its precomputed fingerprint.\n\t */\n\tserverCertificate?: string | BufferSource;\n}\n\n/** Options for {@link connect}. */\nexport interface ConnectProps {\n\t/** The relay URL. */\n\turl: URL;\n\n\t/** WebTransport options. */\n\twebtransport?: WebTransportProps;\n\n\t/** WebSocket (fallback) options. */\n\twebsocket?: WebSocketProps;\n\n\t/**\n\t * Use a pre-existing WebTransport session instead of connecting; skips the\n\t * WebTransport/WebSocket race. The publisher acquires the session's datagram\n\t * writer lock (`datagrams.writable.getWriter()`) for the session's lifetime,\n\t * so the caller must not hold it. Aborting via {@link ConnectProps.signal}\n\t * closes this session, so don't share one you intend to reuse afterwards.\n\t */\n\ttransport?: WebTransport;\n\n\t/**\n\t * Whether the relay supports broadcast discovery; see {@link Established.discovery}.\n\t * Defaults to true.\n\t */\n\tdiscovery?: boolean;\n\n\t/**\n\t * The origin whose broadcasts the session announces and serves to the peer. Omit to\n\t * publish nothing.\n\t *\n\t * The origin is borrowed, not owned: closing the session leaves its broadcasts alone,\n\t * and the same origin can back several sessions (or successive reconnects), each\n\t * announcing the table for as long as it lasts.\n\t */\n\tpublish?: OriginConsumer;\n\n\t/**\n\t * The origin the session feeds with the peer's announced broadcasts. Omit to discover\n\t * nothing.\n\t *\n\t * Everything the peer announces appears in the origin's table for the session's\n\t * lifetime, consumable by path; the entries retract when the session dies. Pass the\n\t * producer behind {@link ConnectProps.publish} to route both directions through one\n\t * origin: a locally published path is then served back to local consumers directly, and\n\t * the session still never announces the peer's own broadcasts back to it.\n\t */\n\tconsume?: OriginProducer;\n\n\t/**\n\t * Aborts the connection attempt with the signal's reason. An already-aborted\n\t * signal rejects before anything opens, and aborting after the connection is\n\t * established has no effect. Use `AbortSignal.timeout(ms)` for a deadline.\n\t */\n\tsignal?: AbortSignal;\n}\n\n/** The per-session wiring shared by every negotiated protocol path. */\ntype SessionProps = {\n\tdiscovery: boolean;\n\tpublish?: OriginConsumer;\n};\n\n// Save if WebSocket won the last race, so we won't give QUIC a head start next time.\nconst websocketWon = new Set<string>();\n\n/** The default connect signal: never aborts. */\nconst NEVER_ABORTED = new AbortController().signal;\n\n/**\n * Establishes a connection to a MOQ server.\n *\n * @param url - The URL of the server to connect to\n * @param props - Connection options\n * @returns A promise that resolves to an established session\n */\nexport async function connect({ url, ...props }: ConnectProps): Promise<Established> {\n\tconst signal = props.signal ?? NEVER_ABORTED;\n\tsignal.throwIfAborted();\n\n\t// Resolves on abort so every in-flight transport tears itself down.\n\tconst { promise: abort, resolve } = Promise.withResolvers<void>();\n\tconst onAbort = () => resolve();\n\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\n\tconst pending = connectInner(url, props, abort);\n\ttry {\n\t\t// A `pending` rejection propagates unless the abort beat it to the finish line.\n\t\tconst connection = await Promise.race([pending, abort.then(() => undefined)]);\n\t\tif (connection && !signal.aborted) {\n\t\t\tif (props.consume) forwardAnnounced(connection, props.consume);\n\t\t\treturn connection;\n\t\t}\n\n\t\t// Close a connection that settles after the abort.\n\t\tpending.then((conn) => conn.close()).catch(() => {});\n\t\tthrow signal.reason;\n\t} finally {\n\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t}\n}\n\nasync function connectInner(url: URL, props: Omit<ConnectProps, \"url\">, abort: Promise<void>): Promise<Established> {\n\tconst wiring: SessionProps = {\n\t\tdiscovery: props.discovery ?? true,\n\t\tpublish: props.publish,\n\t};\n\n\tif (props.transport) {\n\t\tconst transport = props.transport;\n\t\tvoid abort.then(() => transport.close());\n\t\treturn connectTransport(url, transport, wiring);\n\t}\n\n\t// Stop transports after one connects or the caller aborts.\n\tconst { promise: raced, resolve: done } = Promise.withResolvers<void>();\n\tconst cancel = Promise.race([raced, abort]);\n\n\tconst webtransport = isWebTransportSupported() ? connectWebTransport(url, cancel, props.webtransport) : undefined;\n\n\t// Give QUIC a head start to connect before trying WebSocket, unless WebSocket has won in the past.\n\t// NOTE that QUIC should be faster because it involves 1/2 fewer RTTs.\n\tconst headstart =\n\t\t!webtransport || websocketWon.has(url.toString()) ? 0 : (props.websocket?.delay ?? DEFAULT_WEBSOCKET_DELAY_MS);\n\tconst websocket =\n\t\tprops.websocket?.enabled !== false\n\t\t\t? connectWebSocket(props.websocket?.url ?? url, headstart, cancel)\n\t\t\t: undefined;\n\n\tif (!websocket && !webtransport) {\n\t\tthrow new Error(\"no transport available; WebTransport not supported and WebSocket is disabled\");\n\t}\n\n\t// Race the available transports, using `.any` to ignore if one participant has an error.\n\t// `webtransport`/`websocket` are `Promise | undefined`, so test existence explicitly: a\n\t// promise is always truthy, so bare truthiness here would be a misused-promise.\n\tconst session = await Promise.any(\n\t\twebtransport !== undefined\n\t\t\t? websocket !== undefined\n\t\t\t\t? [websocket, webtransport]\n\t\t\t\t: [webtransport]\n\t\t\t: [websocket],\n\t);\n\tdone();\n\n\tif (!session) throw new Error(\"no transport available\");\n\n\t// Abort the setup handshake without leaking the selected transport.\n\tvoid abort.then(() => session.close());\n\n\t// Save if WebSocket won the last race, so we won't give QUIC a head start next time.\n\tif (session instanceof Session) {\n\t\t// Still a warning, not a debug line: losing the race means we fell back off QUIC.\n\t\tif (dev()) console.warn(redact(url), \"connected via WebSocket\");\n\t\twebsocketWon.add(url.toString());\n\t} else if (dev()) {\n\t\tconsole.debug(redact(url), \"connected via WebTransport\");\n\t}\n\n\t// The remaining setup is identical whether the transport was raced or supplied.\n\treturn await connectTransport(url, session as WebTransport, wiring);\n}\n\nasync function connectTransport(url: URL, session: WebTransport, wiring: SessionProps): Promise<Established> {\n\tconst closed = session.closed.then(fromClose, error);\n\tconst terminal = closed.then((cause) => {\n\t\tthrow cause ?? new Error(\"session closed during SETUP\");\n\t});\n\n\ttry {\n\t\treturn await Promise.race([terminal, negotiate(url, session, wiring)]);\n\t} catch (cause) {\n\t\t// A session shutdown can reject its SETUP stream before `closed` publishes the\n\t\t// peer's close code. Wait briefly without closing locally, since a local clean close\n\t\t// could overwrite that code. A reset-only peer is cleaned up after the grace period.\n\t\tconst pending = Symbol(\"session close pending\");\n\t\tconst final = await Promise.race([\n\t\t\tclosed,\n\t\t\tnew Promise<typeof pending>((resolve) => setTimeout(() => resolve(pending), SETUP_CLOSE_GRACE_MS)),\n\t\t]);\n\t\tif (final !== pending) {\n\t\t\tif (final) throw final;\n\t\t\tthrow cause;\n\t\t}\n\n\t\tsession.close();\n\t\tthrow cause;\n\t}\n}\n\n// Negotiate the MoQ protocol over an established transport. The caller races this against\n// the session closing so a close code is not lost behind a failed or stalled SETUP stream.\nasync function negotiate(url: URL, session: WebTransport, wiring: SessionProps): Promise<Established> {\n\t// The DOM lib has no `protocol` property yet. It is \"\" when none was negotiated, and\n\t// undefined in a browser that predates subprotocols (Firefox before 155).\n\tconst protocol: string | undefined = (session as { protocol?: string }).protocol || undefined;\n\tif (dev()) console.debug(redact(url), \"negotiated ALPN:\", protocol ?? \"(none)\");\n\n\t// Choose setup encoding based on negotiated WebTransport protocol (if any).\n\tlet setupVersion: Ietf.Version;\n\tconst modernVersion =\n\t\tprotocol === Ietf.ALPN.DRAFT_22\n\t\t\t? Ietf.Version.DRAFT_22\n\t\t\t: protocol === Ietf.ALPN.DRAFT_21\n\t\t\t\t? Ietf.Version.DRAFT_21\n\t\t\t\t: protocol === Ietf.ALPN.DRAFT_20\n\t\t\t\t\t? Ietf.Version.DRAFT_20\n\t\t\t\t\t: protocol === Ietf.ALPN.DRAFT_19\n\t\t\t\t\t\t? Ietf.Version.DRAFT_19\n\t\t\t\t\t\t: protocol === Ietf.ALPN.DRAFT_18\n\t\t\t\t\t\t\t? Ietf.Version.DRAFT_18\n\t\t\t\t\t\t\t: protocol === Ietf.ALPN.DRAFT_17\n\t\t\t\t\t\t\t\t? Ietf.Version.DRAFT_17\n\t\t\t\t\t\t\t\t: undefined;\n\tif (modernVersion !== undefined) {\n\t\treturn await handshakeAlpn(url, session, modernVersion, wiring);\n\t} else if (protocol === Ietf.ALPN.DRAFT_16) {\n\t\tsetupVersion = Ietf.Version.DRAFT_16;\n\t} else if (protocol === Ietf.ALPN.DRAFT_15) {\n\t\tsetupVersion = Ietf.Version.DRAFT_15;\n\t} else if (protocol === Lite.ALPN_07_WIP) {\n\t\treturn new Lite.Connection({ url, quic: session, version: Lite.Version.DRAFT_07, ...wiring });\n\t} else if (protocol === Lite.ALPN_06) {\n\t\treturn new Lite.Connection({ url, quic: session, version: Lite.Version.DRAFT_06, ...wiring });\n\t} else if (protocol === Lite.ALPN_05) {\n\t\treturn new Lite.Connection({ url, quic: session, version: Lite.Version.DRAFT_05, ...wiring });\n\t} else if (protocol === Lite.ALPN_04) {\n\t\treturn new Lite.Connection({ url, quic: session, version: Lite.Version.DRAFT_04, ...wiring });\n\t} else if (protocol === Lite.ALPN_03) {\n\t\treturn new Lite.Connection({ url, quic: session, version: Lite.Version.DRAFT_03, ...wiring });\n\t} else if (protocol === Lite.ALPN || protocol === \"\" || protocol === undefined) {\n\t\tsetupVersion = Ietf.Version.DRAFT_14;\n\t} else {\n\t\tthrow new Error(`unsupported WebTransport protocol: ${protocol}`);\n\t}\n\n\tconst stream = await Stream.open(session, { version: setupVersion });\n\tawait stream.writer.u53(Lite.StreamId.ClientCompat);\n\n\tconst encoder = new TextEncoder();\n\n\tconst params = new Ietf.SetupOptions();\n\tparams.setVarint(Ietf.SetupOption.MaxRequestId, 42069n);\n\tparams.setBytes(Ietf.SetupOption.Implementation, encoder.encode(\"moq-lite-js\"));\n\tIetf.solicitIntoSetup(params);\n\tIetf.hiddenIntoSetup(params);\n\n\tconst client = new Ietf.ClientSetup({\n\t\tversions:\n\t\t\tsetupVersion === Ietf.Version.DRAFT_16\n\t\t\t\t? [Ietf.Version.DRAFT_16]\n\t\t\t\t: setupVersion === Ietf.Version.DRAFT_15\n\t\t\t\t\t? [Ietf.Version.DRAFT_15]\n\t\t\t\t\t: [Lite.Version.DRAFT_02, Lite.Version.DRAFT_01, Ietf.Version.DRAFT_14],\n\t\tparameters: params,\n\t});\n\tawait client.encode(stream.writer, setupVersion);\n\n\tconst serverCompat = await stream.reader.u53();\n\tif (serverCompat !== Lite.StreamId.ServerCompat) {\n\t\tthrow new Error(`unsupported server message type: ${serverCompat.toString()}`);\n\t}\n\n\tconst server = await Ietf.ServerSetup.decode(stream.reader, setupVersion);\n\n\tif (Object.values(Lite.Version).includes(server.version as Lite.Version)) {\n\t\treturn new Lite.Connection({\n\t\t\turl,\n\t\t\tquic: session,\n\t\t\tversion: server.version as Lite.Version,\n\t\t\tsession: stream,\n\t\t\t...wiring,\n\t\t});\n\t} else if (Object.values(Ietf.Version).includes(server.version as Ietf.Version)) {\n\t\tconst maxRequestId = server.parameters.getVarint(Ietf.SetupOption.MaxRequestId) ?? 0n;\n\t\treturn new Ietf.Connection({\n\t\t\t...wiring,\n\t\t\tclient: true,\n\t\t\turl,\n\t\t\tquic: session,\n\t\t\tcontrol: stream,\n\t\t\tmaxRequestId,\n\t\t\tversion: server.version as Ietf.IetfVersion,\n\t\t\tsolicit: Ietf.solicitFromSetup(server.parameters),\n\t\t\thidden: Ietf.hiddenFromSetup(server.parameters),\n\t\t});\n\t} else {\n\t\tthrow new Error(`unsupported server version: ${server.version.toString()}`);\n\t}\n}\n\n/**\n * Draft-17+ client handshake. ALPN already pinned the version; SETUP is\n * exchanged over a pair of uni streams using stream type 0x2F00.\n */\nasync function handshakeAlpn(\n\turl: URL,\n\tsession: WebTransport,\n\tversion: Ietf.IetfVersion,\n\twiring: SessionProps,\n): Promise<Established> {\n\tconst { control, early, solicit, hidden, cluster } = await exchangeSetup(session, version, \"moq-lite-js\");\n\n\treturn new Ietf.Connection({\n\t\t...wiring,\n\t\tclient: true,\n\t\turl,\n\t\tquic: session,\n\t\tcontrol,\n\t\tearly,\n\t\tsolicit,\n\t\thidden,\n\t\tcluster,\n\t\t// v17+ uses NativeSession which manages its own request IDs; maxRequestId is unused.\n\t\tmaxRequestId: 0n,\n\t\tversion,\n\t});\n}\n\n// One entry of the DOM `serverCertificateHashes`, derived without naming the lib type.\ntype WebTransportHash = NonNullable<WebTransportOptions[\"serverCertificateHashes\"]>[number];\n\n// Strip PEM armor and base64-decode to the raw DER bytes.\nfunction pemToDer(pem: string): Uint8Array<ArrayBuffer> {\n\tconst match = pem.match(/-----BEGIN CERTIFICATE-----([\\s\\S]+?)-----END CERTIFICATE-----/);\n\tif (!match) {\n\t\tthrow new Error(\"invalid PEM certificate: missing -----BEGIN/END CERTIFICATE----- armor\");\n\t}\n\n\tconst binary = atob(match[1].replace(/\\s+/g, \"\"));\n\tconst der = new Uint8Array(binary.length);\n\tfor (let i = 0; i < binary.length; i++) {\n\t\tder[i] = binary.charCodeAt(i);\n\t}\n\treturn der;\n}\n\n/**\n * Compute the SHA-256 hash of a certificate, the value `serverCertificateHashes`\n * pins. Accepts a PEM string or raw DER bytes. Matches the hex fingerprints a moq\n * server reports, so `Hex.fromBytes(await certificateHash(pem))` round-trips.\n */\nexport async function certificateHash(cert: string | BufferSource): Promise<Uint8Array<ArrayBuffer>> {\n\tconst der = typeof cert === \"string\" ? pemToDer(cert) : cert;\n\tconst digest = await crypto.subtle.digest(\"SHA-256\", der);\n\treturn new Uint8Array(digest);\n}\n\n// Normalize our friendlier pinning options into the DOM `serverCertificateHashes`.\nasync function resolveCertificateHashes(options?: WebTransportProps): Promise<WebTransportHash[] | undefined> {\n\tconst hashes: WebTransportHash[] = [];\n\n\tfor (const hash of options?.serverCertificateHashes ?? []) {\n\t\tconst value = typeof hash.value === \"string\" ? Hex.toBytes(hash.value) : hash.value;\n\t\thashes.push({ algorithm: hash.algorithm ?? \"sha-256\", value });\n\t}\n\n\tif (options?.serverCertificate !== undefined) {\n\t\thashes.push({ algorithm: \"sha-256\", value: await certificateHash(options.serverCertificate) });\n\t}\n\n\treturn hashes.length > 0 ? hashes : undefined;\n}\n\nasync function connectWebTransport(\n\turl: URL,\n\tcancel: Promise<void>,\n\toptions?: WebTransportProps,\n): Promise<WebTransport | undefined> {\n\tlet finalUrl = url;\n\n\t// Our custom pinning fields are normalized separately; the rest are DOM options.\n\tconst { serverCertificate: _cert, serverCertificateHashes: _hashes, ...webtransport } = options ?? {};\n\n\tconst finalOptions: WebTransportOptions = {\n\t\tallowPooling: false,\n\t\tcongestionControl: \"low-latency\",\n\t\tprotocols: [\n\t\t\t// Lite.ALPN_07_WIP is intentionally omitted: lite-07 is work-in-progress and\n\t\t\t// not advertised by default (negotiate still accepts it if a server selects it).\n\t\t\tLite.ALPN_06,\n\t\t\tLite.ALPN_05,\n\t\t\tLite.ALPN_04,\n\t\t\tLite.ALPN_03,\n\t\t\tLite.ALPN,\n\t\t\tIetf.ALPN.DRAFT_22,\n\t\t\tIetf.ALPN.DRAFT_21,\n\t\t\tIetf.ALPN.DRAFT_20,\n\t\t\tIetf.ALPN.DRAFT_19,\n\t\t\tIetf.ALPN.DRAFT_18,\n\t\t\tIetf.ALPN.DRAFT_17,\n\t\t\tIetf.ALPN.DRAFT_16,\n\t\t\tIetf.ALPN.DRAFT_15,\n\t\t],\n\t\t...webtransport,\n\t};\n\n\t// Accumulate caller-provided pins first, then append anything we fetch below,\n\t// so a fetched fingerprint never clobbers hashes passed in via options.\n\tconst hashes = (await resolveCertificateHashes(options)) ?? [];\n\n\t// Only perform certificate fetch and URL rewrite when polyfill is not needed\n\t// This is needed because WebTransport is a butt to work with in local development.\n\tif (url.protocol === \"http:\") {\n\t\tconst fingerprintUrl = new URL(url);\n\t\tfingerprintUrl.pathname = \"/certificate.sha256\";\n\t\t// The certificate endpoint is unauthenticated, so don't hand it the token.\n\t\tfingerprintUrl.search = \"\";\n\n\t\t// Dev-only path: http:// can't be a real WebTransport origin, so we fetch the\n\t\t// self-signed cert's hash over plain HTTP and pin it. Production uses https://\n\t\t// and never reaches here. Keep this at debug so it doesn't read as a problem.\n\t\tif (dev()) {\n\t\t\tconsole.debug(\n\t\t\t\tredact(fingerprintUrl),\n\t\t\t\t\"performing an insecure fingerprint fetch; use https:// in production\",\n\t\t\t);\n\t\t}\n\n\t\t// Fetch the fingerprint from the server.\n\t\t// TODO cancel the request if the effect is cancelled.\n\t\tconst fingerprint = await Promise.race([fetch(fingerprintUrl), cancel]);\n\t\tif (!fingerprint) return undefined;\n\n\t\tconst fingerprintText = await Promise.race([fingerprint.text(), cancel]);\n\t\tif (fingerprintText === undefined) return undefined;\n\n\t\thashes.push({ algorithm: \"sha-256\", value: Hex.toBytes(fingerprintText) });\n\n\t\tfinalUrl = new URL(url);\n\t\tfinalUrl.protocol = \"https:\";\n\t}\n\n\tif (hashes.length > 0) {\n\t\tfinalOptions.serverCertificateHashes = hashes;\n\t}\n\n\tconst quic = new WebTransport(finalUrl, finalOptions);\n\n\t// Both .ready and .closed reject on failure; catch .closed to avoid an unhandled rejection.\n\tquic.closed.catch(() => {});\n\n\t// Wait for the WebTransport to connect, or for the cancel promise to resolve.\n\t// Close the connection if we lost the race.\n\tconst loaded = await Promise.race([quic.ready.then(() => true), cancel]);\n\tif (!loaded) {\n\t\tquic.close();\n\t\treturn undefined;\n\t}\n\n\treturn quic;\n}\n\n// TODO accept arguments to control the port/path used.\nasync function connectWebSocket(url: URL, delay: number, cancel: Promise<void>): Promise<Session | undefined> {\n\tconst timer = new Promise<void>((resolve) => setTimeout(resolve, delay));\n\n\tconst active = await Promise.race([cancel, timer.then(() => true)]);\n\tif (!active) return undefined;\n\n\t// moq-transport-18 and newer are pinned to qmux-01. Every other ALPN we\n\t// support is currently negotiated as `qmux-00.{alpn}` on the wire, but we\n\t// don't want to lock that in: set the value to `null` so the polyfill\n\t// advertises every QMux draft it knows about and the server picks one.\n\t// Insertion order is the negotiation preference on the wire.\n\tconst versions = {\n\t\t// Lite.ALPN_07_WIP omitted on purpose: lite-07 is work-in-progress, not advertised by default.\n\t\t[Lite.ALPN_06]: null,\n\t\t[Lite.ALPN_05]: null,\n\t\t[Lite.ALPN_04]: null,\n\t\t[Lite.ALPN_03]: null,\n\t\t[Lite.ALPN]: null,\n\t\t[Ietf.ALPN.DRAFT_22]: \"qmux-01\",\n\t\t[Ietf.ALPN.DRAFT_21]: \"qmux-01\",\n\t\t[Ietf.ALPN.DRAFT_20]: \"qmux-01\",\n\t\t[Ietf.ALPN.DRAFT_19]: \"qmux-01\",\n\t\t[Ietf.ALPN.DRAFT_18]: \"qmux-01\",\n\t\t[Ietf.ALPN.DRAFT_17]: null,\n\t\t[Ietf.ALPN.DRAFT_16]: null,\n\t\t[Ietf.ALPN.DRAFT_15]: null,\n\t} as const satisfies Record<string, QmuxVersion | QmuxVersion[] | null>;\n\n\t// The default (`requireProtocol: false`) also advertises bare `qmux-01`,\n\t// `qmux-00`, and `webtransport` so we still interop with relays that only\n\t// know a wire-format version (today's moq-relay only accepts bare\n\t// `webtransport`).\n\tconst quic = new Session(url, {\n\t\tprotocols: Object.keys(versions),\n\t\tversions,\n\t});\n\n\t// Wait for the WebSocket to connect, or for the cancel promise to resolve.\n\t// `ready` rejects on a refused/failed connection, so a throw here is the caller's\n\t// cue to retry; a lost cancel race instead resolves and we close the loser.\n\tconst loaded = await Promise.race([quic.ready.then(() => true), cancel]);\n\tif (!loaded) {\n\t\tquic.close();\n\t\treturn undefined;\n\t}\n\n\treturn quic;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"connect.js","sourceRoot":"","sources":["../../src/connection/connect.ts"],"names":[],"mappings":"AAAA,OAAO,OAAwC,MAAM,WAAW,CAAC;AACjE,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,KAAK,IAAI,MAAM,kBAAkB,CAAC;AACzC,OAAO,KAAK,IAAI,MAAM,kBAAkB,CAAC;AAEzC,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AACtC,OAAO,KAAK,IAAI,MAAM,YAAY,CAAC;AACnC,OAAO,KAAK,GAAG,MAAM,gBAAgB,CAAC;AACtC,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,EAAE,uBAAuB,EAAE,MAAM,cAAc,CAAC;AAEvD,OAAO,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAChD,OAAO,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAE/C,gFAAgF;AAChF,MAAM,0BAA0B,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;AAEnD,0FAA0F;AAC1F,gGAAgG;AAChG,MAAM,oBAAoB,GAAG,GAAG,CAAC;AA2GjC,qFAAqF;AACrF,MAAM,YAAY,GAAG,IAAI,GAAG,EAAU,CAAC;AAEvC,gDAAgD;AAChD,MAAM,aAAa,GAAG,IAAI,eAAe,EAAE,CAAC,MAAM,CAAC;AAEnD;;;;;;GAMG;AACH,MAAM,CAAC,KA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,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,SAAS;QAC/B,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,SAAS;QAC/B,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,SAAS;QAC/B,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,IAAI;QAC1B,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,IAAI;QAC1B,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,IAAI;KAC4C,CAAC;IAExE,yEAAyE;IACzE,0EAA0E;IAC1E,kEAAkE;IAClE,mBAAmB;IACnB,MAAM,IAAI,GAAG,IAAI,OAAO,CAAC,GAAG,EAAE;QAC7B,SAAS,EAAE,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC;QAChC,QAAQ;KACR,CAAC,CAAC;IAEH,2EAA2E;IAC3E,kFAAkF;IAClF,4EAA4E;IAC5E,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACzE,IAAI,CAAC,MAAM,EAAE,CAAC;QACb,IAAI,CAAC,KAAK,EAAE,CAAC;QACb,OAAO,SAAS,CAAC;IAClB,CAAC;IAED,OAAO,IAAI,CAAC;AACb,CAAC","sourcesContent":["import Session, { type Version as QmuxVersion } from \"@moq/qmux\";\nimport { error, fromClose } from \"../error.ts\";\nimport * as Ietf from \"../ietf/index.ts\";\nimport * as Lite from \"../lite/index.ts\";\nimport type { Consumer as OriginConsumer, Producer as OriginProducer } from \"../origin.ts\";\nimport { Stream } from \"../stream.ts\";\nimport * as Time from \"../time.ts\";\nimport * as Hex from \"../util/hex.ts\";\nimport { dev, redact } from \"../util/log.ts\";\nimport { isWebTransportSupported } from \"./browser.ts\";\nimport type { Established } from \"./established.ts\";\nimport { forwardAnnounced } from \"./forward.ts\";\nimport { exchangeSetup } from \"./handshake.ts\";\n\n// Default head start for WebTransport before attempting the WebSocket fallback.\nconst DEFAULT_WEBSOCKET_DELAY_MS = Time.Milli(500);\n\n// RESET_STREAM and CONNECTION_CLOSE are separate transport notifications. Give the latter\n// time to surface its authoritative code without letting a reset-only peer stall SETUP forever.\nconst SETUP_CLOSE_GRACE_MS = 100;\n\n/** Tuning for the WebSocket fallback used when WebTransport is unavailable or loses the connect race. */\nexport interface WebSocketProps {\n\t/** Enable the WebSocket fallback. Defaults to `true`. */\n\tenabled?: boolean;\n\n\t/** Use a different URL than WebTransport. By default, `https` maps to `wss` and `http` to `ws`. */\n\turl?: URL;\n\n\t/**\n\t * The delay in milliseconds before attempting the WebSocket fallback (default: 500).\n\t * If WebSocket won the previous race for a given URL, this is 0.\n\t */\n\tdelay?: Time.Milli;\n}\n\n/**\n * A server certificate hash used to pin a self-signed server, one entry of\n * `serverCertificateHashes`. Unlike the DOM type, `value` also accepts a hex string (the\n * format moq servers report via their certificate fingerprints), decoded automatically.\n */\nexport interface CertificateHash {\n\t/** The hash algorithm. Defaults to `sha-256` (the only supported value). */\n\talgorithm?: \"sha-256\";\n\t/** The certificate hash: raw bytes or a hex string. */\n\tvalue: BufferSource | string;\n}\n\n/** WebTransport options extended with friendlier certificate pinning (hex hashes or a raw certificate). */\nexport interface WebTransportProps extends Omit<WebTransportOptions, \"serverCertificateHashes\"> {\n\t/**\n\t * Pin the server to one or more certificate hashes. Each `value` may be raw\n\t * bytes or a hex string; the algorithm defaults to `sha-256`.\n\t */\n\tserverCertificateHashes?: CertificateHash[];\n\n\t/**\n\t * Pin the server by supplying its certificate directly; the SHA-256 hash is\n\t * computed for you. Accepts a PEM string or raw DER bytes. Use this when you\n\t * have the certificate but not its precomputed fingerprint.\n\t */\n\tserverCertificate?: string | BufferSource;\n}\n\n/** Options for {@link connect}. */\nexport interface ConnectProps {\n\t/** The relay URL. */\n\turl: URL;\n\n\t/** WebTransport options. */\n\twebtransport?: WebTransportProps;\n\n\t/** WebSocket (fallback) options. */\n\twebsocket?: WebSocketProps;\n\n\t/**\n\t * Use a pre-existing WebTransport session instead of connecting; skips the\n\t * WebTransport/WebSocket race. The publisher acquires the session's datagram\n\t * writer lock (`datagrams.writable.getWriter()`) for the session's lifetime,\n\t * so the caller must not hold it. Aborting via {@link ConnectProps.signal}\n\t * closes this session, so don't share one you intend to reuse afterwards.\n\t */\n\ttransport?: WebTransport;\n\n\t/**\n\t * Whether the relay supports broadcast discovery; see {@link Established.discovery}.\n\t * Defaults to true.\n\t */\n\tdiscovery?: boolean;\n\n\t/**\n\t * The origin whose broadcasts the session announces and serves to the peer. Omit to\n\t * publish nothing.\n\t *\n\t * The origin is borrowed, not owned: closing the session leaves its broadcasts alone,\n\t * and the same origin can back several sessions (or successive reconnects), each\n\t * announcing the table for as long as it lasts.\n\t */\n\tpublish?: OriginConsumer;\n\n\t/**\n\t * The origin the session feeds with the peer's announced broadcasts. Omit to discover\n\t * nothing.\n\t *\n\t * Everything the peer announces appears in the origin's table for the session's\n\t * lifetime, consumable by path; the entries retract when the session dies. Pass the\n\t * producer behind {@link ConnectProps.publish} to route both directions through one\n\t * origin: a locally published path is then served back to local consumers directly, and\n\t * the session still never announces the peer's own broadcasts back to it.\n\t */\n\tconsume?: OriginProducer;\n\n\t/**\n\t * Aborts the connection attempt with the signal's reason. An already-aborted\n\t * signal rejects before anything opens, and aborting after the connection is\n\t * established has no effect. Use `AbortSignal.timeout(ms)` for a deadline.\n\t */\n\tsignal?: AbortSignal;\n}\n\n/** The per-session wiring shared by every negotiated protocol path. */\ntype SessionProps = {\n\tdiscovery: boolean;\n\tpublish?: OriginConsumer;\n};\n\n// Save if WebSocket won the last race, so we won't give QUIC a head start next time.\nconst websocketWon = new Set<string>();\n\n/** The default connect signal: never aborts. */\nconst NEVER_ABORTED = new AbortController().signal;\n\n/**\n * Establishes a connection to a MOQ server.\n *\n * @param url - The URL of the server to connect to\n * @param props - Connection options\n * @returns A promise that resolves to an established session\n */\nexport async function connect({ url, ...props }: ConnectProps): Promise<Established> {\n\tconst signal = props.signal ?? NEVER_ABORTED;\n\tsignal.throwIfAborted();\n\n\t// Resolves on abort so every in-flight transport tears itself down.\n\tconst { promise: abort, resolve } = Promise.withResolvers<void>();\n\tconst onAbort = () => resolve();\n\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\n\tconst pending = connectInner(url, props, abort);\n\ttry {\n\t\t// A `pending` rejection propagates unless the abort beat it to the finish line.\n\t\tconst connection = await Promise.race([pending, abort.then(() => undefined)]);\n\t\tif (connection && !signal.aborted) {\n\t\t\tif (props.consume) forwardAnnounced(connection, props.consume);\n\t\t\treturn connection;\n\t\t}\n\n\t\t// Close a connection that settles after the abort.\n\t\tpending.then((conn) => conn.close()).catch(() => {});\n\t\tthrow signal.reason;\n\t} finally {\n\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t}\n}\n\nasync function connectInner(url: URL, props: Omit<ConnectProps, \"url\">, abort: Promise<void>): Promise<Established> {\n\tconst wiring: SessionProps = {\n\t\tdiscovery: props.discovery ?? true,\n\t\tpublish: props.publish,\n\t};\n\n\tif (props.transport) {\n\t\tconst transport = props.transport;\n\t\tvoid abort.then(() => transport.close());\n\t\treturn connectTransport(url, transport, wiring);\n\t}\n\n\t// Stop transports after one connects or the caller aborts.\n\tconst { promise: raced, resolve: done } = Promise.withResolvers<void>();\n\tconst cancel = Promise.race([raced, abort]);\n\n\tconst webtransport = isWebTransportSupported() ? connectWebTransport(url, cancel, props.webtransport) : undefined;\n\n\t// Give QUIC a head start to connect before trying WebSocket, unless WebSocket has won in the past.\n\t// NOTE that QUIC should be faster because it involves 1/2 fewer RTTs.\n\tconst headstart =\n\t\t!webtransport || websocketWon.has(url.toString()) ? 0 : (props.websocket?.delay ?? DEFAULT_WEBSOCKET_DELAY_MS);\n\tconst websocket =\n\t\tprops.websocket?.enabled !== false\n\t\t\t? connectWebSocket(props.websocket?.url ?? url, headstart, cancel)\n\t\t\t: undefined;\n\n\tif (!websocket && !webtransport) {\n\t\tthrow new Error(\"no transport available; WebTransport not supported and WebSocket is disabled\");\n\t}\n\n\t// Race the available transports, using `.any` to ignore if one participant has an error.\n\t// `webtransport`/`websocket` are `Promise | undefined`, so test existence explicitly: a\n\t// promise is always truthy, so bare truthiness here would be a misused-promise.\n\tconst session = await Promise.any(\n\t\twebtransport !== undefined\n\t\t\t? websocket !== undefined\n\t\t\t\t? [websocket, webtransport]\n\t\t\t\t: [webtransport]\n\t\t\t: [websocket],\n\t);\n\tdone();\n\n\tif (!session) throw new Error(\"no transport available\");\n\n\t// Abort the setup handshake without leaking the selected transport.\n\tvoid abort.then(() => session.close());\n\n\t// Save if WebSocket won the last race, so we won't give QUIC a head start next time.\n\tif (session instanceof Session) {\n\t\t// Still a warning, not a debug line: losing the race means we fell back off QUIC.\n\t\tif (dev()) console.warn(redact(url), \"connected via WebSocket\");\n\t\twebsocketWon.add(url.toString());\n\t} else if (dev()) {\n\t\tconsole.debug(redact(url), \"connected via WebTransport\");\n\t}\n\n\t// The remaining setup is identical whether the transport was raced or supplied.\n\treturn await connectTransport(url, session as WebTransport, wiring);\n}\n\nasync function connectTransport(url: URL, session: WebTransport, wiring: SessionProps): Promise<Established> {\n\tconst closed = session.closed.then(fromClose, error);\n\tconst terminal = closed.then((cause) => {\n\t\tthrow cause ?? new Error(\"session closed during SETUP\");\n\t});\n\n\ttry {\n\t\treturn await Promise.race([terminal, negotiate(url, session, wiring)]);\n\t} catch (cause) {\n\t\t// A session shutdown can reject its SETUP stream before `closed` publishes the\n\t\t// peer's close code. Wait briefly without closing locally, since a local clean close\n\t\t// could overwrite that code. A reset-only peer is cleaned up after the grace period.\n\t\tconst pending = Symbol(\"session close pending\");\n\t\tconst final = await Promise.race([\n\t\t\tclosed,\n\t\t\tnew Promise<typeof pending>((resolve) => setTimeout(() => resolve(pending), SETUP_CLOSE_GRACE_MS)),\n\t\t]);\n\t\tif (final !== pending) {\n\t\t\tif (final) throw final;\n\t\t\tthrow cause;\n\t\t}\n\n\t\tsession.close();\n\t\tthrow cause;\n\t}\n}\n\n// Negotiate the MoQ protocol over an established transport. The caller races this against\n// the session closing so a close code is not lost behind a failed or stalled SETUP stream.\nasync function negotiate(url: URL, session: WebTransport, wiring: SessionProps): Promise<Established> {\n\t// The DOM lib has no `protocol` property yet. It is \"\" when none was negotiated, and\n\t// undefined in a browser that predates subprotocols (Firefox before 155).\n\tconst protocol: string | undefined = (session as { protocol?: string }).protocol || undefined;\n\tif (dev()) console.debug(redact(url), \"negotiated ALPN:\", protocol ?? \"(none)\");\n\n\t// Choose setup encoding based on negotiated WebTransport protocol (if any).\n\tlet setupVersion: Ietf.Version;\n\tconst modernVersion =\n\t\tprotocol === Ietf.ALPN.DRAFT_22\n\t\t\t? Ietf.Version.DRAFT_22\n\t\t\t: protocol === Ietf.ALPN.DRAFT_21\n\t\t\t\t? Ietf.Version.DRAFT_21\n\t\t\t\t: protocol === Ietf.ALPN.DRAFT_20\n\t\t\t\t\t? Ietf.Version.DRAFT_20\n\t\t\t\t\t: protocol === Ietf.ALPN.DRAFT_19\n\t\t\t\t\t\t? Ietf.Version.DRAFT_19\n\t\t\t\t\t\t: protocol === Ietf.ALPN.DRAFT_18\n\t\t\t\t\t\t\t? Ietf.Version.DRAFT_18\n\t\t\t\t\t\t\t: protocol === Ietf.ALPN.DRAFT_17\n\t\t\t\t\t\t\t\t? Ietf.Version.DRAFT_17\n\t\t\t\t\t\t\t\t: undefined;\n\tif (modernVersion !== undefined) {\n\t\treturn await handshakeAlpn(url, session, modernVersion, wiring);\n\t} else if (protocol === Ietf.ALPN.DRAFT_16) {\n\t\tsetupVersion = Ietf.Version.DRAFT_16;\n\t} else if (protocol === Ietf.ALPN.DRAFT_15) {\n\t\tsetupVersion = Ietf.Version.DRAFT_15;\n\t} else if (protocol === Lite.ALPN_07_WIP) {\n\t\treturn new Lite.Connection({ url, quic: session, version: Lite.Version.DRAFT_07, ...wiring });\n\t} else if (protocol === Lite.ALPN_06) {\n\t\treturn new Lite.Connection({ url, quic: session, version: Lite.Version.DRAFT_06, ...wiring });\n\t} else if (protocol === Lite.ALPN_05) {\n\t\treturn new Lite.Connection({ url, quic: session, version: Lite.Version.DRAFT_05, ...wiring });\n\t} else if (protocol === Lite.ALPN_04) {\n\t\treturn new Lite.Connection({ url, quic: session, version: Lite.Version.DRAFT_04, ...wiring });\n\t} else if (protocol === Lite.ALPN_03) {\n\t\treturn new Lite.Connection({ url, quic: session, version: Lite.Version.DRAFT_03, ...wiring });\n\t} else if (protocol === Lite.ALPN || protocol === \"\" || protocol === undefined) {\n\t\tsetupVersion = Ietf.Version.DRAFT_14;\n\t} else {\n\t\tthrow new Error(`unsupported WebTransport protocol: ${protocol}`);\n\t}\n\n\tconst stream = await Stream.open(session, { version: setupVersion });\n\tawait stream.writer.u53(Lite.StreamId.ClientCompat);\n\n\tconst encoder = new TextEncoder();\n\n\tconst params = new Ietf.SetupOptions();\n\tparams.setVarint(Ietf.SetupOption.MaxRequestId, 42069n);\n\tparams.setBytes(Ietf.SetupOption.Implementation, encoder.encode(\"moq-lite-js\"));\n\tIetf.solicitIntoSetup(params);\n\tIetf.hiddenIntoSetup(params);\n\n\tconst client = new Ietf.ClientSetup({\n\t\tversions:\n\t\t\tsetupVersion === Ietf.Version.DRAFT_16\n\t\t\t\t? [Ietf.Version.DRAFT_16]\n\t\t\t\t: setupVersion === Ietf.Version.DRAFT_15\n\t\t\t\t\t? [Ietf.Version.DRAFT_15]\n\t\t\t\t\t: [Lite.Version.DRAFT_02, Lite.Version.DRAFT_01, Ietf.Version.DRAFT_14],\n\t\tparameters: params,\n\t});\n\tawait client.encode(stream.writer, setupVersion);\n\n\tconst serverCompat = await stream.reader.u53();\n\tif (serverCompat !== Lite.StreamId.ServerCompat) {\n\t\tthrow new Error(`unsupported server message type: ${serverCompat.toString()}`);\n\t}\n\n\tconst server = await Ietf.ServerSetup.decode(stream.reader, setupVersion);\n\n\tif (Object.values(Lite.Version).includes(server.version as Lite.Version)) {\n\t\treturn new Lite.Connection({\n\t\t\turl,\n\t\t\tquic: session,\n\t\t\tversion: server.version as Lite.Version,\n\t\t\tsession: stream,\n\t\t\t...wiring,\n\t\t});\n\t} else if (Object.values(Ietf.Version).includes(server.version as Ietf.Version)) {\n\t\tconst maxRequestId = server.parameters.getVarint(Ietf.SetupOption.MaxRequestId) ?? 0n;\n\t\treturn new Ietf.Connection({\n\t\t\t...wiring,\n\t\t\tclient: true,\n\t\t\turl,\n\t\t\tquic: session,\n\t\t\tcontrol: stream,\n\t\t\tmaxRequestId,\n\t\t\tversion: server.version as Ietf.IetfVersion,\n\t\t\tsolicit: Ietf.solicitFromSetup(server.parameters),\n\t\t\thidden: Ietf.hiddenFromSetup(server.parameters),\n\t\t});\n\t} else {\n\t\tthrow new Error(`unsupported server version: ${server.version.toString()}`);\n\t}\n}\n\n/**\n * Draft-17+ client handshake. ALPN already pinned the version; SETUP is\n * exchanged over a pair of uni streams using stream type 0x2F00.\n */\nasync function handshakeAlpn(\n\turl: URL,\n\tsession: WebTransport,\n\tversion: Ietf.IetfVersion,\n\twiring: SessionProps,\n): Promise<Established> {\n\tconst { control, early, solicit, hidden, cluster } = await exchangeSetup(session, version, \"moq-lite-js\");\n\n\treturn new Ietf.Connection({\n\t\t...wiring,\n\t\tclient: true,\n\t\turl,\n\t\tquic: session,\n\t\tcontrol,\n\t\tearly,\n\t\tsolicit,\n\t\thidden,\n\t\tcluster,\n\t\t// v17+ uses NativeSession which manages its own request IDs; maxRequestId is unused.\n\t\tmaxRequestId: 0n,\n\t\tversion,\n\t});\n}\n\n// One entry of the DOM `serverCertificateHashes`, derived without naming the lib type.\ntype WebTransportHash = NonNullable<WebTransportOptions[\"serverCertificateHashes\"]>[number];\n\n// Strip PEM armor and base64-decode to the raw DER bytes.\nfunction pemToDer(pem: string): Uint8Array<ArrayBuffer> {\n\t// indexOf rather than a lazy regex, which goes quadratic on repeated BEGIN lines without an END.\n\tconst begin = \"-----BEGIN CERTIFICATE-----\";\n\tconst start = pem.indexOf(begin);\n\tconst end = start < 0 ? -1 : pem.indexOf(\"-----END CERTIFICATE-----\", start + begin.length);\n\tconst body = end < 0 ? \"\" : pem.slice(start + begin.length, end).replace(/\\s+/g, \"\");\n\tif (!body) {\n\t\tthrow new Error(\"invalid PEM certificate: missing -----BEGIN/END CERTIFICATE----- armor\");\n\t}\n\n\tconst binary = atob(body);\n\tconst der = new Uint8Array(binary.length);\n\tfor (let i = 0; i < binary.length; i++) {\n\t\tder[i] = binary.charCodeAt(i);\n\t}\n\treturn der;\n}\n\n/**\n * Compute the SHA-256 hash of a certificate, the value `serverCertificateHashes`\n * pins. Accepts a PEM string or raw DER bytes. Matches the hex fingerprints a moq\n * server reports, so `Hex.fromBytes(await certificateHash(pem))` round-trips.\n */\nexport async function certificateHash(cert: string | BufferSource): Promise<Uint8Array<ArrayBuffer>> {\n\tconst der = typeof cert === \"string\" ? pemToDer(cert) : cert;\n\tconst digest = await crypto.subtle.digest(\"SHA-256\", der);\n\treturn new Uint8Array(digest);\n}\n\n// Normalize our friendlier pinning options into the DOM `serverCertificateHashes`.\nasync function resolveCertificateHashes(options?: WebTransportProps): Promise<WebTransportHash[] | undefined> {\n\tconst hashes: WebTransportHash[] = [];\n\n\tfor (const hash of options?.serverCertificateHashes ?? []) {\n\t\tconst value = typeof hash.value === \"string\" ? Hex.toBytes(hash.value) : hash.value;\n\t\thashes.push({ algorithm: hash.algorithm ?? \"sha-256\", value });\n\t}\n\n\tif (options?.serverCertificate !== undefined) {\n\t\thashes.push({ algorithm: \"sha-256\", value: await certificateHash(options.serverCertificate) });\n\t}\n\n\treturn hashes.length > 0 ? hashes : undefined;\n}\n\nasync function connectWebTransport(\n\turl: URL,\n\tcancel: Promise<void>,\n\toptions?: WebTransportProps,\n): Promise<WebTransport | undefined> {\n\tlet finalUrl = url;\n\n\t// Our custom pinning fields are normalized separately; the rest are DOM options.\n\tconst { serverCertificate: _cert, serverCertificateHashes: _hashes, ...webtransport } = options ?? {};\n\n\tconst finalOptions: WebTransportOptions = {\n\t\tallowPooling: false,\n\t\tcongestionControl: \"low-latency\",\n\t\tprotocols: [\n\t\t\t// Lite.ALPN_07_WIP is intentionally omitted: lite-07 is work-in-progress and\n\t\t\t// not advertised by default (negotiate still accepts it if a server selects it).\n\t\t\tLite.ALPN_06,\n\t\t\tLite.ALPN_05,\n\t\t\tLite.ALPN_04,\n\t\t\tLite.ALPN_03,\n\t\t\tLite.ALPN,\n\t\t\tIetf.ALPN.DRAFT_22,\n\t\t\tIetf.ALPN.DRAFT_21,\n\t\t\tIetf.ALPN.DRAFT_20,\n\t\t\tIetf.ALPN.DRAFT_19,\n\t\t\tIetf.ALPN.DRAFT_18,\n\t\t\tIetf.ALPN.DRAFT_17,\n\t\t\tIetf.ALPN.DRAFT_16,\n\t\t\tIetf.ALPN.DRAFT_15,\n\t\t],\n\t\t...webtransport,\n\t};\n\n\t// Accumulate caller-provided pins first, then append anything we fetch below,\n\t// so a fetched fingerprint never clobbers hashes passed in via options.\n\tconst hashes = (await resolveCertificateHashes(options)) ?? [];\n\n\t// Only perform certificate fetch and URL rewrite when polyfill is not needed\n\t// This is needed because WebTransport is a butt to work with in local development.\n\tif (url.protocol === \"http:\") {\n\t\tconst fingerprintUrl = new URL(url);\n\t\tfingerprintUrl.pathname = \"/certificate.sha256\";\n\t\t// The certificate endpoint is unauthenticated, so don't hand it the token.\n\t\tfingerprintUrl.search = \"\";\n\n\t\t// Dev-only path: http:// can't be a real WebTransport origin, so we fetch the\n\t\t// self-signed cert's hash over plain HTTP and pin it. Production uses https://\n\t\t// and never reaches here. Keep this at debug so it doesn't read as a problem.\n\t\tif (dev()) {\n\t\t\tconsole.debug(\n\t\t\t\tredact(fingerprintUrl),\n\t\t\t\t\"performing an insecure fingerprint fetch; use https:// in production\",\n\t\t\t);\n\t\t}\n\n\t\t// Fetch the fingerprint from the server.\n\t\t// TODO cancel the request if the effect is cancelled.\n\t\tconst fingerprint = await Promise.race([fetch(fingerprintUrl), cancel]);\n\t\tif (!fingerprint) return undefined;\n\n\t\tconst fingerprintText = await Promise.race([fingerprint.text(), cancel]);\n\t\tif (fingerprintText === undefined) return undefined;\n\n\t\thashes.push({ algorithm: \"sha-256\", value: Hex.toBytes(fingerprintText) });\n\n\t\tfinalUrl = new URL(url);\n\t\tfinalUrl.protocol = \"https:\";\n\t}\n\n\tif (hashes.length > 0) {\n\t\tfinalOptions.serverCertificateHashes = hashes;\n\t}\n\n\tconst quic = new WebTransport(finalUrl, finalOptions);\n\n\t// Both .ready and .closed reject on failure; catch .closed to avoid an unhandled rejection.\n\tquic.closed.catch(() => {});\n\n\t// Wait for the WebTransport to connect, or for the cancel promise to resolve.\n\t// Close the connection if we lost the race.\n\tconst loaded = await Promise.race([quic.ready.then(() => true), cancel]);\n\tif (!loaded) {\n\t\tquic.close();\n\t\treturn undefined;\n\t}\n\n\treturn quic;\n}\n\n// TODO accept arguments to control the port/path used.\nasync function connectWebSocket(url: URL, delay: number, cancel: Promise<void>): Promise<Session | undefined> {\n\tconst timer = new Promise<void>((resolve) => setTimeout(resolve, delay));\n\n\tconst active = await Promise.race([cancel, timer.then(() => true)]);\n\tif (!active) return undefined;\n\n\t// moq-transport-18 and newer are pinned to qmux-01. Every other ALPN we\n\t// support is currently negotiated as `qmux-00.{alpn}` on the wire, but we\n\t// don't want to lock that in: set the value to `null` so the polyfill\n\t// advertises every QMux draft it knows about and the server picks one.\n\t// Insertion order is the negotiation preference on the wire.\n\tconst versions = {\n\t\t// Lite.ALPN_07_WIP omitted on purpose: lite-07 is work-in-progress, not advertised by default.\n\t\t[Lite.ALPN_06]: null,\n\t\t[Lite.ALPN_05]: null,\n\t\t[Lite.ALPN_04]: null,\n\t\t[Lite.ALPN_03]: null,\n\t\t[Lite.ALPN]: null,\n\t\t[Ietf.ALPN.DRAFT_22]: \"qmux-01\",\n\t\t[Ietf.ALPN.DRAFT_21]: \"qmux-01\",\n\t\t[Ietf.ALPN.DRAFT_20]: \"qmux-01\",\n\t\t[Ietf.ALPN.DRAFT_19]: \"qmux-01\",\n\t\t[Ietf.ALPN.DRAFT_18]: \"qmux-01\",\n\t\t[Ietf.ALPN.DRAFT_17]: null,\n\t\t[Ietf.ALPN.DRAFT_16]: null,\n\t\t[Ietf.ALPN.DRAFT_15]: null,\n\t} as const satisfies Record<string, QmuxVersion | QmuxVersion[] | null>;\n\n\t// The default (`requireProtocol: false`) also advertises bare `qmux-01`,\n\t// `qmux-00`, and `webtransport` so we still interop with relays that only\n\t// know a wire-format version (today's moq-relay only accepts bare\n\t// `webtransport`).\n\tconst quic = new Session(url, {\n\t\tprotocols: Object.keys(versions),\n\t\tversions,\n\t});\n\n\t// Wait for the WebSocket to connect, or for the cancel promise to resolve.\n\t// `ready` rejects on a refused/failed connection, so a throw here is the caller's\n\t// cue to retry; a lost cancel race instead resolves and we close the loser.\n\tconst loaded = await Promise.race([quic.ready.then(() => true), cancel]);\n\tif (!loaded) {\n\t\tquic.close();\n\t\treturn undefined;\n\t}\n\n\treturn quic;\n}\n"]}
|
package/lite/subscriber.d.ts
CHANGED
|
@@ -35,6 +35,7 @@ export declare class Subscriber {
|
|
|
35
35
|
consume(path: Path.Valid): broadcast.Consumer;
|
|
36
36
|
resolveTrackInfo(broadcast: Path.Valid, track: string): Promise<track.Info>;
|
|
37
37
|
fetchGroup(broadcast: Path.Valid, track: string, sequence: number, options?: track.FetchGroupOptions): Promise<netGroup.Consumer>;
|
|
38
|
+
private runResponses;
|
|
38
39
|
runProbe(): Promise<void>;
|
|
39
40
|
/**
|
|
40
41
|
* Ends every subscribed track: cleanly for a deliberate close, or with `err` when the
|
package/lite/subscriber.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"subscriber.d.ts","sourceRoot":"","sources":["../../src/lite/subscriber.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,QAAQ,MAAM,iBAAiB,CAAC;AAC5C,OAAO,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,OAAO,KAAK,IAAI,MAAM,YAAY,CAAC;AAInC,OAAO,KAAK,KAAK,KAAK,MAAM,aAAa,CAAC;AA8B1C,OAAO,EAQN,OAAO,EACP,MAAM,cAAc,CAAC;AAsEtB,qBAAa,UAAU;;IAItB,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;IAG1B,QAAQ,CAAC,GAAG,EAAE,GAAG,CAAC;IAsDlB;;;;;;;;;;;OAWG;IACH,SAAS,CAAC,KAAK,GAAE,IAAI,CAAC,OAA4B,EAAE,OAAO,CAAC,EAAE,QAAQ,CAAC,OAAO,GAAG,QAAQ,CAAC,QAAQ,CAKjG;IAsRD;;;;;;;;;OASG;IACH,OAAO,CAAC,IAAI,EAAE,IAAI,CAAC,KAAK,GAAG,SAAS,CAAC,QAAQ,CAE5C;IA6OK,gBAAgB,CAAC,SAAS,EAAE,IAAI,CAAC,KAAK,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,CAKhF;IAIK,UAAU,CACf,SAAS,EAAE,IAAI,CAAC,KAAK,EACrB,KAAK,EAAE,MAAM,EACb,QAAQ,EAAE,MAAM,EAChB,OAAO,GAAE,KAAK,CAAC,iBAAsB,GACnC,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAgC5B;YA+Ga,YAAY;IAkSpB,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC,CA0C9B;IAED;;;OAGG;IACH,KAAK,CAAC,GAAG,CAAC,EAAE,KAAK,QAgBhB;CACD"}
|
package/lite/subscriber.js
CHANGED
|
@@ -450,7 +450,7 @@ export class Subscriber {
|
|
|
450
450
|
// flight, so the track ends only once the tail is accounted for. A reset rejects
|
|
451
451
|
// instead, so the track ends with that error rather than a clean tail.
|
|
452
452
|
const responses = supportsTrackStream(this.version)
|
|
453
|
-
? this
|
|
453
|
+
? this.runResponses(stream, entry)
|
|
454
454
|
: stream.reader.closed;
|
|
455
455
|
const closed = responses.then(() => this.#settleTail(entry));
|
|
456
456
|
// A reset that lands after the race below settled is moot; the race observes one before.
|
|
@@ -720,12 +720,12 @@ export class Subscriber {
|
|
|
720
720
|
// Reads SUBSCRIBE_START/END/DROP on the subscribe stream until FIN (lite-05+), recording
|
|
721
721
|
// the range the tail is accounted against. SUBSCRIBE_END declares the track's end right
|
|
722
722
|
// away, so a consumer learns it before the last groups arrive. The publisher must declare
|
|
723
|
-
// the end before FIN; resets and malformed responses reject
|
|
724
|
-
async
|
|
723
|
+
// the end before FIN unless we cancelled locally; resets and malformed responses reject.
|
|
724
|
+
async runResponses(stream, entry) {
|
|
725
725
|
for (;;) {
|
|
726
726
|
const resp = await decodeSubscribeResponseMaybe(stream.reader, this.version);
|
|
727
727
|
if (!resp) {
|
|
728
|
-
if (entry.end === undefined)
|
|
728
|
+
if (entry.end === undefined && entry.track.closed.peek() === undefined)
|
|
729
729
|
throw new ProtocolViolation("subscribe stream ended without SUBSCRIBE_END");
|
|
730
730
|
return;
|
|
731
731
|
}
|
package/lite/subscriber.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"subscriber.js","sourceRoot":"","sources":["../../src/lite/subscriber.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,KAAK,QAAQ,MAAM,iBAAiB,CAAC;AAC5C,OAAO,KAAK,SAAS,MAAM,iBAAiB,CAAC;AAE7C,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAC/C,OAAO,EAAE,cAAc,EAAE,KAAK,EAAE,iBAAiB,EAAE,MAAM,EAAE,UAAU,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AACtH,OAAO,KAAK,QAAQ,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,IAAI,EAAY,QAAQ,EAAc,SAAS,EAAE,WAAW,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AACjH,OAAO,E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CAAC,CAAC,IAAI,EAAE,KAAK,CAAC,MAAM,EAAE,CAAC,IAAI,CAAC,GAAgB,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;QACnG,IAAI,KAAK,KAAK,IAAI;YAAE,OAAO,KAAU,CAAC;QACtC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,EAAE;YAAE,MAAM,IAAI,WAAW,CAAC,UAAU,CAAC,MAAM,EAAE,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC,CAAC;IACzF,CAAC;AACF,CAAC;AAED;;;;;GAKG;AACH,MAAM,gBAAiB,SAAQ,SAAS,CAAC,QAAQ;IAChD,WAAW,CAAa;IACxB,KAAK,CAAa;IAElB,YAAY,UAAsB,EAAE,IAAgB,EAAE,KAAa;QAClE,KAAK,CAAC,KAAK,CAAC,CAAC;QACb,qBAAqB,CAAC,IAAI,EAAE;YAC3B,gBAAgB,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,UAAU,CAAC,gBAAgB,CAAC,IAAI,EAAE,IAAI,CAAC;YACnE,UAAU,EAAE,CAAC,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,UAAU,CAAC,IAAI,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,CAAC;SAC7F,CAAC,CAAC;QACH,IAAI,CAAC,WAAW,GAAG,UAAU,CAAC;QAC9B,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;IACnB,CAAC;IAED,4FAA4F;IAC5F,iCAAiC;IACxB,KAAK;QACb,OAAO,IAAI,gBAAgB,CAAC,IAAI,CAAC,WAAW,EAAE,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,UAAU,EAAE,CAAC,CAAC;IAC9E,CAAC;CACD","sourcesContent":["import { race, Signal } from \"@moq/signals\";\nimport * as announce from \"../announced.ts\";\nimport * as broadcast from \"../broadcast.ts\";\nimport type { Probe as ProbeStats } from \"../connection/stats.ts\";\nimport { BroadcastCache } from \"../consume.ts\";\nimport { controlTimeout, error, ProtocolViolation, reason, StreamCode, StreamError, sessionCause } from \"../error.ts\";\nimport * as netGroup from \"../group.ts\";\nimport { Cost, type Hop, MAX_HOPS, type Route, randomHop, routesEqual, stampHops, UNKNOWN_HOP } from \"../hop.ts\";\nimport { groupBounds, hiddenBelow, scopeCaptures, scopeHead, scopeOverlaps } from \"../internal.ts\";\nimport * as Path from \"../path.ts\";\nimport { type OpenOptions, type Reader, Stream } from \"../stream.ts\";\nimport { TAIL_GRACE_MS, Tail } from \"../tail.ts\";\nimport * as Time from \"../time.ts\";\nimport type * as track from \"../track.ts\";\nimport { untilAborted } from \"../util/abort.ts\";\nimport { TimeoutError, withTimeout } from \"../util/timeout.ts\";\nimport { overrideBroadcastWire, wireOf } from \"../wire.ts\";\nimport {\n\tAnnounceHistory,\n\tAnnounceInit,\n\tAnnounceOk,\n\tAnnounceRequest,\n\tdecodeAnnounceBroadcastMaybe,\n} from \"./announce.ts\";\nimport { Datagram as DatagramMessage } from \"./datagram.ts\";\nimport * as DatagramStream from \"./datagram_stream.ts\";\nimport { Fetch as FetchMessage } from \"./fetch.ts\";\nimport { frameDecoder, type Group as GroupMessage, readFrames } from \"./group.ts\";\nimport { sendOrder } from \"./priority.ts\";\nimport { Probe } from \"./probe.ts\";\nimport { ProbeLevel, type Setup } from \"./setup.ts\";\nimport { StreamId } from \"./stream.ts\";\nimport {\n\tdecodeSubscribeResponse,\n\tdecodeSubscribeResponseMaybe,\n\tEMPTY_RANGE,\n\temptyRange,\n\texclusiveGroupEnd,\n\tinclusiveGroupEnd,\n\tSubscribe,\n\tSubscribeUpdate,\n} from \"./subscribe.ts\";\nimport { TrackInfo, Track as TrackMessage } from \"./track.ts\";\nimport {\n\thasAnnounceId,\n\thasAnnounceOk,\n\thasDatagrams,\n\thasProbeRtt,\n\thasStreamCount,\n\tresolvesStart,\n\trestartSupported,\n\tVersion,\n} from \"./version.ts\";\n\n// Bound on how long stream-open plus the first response (SUBSCRIBE_OK on older\n// drafts, or TRACK_INFO on lite-05+) may take. Browsers cap concurrent QUIC streams\n// (Chrome ~100) and we open with waitUntilAvailable, so past the cap the open blocks\n// until the peer frees a slot. The timeout turns a stall into a clear error.\nconst SUBSCRIBE_SETUP_TIMEOUT_MS = 10_000;\n\n// The TRACK stream and implicit SUBSCRIBE acceptance are lite-05+.\nfunction supportsTrackStream(version: Version): boolean {\n\tswitch (version) {\n\t\tcase Version.DRAFT_01:\n\t\tcase Version.DRAFT_02:\n\t\tcase Version.DRAFT_03:\n\t\tcase Version.DRAFT_04:\n\t\t\treturn false;\n\t\tdefault:\n\t\t\treturn true;\n\t}\n}\n\ninterface SubscribeEntry {\n\t// The write side: incoming GROUP streams are routed here. The application reads\n\t// the matching track.Subscriber it got from broadcast.Consumer.subscribe.\n\ttrack: track.Producer;\n\t// Per-frame timestamp scale (0 = none). undefined until it's known (from TRACK_INFO\n\t// on lite-05+, or implicit defaults on older drafts). A non-zero value means each\n\t// frame on the group stream is prefixed with a zigzag-delta timestamp varint that\n\t// runGroup must consume to stay in sync; group streams block on it before decoding,\n\t// since a group's QUIC stream can race ahead of the subscribe stream.\n\ttimescale: Signal<number | undefined>;\n\t// The group streams received, so the subscription can wait for the ones still owed\n\t// after the publisher ends it.\n\ttail: Tail;\n\t// The first group the SUBSCRIBE asked for, if any.\n\trequested?: number;\n\t// The first group the publisher serves (SUBSCRIBE_START) and the track's exclusive end\n\t// (SUBSCRIBE_END), once it declares them.\n\tstart?: number;\n\tend?: number;\n\t// Group streams opened by the publisher, when SUBSCRIBE_END carries the count.\n\tstreams?: number;\n}\n\n/**\n * Handles subscribing to broadcasts and managing their lifecycle.\n *\n * @internal\n */\n// What we close a session with on a protocol violation.\n//\n// The draft names the condition but assigns no numbers, so this is the Rust\n// implementation's code for `Error::ProtocolViolation`: matching it is what makes the\n// two report the same thing, where the default 0 would tell the peer it closed cleanly.\nconst PROTOCOL_VIOLATION_CODE = 15;\n\n// WebTransport rejects a close reason over 1024 bytes of UTF-8 by throwing, so a reason\n// built from peer-supplied data has to be bounded before it gets there. A broadcast path\n// is peer-supplied and long enough to reach this on its own.\nconst MAX_CLOSE_REASON = 1024;\n\n// The longest prefix of `text` that fits a close reason. `encodeInto` stops on a whole\n// code point, so `read` never lands mid-character the way slicing bytes would.\nfunction closeReason(text: string): string {\n\tconst encoder = new TextEncoder();\n\tconst buf = new Uint8Array(MAX_CLOSE_REASON);\n\tconst { read } = encoder.encodeInto(text, buf);\n\treturn text.slice(0, read);\n}\n\nexport class Subscriber {\n\t#quic: WebTransport;\n\n\t// The version of the connection.\n\treadonly version: Version;\n\n\t// Shared with the Publisher so reflected announces can be dropped on receipt.\n\treadonly hop: Hop;\n\n\t// Our subscribed tracks. `timescale` resolves once known (from TRACK_INFO on\n\t// lite-05+, or implicit defaults on older drafts); group streams block on it\n\t// before decoding any frame, since a group's QUIC stream can race ahead.\n\t#subscribes = new Map<bigint, SubscribeEntry>();\n\t#subscribeNext = 0n;\n\n\t// Dedup consumed broadcasts per path: repeat consume() calls share one subscription.\n\t#consumes = new BroadcastCache();\n\n\t// A random Hop ID of this connection's own, written as the first hop of any chain that\n\t// names no publisher, so a publisher that reconnects reads as a new one.\n\t#stamp: Hop;\n\n\t// Dedup in-flight one-shot fetches, keyed by [broadcast, track, sequence]. Concurrent (or\n\t// repeat, while still open) fetchGroup() calls for the same group share one FETCH stream and\n\t// each get an independent mirror; the entry is evicted once the group closes.\n\t#fetches = new Map<string, { group: netGroup.Producer; accepted: Promise<void> }>();\n\n\t// The peer's PROBE estimates, written as they arrive (Lite03+ only).\n\t#probe?: Signal<ProbeStats>;\n\n\t// The peer's SETUP (lite-05+), undefined until it arrives. Gates opening the PROBE\n\t// stream on the peer having advertised Probe >= Report.\n\t#peerSetup?: Signal<Setup | undefined>;\n\n\t// Distinguishes failures from streams torn down by Subscriber.close().\n\t#closed = new AbortController();\n\t/**\n\t * Creates a new Subscriber instance.\n\t * @param quic - The WebTransport session to use\n\t * @param version - The protocol version\n\t * @param origin - Hop id shared with the Publisher\n\t * @param probe - Optional sink for the peer's PROBE estimates\n\t * @param peerSetup - Optional peer SETUP slot for capability gating (lite-05+)\n\t *\n\t * @internal\n\t */\n\tconstructor(\n\t\tquic: WebTransport,\n\t\tversion: Version,\n\t\thop: Hop,\n\t\tprobe?: Signal<ProbeStats>,\n\t\tpeerSetup?: Signal<Setup | undefined>,\n\t) {\n\t\tthis.#quic = quic;\n\t\tthis.version = version;\n\t\tthis.hop = hop;\n\t\tthis.#stamp = randomHop();\n\t\tthis.#probe = probe;\n\t\tthis.#peerSetup = peerSetup;\n\t}\n\n\t/**\n\t * Subscribe to broadcast announcements matching `scope`. Paths are relative\n\t * to the session, not the scope.\n\t *\n\t * Reflected announces (those whose hop chain already includes this\n\t * connection) are always dropped: moq-lite-06 has none to keep, and older\n\t * versions stay consistent with that.\n\t *\n\t * Hidden routes (a `.`-prefixed segment below the scope's head) are left out unless\n\t * `options.hidden` opts in. The opt-in rides the request on lite-07+; an older peer\n\t * never hides anything, so the rule is also applied here.\n\t */\n\tannounced(scope: Path.Pattern = Path.Pattern.all(), options?: announce.Options): announce.Consumer {\n\t\tconst announced = new announce.Producer();\n\t\t// The wire speaks announce interest by prefix, and echoes suffixes beneath it.\n\t\tvoid this.#runAnnounced(announced, scopeHead(scope), scope, options?.hidden ?? false);\n\t\treturn announced.consume();\n\t}\n\n\tasync #runAnnounced(\n\t\tannounced: announce.Producer,\n\t\tprefix: Path.Valid,\n\t\tscope: Path.Pattern,\n\t\thidden: boolean,\n\t): Promise<void> {\n\t\tconsole.debug(`announced: prefix=${prefix}`);\n\t\t// Lite04/05: send our own session-level Hop ID so the peer can skip announces\n\t\t// whose hop chain already passed through us. Encoding drops it on every other\n\t\t// version, where we drop the reflected announce on receipt instead. Matches the\n\t\t// Rust subscriber's `exclude_hop: self.self_origin.id` in `run_announce_prefix`.\n\t\tconst msg = new AnnounceRequest(prefix, this.hop, hidden);\n\t\tconst visible = (path: Path.Valid) => scopeOverlaps(scope, path) && (hidden || !hiddenBelow(prefix, path));\n\n\t\t// Opened outside the try so the catch can reach it: a protocol violation below has\n\t\t// to reset the stream, not just close our side of it.\n\t\tlet stream: Stream;\n\t\ttry {\n\t\t\tstream = await Stream.open(this.#quic, { version: this.version });\n\t\t} catch (err: unknown) {\n\t\t\tannounced.close(error(err));\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\t// Send the announce interest.\n\t\t\tawait stream.writer.u53(StreamId.Announce);\n\t\t\tawait msg.encode(stream.writer, this.version);\n\n\t\t\t// Lite05+: the publisher reports its own Hop ID before any announces.\n\t\t\t// It no longer stamps itself onto each hop chain, so we append it here to\n\t\t\t// keep the reflected-announce loop check seeing the full chain.\n\t\t\tlet responderOrigin: Hop | undefined;\n\t\t\tif (hasAnnounceOk(this.version)) {\n\t\t\t\tconst ok = await AnnounceOk.decode(stream.reader, this.version);\n\t\t\t\t// Keep a withheld 0: it names nobody for loop detection, but it is the\n\t\t\t\t// anonymous mark and must travel the reconstructed chain. Assigned identities\n\t\t\t\t// stay off this hop and are never forwarded.\n\t\t\t\tresponderOrigin = ok.hop;\n\t\t\t}\n\n\t\t\t// Every advertisement the peer currently has live, keyed by suffix (at most one\n\t\t\t// per path is current, and every announce on this stream shares `prefix`).\n\t\t\t//\n\t\t\t// An advertisement skipped locally as a reflected loop is recorded with\n\t\t\t// `publisher: undefined` and `live: false`: the peer numbered it and will retract\n\t\t\t// it regardless of what we made of it, so its path is not free. Dropping it from\n\t\t\t// the map instead would let a later announce take the path, and the skipped one's\n\t\t\t// `endedId` would then retract that one's state.\n\t\t\t//\n\t\t\t// `publisher` is what lets a restart tell a route change (same publisher) from a\n\t\t\t// new publisher on the route, whose content the next consume must not share\n\t\t\t// with the old one's.\n\t\t\ttype Advertisement = {\n\t\t\t\tpublisher: Hop | undefined;\n\t\t\t\tlive: boolean;\n\t\t\t\troute: Route;\n\t\t\t\tcaptures: Path.Pattern[] | undefined;\n\t\t\t};\n\t\t\tconst advertised = new Map<Path.Valid, Advertisement>();\n\n\t\t\tswitch (this.version) {\n\t\t\t\tcase Version.DRAFT_01:\n\t\t\t\tcase Version.DRAFT_02: {\n\t\t\t\t\t// Receive ANNOUNCE_INIT first\n\t\t\t\t\tconst init = await AnnounceInit.decode(stream.reader, this.version);\n\n\t\t\t\t\t// Process initial announcements. These are advertisements like any other, so\n\t\t\t\t\t// they go on record and obey the same one-per-path rule: the initial set\n\t\t\t\t\t// naming a path twice is the same violation as two ANNOUNCE_STARTs for it,\n\t\t\t\t\t// and the record is what catches either. Draft01/02 carry no hop ids and no\n\t\t\t\t\t// ANNOUNCE_OK, so this connection's stamp names the publisher.\n\t\t\t\t\tfor (const suffix of init.suffixes) {\n\t\t\t\t\t\tconst path = Path.join(prefix, suffix);\n\t\t\t\t\t\tif (advertised.has(path)) {\n\t\t\t\t\t\t\tthrow new ProtocolViolation(`duplicate announce for ${path}`);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst route = { hops: [this.#stamp, UNKNOWN_HOP], cost: Cost.zero };\n\t\t\t\t\t\tconst live = visible(path);\n\t\t\t\t\t\tconst captures = scopeCaptures(scope, path);\n\t\t\t\t\t\tadvertised.set(path, { publisher: this.#stamp, live, route, captures });\n\t\t\t\t\t\tif (!live) continue;\n\t\t\t\t\t\tconsole.debug(`announced: broadcast=${path} active=true`);\n\t\t\t\t\t\tannounced.append({ prefix: path, captures, kind: \"announced\", route });\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tdefault:\n\t\t\t\t\t// Draft03+: no AnnounceInit, initial state comes via Announce messages.\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t// Lite06+: announce ids. Each received `active` implicitly assigns the next\n\t\t\t// per-stream ordinal; `endedId`/`restart` reference it, and lite-07 bases copy\n\t\t\t// from it. Tracked even for announces we skip as reflected, since the sender\n\t\t\t// doesn't know we skipped.\n\t\t\tconst history = new AnnounceHistory();\n\n\t\t\t// Receive announce updates (for Draft03, this includes initial state)\n\t\t\tfor (;;) {\n\t\t\t\tconst announce = await race([\n\t\t\t\t\tdecodeAnnounceBroadcastMaybe(stream.reader, this.version),\n\t\t\t\t\tannounced.closed,\n\t\t\t\t]);\n\t\t\t\t// undefined: the stream ended. null: the consumer closed cleanly.\n\t\t\t\tif (!announce) break;\n\t\t\t\tif (announce instanceof Error) throw announce;\n\n\t\t\t\tlet path: Path.Valid;\n\t\t\t\tlet active: boolean;\n\t\t\t\t// Present on active/restart; ended messages never carry hops worth checking.\n\t\t\t\tlet hops: Hop[] | undefined;\n\t\t\t\tlet cost: Cost | undefined;\n\n\t\t\t\tswitch (announce.status) {\n\t\t\t\t\tcase \"active\": {\n\t\t\t\t\t\tconst resolved = hasAnnounceId(this.version) ? history.start(announce) : announce;\n\t\t\t\t\t\t// The wire names the suffix beneath the interest prefix; the consumer\n\t\t\t\t\t\t// sees the covered path from the session root.\n\t\t\t\t\t\tpath = Path.join(prefix, resolved.suffix);\n\t\t\t\t\t\tactive = true;\n\t\t\t\t\t\thops = resolved.hops;\n\t\t\t\t\t\tcost = announce.cost;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase \"ended\":\n\t\t\t\t\t\tpath = Path.join(prefix, announce.suffix);\n\t\t\t\t\t\tactive = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"endedId\":\n\t\t\t\t\t\t// Resolve and retire the id; an unknown or retired id is a protocol violation.\n\t\t\t\t\t\tpath = Path.join(prefix, history.end(announce.id));\n\t\t\t\t\t\tactive = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"restart\": {\n\t\t\t\t\t\t// Resolve the id; it stays live (the replacement reuses it).\n\t\t\t\t\t\tconst resolved = history.update(announce);\n\t\t\t\t\t\tpath = Path.join(prefix, resolved.suffix);\n\t\t\t\t\t\tactive = true;\n\t\t\t\t\t\thops = resolved.hops;\n\t\t\t\t\t\tcost = announce.cost;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase \"skipped\":\n\t\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t// One current advertisement per path per stream, decided before anything below\n\t\t\t\t// can skip this announcement. A second ANNOUNCE_START for a path the peer\n\t\t\t\t// already advertised is a violation whether or not its route would be usable\n\t\t\t\t// here, and whether or not we kept the first; letting a skip pre-empt it would\n\t\t\t\t// retract the live route and leave the stream open on a peer already out of\n\t\t\t\t// spec.\n\t\t\t\t//\n\t\t\t\t// lite-05 alone is exempt, where a duplicate ANNOUNCE *is* the replacement\n\t\t\t\t// idiom. lite-06 gave that its own message and older versions never had one, so\n\t\t\t\t// a duplicate means the same thing on both sides of it. Mirrors the branch the\n\t\t\t\t// Rust announce loop takes before `start_announce`.\n\t\t\t\tconst duplicateIsRestart = restartSupported(this.version) && !hasAnnounceId(this.version);\n\t\t\t\tif (announce.status === \"active\" && !duplicateIsRestart && advertised.has(path)) {\n\t\t\t\t\tthrow new ProtocolViolation(`duplicate announce for ${path}`);\n\t\t\t\t}\n\n\t\t\t\t// Retract the path: forget the advertisement, drop the shared consume entry so a\n\t\t\t\t// later announce subscribes fresh rather than cloning the dead generation's tracks,\n\t\t\t\t// and tell the consumer. A no-op for an advertisement never surfaced, which is\n\t\t\t\t// what an id retiring a skipped announce resolves to.\n\t\t\t\tconst retract = () => {\n\t\t\t\t\tconst previous = advertised.get(path);\n\t\t\t\t\tadvertised.delete(path);\n\t\t\t\t\tif (!previous?.live) return;\n\t\t\t\t\tthis.#consumes.evict(path);\n\t\t\t\t\tconsole.debug(`announced: broadcast=${path} active=false`);\n\t\t\t\t\tannounced.append({\n\t\t\t\t\t\tprefix: path,\n\t\t\t\t\t\tcaptures: previous.captures,\n\t\t\t\t\t\tkind: \"retracted\",\n\t\t\t\t\t\troute: previous.route,\n\t\t\t\t\t});\n\t\t\t\t};\n\n\t\t\t\t// In Lite05+ the sender's origin arrives via AnnounceOk, not in each hop\n\t\t\t\t// list, so fold it back in before checking.\n\t\t\t\tif (hops !== undefined) {\n\t\t\t\t\tconst full = responderOrigin !== undefined ? [...hops, responderOrigin] : hops;\n\t\t\t\t\tif (full.includes(this.hop)) {\n\t\t\t\t\t\t// A reflected restart means the peer's remaining route loops back through\n\t\t\t\t\t\t// us, so the route is gone even though the message says active. The\n\t\t\t\t\t\t// advertisement stays live: the peer still holds the path and its id still\n\t\t\t\t\t\t// resolves here.\n\t\t\t\t\t\tretract();\n\t\t\t\t\t\tadvertised.set(path, {\n\t\t\t\t\t\t\tpublisher: undefined,\n\t\t\t\t\t\t\tlive: false,\n\t\t\t\t\t\t\troute: { hops: full, cost: Cost.zero },\n\t\t\t\t\t\t\tcaptures: undefined,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (!active) {\n\t\t\t\t\tretract();\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t// The first hop identifies the original publisher; an empty chain means the\n\t\t\t\t// peer itself originated it. One that names nobody (lite-01..03, or a peer\n\t\t\t\t// reporting 0) gets this connection's stamp in front of its 0.\n\t\t\t\tconst fullHops = stampHops(\n\t\t\t\t\thops !== undefined && responderOrigin !== undefined\n\t\t\t\t\t\t? [...hops, responderOrigin]\n\t\t\t\t\t\t: [...(hops ?? [])],\n\t\t\t\t\tthis.#stamp,\n\t\t\t\t);\n\t\t\t\t// Appending a withheld AnnounceOk(0) onto a 32-entry list is the same\n\t\t\t\t// drop Rust's Hops::push makes: do not expose an overlong chain.\n\t\t\t\tif (fullHops === undefined || fullHops.length > MAX_HOPS) {\n\t\t\t\t\tconsole.debug(`announced: broadcast=${path} dropped (hop chain at MAX_HOPS)`);\n\t\t\t\t\tadvertised.set(path, {\n\t\t\t\t\t\tpublisher: undefined,\n\t\t\t\t\t\tlive: false,\n\t\t\t\t\t\troute: { hops: [], cost: Cost.zero },\n\t\t\t\t\t\tcaptures: undefined,\n\t\t\t\t\t});\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst publisher = fullHops[0];\n\t\t\t\tconst route: Route = { hops: fullHops, cost: cost ?? Cost.zero };\n\t\t\t\tconst captures = scopeCaptures(scope, path);\n\t\t\t\tif (!visible(path)) {\n\t\t\t\t\tadvertised.set(path, { publisher, live: false, route, captures });\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t// A second advertisement for a path we already carry is a restart: either an\n\t\t\t\t// explicit ANNOUNCE_UPDATE, or (lite-05) a duplicate ANNOUNCE. It updates the\n\t\t\t\t// route in place, so a forwarder re-prices without retracting.\n\t\t\t\tconst previous = advertised.get(path);\n\t\t\t\tif (previous?.live) {\n\t\t\t\t\t// A different publisher took the path. Subscriptions already open drain\n\t\t\t\t\t// the old copy, but the next consume starts fresh rather than reusing the\n\t\t\t\t\t// old publisher's cached track info.\n\t\t\t\t\tif (previous.publisher !== publisher) this.#consumes.evict(path);\n\t\t\t\t\tadvertised.set(path, { publisher, live: true, route, captures });\n\t\t\t\t\tconsole.debug(`announced: broadcast=${path} rerouted`);\n\t\t\t\t\tif (!routesEqual(previous.route, route)) {\n\t\t\t\t\t\tannounced.append({ prefix: path, captures, kind: \"updated\", route });\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tadvertised.set(path, { publisher, live: true, route, captures });\n\n\t\t\t\tconsole.debug(`announced: broadcast=${path} active=true`);\n\t\t\t\tannounced.append({ prefix: path, captures, kind: \"announced\", route });\n\t\t\t}\n\n\t\t\tannounced.close();\n\t\t} catch (err: unknown) {\n\t\t\tconst e = error(err);\n\t\t\t// Reaches here on a protocol violation the peer committed (a second\n\t\t\t// advertisement for a live path, an unknown announce id) as well as on a\n\t\t\t// transport failure. Either way the peer has to be told: closing only our side\n\t\t\t// would leave it announcing into a stream nobody reads.\n\t\t\tstream.abort(e);\n\t\t\tannounced.close(e);\n\t\t\t// A violation ends the session, not just this stream, so a nonconforming peer\n\t\t\t// cannot repeat it on the next one. Matches `ietf::Subscriber` and the Rust\n\t\t\t// lite subscriber, where the announce half only ever ends the session on error.\n\t\t\tif (e instanceof ProtocolViolation) {\n\t\t\t\tthis.#quic.close({ closeCode: PROTOCOL_VIOLATION_CODE, reason: closeReason(reason(e)) });\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Consumes a broadcast from the connection.\n\t *\n\t * Deduplicated per path: repeat calls for the same still-live path share one reference-counted\n\t * broadcast (and one upstream subscription). The shared broadcast closes once every caller has\n\t * closed its handle, so callers close normally.\n\t *\n\t * @param name - The name of the broadcast to consume\n\t * @returns A Broadcast instance\n\t */\n\tconsume(path: Path.Valid): broadcast.Consumer {\n\t\treturn this.#consumes.get(path) ?? this.#consumes.insert(path, this.#createConsume(path));\n\t}\n\n\t#createConsume(path: Path.Valid): broadcast.Consumer {\n\t\t// A consumed broadcast resolves info() and fetchGroup() over the wire by reaching\n\t\t// back into this Subscriber (see ConsumeBroadcast below), rather than the wire\n\t\t// installing callbacks on the broadcast.\n\t\tconst consumer = new ConsumeBroadcast(this, path);\n\n\t\tvoid (async () => {\n\t\t\tfor (;;) {\n\t\t\t\tconst request = await wireOf(consumer).requested();\n\t\t\t\tif (!request) break;\n\t\t\t\tvoid this.#runSubscribe(path, request);\n\t\t\t}\n\t\t})();\n\n\t\treturn consumer;\n\t}\n\n\tasync #runSubscribe(broadcast: Path.Valid, request: track.Request) {\n\t\tconst id = this.#subscribeNext++;\n\t\tconst subscription = request.subscription;\n\t\tconst initialBounds = groupBounds(subscription.groups);\n\t\tif (emptyRange({ startGroup: initialBounds.start, endGroup: initialBounds.end })) {\n\t\t\trequest.reject(new Error(EMPTY_RANGE));\n\t\t\treturn;\n\t\t}\n\n\t\t// `timescale` stays undefined until TRACK_INFO (or, on older drafts,\n\t\t// implicit defaults) resolves it; runGroup blocks on it before decoding.\n\t\tconst timescale = new Signal<number | undefined>(undefined);\n\n\t\tconsole.debug(`subscribe start: id=${id} broadcast=${broadcast} track=${request.name}`);\n\t\tconst bounds = groupBounds(subscription.groups);\n\n\t\tconst msg = new Subscribe({\n\t\t\tid,\n\t\t\tbroadcast,\n\t\t\ttrack: request.name,\n\t\t\tpriority: subscription.priority ?? 0,\n\t\t\tmaxAge: subscription.maxAge,\n\t\t\tstartGroup: subscription.groups?.start === undefined ? undefined : bounds.start,\n\t\t\tendGroup: inclusiveGroupEnd(bounds.end),\n\t\t});\n\n\t\t// Open the stream under a timeout. The stream handle flows back via `state`\n\t\t// so the timeout path can abort it if it finishes opening after the deadline.\n\t\tconst state: { stream?: Stream } = {};\n\t\tconst setup = this.#openSubscribe(state, msg, request, id, timescale);\n\n\t\tlet opened: { stream: Stream; entry: SubscribeEntry };\n\t\ttry {\n\t\t\topened = await withTimeout(\n\t\t\t\tsetup,\n\t\t\t\tSUBSCRIBE_SETUP_TIMEOUT_MS,\n\t\t\t\t`subscribe timed out after ${SUBSCRIBE_SETUP_TIMEOUT_MS}ms waiting for the first response (browser stream limit reached?)`,\n\t\t\t);\n\t\t\tconsole.debug(`subscribe ok: id=${id} broadcast=${broadcast} track=${request.name}`);\n\t\t} catch (err) {\n\t\t\t// The setup outlived its deadline waiting for the first response: a control\n\t\t\t// timeout, not content that arrived late.\n\t\t\tconst e = err instanceof TimeoutError ? controlTimeout(err) : await sessionCause(this.#quic, err);\n\t\t\trequest.reject(e);\n\t\t\tthis.#subscribes.delete(id);\n\t\t\tconsole.warn(`subscribe error: id=${id} broadcast=${broadcast} track=${request.name} error=${reason(e)}`);\n\t\t\t// If the stream eventually opens after the timeout, abort it so we\n\t\t\t// don't leak it. Cover both branches: setup may resolve late, or it\n\t\t\t// may reject (e.g. encode/decode failure) after the stream is open.\n\t\t\tsetup.then(\n\t\t\t\t() => state.stream?.abort(e),\n\t\t\t\t() => state.stream?.abort(e),\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tconst { stream, entry } = opened;\n\t\tconst producer = entry.track;\n\t\ttry {\n\t\t\t// Watch for subscription changes and send SUBSCRIBE_UPDATE. Lite01/Lite02\n\t\t\t// don't carry SUBSCRIBE_UPDATE on the wire, so skip the watcher there\n\t\t\t// and just wait on the stream/track like before.\n\t\t\t//\n\t\t\t// On lite-05+ the publisher sends SUBSCRIBE_START/END/DROP on this stream until\n\t\t\t// its FIN; older drafts just close it. Either way group streams can still be in\n\t\t\t// flight, so the track ends only once the tail is accounted for. A reset rejects\n\t\t\t// instead, so the track ends with that error rather than a clean tail.\n\t\t\tconst responses = supportsTrackStream(this.version)\n\t\t\t\t? this.#runResponses(stream, entry)\n\t\t\t\t: stream.reader.closed;\n\t\t\tconst closed = responses.then(() => this.#settleTail(entry));\n\t\t\t// A reset that lands after the race below settled is moot; the race observes one before.\n\t\t\tclosed.catch(() => {});\n\t\t\tconst subscriptionUpdates =\n\t\t\t\tthis.version === Version.DRAFT_01 || this.version === Version.DRAFT_02\n\t\t\t\t\t? undefined\n\t\t\t\t\t: this.#runSubscriptionUpdates(id, broadcast, entry, msg, stream);\n\n\t\t\t// Terminal conditions (stream end, track close, a failed subscription update) settle at most\n\t\t\t// once; race them into one stable promise so the demand loop doesn't re-subscribe each pass.\n\t\t\t// Updates stop quietly at the FIN, which can land before the responses ahead of it are\n\t\t\t// decoded, so only their failure is terminal on its own.\n\t\t\tconst terminal: PromiseLike<unknown>[] = [closed, producer.closed];\n\t\t\tif (subscriptionUpdates !== undefined) terminal.push(subscriptionUpdates.then(() => closed));\n\t\t\tconst done = race(terminal);\n\n\t\t\t// Serve until a terminal condition fires or the last local subscriber leaves. The unused\n\t\t\t// wake is level-triggered: re-check demand so a subscriber that returns before we tear\n\t\t\t// down (e.g. a quickly unmuted tile) resumes on the same subscription.\n\t\t\tconst idle = Symbol(\"idle\");\n\t\t\tfor (;;) {\n\t\t\t\tconst reason = await race([done, producer.unused().then(() => idle)]);\n\t\t\t\tif (reason === idle && producer.closed.peek() === undefined && producer.used.peek()) continue;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tproducer.close();\n\t\t\tstream.close();\n\t\t\tconsole.debug(`subscribe close: id=${id} broadcast=${broadcast} track=${request.name}`);\n\t\t} catch (err) {\n\t\t\tconst e = await sessionCause(this.#quic, err);\n\t\t\tproducer.close(e);\n\t\t\tconsole.warn(`subscribe error: id=${id} broadcast=${broadcast} track=${request.name} error=${reason(e)}`);\n\t\t\tstream.abort(e);\n\t\t} finally {\n\t\t\tthis.#subscribes.delete(id);\n\t\t}\n\t}\n\n\t// Determine the track's immutable properties, accept the request (so the\n\t// application's track.Subscriber resolves and incoming groups have a producer to\n\t// write into), register it, then open the subscribe stream. `state.stream` is\n\t// populated as soon as the subscribe stream opens so the caller can clean it up\n\t// on timeout even before this promise settles.\n\t//\n\t// On lite-05+ the properties come from a TRACK stream opened first, and the\n\t// SUBSCRIBE is accepted implicitly (no SUBSCRIBE_OK). Older drafts carry no\n\t// per-track properties, so they resolve to defaults and just drain SUBSCRIBE_OK.\n\tasync #openSubscribe(\n\t\tstate: { stream?: Stream },\n\t\tmsg: Subscribe,\n\t\trequest: track.Request,\n\t\tid: bigint,\n\t\ttimescale: Signal<number | undefined>,\n\t): Promise<{ stream: Stream; entry: SubscribeEntry }> {\n\t\tlet producer: track.Producer;\n\t\tlet drainOk = false;\n\n\t\tif (supportsTrackStream(this.version)) {\n\t\t\t// Fetch the immutable properties once via the TRACK stream.\n\t\t\tconst info = await this.#trackInfo(msg.broadcast, msg.track);\n\t\t\tproducer = request.accept(this.#toModelInfo(info));\n\t\t\ttimescale.set(info.timescale);\n\t\t} else {\n\t\t\t// Older drafts negotiate nothing per-track: verbatim frames, no timescale.\n\t\t\tproducer = request.accept();\n\t\t\ttimescale.set(0);\n\t\t\tdrainOk = true;\n\t\t}\n\n\t\t// Register before opening SUBSCRIBE so a racing GROUP stream finds the entry.\n\t\tconst entry: SubscribeEntry = {\n\t\t\ttrack: producer,\n\t\t\ttimescale,\n\t\t\t// The effective max age is the stopgap grace: the wrong clock (it bounds\n\t\t\t// presentation-time drift), but it is how long the subscriber was willing to wait\n\t\t\t// for a late group anyway. Already the smaller of the subscriber's and the track's.\n\t\t\ttail: new Tail({\n\t\t\t\tgrace: () => {\n\t\t\t\t\tconst maxAge = producer.subscription.peek()?.maxAge ?? Time.Milli.zero;\n\t\t\t\t\treturn maxAge > 0 ? maxAge : TAIL_GRACE_MS;\n\t\t\t\t},\n\t\t\t}),\n\t\t\trequested: msg.startGroup,\n\t\t};\n\t\tthis.#subscribes.set(id, entry);\n\n\t\tstate.stream = await Stream.open(this.#quic, { version: this.version });\n\t\tawait state.stream.writer.u53(StreamId.Subscribe);\n\t\tawait msg.encode(state.stream.writer, this.version);\n\n\t\tif (drainOk) {\n\t\t\t// The first response MUST be a SUBSCRIBE_OK (older drafts only).\n\t\t\tconst resp = await decodeSubscribeResponse(state.stream.reader, this.version);\n\t\t\tif (!(\"ok\" in resp)) {\n\t\t\t\tthrow new Error(\"first subscribe response must be SUBSCRIBE_OK\");\n\t\t\t}\n\t\t}\n\n\t\treturn { stream: state.stream, entry };\n\t}\n\n\t// Opens a TRACK stream, reads the single TRACK_INFO, and FINs. Lite-05+ only.\n\tasync #trackInfo(broadcast: Path.Valid, track: string): Promise<TrackInfo> {\n\t\treturn this.#exchange({ version: this.version }, async (stream) => {\n\t\t\tawait stream.writer.u53(StreamId.Track);\n\t\t\tawait new TrackMessage(broadcast, track).encode(stream.writer, this.version);\n\t\t\tconst info = await TrackInfo.decode(stream.reader, this.version);\n\t\t\t// The publisher FINs after TRACK_INFO; FIN our side too.\n\t\t\tstream.close();\n\t\t\treturn info;\n\t\t});\n\t}\n\n\t// Opens a stream and runs a request/response exchange on it, resetting the stream if `run`\n\t// fails. Subscriber.close() also resets it while `run` is pending, so a peer that never\n\t// answers cannot hold it open, and a stream that opens after the close is reset at once.\n\tasync #exchange<T>(options: OpenOptions, run: (stream: Stream) => Promise<T>): Promise<T> {\n\t\tconst closed = this.#closed.signal;\n\t\tclosed.throwIfAborted();\n\t\tconst stream = await Stream.open(this.#quic, options);\n\t\tconst abort = () => stream.abort(error(closed.reason));\n\t\tclosed.addEventListener(\"abort\", abort);\n\t\ttry {\n\t\t\tclosed.throwIfAborted();\n\t\t\treturn await run(stream);\n\t\t} catch (err) {\n\t\t\tstream.abort(error(err));\n\t\t\tthrow err;\n\t\t} finally {\n\t\t\tclosed.removeEventListener(\"abort\", abort);\n\t\t}\n\t}\n\n\t// Map the wire TRACK_INFO onto the model track.Info a producer/consumer holds.\n\t#toModelInfo(info: TrackInfo): track.Info {\n\t\treturn {\n\t\t\ttimescale: Time.Timescale(info.timescale),\n\t\t\t// Publisher Max Age rides on the wire, so the local retention window\n\t\t\t// matches what the upstream advertises (relays re-serve with the same bound).\n\t\t\tmaxAge: Time.Milli(info.maxAge),\n\t\t\tpriority: info.priority,\n\t\t};\n\t}\n\n\t// Resolve a track's immutable model info via a TRACK stream (lite-05+), for the\n\t// ConsumeBroadcast backing track.Consumer.query(). On older drafts there's no TRACK\n\t// stream, so this rejects rather than fabricating defaults.\n\tasync resolveTrackInfo(broadcast: Path.Valid, track: string): Promise<track.Info> {\n\t\tif (!supportsTrackStream(this.version)) {\n\t\t\tthrow new Error(\"track info requires moq-lite-05 or newer\");\n\t\t}\n\t\treturn this.#toModelInfo(await this.#trackInfo(broadcast, track));\n\t}\n\n\t// Open a FETCH stream for one group and stream its bare frames into a group, for the\n\t// ConsumeBroadcast backing track.Consumer.fetchGroup() (lite-05+).\n\tasync fetchGroup(\n\t\tbroadcast: Path.Valid,\n\t\ttrack: string,\n\t\tsequence: number,\n\t\toptions: track.FetchGroupOptions = {},\n\t): Promise<netGroup.Consumer> {\n\t\toptions.signal?.throwIfAborted();\n\n\t\t// Coalesce onto a still-open fetch of the same group so we don't open a second FETCH\n\t\t// stream (and re-download it); each caller reads an independent mirror.\n\t\t//\n\t\t// Reserve each caller's mirror before the fetch starts or is awaited: the fetch watches\n\t\t// demand from the start, and a fast FIN cannot discard frames before these callers\n\t\t// receive their handles. An abort closes only this caller's mirror, so the stream is\n\t\t// cancelled once the last one leaves.\n\t\tconst key = JSON.stringify([broadcast, track, sequence]);\n\t\tlet entry = this.#fetches.get(key);\n\t\tlet consumer: netGroup.Consumer;\n\t\tif (entry && !entry.group.isClosed) {\n\t\t\tconsumer = entry.group.mirror();\n\t\t} else {\n\t\t\tconst group = new netGroup.Producer(sequence);\n\t\t\tconsumer = group.mirror();\n\t\t\tentry = { group, accepted: this.#runFetch(broadcast, track, sequence, options.priority ?? 0, group) };\n\t\t\tthis.#fetches.set(key, entry);\n\t\t\tvoid group.closed.then(() => {\n\t\t\t\tif (this.#fetches.get(key)?.group === group) this.#fetches.delete(key);\n\t\t\t});\n\t\t}\n\n\t\ttry {\n\t\t\tawait untilAborted(entry.accepted, options.signal);\n\t\t\treturn consumer;\n\t\t} catch (err) {\n\t\t\tconsumer.close();\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\t// Open the FETCH stream and pump the response into the shared group. Setup errors close the\n\t// group, evict the entry, and reject every caller waiting for acceptance. A setup every caller\n\t// has abandoned is cancelled the same way.\n\tasync #runFetch(\n\t\tbroadcast: Path.Valid,\n\t\ttrack: string,\n\t\tsequence: number,\n\t\tpriority: number,\n\t\tgroup: netGroup.Producer,\n\t): Promise<void> {\n\t\ttry {\n\t\t\tif (!supportsTrackStream(this.version)) {\n\t\t\t\tthrow new Error(\"fetch group requires moq-lite-05 or newer\");\n\t\t\t}\n\n\t\t\t// Lite has no FETCH_OK, so a publisher that never answers would hold the setup forever.\n\t\t\t// Subscriber.close() closing the group releases every caller at any stage, and resets\n\t\t\t// the streams the setup opened.\n\t\t\tconst setup = this.#fetchSetup(broadcast, track, sequence, priority, group);\n\t\t\tlet accepted: { stream: Stream; info: TrackInfo };\n\t\t\ttry {\n\t\t\t\taccepted = await untilAbandoned(group, setup);\n\t\t\t} catch (err: unknown) {\n\t\t\t\t// A setup that finishes just after the close hands back a stream nobody will read.\n\t\t\t\tvoid setup.then(\n\t\t\t\t\t({ stream }) => stream.abort(error(err)),\n\t\t\t\t\t() => void 0,\n\t\t\t\t);\n\t\t\t\tthrow err;\n\t\t\t}\n\n\t\t\tvoid this.#runFetchResponse(accepted.stream, group, Time.Timescale(accepted.info.timescale));\n\t\t} catch (err: unknown) {\n\t\t\tgroup.close(error(err));\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\t// Resolve the track's timescale, then open the FETCH stream and wait for it to be accepted.\n\t// Closing the group during that wait resets the stream.\n\tasync #fetchSetup(\n\t\tbroadcast: Path.Valid,\n\t\ttrack: string,\n\t\tsequence: number,\n\t\tpriority: number,\n\t\tgroup: netGroup.Producer,\n\t): Promise<{ stream: Stream; info: TrackInfo }> {\n\t\tconst info = await untilClosed(group, this.#trackInfo(broadcast, track));\n\t\treturn this.#exchange({ sendOrder: sendOrder({ priority }), version: this.version }, async (stream) => {\n\t\t\tawait stream.writer.u53(StreamId.Fetch);\n\t\t\tawait new FetchMessage({ broadcast, track, priority, group: sequence }).encode(stream.writer, this.version);\n\t\t\t// A byte or an empty-group FIN accepts the fetch; a reset rejects it.\n\t\t\t// done() buffers that byte so the response pump can decode it normally.\n\t\t\tawait untilClosed(group, stream.reader.done());\n\t\t\treturn { stream, info };\n\t\t});\n\t}\n\n\t// Read the FETCH response (bare zigzag-delta-timestamped frames) into the group, then\n\t// FIN. A stream-level failure aborts the group so its reader observes the gap.\n\tasync #runFetchResponse(stream: Stream, group: netGroup.Producer, timescale: Time.Timescale): Promise<void> {\n\t\ttry {\n\t\t\tconst decode = frameDecoder(timescale);\n\n\t\t\t// Serve until the stream FINs, the group closes, or every reader leaves. A group can\n\t\t\t// stay open indefinitely (a catalog or JSON stream), so an abandoned fetch is stopped by\n\t\t\t// demand, not by the stream ending. `unused` is watched across frames as one stable\n\t\t\t// promise; the check is level-triggered, so a coalesced fetch that arrives before we\n\t\t\t// cancel re-arms and resumes.\n\t\t\tconst idle: unique symbol = Symbol(\"idle\");\n\t\t\tlet unused = group.unused().then((): typeof idle => idle);\n\t\t\t// A decode consumes its frame whenever it lands, so one outstanding across a re-arm is\n\t\t\t// kept and awaited again rather than abandoned with its frame.\n\t\t\tlet pending: Promise<netGroup.Frame | undefined> | undefined;\n\t\t\tfor (;;) {\n\t\t\t\t// Buffered frames are written without an await, as in a group stream.\n\t\t\t\tlet frame = pending === undefined ? stream.reader.tryDecode(decode) : undefined;\n\t\t\t\tif (!frame) {\n\t\t\t\t\tpending ??= stream.reader.decodeMaybe(decode);\n\t\t\t\t\tconst next = await race([pending, group.closed, unused]);\n\t\t\t\t\tif (next === idle) {\n\t\t\t\t\t\tif (group.isClosed) break;\n\t\t\t\t\t\tif (group.used.peek()) {\n\t\t\t\t\t\t\tunused = group.unused().then((): typeof idle => idle);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Abandoned mid-group: the truncated group must never end clean.\n\t\t\t\t\t\tthrow new StreamError(StreamCode.Cancel, { message: \"cancel\" });\n\t\t\t\t\t}\n\t\t\t\t\tpending = undefined;\n\t\t\t\t\tif (!next || next instanceof Error) break;\n\t\t\t\t\tframe = next;\n\t\t\t\t}\n\t\t\t\tgroup.writeFrame(frame);\n\t\t\t}\n\n\t\t\tgroup.close();\n\t\t\tstream.close();\n\t\t} catch (err: unknown) {\n\t\t\tconst e = error(err);\n\t\t\tgroup.close(e);\n\t\t\tstream.abort(e);\n\t\t}\n\t}\n\n\t// Reads SUBSCRIBE_START/END/DROP on the subscribe stream until FIN (lite-05+), recording\n\t// the range the tail is accounted against. SUBSCRIBE_END declares the track's end right\n\t// away, so a consumer learns it before the last groups arrive. The publisher must declare\n\t// the end before FIN; resets and malformed responses reject with their failure.\n\tasync #runResponses(stream: Stream, entry: SubscribeEntry): Promise<void> {\n\t\tfor (;;) {\n\t\t\tconst resp = await decodeSubscribeResponseMaybe(stream.reader, this.version);\n\t\t\tif (!resp) {\n\t\t\t\tif (entry.end === undefined)\n\t\t\t\t\tthrow new ProtocolViolation(\"subscribe stream ended without SUBSCRIBE_END\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (\"start\" in resp) {\n\t\t\t\tentry.start = resp.start.group;\n\t\t\t\t// The groups the SUBSCRIBE asked for below it are not waited for, whatever the\n\t\t\t\t// demand asks later. One that still arrives is delivered.\n\t\t\t\tif (entry.requested !== undefined) entry.tail.account(entry.requested, entry.start);\n\t\t\t} else if (\"end\" in resp) {\n\t\t\t\tif (entry.end !== undefined) throw new ProtocolViolation(\"duplicate SUBSCRIBE_END\");\n\t\t\t\tentry.end = resp.end.group;\n\t\t\t\tif (hasStreamCount(this.version)) entry.streams = resp.end.streams;\n\t\t\t\t// A local close can win the race with the response; there is nothing left to end.\n\t\t\t\tif (entry.track.closed.peek() !== undefined) continue;\n\t\t\t\ttry {\n\t\t\t\t\tentry.track.finishAt(entry.end);\n\t\t\t\t} catch (err) {\n\t\t\t\t\t// lite-05 specified an inclusive end, and @moq/net 0.1.3 to 0.1.9 sent one, so\n\t\t\t\t\t// there an end below a received group only costs the early boundary: the FIN\n\t\t\t\t\t// still finishes the track. Later drafts made it exclusive.\n\t\t\t\t\tif (this.version !== Version.DRAFT_05) {\n\t\t\t\t\t\tthrow new ProtocolViolation(`invalid SUBSCRIBE_END: ${reason(error(err))}`);\n\t\t\t\t\t}\n\t\t\t\t\tconsole.warn(`invalid SUBSCRIBE_END: ${reason(error(err))}`);\n\t\t\t\t}\n\t\t\t} else if (\"drop\" in resp) {\n\t\t\t\tentry.tail.account(resp.drop.start, resp.drop.end + 1);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Wait for the group streams the publisher still owes once it has ended the subscription.\n\t//\n\t// lite-07 counts streams, so skipped sequences owe nothing. Older drafts account for\n\t// the range using received headers and SUBSCRIBE_DROP. A counted stream reset before\n\t// its header leaves no trace, so the grace still bounds that wait. Streams whose\n\t// headers arrived keep reading until their own FIN or reset.\n\t#settleTail(entry: SubscribeEntry): Promise<void> {\n\t\tconst { tail, track } = entry;\n\n\t\tconst complete = () => {\n\t\t\tif (entry.streams !== undefined) return tail.streams >= entry.streams;\n\t\t\t// Without SUBSCRIBE_END (older drafts) nothing says which groups are owed.\n\t\t\tif (entry.end === undefined) return false;\n\t\t\t// Without SUBSCRIBE_START the publisher served no group at all.\n\t\t\tif (entry.start === undefined) return true;\n\t\t\t// Owed from the floor the demand last asked for, which an update can move either\n\t\t\t// way, or where SUBSCRIBE_START resolved a live-edge one. The groups the SUBSCRIBE\n\t\t\t// asked for below its SUBSCRIBE_START were accounted for when it arrived.\n\t\t\tconst groups = track.subscription.peek()?.groups;\n\t\t\tconst bounds = groupBounds(groups ?? {});\n\t\t\tconst start = groups?.start === undefined ? entry.start : bounds.start;\n\t\t\tconst end = bounds.end === undefined ? entry.end : Math.min(entry.end, bounds.end);\n\t\t\treturn tail.covers(start, end);\n\t\t};\n\n\t\treturn tail.settle(complete, track.closed);\n\t}\n\n\t/**\n\t * Send SUBSCRIBE_UPDATE messages whenever the track's aggregate subscription changes.\n\t *\n\t * Resolves cleanly when the stream or track closes, so the caller can include\n\t * this in a race without leaving a dangling pending write that would\n\t * become an unhandled rejection if the user calls update after close.\n\t *\n\t * Peeks the signal at the top of every iteration so that updates which landed\n\t * before SubscribeOk arrived (or between iterations, before .next() registered\n\t * its listener) aren't lost.\n\t */\n\tasync #runSubscriptionUpdates(\n\t\tid: bigint,\n\t\tbroadcast: Path.Valid,\n\t\tentry: SubscribeEntry,\n\t\tmsg: Subscribe,\n\t\tstream: Stream,\n\t): Promise<void> {\n\t\tconst track = entry.track;\n\t\tconst stopped: Promise<null> = race([track.closed, stream.reader.closed]).then(() => null);\n\t\tlet lastSent: track.Subscription = {\n\t\t\tpriority: msg.priority,\n\t\t\tmaxAge: Time.Milli(msg.maxAge),\n\t\t\tgroups: {\n\t\t\t\tstart: msg.startGroup === undefined ? undefined : { included: msg.startGroup },\n\t\t\t\tend: msg.endGroup === undefined ? undefined : { excluded: exclusiveGroupEnd(msg.endGroup) ?? 0 },\n\t\t\t},\n\t\t};\n\n\t\tfor (;;) {\n\t\t\tconst current = track.subscription.peek();\n\t\t\tif (current === undefined || this.#sameSubscription(current, lastSent)) {\n\t\t\t\t// Nothing new to send; wait for a change or termination.\n\t\t\t\tconst next = await race([track.subscription.changed(), stopped]);\n\t\t\t\tif (next === null) return;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Demand collapsing to nothing is refused the same way an initial empty\n\t\t\t// request is: the error closes the track, so every local subscriber sees it.\n\t\t\tconst bounds = groupBounds(current.groups);\n\t\t\tif (emptyRange({ startGroup: bounds.start, endGroup: bounds.end })) throw new Error(EMPTY_RANGE);\n\n\t\t\t// A lowered floor owes groups nobody asked for until now.\n\t\t\tif (current.groups?.start !== undefined) {\n\t\t\t\tconst floor = lastSent.groups?.start === undefined ? entry.start : groupBounds(lastSent.groups).start;\n\t\t\t\tentry.tail.demand(bounds.start, floor ?? Number.POSITIVE_INFINITY);\n\t\t\t}\n\n\t\t\t// Round-trip the other Subscribe parameters so the publisher doesn't\n\t\t\t// interpret SUBSCRIBE_UPDATE as a reset of ordered/maxAge/etc.\n\t\t\tconst update = new SubscribeUpdate({\n\t\t\t\tpriority: current.priority ?? 0,\n\t\t\t\tmaxAge: current.maxAge,\n\t\t\t\tstartGroup: current.groups?.start === undefined ? undefined : bounds.start,\n\t\t\t\tendGroup: inclusiveGroupEnd(bounds.end),\n\t\t\t});\n\t\t\tawait update.encode(stream.writer, this.version);\n\t\t\tlastSent = { ...current };\n\t\t\tconsole.debug(`subscribe update: id=${id} broadcast=${broadcast} track=${track.name}`);\n\t\t}\n\t}\n\n\t#sameSubscription(a: track.Subscription, b: track.Subscription): boolean {\n\t\tconst ag = groupBounds(a.groups);\n\t\tconst bg = groupBounds(b.groups);\n\t\t// `groupBounds` reads an omitted start as 0. A pre-06 wire tells them apart: omitted\n\t\t// joins at the publisher's start, and 0 is group 0. Lite-06 encodes both as 0.\n\t\tconst sameStart =\n\t\t\tresolvesStart(this.version) || (a.groups?.start === undefined) === (b.groups?.start === undefined);\n\t\treturn (\n\t\t\t(a.priority ?? 0) === (b.priority ?? 0) &&\n\t\t\t(a.maxAge ?? 0) === (b.maxAge ?? 0) &&\n\t\t\tsameStart &&\n\t\t\tag.start === bg.start &&\n\t\t\tag.end === bg.end\n\t\t);\n\t}\n\n\t/**\n\t * Handles a group message.\n\t * @param group - The group message\n\t * @param stream - The stream to read frames from\n\t *\n\t * @internal\n\t */\n\tasync runGroup(group: GroupMessage, stream: Reader) {\n\t\tconst entry = this.#subscribes.get(group.subscribe);\n\t\tif (!entry) {\n\t\t\tif (group.subscribe >= this.#subscribeNext) {\n\t\t\t\tthrow new Error(`unknown subscription: id=${group.subscribe}`);\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\n\t\tconst { track, timescale, tail } = entry;\n\t\tconst producer = new netGroup.Producer(group.sequence);\n\t\tconst read = tail.open(group.sequence);\n\n\t\ttry {\n\t\t\t// The publisher contradicted its own end, which no later group can repair. lite-05\n\t\t\t// specified an inclusive end, so its last group lands on it: the write below drops\n\t\t\t// only that group there.\n\t\t\tif (entry.end !== undefined && group.sequence >= entry.end && this.version !== Version.DRAFT_05) {\n\t\t\t\tconst violation = new ProtocolViolation(\n\t\t\t\t\t`group ${group.sequence} is at or past the declared end ${entry.end}`,\n\t\t\t\t);\n\t\t\t\ttrack.close(violation);\n\t\t\t\tthrow violation;\n\t\t\t}\n\t\t\ttrack.writeGroup(producer);\n\n\t\t\t// Block until the timescale is known; the group's stream can arrive before\n\t\t\t// TRACK_INFO (or implicit defaults) resolves it on the subscribe stream.\n\t\t\tlet scale = timescale.peek();\n\t\t\twhile (scale === undefined) {\n\t\t\t\tif (track.closed.peek() !== undefined) {\n\t\t\t\t\t// Subscription ended before the scale resolved; nothing to decode.\n\t\t\t\t\tproducer.close();\n\t\t\t\t\tstream.stop(new StreamError(StreamCode.Cancel, { message: \"cancel\" }));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tawait Signal.race(timescale, track.closed);\n\t\t\t\tscale = timescale.peek();\n\t\t\t}\n\n\t\t\tawait readFrames(stream, producer, scale);\n\n\t\t\tproducer.close();\n\t\t\tstream.stop(new StreamError(StreamCode.Cancel, { message: \"cancel\" }));\n\t\t} catch (err: unknown) {\n\t\t\tconst e = await sessionCause(this.#quic, err);\n\t\t\tproducer.close(e);\n\t\t\tstream.stop(e);\n\t\t} finally {\n\t\t\tread();\n\t\t}\n\t}\n\n\t/**\n\t * Receives QUIC datagrams and routes each to its subscription's track producer (lite-05 §6.4).\n\t *\n\t * Returns immediately on a non-datagram transport or pre-lite-05 version. A decode error or an\n\t * unknown subscribe id drops that datagram without tearing down the session (best-effort); the\n\t * loop ends only when the datagram stream closes.\n\t *\n\t * @internal\n\t */\n\tasync runDatagrams(): Promise<void> {\n\t\tif (!hasDatagrams(this.version) || DatagramStream.maxDatagramSize(this.#quic) === 0) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Never reject: this loop is awaited alongside the connection's other tasks, so a\n\t\t// datagram-stream failure must not tear the whole session down (it's best-effort).\n\t\tconst reader = DatagramStream.datagramReader(this.#quic);\n\t\tif (!reader) return;\n\n\t\ttry {\n\t\t\ttry {\n\t\t\t\tfor (;;) {\n\t\t\t\t\tconst { value, done } = await reader.read();\n\t\t\t\t\tif (done) break;\n\t\t\t\t\tif (!value) continue;\n\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this.#routeDatagram(value);\n\t\t\t\t\t} catch (err: unknown) {\n\t\t\t\t\t\tconsole.debug(`dropping datagram: ${reason(err)}`);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\treader.releaseLock();\n\t\t\t}\n\t\t} catch (err: unknown) {\n\t\t\tconst e = error(err);\n\t\t\tif (e.message === \"The session is closed.\") {\n\t\t\t\tconsole.debug(`datagram receive stopped: ${e.message}`);\n\t\t\t} else {\n\t\t\t\tconsole.warn(\"datagram stream error\", err);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Decode one datagram body and hand it to the matching subscription's producer. Drops the\n\t// datagram (best-effort) if the subscription is unknown/closed or its timescale isn't resolved.\n\tasync #routeDatagram(payload: Uint8Array): Promise<void> {\n\t\tconst dg = await DatagramMessage.decode(payload, this.version);\n\n\t\tconst entry = this.#subscribes.get(dg.subscribe);\n\t\tif (!entry) return; // Unknown or already-closed subscription.\n\n\t\t// Datagrams are lite-05+, which always negotiates a timescale; if it hasn't resolved\n\t\t// yet (the datagram raced ahead of TRACK_INFO), drop rather than guess.\n\t\tconst scale = entry.timescale.peek();\n\t\tif (!scale) return;\n\n\t\tconst timestamp = new Time.Timestamp(dg.timestamp, Time.Timescale(scale));\n\t\t// A datagram's sequence is never owed a stream, so it never holds the tail open.\n\t\tentry.tail.account(dg.sequence, dg.sequence + 1);\n\t\tentry.track.insertDatagram(dg.sequence, timestamp, dg.payload);\n\t}\n\n\t/**\n\t * Opens a PROBE bidi stream to receive bandwidth estimates from the publisher.\n\t * Returns immediately if recv bandwidth is not supported.\n\t *\n\t * Probe is best-effort telemetry: a stream-level failure (peer reset, FIN,\n\t * missing peer support, transport hiccup) is caught and logged, never\n\t * propagated to the connection. On exit the bandwidth/RTT signals are\n\t * cleared so consumers see them as stale.\n\t *\n\t * @internal\n\t */\n\t// Await the peer's advertised probe level, blocking until its SETUP arrives. The peer\n\t// MUST send exactly one SETUP, so this resolves once that stream is read.\n\tasync #peerProbeLevel(peerSetup: Signal<Setup | undefined>): Promise<ProbeLevel> {\n\t\tlet setup = peerSetup.peek();\n\t\twhile (setup === undefined) {\n\t\t\tsetup = await peerSetup.changed();\n\t\t}\n\t\treturn setup.probe;\n\t}\n\n\tasync runProbe(): Promise<void> {\n\t\tif (!this.#probe) return;\n\t\tif (this.version === Version.DRAFT_01 || this.version === Version.DRAFT_02) return;\n\n\t\t// Lite-05+ gates the PROBE stream on the peer advertising Probe >= Report in its\n\t\t// SETUP. Wait for the SETUP, then bail if the peer can't report bitrate. Older\n\t\t// drafts have no SETUP, so they keep probing unconditionally.\n\t\tif (this.#peerSetup) {\n\t\t\tconst probe = await this.#peerProbeLevel(this.#peerSetup);\n\t\t\tif (probe < ProbeLevel.Report) return;\n\t\t}\n\n\t\t// Probe is best-effort: any failure (stream reset by peer, missing peer support,\n\t\t// transport hiccup) MUST NOT tear down the connection. On error, drop the\n\t\t// estimates so consumers know they're stale.\n\t\ttry {\n\t\t\tconst stream = await Stream.open(this.#quic, { version: this.version });\n\t\t\tawait stream.writer.u53(StreamId.Probe);\n\n\t\t\tfor (;;) {\n\t\t\t\tconst probe = await Probe.decodeMaybe(stream.reader, this.version);\n\t\t\t\tif (!probe) break;\n\t\t\t\t// lite-03 carries no RTT field, so an absent value there means \"not\n\t\t\t\t// carried\" and the last reading stands. From lite-04 the field is\n\t\t\t\t// always present and 0 explicitly means unknown, so undefined is the\n\t\t\t\t// peer retracting a value we would otherwise hold forever.\n\t\t\t\tconst prev = this.#probe.peek();\n\t\t\t\tconst rtt = probe.rtt !== undefined ? Time.Milli(probe.rtt) : undefined;\n\t\t\t\tthis.#probe.set({\n\t\t\t\t\t// `undefined` is the peer reporting \"unknown\", not an estimate of\n\t\t\t\t\t// zero; letting it through would become a real 0 bps ABR target.\n\t\t\t\t\testimatedRecvRate: probe.bitrate,\n\t\t\t\t\trtt: hasProbeRtt(this.version) ? rtt : (rtt ?? prev.rtt),\n\t\t\t\t});\n\t\t\t}\n\t\t} catch (err: unknown) {\n\t\t\tif (!this.#closed.signal.aborted) {\n\t\t\t\tconsole.warn(\"probe stream error\", err);\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.#probe.set({});\n\t\t}\n\t}\n\n\t/**\n\t * Ends every subscribed track: cleanly for a deliberate close, or with `err` when the\n\t * session died, since those tracks were cut off rather than ended.\n\t */\n\tclose(err?: Error) {\n\t\t// A fetch or setup exchange cut off by the session is incomplete even on a deliberate\n\t\t// close, so it always ends with an error.\n\t\tconst cut = err ?? new StreamError(StreamCode.SessionClosed, { message: \"session closed\" });\n\t\tthis.#closed.abort(cut);\n\n\t\tfor (const { track } of this.#subscribes.values()) {\n\t\t\ttrack.close(err);\n\t\t}\n\n\t\tthis.#subscribes.clear();\n\n\t\t// This also releases callers still awaiting acceptance.\n\t\tfor (const { group } of this.#fetches.values()) {\n\t\t\tgroup.close(cut);\n\t\t}\n\t}\n}\n\n// Settles with `step`, or rejects with the group's error once it closes first. A publisher\n// may never answer a FETCH, so Subscriber.close() closing the group is what releases it.\nasync function untilClosed<T>(group: netGroup.Producer, step: Promise<T>): Promise<T> {\n\tconst value = await race([step, group.closed]);\n\tconst closed = group.closed.peek();\n\tif (closed !== undefined) throw closed ?? new Error(\"fetch closed before it was accepted\");\n\treturn value as T;\n}\n\n// Like untilClosed, but also cancels once every reader has left. Demand is level-triggered, so a\n// caller that coalesces onto the group before the check re-arms it.\nasync function untilAbandoned<T>(group: netGroup.Producer, step: Promise<T>): Promise<T> {\n\tconst idle: unique symbol = Symbol(\"idle\");\n\tfor (;;) {\n\t\tconst value = await untilClosed(group, race([step, group.unused().then((): typeof idle => idle)]));\n\t\tif (value !== idle) return value as T;\n\t\tif (!group.used.peek()) throw new StreamError(StreamCode.Cancel, { message: \"cancel\" });\n\t}\n}\n\n/**\n * A broadcast consumed from a lite session. It resolves `track.Consumer.query()` and\n * `.fetchGroup()` over the wire (lite-05+ TRACK / FETCH streams) by reaching into the\n * {@link Subscriber} it was opened from, the way the Rust `BroadcastConsumer` holds its\n * session. Live subscribes still flow through the inherited requested() queue.\n */\nclass ConsumeBroadcast extends broadcast.Consumer {\n\t#subscriber: Subscriber;\n\t#path: Path.Valid;\n\n\tconstructor(subscriber: Subscriber, path: Path.Valid, state?: never) {\n\t\tsuper(state);\n\t\toverrideBroadcastWire(this, {\n\t\t\tresolveTrackInfo: (name) => subscriber.resolveTrackInfo(path, name),\n\t\t\tfetchGroup: (name, sequence, options) => subscriber.fetchGroup(path, name, sequence, options),\n\t\t});\n\t\tthis.#subscriber = subscriber;\n\t\tthis.#path = path;\n\t}\n\n\t// Preserve the subclass (and its wire-backed info/fetchGroup) when the consume cache shares\n\t// this broadcast across callers.\n\toverride clone(): ConsumeBroadcast {\n\t\treturn new ConsumeBroadcast(this.#subscriber, this.#path, this.shareState());\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"subscriber.js","sourceRoot":"","sources":["../../src/lite/subscriber.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,KAAK,QAAQ,MAAM,iBAAiB,CAAC;AAC5C,OAAO,KAAK,SAAS,MAAM,iBAAiB,CAAC;AAE7C,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAC/C,OAAO,EAAE,cAAc,EAAE,KAAK,EAAE,iBAAiB,EAAE,MAAM,EAAE,UAAU,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AACtH,OAAO,KAAK,QAAQ,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,IAAI,EAAY,QAAQ,EAAc,SAAS,EAAE,WAAW,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AACjH,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,aAAa,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AACnG,OAAO,KAAK,IAAI,MAAM,YAAY,CAAC;AACnC,OAAO,EAAiC,MAAM,EAAE,MAAM,cAAc,CAAC;AACrE,OAAO,EAAE,aAAa,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AACjD,OAAO,KAAK,IAAI,MAAM,YAAY,CAAC;AAEnC,OAAO,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAChD,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAC/D,OAAO,EAAE,qBAAqB,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC;AAC3D,OAAO,EACN,eAAe,EACf,YAAY,EACZ,UAAU,EACV,eAAe,EACf,4BAA4B,GAC5B,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,QAAQ,IAAI,e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C,CAAC;QACb,qBAAqB,CAAC,IAAI,EAAE;YAC3B,gBAAgB,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,UAAU,CAAC,gBAAgB,CAAC,IAAI,EAAE,IAAI,CAAC;YACnE,UAAU,EAAE,CAAC,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,UAAU,CAAC,IAAI,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,CAAC;SAC7F,CAAC,CAAC;QACH,IAAI,CAAC,WAAW,GAAG,UAAU,CAAC;QAC9B,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;IACnB,CAAC;IAED,4FAA4F;IAC5F,iCAAiC;IACxB,KAAK;QACb,OAAO,IAAI,gBAAgB,CAAC,IAAI,CAAC,WAAW,EAAE,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,UAAU,EAAE,CAAC,CAAC;IAC9E,CAAC;CACD","sourcesContent":["import { race, Signal } from \"@moq/signals\";\nimport * as announce from \"../announced.ts\";\nimport * as broadcast from \"../broadcast.ts\";\nimport type { Probe as ProbeStats } from \"../connection/stats.ts\";\nimport { BroadcastCache } from \"../consume.ts\";\nimport { controlTimeout, error, ProtocolViolation, reason, StreamCode, StreamError, sessionCause } from \"../error.ts\";\nimport * as netGroup from \"../group.ts\";\nimport { Cost, type Hop, MAX_HOPS, type Route, randomHop, routesEqual, stampHops, UNKNOWN_HOP } from \"../hop.ts\";\nimport { groupBounds, hiddenBelow, scopeCaptures, scopeHead, scopeOverlaps } from \"../internal.ts\";\nimport * as Path from \"../path.ts\";\nimport { type OpenOptions, type Reader, Stream } from \"../stream.ts\";\nimport { TAIL_GRACE_MS, Tail } from \"../tail.ts\";\nimport * as Time from \"../time.ts\";\nimport type * as track from \"../track.ts\";\nimport { untilAborted } from \"../util/abort.ts\";\nimport { TimeoutError, withTimeout } from \"../util/timeout.ts\";\nimport { overrideBroadcastWire, wireOf } from \"../wire.ts\";\nimport {\n\tAnnounceHistory,\n\tAnnounceInit,\n\tAnnounceOk,\n\tAnnounceRequest,\n\tdecodeAnnounceBroadcastMaybe,\n} from \"./announce.ts\";\nimport { Datagram as DatagramMessage } from \"./datagram.ts\";\nimport * as DatagramStream from \"./datagram_stream.ts\";\nimport { Fetch as FetchMessage } from \"./fetch.ts\";\nimport { frameDecoder, type Group as GroupMessage, readFrames } from \"./group.ts\";\nimport { sendOrder } from \"./priority.ts\";\nimport { Probe } from \"./probe.ts\";\nimport { ProbeLevel, type Setup } from \"./setup.ts\";\nimport { StreamId } from \"./stream.ts\";\nimport {\n\tdecodeSubscribeResponse,\n\tdecodeSubscribeResponseMaybe,\n\tEMPTY_RANGE,\n\temptyRange,\n\texclusiveGroupEnd,\n\tinclusiveGroupEnd,\n\tSubscribe,\n\tSubscribeUpdate,\n} from \"./subscribe.ts\";\nimport { TrackInfo, Track as TrackMessage } from \"./track.ts\";\nimport {\n\thasAnnounceId,\n\thasAnnounceOk,\n\thasDatagrams,\n\thasProbeRtt,\n\thasStreamCount,\n\tresolvesStart,\n\trestartSupported,\n\tVersion,\n} from \"./version.ts\";\n\n// Bound on how long stream-open plus the first response (SUBSCRIBE_OK on older\n// drafts, or TRACK_INFO on lite-05+) may take. Browsers cap concurrent QUIC streams\n// (Chrome ~100) and we open with waitUntilAvailable, so past the cap the open blocks\n// until the peer frees a slot. The timeout turns a stall into a clear error.\nconst SUBSCRIBE_SETUP_TIMEOUT_MS = 10_000;\n\n// The TRACK stream and implicit SUBSCRIBE acceptance are lite-05+.\nfunction supportsTrackStream(version: Version): boolean {\n\tswitch (version) {\n\t\tcase Version.DRAFT_01:\n\t\tcase Version.DRAFT_02:\n\t\tcase Version.DRAFT_03:\n\t\tcase Version.DRAFT_04:\n\t\t\treturn false;\n\t\tdefault:\n\t\t\treturn true;\n\t}\n}\n\ninterface SubscribeEntry {\n\t// The write side: incoming GROUP streams are routed here. The application reads\n\t// the matching track.Subscriber it got from broadcast.Consumer.subscribe.\n\ttrack: track.Producer;\n\t// Per-frame timestamp scale (0 = none). undefined until it's known (from TRACK_INFO\n\t// on lite-05+, or implicit defaults on older drafts). A non-zero value means each\n\t// frame on the group stream is prefixed with a zigzag-delta timestamp varint that\n\t// runGroup must consume to stay in sync; group streams block on it before decoding,\n\t// since a group's QUIC stream can race ahead of the subscribe stream.\n\ttimescale: Signal<number | undefined>;\n\t// The group streams received, so the subscription can wait for the ones still owed\n\t// after the publisher ends it.\n\ttail: Tail;\n\t// The first group the SUBSCRIBE asked for, if any.\n\trequested?: number;\n\t// The first group the publisher serves (SUBSCRIBE_START) and the track's exclusive end\n\t// (SUBSCRIBE_END), once it declares them.\n\tstart?: number;\n\tend?: number;\n\t// Group streams opened by the publisher, when SUBSCRIBE_END carries the count.\n\tstreams?: number;\n}\n\n/**\n * Handles subscribing to broadcasts and managing their lifecycle.\n *\n * @internal\n */\n// What we close a session with on a protocol violation.\n//\n// The draft names the condition but assigns no numbers, so this is the Rust\n// implementation's code for `Error::ProtocolViolation`: matching it is what makes the\n// two report the same thing, where the default 0 would tell the peer it closed cleanly.\nconst PROTOCOL_VIOLATION_CODE = 15;\n\n// WebTransport rejects a close reason over 1024 bytes of UTF-8 by throwing, so a reason\n// built from peer-supplied data has to be bounded before it gets there. A broadcast path\n// is peer-supplied and long enough to reach this on its own.\nconst MAX_CLOSE_REASON = 1024;\n\n// The longest prefix of `text` that fits a close reason. `encodeInto` stops on a whole\n// code point, so `read` never lands mid-character the way slicing bytes would.\nfunction closeReason(text: string): string {\n\tconst encoder = new TextEncoder();\n\tconst buf = new Uint8Array(MAX_CLOSE_REASON);\n\tconst { read } = encoder.encodeInto(text, buf);\n\treturn text.slice(0, read);\n}\n\nexport class Subscriber {\n\t#quic: WebTransport;\n\n\t// The version of the connection.\n\treadonly version: Version;\n\n\t// Shared with the Publisher so reflected announces can be dropped on receipt.\n\treadonly hop: Hop;\n\n\t// Our subscribed tracks. `timescale` resolves once known (from TRACK_INFO on\n\t// lite-05+, or implicit defaults on older drafts); group streams block on it\n\t// before decoding any frame, since a group's QUIC stream can race ahead.\n\t#subscribes = new Map<bigint, SubscribeEntry>();\n\t#subscribeNext = 0n;\n\n\t// Dedup consumed broadcasts per path: repeat consume() calls share one subscription.\n\t#consumes = new BroadcastCache();\n\n\t// A random Hop ID of this connection's own, written as the first hop of any chain that\n\t// names no publisher, so a publisher that reconnects reads as a new one.\n\t#stamp: Hop;\n\n\t// Dedup in-flight one-shot fetches, keyed by [broadcast, track, sequence]. Concurrent (or\n\t// repeat, while still open) fetchGroup() calls for the same group share one FETCH stream and\n\t// each get an independent mirror; the entry is evicted once the group closes.\n\t#fetches = new Map<string, { group: netGroup.Producer; accepted: Promise<void> }>();\n\n\t// The peer's PROBE estimates, written as they arrive (Lite03+ only).\n\t#probe?: Signal<ProbeStats>;\n\n\t// The peer's SETUP (lite-05+), undefined until it arrives. Gates opening the PROBE\n\t// stream on the peer having advertised Probe >= Report.\n\t#peerSetup?: Signal<Setup | undefined>;\n\n\t// Distinguishes failures from streams torn down by Subscriber.close().\n\t#closed = new AbortController();\n\t/**\n\t * Creates a new Subscriber instance.\n\t * @param quic - The WebTransport session to use\n\t * @param version - The protocol version\n\t * @param origin - Hop id shared with the Publisher\n\t * @param probe - Optional sink for the peer's PROBE estimates\n\t * @param peerSetup - Optional peer SETUP slot for capability gating (lite-05+)\n\t *\n\t * @internal\n\t */\n\tconstructor(\n\t\tquic: WebTransport,\n\t\tversion: Version,\n\t\thop: Hop,\n\t\tprobe?: Signal<ProbeStats>,\n\t\tpeerSetup?: Signal<Setup | undefined>,\n\t) {\n\t\tthis.#quic = quic;\n\t\tthis.version = version;\n\t\tthis.hop = hop;\n\t\tthis.#stamp = randomHop();\n\t\tthis.#probe = probe;\n\t\tthis.#peerSetup = peerSetup;\n\t}\n\n\t/**\n\t * Subscribe to broadcast announcements matching `scope`. Paths are relative\n\t * to the session, not the scope.\n\t *\n\t * Reflected announces (those whose hop chain already includes this\n\t * connection) are always dropped: moq-lite-06 has none to keep, and older\n\t * versions stay consistent with that.\n\t *\n\t * Hidden routes (a `.`-prefixed segment below the scope's head) are left out unless\n\t * `options.hidden` opts in. The opt-in rides the request on lite-07+; an older peer\n\t * never hides anything, so the rule is also applied here.\n\t */\n\tannounced(scope: Path.Pattern = Path.Pattern.all(), options?: announce.Options): announce.Consumer {\n\t\tconst announced = new announce.Producer();\n\t\t// The wire speaks announce interest by prefix, and echoes suffixes beneath it.\n\t\tvoid this.#runAnnounced(announced, scopeHead(scope), scope, options?.hidden ?? false);\n\t\treturn announced.consume();\n\t}\n\n\tasync #runAnnounced(\n\t\tannounced: announce.Producer,\n\t\tprefix: Path.Valid,\n\t\tscope: Path.Pattern,\n\t\thidden: boolean,\n\t): Promise<void> {\n\t\tconsole.debug(`announced: prefix=${prefix}`);\n\t\t// Lite04/05: send our own session-level Hop ID so the peer can skip announces\n\t\t// whose hop chain already passed through us. Encoding drops it on every other\n\t\t// version, where we drop the reflected announce on receipt instead. Matches the\n\t\t// Rust subscriber's `exclude_hop: self.self_origin.id` in `run_announce_prefix`.\n\t\tconst msg = new AnnounceRequest(prefix, this.hop, hidden);\n\t\tconst visible = (path: Path.Valid) => scopeOverlaps(scope, path) && (hidden || !hiddenBelow(prefix, path));\n\n\t\t// Opened outside the try so the catch can reach it: a protocol violation below has\n\t\t// to reset the stream, not just close our side of it.\n\t\tlet stream: Stream;\n\t\ttry {\n\t\t\tstream = await Stream.open(this.#quic, { version: this.version });\n\t\t} catch (err: unknown) {\n\t\t\tannounced.close(error(err));\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\t// Send the announce interest.\n\t\t\tawait stream.writer.u53(StreamId.Announce);\n\t\t\tawait msg.encode(stream.writer, this.version);\n\n\t\t\t// Lite05+: the publisher reports its own Hop ID before any announces.\n\t\t\t// It no longer stamps itself onto each hop chain, so we append it here to\n\t\t\t// keep the reflected-announce loop check seeing the full chain.\n\t\t\tlet responderOrigin: Hop | undefined;\n\t\t\tif (hasAnnounceOk(this.version)) {\n\t\t\t\tconst ok = await AnnounceOk.decode(stream.reader, this.version);\n\t\t\t\t// Keep a withheld 0: it names nobody for loop detection, but it is the\n\t\t\t\t// anonymous mark and must travel the reconstructed chain. Assigned identities\n\t\t\t\t// stay off this hop and are never forwarded.\n\t\t\t\tresponderOrigin = ok.hop;\n\t\t\t}\n\n\t\t\t// Every advertisement the peer currently has live, keyed by suffix (at most one\n\t\t\t// per path is current, and every announce on this stream shares `prefix`).\n\t\t\t//\n\t\t\t// An advertisement skipped locally as a reflected loop is recorded with\n\t\t\t// `publisher: undefined` and `live: false`: the peer numbered it and will retract\n\t\t\t// it regardless of what we made of it, so its path is not free. Dropping it from\n\t\t\t// the map instead would let a later announce take the path, and the skipped one's\n\t\t\t// `endedId` would then retract that one's state.\n\t\t\t//\n\t\t\t// `publisher` is what lets a restart tell a route change (same publisher) from a\n\t\t\t// new publisher on the route, whose content the next consume must not share\n\t\t\t// with the old one's.\n\t\t\ttype Advertisement = {\n\t\t\t\tpublisher: Hop | undefined;\n\t\t\t\tlive: boolean;\n\t\t\t\troute: Route;\n\t\t\t\tcaptures: Path.Pattern[] | undefined;\n\t\t\t};\n\t\t\tconst advertised = new Map<Path.Valid, Advertisement>();\n\n\t\t\tswitch (this.version) {\n\t\t\t\tcase Version.DRAFT_01:\n\t\t\t\tcase Version.DRAFT_02: {\n\t\t\t\t\t// Receive ANNOUNCE_INIT first\n\t\t\t\t\tconst init = await AnnounceInit.decode(stream.reader, this.version);\n\n\t\t\t\t\t// Process initial announcements. These are advertisements like any other, so\n\t\t\t\t\t// they go on record and obey the same one-per-path rule: the initial set\n\t\t\t\t\t// naming a path twice is the same violation as two ANNOUNCE_STARTs for it,\n\t\t\t\t\t// and the record is what catches either. Draft01/02 carry no hop ids and no\n\t\t\t\t\t// ANNOUNCE_OK, so this connection's stamp names the publisher.\n\t\t\t\t\tfor (const suffix of init.suffixes) {\n\t\t\t\t\t\tconst path = Path.join(prefix, suffix);\n\t\t\t\t\t\tif (advertised.has(path)) {\n\t\t\t\t\t\t\tthrow new ProtocolViolation(`duplicate announce for ${path}`);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst route = { hops: [this.#stamp, UNKNOWN_HOP], cost: Cost.zero };\n\t\t\t\t\t\tconst live = visible(path);\n\t\t\t\t\t\tconst captures = scopeCaptures(scope, path);\n\t\t\t\t\t\tadvertised.set(path, { publisher: this.#stamp, live, route, captures });\n\t\t\t\t\t\tif (!live) continue;\n\t\t\t\t\t\tconsole.debug(`announced: broadcast=${path} active=true`);\n\t\t\t\t\t\tannounced.append({ prefix: path, captures, kind: \"announced\", route });\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tdefault:\n\t\t\t\t\t// Draft03+: no AnnounceInit, initial state comes via Announce messages.\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t// Lite06+: announce ids. Each received `active` implicitly assigns the next\n\t\t\t// per-stream ordinal; `endedId`/`restart` reference it, and lite-07 bases copy\n\t\t\t// from it. Tracked even for announces we skip as reflected, since the sender\n\t\t\t// doesn't know we skipped.\n\t\t\tconst history = new AnnounceHistory();\n\n\t\t\t// Receive announce updates (for Draft03, this includes initial state)\n\t\t\tfor (;;) {\n\t\t\t\tconst announce = await race([\n\t\t\t\t\tdecodeAnnounceBroadcastMaybe(stream.reader, this.version),\n\t\t\t\t\tannounced.closed,\n\t\t\t\t]);\n\t\t\t\t// undefined: the stream ended. null: the consumer closed cleanly.\n\t\t\t\tif (!announce) break;\n\t\t\t\tif (announce instanceof Error) throw announce;\n\n\t\t\t\tlet path: Path.Valid;\n\t\t\t\tlet active: boolean;\n\t\t\t\t// Present on active/restart; ended messages never carry hops worth checking.\n\t\t\t\tlet hops: Hop[] | undefined;\n\t\t\t\tlet cost: Cost | undefined;\n\n\t\t\t\tswitch (announce.status) {\n\t\t\t\t\tcase \"active\": {\n\t\t\t\t\t\tconst resolved = hasAnnounceId(this.version) ? history.start(announce) : announce;\n\t\t\t\t\t\t// The wire names the suffix beneath the interest prefix; the consumer\n\t\t\t\t\t\t// sees the covered path from the session root.\n\t\t\t\t\t\tpath = Path.join(prefix, resolved.suffix);\n\t\t\t\t\t\tactive = true;\n\t\t\t\t\t\thops = resolved.hops;\n\t\t\t\t\t\tcost = announce.cost;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase \"ended\":\n\t\t\t\t\t\tpath = Path.join(prefix, announce.suffix);\n\t\t\t\t\t\tactive = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"endedId\":\n\t\t\t\t\t\t// Resolve and retire the id; an unknown or retired id is a protocol violation.\n\t\t\t\t\t\tpath = Path.join(prefix, history.end(announce.id));\n\t\t\t\t\t\tactive = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"restart\": {\n\t\t\t\t\t\t// Resolve the id; it stays live (the replacement reuses it).\n\t\t\t\t\t\tconst resolved = history.update(announce);\n\t\t\t\t\t\tpath = Path.join(prefix, resolved.suffix);\n\t\t\t\t\t\tactive = true;\n\t\t\t\t\t\thops = resolved.hops;\n\t\t\t\t\t\tcost = announce.cost;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase \"skipped\":\n\t\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t// One current advertisement per path per stream, decided before anything below\n\t\t\t\t// can skip this announcement. A second ANNOUNCE_START for a path the peer\n\t\t\t\t// already advertised is a violation whether or not its route would be usable\n\t\t\t\t// here, and whether or not we kept the first; letting a skip pre-empt it would\n\t\t\t\t// retract the live route and leave the stream open on a peer already out of\n\t\t\t\t// spec.\n\t\t\t\t//\n\t\t\t\t// lite-05 alone is exempt, where a duplicate ANNOUNCE *is* the replacement\n\t\t\t\t// idiom. lite-06 gave that its own message and older versions never had one, so\n\t\t\t\t// a duplicate means the same thing on both sides of it. Mirrors the branch the\n\t\t\t\t// Rust announce loop takes before `start_announce`.\n\t\t\t\tconst duplicateIsRestart = restartSupported(this.version) && !hasAnnounceId(this.version);\n\t\t\t\tif (announce.status === \"active\" && !duplicateIsRestart && advertised.has(path)) {\n\t\t\t\t\tthrow new ProtocolViolation(`duplicate announce for ${path}`);\n\t\t\t\t}\n\n\t\t\t\t// Retract the path: forget the advertisement, drop the shared consume entry so a\n\t\t\t\t// later announce subscribes fresh rather than cloning the dead generation's tracks,\n\t\t\t\t// and tell the consumer. A no-op for an advertisement never surfaced, which is\n\t\t\t\t// what an id retiring a skipped announce resolves to.\n\t\t\t\tconst retract = () => {\n\t\t\t\t\tconst previous = advertised.get(path);\n\t\t\t\t\tadvertised.delete(path);\n\t\t\t\t\tif (!previous?.live) return;\n\t\t\t\t\tthis.#consumes.evict(path);\n\t\t\t\t\tconsole.debug(`announced: broadcast=${path} active=false`);\n\t\t\t\t\tannounced.append({\n\t\t\t\t\t\tprefix: path,\n\t\t\t\t\t\tcaptures: previous.captures,\n\t\t\t\t\t\tkind: \"retracted\",\n\t\t\t\t\t\troute: previous.route,\n\t\t\t\t\t});\n\t\t\t\t};\n\n\t\t\t\t// In Lite05+ the sender's origin arrives via AnnounceOk, not in each hop\n\t\t\t\t// list, so fold it back in before checking.\n\t\t\t\tif (hops !== undefined) {\n\t\t\t\t\tconst full = responderOrigin !== undefined ? [...hops, responderOrigin] : hops;\n\t\t\t\t\tif (full.includes(this.hop)) {\n\t\t\t\t\t\t// A reflected restart means the peer's remaining route loops back through\n\t\t\t\t\t\t// us, so the route is gone even though the message says active. The\n\t\t\t\t\t\t// advertisement stays live: the peer still holds the path and its id still\n\t\t\t\t\t\t// resolves here.\n\t\t\t\t\t\tretract();\n\t\t\t\t\t\tadvertised.set(path, {\n\t\t\t\t\t\t\tpublisher: undefined,\n\t\t\t\t\t\t\tlive: false,\n\t\t\t\t\t\t\troute: { hops: full, cost: Cost.zero },\n\t\t\t\t\t\t\tcaptures: undefined,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (!active) {\n\t\t\t\t\tretract();\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t// The first hop identifies the original publisher; an empty chain means the\n\t\t\t\t// peer itself originated it. One that names nobody (lite-01..03, or a peer\n\t\t\t\t// reporting 0) gets this connection's stamp in front of its 0.\n\t\t\t\tconst fullHops = stampHops(\n\t\t\t\t\thops !== undefined && responderOrigin !== undefined\n\t\t\t\t\t\t? [...hops, responderOrigin]\n\t\t\t\t\t\t: [...(hops ?? [])],\n\t\t\t\t\tthis.#stamp,\n\t\t\t\t);\n\t\t\t\t// Appending a withheld AnnounceOk(0) onto a 32-entry list is the same\n\t\t\t\t// drop Rust's Hops::push makes: do not expose an overlong chain.\n\t\t\t\tif (fullHops === undefined || fullHops.length > MAX_HOPS) {\n\t\t\t\t\tconsole.debug(`announced: broadcast=${path} dropped (hop chain at MAX_HOPS)`);\n\t\t\t\t\tadvertised.set(path, {\n\t\t\t\t\t\tpublisher: undefined,\n\t\t\t\t\t\tlive: false,\n\t\t\t\t\t\troute: { hops: [], cost: Cost.zero },\n\t\t\t\t\t\tcaptures: undefined,\n\t\t\t\t\t});\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst publisher = fullHops[0];\n\t\t\t\tconst route: Route = { hops: fullHops, cost: cost ?? Cost.zero };\n\t\t\t\tconst captures = scopeCaptures(scope, path);\n\t\t\t\tif (!visible(path)) {\n\t\t\t\t\tadvertised.set(path, { publisher, live: false, route, captures });\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t// A second advertisement for a path we already carry is a restart: either an\n\t\t\t\t// explicit ANNOUNCE_UPDATE, or (lite-05) a duplicate ANNOUNCE. It updates the\n\t\t\t\t// route in place, so a forwarder re-prices without retracting.\n\t\t\t\tconst previous = advertised.get(path);\n\t\t\t\tif (previous?.live) {\n\t\t\t\t\t// A different publisher took the path. Subscriptions already open drain\n\t\t\t\t\t// the old copy, but the next consume starts fresh rather than reusing the\n\t\t\t\t\t// old publisher's cached track info.\n\t\t\t\t\tif (previous.publisher !== publisher) this.#consumes.evict(path);\n\t\t\t\t\tadvertised.set(path, { publisher, live: true, route, captures });\n\t\t\t\t\tconsole.debug(`announced: broadcast=${path} rerouted`);\n\t\t\t\t\tif (!routesEqual(previous.route, route)) {\n\t\t\t\t\t\tannounced.append({ prefix: path, captures, kind: \"updated\", route });\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tadvertised.set(path, { publisher, live: true, route, captures });\n\n\t\t\t\tconsole.debug(`announced: broadcast=${path} active=true`);\n\t\t\t\tannounced.append({ prefix: path, captures, kind: \"announced\", route });\n\t\t\t}\n\n\t\t\tannounced.close();\n\t\t} catch (err: unknown) {\n\t\t\tconst e = error(err);\n\t\t\t// Reaches here on a protocol violation the peer committed (a second\n\t\t\t// advertisement for a live path, an unknown announce id) as well as on a\n\t\t\t// transport failure. Either way the peer has to be told: closing only our side\n\t\t\t// would leave it announcing into a stream nobody reads.\n\t\t\tstream.abort(e);\n\t\t\tannounced.close(e);\n\t\t\t// A violation ends the session, not just this stream, so a nonconforming peer\n\t\t\t// cannot repeat it on the next one. Matches `ietf::Subscriber` and the Rust\n\t\t\t// lite subscriber, where the announce half only ever ends the session on error.\n\t\t\tif (e instanceof ProtocolViolation) {\n\t\t\t\tthis.#quic.close({ closeCode: PROTOCOL_VIOLATION_CODE, reason: closeReason(reason(e)) });\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Consumes a broadcast from the connection.\n\t *\n\t * Deduplicated per path: repeat calls for the same still-live path share one reference-counted\n\t * broadcast (and one upstream subscription). The shared broadcast closes once every caller has\n\t * closed its handle, so callers close normally.\n\t *\n\t * @param name - The name of the broadcast to consume\n\t * @returns A Broadcast instance\n\t */\n\tconsume(path: Path.Valid): broadcast.Consumer {\n\t\treturn this.#consumes.get(path) ?? this.#consumes.insert(path, this.#createConsume(path));\n\t}\n\n\t#createConsume(path: Path.Valid): broadcast.Consumer {\n\t\t// A consumed broadcast resolves info() and fetchGroup() over the wire by reaching\n\t\t// back into this Subscriber (see ConsumeBroadcast below), rather than the wire\n\t\t// installing callbacks on the broadcast.\n\t\tconst consumer = new ConsumeBroadcast(this, path);\n\n\t\tvoid (async () => {\n\t\t\tfor (;;) {\n\t\t\t\tconst request = await wireOf(consumer).requested();\n\t\t\t\tif (!request) break;\n\t\t\t\tvoid this.#runSubscribe(path, request);\n\t\t\t}\n\t\t})();\n\n\t\treturn consumer;\n\t}\n\n\tasync #runSubscribe(broadcast: Path.Valid, request: track.Request) {\n\t\tconst id = this.#subscribeNext++;\n\t\tconst subscription = request.subscription;\n\t\tconst initialBounds = groupBounds(subscription.groups);\n\t\tif (emptyRange({ startGroup: initialBounds.start, endGroup: initialBounds.end })) {\n\t\t\trequest.reject(new Error(EMPTY_RANGE));\n\t\t\treturn;\n\t\t}\n\n\t\t// `timescale` stays undefined until TRACK_INFO (or, on older drafts,\n\t\t// implicit defaults) resolves it; runGroup blocks on it before decoding.\n\t\tconst timescale = new Signal<number | undefined>(undefined);\n\n\t\tconsole.debug(`subscribe start: id=${id} broadcast=${broadcast} track=${request.name}`);\n\t\tconst bounds = groupBounds(subscription.groups);\n\n\t\tconst msg = new Subscribe({\n\t\t\tid,\n\t\t\tbroadcast,\n\t\t\ttrack: request.name,\n\t\t\tpriority: subscription.priority ?? 0,\n\t\t\tmaxAge: subscription.maxAge,\n\t\t\tstartGroup: subscription.groups?.start === undefined ? undefined : bounds.start,\n\t\t\tendGroup: inclusiveGroupEnd(bounds.end),\n\t\t});\n\n\t\t// Open the stream under a timeout. The stream handle flows back via `state`\n\t\t// so the timeout path can abort it if it finishes opening after the deadline.\n\t\tconst state: { stream?: Stream } = {};\n\t\tconst setup = this.#openSubscribe(state, msg, request, id, timescale);\n\n\t\tlet opened: { stream: Stream; entry: SubscribeEntry };\n\t\ttry {\n\t\t\topened = await withTimeout(\n\t\t\t\tsetup,\n\t\t\t\tSUBSCRIBE_SETUP_TIMEOUT_MS,\n\t\t\t\t`subscribe timed out after ${SUBSCRIBE_SETUP_TIMEOUT_MS}ms waiting for the first response (browser stream limit reached?)`,\n\t\t\t);\n\t\t\tconsole.debug(`subscribe ok: id=${id} broadcast=${broadcast} track=${request.name}`);\n\t\t} catch (err) {\n\t\t\t// The setup outlived its deadline waiting for the first response: a control\n\t\t\t// timeout, not content that arrived late.\n\t\t\tconst e = err instanceof TimeoutError ? controlTimeout(err) : await sessionCause(this.#quic, err);\n\t\t\trequest.reject(e);\n\t\t\tthis.#subscribes.delete(id);\n\t\t\tconsole.warn(`subscribe error: id=${id} broadcast=${broadcast} track=${request.name} error=${reason(e)}`);\n\t\t\t// If the stream eventually opens after the timeout, abort it so we\n\t\t\t// don't leak it. Cover both branches: setup may resolve late, or it\n\t\t\t// may reject (e.g. encode/decode failure) after the stream is open.\n\t\t\tsetup.then(\n\t\t\t\t() => state.stream?.abort(e),\n\t\t\t\t() => state.stream?.abort(e),\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tconst { stream, entry } = opened;\n\t\tconst producer = entry.track;\n\t\ttry {\n\t\t\t// Watch for subscription changes and send SUBSCRIBE_UPDATE. Lite01/Lite02\n\t\t\t// don't carry SUBSCRIBE_UPDATE on the wire, so skip the watcher there\n\t\t\t// and just wait on the stream/track like before.\n\t\t\t//\n\t\t\t// On lite-05+ the publisher sends SUBSCRIBE_START/END/DROP on this stream until\n\t\t\t// its FIN; older drafts just close it. Either way group streams can still be in\n\t\t\t// flight, so the track ends only once the tail is accounted for. A reset rejects\n\t\t\t// instead, so the track ends with that error rather than a clean tail.\n\t\t\tconst responses = supportsTrackStream(this.version)\n\t\t\t\t? this.runResponses(stream, entry)\n\t\t\t\t: stream.reader.closed;\n\t\t\tconst closed = responses.then(() => this.#settleTail(entry));\n\t\t\t// A reset that lands after the race below settled is moot; the race observes one before.\n\t\t\tclosed.catch(() => {});\n\t\t\tconst subscriptionUpdates =\n\t\t\t\tthis.version === Version.DRAFT_01 || this.version === Version.DRAFT_02\n\t\t\t\t\t? undefined\n\t\t\t\t\t: this.#runSubscriptionUpdates(id, broadcast, entry, msg, stream);\n\n\t\t\t// Terminal conditions (stream end, track close, a failed subscription update) settle at most\n\t\t\t// once; race them into one stable promise so the demand loop doesn't re-subscribe each pass.\n\t\t\t// Updates stop quietly at the FIN, which can land before the responses ahead of it are\n\t\t\t// decoded, so only their failure is terminal on its own.\n\t\t\tconst terminal: PromiseLike<unknown>[] = [closed, producer.closed];\n\t\t\tif (subscriptionUpdates !== undefined) terminal.push(subscriptionUpdates.then(() => closed));\n\t\t\tconst done = race(terminal);\n\n\t\t\t// Serve until a terminal condition fires or the last local subscriber leaves. The unused\n\t\t\t// wake is level-triggered: re-check demand so a subscriber that returns before we tear\n\t\t\t// down (e.g. a quickly unmuted tile) resumes on the same subscription.\n\t\t\tconst idle = Symbol(\"idle\");\n\t\t\tfor (;;) {\n\t\t\t\tconst reason = await race([done, producer.unused().then(() => idle)]);\n\t\t\t\tif (reason === idle && producer.closed.peek() === undefined && producer.used.peek()) continue;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tproducer.close();\n\t\t\tstream.close();\n\t\t\tconsole.debug(`subscribe close: id=${id} broadcast=${broadcast} track=${request.name}`);\n\t\t} catch (err) {\n\t\t\tconst e = await sessionCause(this.#quic, err);\n\t\t\tproducer.close(e);\n\t\t\tconsole.warn(`subscribe error: id=${id} broadcast=${broadcast} track=${request.name} error=${reason(e)}`);\n\t\t\tstream.abort(e);\n\t\t} finally {\n\t\t\tthis.#subscribes.delete(id);\n\t\t}\n\t}\n\n\t// Determine the track's immutable properties, accept the request (so the\n\t// application's track.Subscriber resolves and incoming groups have a producer to\n\t// write into), register it, then open the subscribe stream. `state.stream` is\n\t// populated as soon as the subscribe stream opens so the caller can clean it up\n\t// on timeout even before this promise settles.\n\t//\n\t// On lite-05+ the properties come from a TRACK stream opened first, and the\n\t// SUBSCRIBE is accepted implicitly (no SUBSCRIBE_OK). Older drafts carry no\n\t// per-track properties, so they resolve to defaults and just drain SUBSCRIBE_OK.\n\tasync #openSubscribe(\n\t\tstate: { stream?: Stream },\n\t\tmsg: Subscribe,\n\t\trequest: track.Request,\n\t\tid: bigint,\n\t\ttimescale: Signal<number | undefined>,\n\t): Promise<{ stream: Stream; entry: SubscribeEntry }> {\n\t\tlet producer: track.Producer;\n\t\tlet drainOk = false;\n\n\t\tif (supportsTrackStream(this.version)) {\n\t\t\t// Fetch the immutable properties once via the TRACK stream.\n\t\t\tconst info = await this.#trackInfo(msg.broadcast, msg.track);\n\t\t\tproducer = request.accept(this.#toModelInfo(info));\n\t\t\ttimescale.set(info.timescale);\n\t\t} else {\n\t\t\t// Older drafts negotiate nothing per-track: verbatim frames, no timescale.\n\t\t\tproducer = request.accept();\n\t\t\ttimescale.set(0);\n\t\t\tdrainOk = true;\n\t\t}\n\n\t\t// Register before opening SUBSCRIBE so a racing GROUP stream finds the entry.\n\t\tconst entry: SubscribeEntry = {\n\t\t\ttrack: producer,\n\t\t\ttimescale,\n\t\t\t// The effective max age is the stopgap grace: the wrong clock (it bounds\n\t\t\t// presentation-time drift), but it is how long the subscriber was willing to wait\n\t\t\t// for a late group anyway. Already the smaller of the subscriber's and the track's.\n\t\t\ttail: new Tail({\n\t\t\t\tgrace: () => {\n\t\t\t\t\tconst maxAge = producer.subscription.peek()?.maxAge ?? Time.Milli.zero;\n\t\t\t\t\treturn maxAge > 0 ? maxAge : TAIL_GRACE_MS;\n\t\t\t\t},\n\t\t\t}),\n\t\t\trequested: msg.startGroup,\n\t\t};\n\t\tthis.#subscribes.set(id, entry);\n\n\t\tstate.stream = await Stream.open(this.#quic, { version: this.version });\n\t\tawait state.stream.writer.u53(StreamId.Subscribe);\n\t\tawait msg.encode(state.stream.writer, this.version);\n\n\t\tif (drainOk) {\n\t\t\t// The first response MUST be a SUBSCRIBE_OK (older drafts only).\n\t\t\tconst resp = await decodeSubscribeResponse(state.stream.reader, this.version);\n\t\t\tif (!(\"ok\" in resp)) {\n\t\t\t\tthrow new Error(\"first subscribe response must be SUBSCRIBE_OK\");\n\t\t\t}\n\t\t}\n\n\t\treturn { stream: state.stream, entry };\n\t}\n\n\t// Opens a TRACK stream, reads the single TRACK_INFO, and FINs. Lite-05+ only.\n\tasync #trackInfo(broadcast: Path.Valid, track: string): Promise<TrackInfo> {\n\t\treturn this.#exchange({ version: this.version }, async (stream) => {\n\t\t\tawait stream.writer.u53(StreamId.Track);\n\t\t\tawait new TrackMessage(broadcast, track).encode(stream.writer, this.version);\n\t\t\tconst info = await TrackInfo.decode(stream.reader, this.version);\n\t\t\t// The publisher FINs after TRACK_INFO; FIN our side too.\n\t\t\tstream.close();\n\t\t\treturn info;\n\t\t});\n\t}\n\n\t// Opens a stream and runs a request/response exchange on it, resetting the stream if `run`\n\t// fails. Subscriber.close() also resets it while `run` is pending, so a peer that never\n\t// answers cannot hold it open, and a stream that opens after the close is reset at once.\n\tasync #exchange<T>(options: OpenOptions, run: (stream: Stream) => Promise<T>): Promise<T> {\n\t\tconst closed = this.#closed.signal;\n\t\tclosed.throwIfAborted();\n\t\tconst stream = await Stream.open(this.#quic, options);\n\t\tconst abort = () => stream.abort(error(closed.reason));\n\t\tclosed.addEventListener(\"abort\", abort);\n\t\ttry {\n\t\t\tclosed.throwIfAborted();\n\t\t\treturn await run(stream);\n\t\t} catch (err) {\n\t\t\tstream.abort(error(err));\n\t\t\tthrow err;\n\t\t} finally {\n\t\t\tclosed.removeEventListener(\"abort\", abort);\n\t\t}\n\t}\n\n\t// Map the wire TRACK_INFO onto the model track.Info a producer/consumer holds.\n\t#toModelInfo(info: TrackInfo): track.Info {\n\t\treturn {\n\t\t\ttimescale: Time.Timescale(info.timescale),\n\t\t\t// Publisher Max Age rides on the wire, so the local retention window\n\t\t\t// matches what the upstream advertises (relays re-serve with the same bound).\n\t\t\tmaxAge: Time.Milli(info.maxAge),\n\t\t\tpriority: info.priority,\n\t\t};\n\t}\n\n\t// Resolve a track's immutable model info via a TRACK stream (lite-05+), for the\n\t// ConsumeBroadcast backing track.Consumer.query(). On older drafts there's no TRACK\n\t// stream, so this rejects rather than fabricating defaults.\n\tasync resolveTrackInfo(broadcast: Path.Valid, track: string): Promise<track.Info> {\n\t\tif (!supportsTrackStream(this.version)) {\n\t\t\tthrow new Error(\"track info requires moq-lite-05 or newer\");\n\t\t}\n\t\treturn this.#toModelInfo(await this.#trackInfo(broadcast, track));\n\t}\n\n\t// Open a FETCH stream for one group and stream its bare frames into a group, for the\n\t// ConsumeBroadcast backing track.Consumer.fetchGroup() (lite-05+).\n\tasync fetchGroup(\n\t\tbroadcast: Path.Valid,\n\t\ttrack: string,\n\t\tsequence: number,\n\t\toptions: track.FetchGroupOptions = {},\n\t): Promise<netGroup.Consumer> {\n\t\toptions.signal?.throwIfAborted();\n\n\t\t// Coalesce onto a still-open fetch of the same group so we don't open a second FETCH\n\t\t// stream (and re-download it); each caller reads an independent mirror.\n\t\t//\n\t\t// Reserve each caller's mirror before the fetch starts or is awaited: the fetch watches\n\t\t// demand from the start, and a fast FIN cannot discard frames before these callers\n\t\t// receive their handles. An abort closes only this caller's mirror, so the stream is\n\t\t// cancelled once the last one leaves.\n\t\tconst key = JSON.stringify([broadcast, track, sequence]);\n\t\tlet entry = this.#fetches.get(key);\n\t\tlet consumer: netGroup.Consumer;\n\t\tif (entry && !entry.group.isClosed) {\n\t\t\tconsumer = entry.group.mirror();\n\t\t} else {\n\t\t\tconst group = new netGroup.Producer(sequence);\n\t\t\tconsumer = group.mirror();\n\t\t\tentry = { group, accepted: this.#runFetch(broadcast, track, sequence, options.priority ?? 0, group) };\n\t\t\tthis.#fetches.set(key, entry);\n\t\t\tvoid group.closed.then(() => {\n\t\t\t\tif (this.#fetches.get(key)?.group === group) this.#fetches.delete(key);\n\t\t\t});\n\t\t}\n\n\t\ttry {\n\t\t\tawait untilAborted(entry.accepted, options.signal);\n\t\t\treturn consumer;\n\t\t} catch (err) {\n\t\t\tconsumer.close();\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\t// Open the FETCH stream and pump the response into the shared group. Setup errors close the\n\t// group, evict the entry, and reject every caller waiting for acceptance. A setup every caller\n\t// has abandoned is cancelled the same way.\n\tasync #runFetch(\n\t\tbroadcast: Path.Valid,\n\t\ttrack: string,\n\t\tsequence: number,\n\t\tpriority: number,\n\t\tgroup: netGroup.Producer,\n\t): Promise<void> {\n\t\ttry {\n\t\t\tif (!supportsTrackStream(this.version)) {\n\t\t\t\tthrow new Error(\"fetch group requires moq-lite-05 or newer\");\n\t\t\t}\n\n\t\t\t// Lite has no FETCH_OK, so a publisher that never answers would hold the setup forever.\n\t\t\t// Subscriber.close() closing the group releases every caller at any stage, and resets\n\t\t\t// the streams the setup opened.\n\t\t\tconst setup = this.#fetchSetup(broadcast, track, sequence, priority, group);\n\t\t\tlet accepted: { stream: Stream; info: TrackInfo };\n\t\t\ttry {\n\t\t\t\taccepted = await untilAbandoned(group, setup);\n\t\t\t} catch (err: unknown) {\n\t\t\t\t// A setup that finishes just after the close hands back a stream nobody will read.\n\t\t\t\tvoid setup.then(\n\t\t\t\t\t({ stream }) => stream.abort(error(err)),\n\t\t\t\t\t() => void 0,\n\t\t\t\t);\n\t\t\t\tthrow err;\n\t\t\t}\n\n\t\t\tvoid this.#runFetchResponse(accepted.stream, group, Time.Timescale(accepted.info.timescale));\n\t\t} catch (err: unknown) {\n\t\t\tgroup.close(error(err));\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\t// Resolve the track's timescale, then open the FETCH stream and wait for it to be accepted.\n\t// Closing the group during that wait resets the stream.\n\tasync #fetchSetup(\n\t\tbroadcast: Path.Valid,\n\t\ttrack: string,\n\t\tsequence: number,\n\t\tpriority: number,\n\t\tgroup: netGroup.Producer,\n\t): Promise<{ stream: Stream; info: TrackInfo }> {\n\t\tconst info = await untilClosed(group, this.#trackInfo(broadcast, track));\n\t\treturn this.#exchange({ sendOrder: sendOrder({ priority }), version: this.version }, async (stream) => {\n\t\t\tawait stream.writer.u53(StreamId.Fetch);\n\t\t\tawait new FetchMessage({ broadcast, track, priority, group: sequence }).encode(stream.writer, this.version);\n\t\t\t// A byte or an empty-group FIN accepts the fetch; a reset rejects it.\n\t\t\t// done() buffers that byte so the response pump can decode it normally.\n\t\t\tawait untilClosed(group, stream.reader.done());\n\t\t\treturn { stream, info };\n\t\t});\n\t}\n\n\t// Read the FETCH response (bare zigzag-delta-timestamped frames) into the group, then\n\t// FIN. A stream-level failure aborts the group so its reader observes the gap.\n\tasync #runFetchResponse(stream: Stream, group: netGroup.Producer, timescale: Time.Timescale): Promise<void> {\n\t\ttry {\n\t\t\tconst decode = frameDecoder(timescale);\n\n\t\t\t// Serve until the stream FINs, the group closes, or every reader leaves. A group can\n\t\t\t// stay open indefinitely (a catalog or JSON stream), so an abandoned fetch is stopped by\n\t\t\t// demand, not by the stream ending. `unused` is watched across frames as one stable\n\t\t\t// promise; the check is level-triggered, so a coalesced fetch that arrives before we\n\t\t\t// cancel re-arms and resumes.\n\t\t\tconst idle: unique symbol = Symbol(\"idle\");\n\t\t\tlet unused = group.unused().then((): typeof idle => idle);\n\t\t\t// A decode consumes its frame whenever it lands, so one outstanding across a re-arm is\n\t\t\t// kept and awaited again rather than abandoned with its frame.\n\t\t\tlet pending: Promise<netGroup.Frame | undefined> | undefined;\n\t\t\tfor (;;) {\n\t\t\t\t// Buffered frames are written without an await, as in a group stream.\n\t\t\t\tlet frame = pending === undefined ? stream.reader.tryDecode(decode) : undefined;\n\t\t\t\tif (!frame) {\n\t\t\t\t\tpending ??= stream.reader.decodeMaybe(decode);\n\t\t\t\t\tconst next = await race([pending, group.closed, unused]);\n\t\t\t\t\tif (next === idle) {\n\t\t\t\t\t\tif (group.isClosed) break;\n\t\t\t\t\t\tif (group.used.peek()) {\n\t\t\t\t\t\t\tunused = group.unused().then((): typeof idle => idle);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Abandoned mid-group: the truncated group must never end clean.\n\t\t\t\t\t\tthrow new StreamError(StreamCode.Cancel, { message: \"cancel\" });\n\t\t\t\t\t}\n\t\t\t\t\tpending = undefined;\n\t\t\t\t\tif (!next || next instanceof Error) break;\n\t\t\t\t\tframe = next;\n\t\t\t\t}\n\t\t\t\tgroup.writeFrame(frame);\n\t\t\t}\n\n\t\t\tgroup.close();\n\t\t\tstream.close();\n\t\t} catch (err: unknown) {\n\t\t\tconst e = error(err);\n\t\t\tgroup.close(e);\n\t\t\tstream.abort(e);\n\t\t}\n\t}\n\n\t// Reads SUBSCRIBE_START/END/DROP on the subscribe stream until FIN (lite-05+), recording\n\t// the range the tail is accounted against. SUBSCRIBE_END declares the track's end right\n\t// away, so a consumer learns it before the last groups arrive. The publisher must declare\n\t// the end before FIN unless we cancelled locally; resets and malformed responses reject.\n\tprivate async runResponses(stream: Stream, entry: SubscribeEntry): Promise<void> {\n\t\tfor (;;) {\n\t\t\tconst resp = await decodeSubscribeResponseMaybe(stream.reader, this.version);\n\t\t\tif (!resp) {\n\t\t\t\tif (entry.end === undefined && entry.track.closed.peek() === undefined)\n\t\t\t\t\tthrow new ProtocolViolation(\"subscribe stream ended without SUBSCRIBE_END\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (\"start\" in resp) {\n\t\t\t\tentry.start = resp.start.group;\n\t\t\t\t// The groups the SUBSCRIBE asked for below it are not waited for, whatever the\n\t\t\t\t// demand asks later. One that still arrives is delivered.\n\t\t\t\tif (entry.requested !== undefined) entry.tail.account(entry.requested, entry.start);\n\t\t\t} else if (\"end\" in resp) {\n\t\t\t\tif (entry.end !== undefined) throw new ProtocolViolation(\"duplicate SUBSCRIBE_END\");\n\t\t\t\tentry.end = resp.end.group;\n\t\t\t\tif (hasStreamCount(this.version)) entry.streams = resp.end.streams;\n\t\t\t\t// A local close can win the race with the response; there is nothing left to end.\n\t\t\t\tif (entry.track.closed.peek() !== undefined) continue;\n\t\t\t\ttry {\n\t\t\t\t\tentry.track.finishAt(entry.end);\n\t\t\t\t} catch (err) {\n\t\t\t\t\t// lite-05 specified an inclusive end, and @moq/net 0.1.3 to 0.1.9 sent one, so\n\t\t\t\t\t// there an end below a received group only costs the early boundary: the FIN\n\t\t\t\t\t// still finishes the track. Later drafts made it exclusive.\n\t\t\t\t\tif (this.version !== Version.DRAFT_05) {\n\t\t\t\t\t\tthrow new ProtocolViolation(`invalid SUBSCRIBE_END: ${reason(error(err))}`);\n\t\t\t\t\t}\n\t\t\t\t\tconsole.warn(`invalid SUBSCRIBE_END: ${reason(error(err))}`);\n\t\t\t\t}\n\t\t\t} else if (\"drop\" in resp) {\n\t\t\t\tentry.tail.account(resp.drop.start, resp.drop.end + 1);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Wait for the group streams the publisher still owes once it has ended the subscription.\n\t//\n\t// lite-07 counts streams, so skipped sequences owe nothing. Older drafts account for\n\t// the range using received headers and SUBSCRIBE_DROP. A counted stream reset before\n\t// its header leaves no trace, so the grace still bounds that wait. Streams whose\n\t// headers arrived keep reading until their own FIN or reset.\n\t#settleTail(entry: SubscribeEntry): Promise<void> {\n\t\tconst { tail, track } = entry;\n\n\t\tconst complete = () => {\n\t\t\tif (entry.streams !== undefined) return tail.streams >= entry.streams;\n\t\t\t// Without SUBSCRIBE_END (older drafts) nothing says which groups are owed.\n\t\t\tif (entry.end === undefined) return false;\n\t\t\t// Without SUBSCRIBE_START the publisher served no group at all.\n\t\t\tif (entry.start === undefined) return true;\n\t\t\t// Owed from the floor the demand last asked for, which an update can move either\n\t\t\t// way, or where SUBSCRIBE_START resolved a live-edge one. The groups the SUBSCRIBE\n\t\t\t// asked for below its SUBSCRIBE_START were accounted for when it arrived.\n\t\t\tconst groups = track.subscription.peek()?.groups;\n\t\t\tconst bounds = groupBounds(groups ?? {});\n\t\t\tconst start = groups?.start === undefined ? entry.start : bounds.start;\n\t\t\tconst end = bounds.end === undefined ? entry.end : Math.min(entry.end, bounds.end);\n\t\t\treturn tail.covers(start, end);\n\t\t};\n\n\t\treturn tail.settle(complete, track.closed);\n\t}\n\n\t/**\n\t * Send SUBSCRIBE_UPDATE messages whenever the track's aggregate subscription changes.\n\t *\n\t * Resolves cleanly when the stream or track closes, so the caller can include\n\t * this in a race without leaving a dangling pending write that would\n\t * become an unhandled rejection if the user calls update after close.\n\t *\n\t * Peeks the signal at the top of every iteration so that updates which landed\n\t * before SubscribeOk arrived (or between iterations, before .next() registered\n\t * its listener) aren't lost.\n\t */\n\tasync #runSubscriptionUpdates(\n\t\tid: bigint,\n\t\tbroadcast: Path.Valid,\n\t\tentry: SubscribeEntry,\n\t\tmsg: Subscribe,\n\t\tstream: Stream,\n\t): Promise<void> {\n\t\tconst track = entry.track;\n\t\tconst stopped: Promise<null> = race([track.closed, stream.reader.closed]).then(() => null);\n\t\tlet lastSent: track.Subscription = {\n\t\t\tpriority: msg.priority,\n\t\t\tmaxAge: Time.Milli(msg.maxAge),\n\t\t\tgroups: {\n\t\t\t\tstart: msg.startGroup === undefined ? undefined : { included: msg.startGroup },\n\t\t\t\tend: msg.endGroup === undefined ? undefined : { excluded: exclusiveGroupEnd(msg.endGroup) ?? 0 },\n\t\t\t},\n\t\t};\n\n\t\tfor (;;) {\n\t\t\tconst current = track.subscription.peek();\n\t\t\tif (current === undefined || this.#sameSubscription(current, lastSent)) {\n\t\t\t\t// Nothing new to send; wait for a change or termination.\n\t\t\t\tconst next = await race([track.subscription.changed(), stopped]);\n\t\t\t\tif (next === null) return;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Demand collapsing to nothing is refused the same way an initial empty\n\t\t\t// request is: the error closes the track, so every local subscriber sees it.\n\t\t\tconst bounds = groupBounds(current.groups);\n\t\t\tif (emptyRange({ startGroup: bounds.start, endGroup: bounds.end })) throw new Error(EMPTY_RANGE);\n\n\t\t\t// A lowered floor owes groups nobody asked for until now.\n\t\t\tif (current.groups?.start !== undefined) {\n\t\t\t\tconst floor = lastSent.groups?.start === undefined ? entry.start : groupBounds(lastSent.groups).start;\n\t\t\t\tentry.tail.demand(bounds.start, floor ?? Number.POSITIVE_INFINITY);\n\t\t\t}\n\n\t\t\t// Round-trip the other Subscribe parameters so the publisher doesn't\n\t\t\t// interpret SUBSCRIBE_UPDATE as a reset of ordered/maxAge/etc.\n\t\t\tconst update = new SubscribeUpdate({\n\t\t\t\tpriority: current.priority ?? 0,\n\t\t\t\tmaxAge: current.maxAge,\n\t\t\t\tstartGroup: current.groups?.start === undefined ? undefined : bounds.start,\n\t\t\t\tendGroup: inclusiveGroupEnd(bounds.end),\n\t\t\t});\n\t\t\tawait update.encode(stream.writer, this.version);\n\t\t\tlastSent = { ...current };\n\t\t\tconsole.debug(`subscribe update: id=${id} broadcast=${broadcast} track=${track.name}`);\n\t\t}\n\t}\n\n\t#sameSubscription(a: track.Subscription, b: track.Subscription): boolean {\n\t\tconst ag = groupBounds(a.groups);\n\t\tconst bg = groupBounds(b.groups);\n\t\t// `groupBounds` reads an omitted start as 0. A pre-06 wire tells them apart: omitted\n\t\t// joins at the publisher's start, and 0 is group 0. Lite-06 encodes both as 0.\n\t\tconst sameStart =\n\t\t\tresolvesStart(this.version) || (a.groups?.start === undefined) === (b.groups?.start === undefined);\n\t\treturn (\n\t\t\t(a.priority ?? 0) === (b.priority ?? 0) &&\n\t\t\t(a.maxAge ?? 0) === (b.maxAge ?? 0) &&\n\t\t\tsameStart &&\n\t\t\tag.start === bg.start &&\n\t\t\tag.end === bg.end\n\t\t);\n\t}\n\n\t/**\n\t * Handles a group message.\n\t * @param group - The group message\n\t * @param stream - The stream to read frames from\n\t *\n\t * @internal\n\t */\n\tasync runGroup(group: GroupMessage, stream: Reader) {\n\t\tconst entry = this.#subscribes.get(group.subscribe);\n\t\tif (!entry) {\n\t\t\tif (group.subscribe >= this.#subscribeNext) {\n\t\t\t\tthrow new Error(`unknown subscription: id=${group.subscribe}`);\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\n\t\tconst { track, timescale, tail } = entry;\n\t\tconst producer = new netGroup.Producer(group.sequence);\n\t\tconst read = tail.open(group.sequence);\n\n\t\ttry {\n\t\t\t// The publisher contradicted its own end, which no later group can repair. lite-05\n\t\t\t// specified an inclusive end, so its last group lands on it: the write below drops\n\t\t\t// only that group there.\n\t\t\tif (entry.end !== undefined && group.sequence >= entry.end && this.version !== Version.DRAFT_05) {\n\t\t\t\tconst violation = new ProtocolViolation(\n\t\t\t\t\t`group ${group.sequence} is at or past the declared end ${entry.end}`,\n\t\t\t\t);\n\t\t\t\ttrack.close(violation);\n\t\t\t\tthrow violation;\n\t\t\t}\n\t\t\ttrack.writeGroup(producer);\n\n\t\t\t// Block until the timescale is known; the group's stream can arrive before\n\t\t\t// TRACK_INFO (or implicit defaults) resolves it on the subscribe stream.\n\t\t\tlet scale = timescale.peek();\n\t\t\twhile (scale === undefined) {\n\t\t\t\tif (track.closed.peek() !== undefined) {\n\t\t\t\t\t// Subscription ended before the scale resolved; nothing to decode.\n\t\t\t\t\tproducer.close();\n\t\t\t\t\tstream.stop(new StreamError(StreamCode.Cancel, { message: \"cancel\" }));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tawait Signal.race(timescale, track.closed);\n\t\t\t\tscale = timescale.peek();\n\t\t\t}\n\n\t\t\tawait readFrames(stream, producer, scale);\n\n\t\t\tproducer.close();\n\t\t\tstream.stop(new StreamError(StreamCode.Cancel, { message: \"cancel\" }));\n\t\t} catch (err: unknown) {\n\t\t\tconst e = await sessionCause(this.#quic, err);\n\t\t\tproducer.close(e);\n\t\t\tstream.stop(e);\n\t\t} finally {\n\t\t\tread();\n\t\t}\n\t}\n\n\t/**\n\t * Receives QUIC datagrams and routes each to its subscription's track producer (lite-05 §6.4).\n\t *\n\t * Returns immediately on a non-datagram transport or pre-lite-05 version. A decode error or an\n\t * unknown subscribe id drops that datagram without tearing down the session (best-effort); the\n\t * loop ends only when the datagram stream closes.\n\t *\n\t * @internal\n\t */\n\tasync runDatagrams(): Promise<void> {\n\t\tif (!hasDatagrams(this.version) || DatagramStream.maxDatagramSize(this.#quic) === 0) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Never reject: this loop is awaited alongside the connection's other tasks, so a\n\t\t// datagram-stream failure must not tear the whole session down (it's best-effort).\n\t\tconst reader = DatagramStream.datagramReader(this.#quic);\n\t\tif (!reader) return;\n\n\t\ttry {\n\t\t\ttry {\n\t\t\t\tfor (;;) {\n\t\t\t\t\tconst { value, done } = await reader.read();\n\t\t\t\t\tif (done) break;\n\t\t\t\t\tif (!value) continue;\n\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this.#routeDatagram(value);\n\t\t\t\t\t} catch (err: unknown) {\n\t\t\t\t\t\tconsole.debug(`dropping datagram: ${reason(err)}`);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\treader.releaseLock();\n\t\t\t}\n\t\t} catch (err: unknown) {\n\t\t\tconst e = error(err);\n\t\t\tif (e.message === \"The session is closed.\") {\n\t\t\t\tconsole.debug(`datagram receive stopped: ${e.message}`);\n\t\t\t} else {\n\t\t\t\tconsole.warn(\"datagram stream error\", err);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Decode one datagram body and hand it to the matching subscription's producer. Drops the\n\t// datagram (best-effort) if the subscription is unknown/closed or its timescale isn't resolved.\n\tasync #routeDatagram(payload: Uint8Array): Promise<void> {\n\t\tconst dg = await DatagramMessage.decode(payload, this.version);\n\n\t\tconst entry = this.#subscribes.get(dg.subscribe);\n\t\tif (!entry) return; // Unknown or already-closed subscription.\n\n\t\t// Datagrams are lite-05+, which always negotiates a timescale; if it hasn't resolved\n\t\t// yet (the datagram raced ahead of TRACK_INFO), drop rather than guess.\n\t\tconst scale = entry.timescale.peek();\n\t\tif (!scale) return;\n\n\t\tconst timestamp = new Time.Timestamp(dg.timestamp, Time.Timescale(scale));\n\t\t// A datagram's sequence is never owed a stream, so it never holds the tail open.\n\t\tentry.tail.account(dg.sequence, dg.sequence + 1);\n\t\tentry.track.insertDatagram(dg.sequence, timestamp, dg.payload);\n\t}\n\n\t/**\n\t * Opens a PROBE bidi stream to receive bandwidth estimates from the publisher.\n\t * Returns immediately if recv bandwidth is not supported.\n\t *\n\t * Probe is best-effort telemetry: a stream-level failure (peer reset, FIN,\n\t * missing peer support, transport hiccup) is caught and logged, never\n\t * propagated to the connection. On exit the bandwidth/RTT signals are\n\t * cleared so consumers see them as stale.\n\t *\n\t * @internal\n\t */\n\t// Await the peer's advertised probe level, blocking until its SETUP arrives. The peer\n\t// MUST send exactly one SETUP, so this resolves once that stream is read.\n\tasync #peerProbeLevel(peerSetup: Signal<Setup | undefined>): Promise<ProbeLevel> {\n\t\tlet setup = peerSetup.peek();\n\t\twhile (setup === undefined) {\n\t\t\tsetup = await peerSetup.changed();\n\t\t}\n\t\treturn setup.probe;\n\t}\n\n\tasync runProbe(): Promise<void> {\n\t\tif (!this.#probe) return;\n\t\tif (this.version === Version.DRAFT_01 || this.version === Version.DRAFT_02) return;\n\n\t\t// Lite-05+ gates the PROBE stream on the peer advertising Probe >= Report in its\n\t\t// SETUP. Wait for the SETUP, then bail if the peer can't report bitrate. Older\n\t\t// drafts have no SETUP, so they keep probing unconditionally.\n\t\tif (this.#peerSetup) {\n\t\t\tconst probe = await this.#peerProbeLevel(this.#peerSetup);\n\t\t\tif (probe < ProbeLevel.Report) return;\n\t\t}\n\n\t\t// Probe is best-effort: any failure (stream reset by peer, missing peer support,\n\t\t// transport hiccup) MUST NOT tear down the connection. On error, drop the\n\t\t// estimates so consumers know they're stale.\n\t\ttry {\n\t\t\tconst stream = await Stream.open(this.#quic, { version: this.version });\n\t\t\tawait stream.writer.u53(StreamId.Probe);\n\n\t\t\tfor (;;) {\n\t\t\t\tconst probe = await Probe.decodeMaybe(stream.reader, this.version);\n\t\t\t\tif (!probe) break;\n\t\t\t\t// lite-03 carries no RTT field, so an absent value there means \"not\n\t\t\t\t// carried\" and the last reading stands. From lite-04 the field is\n\t\t\t\t// always present and 0 explicitly means unknown, so undefined is the\n\t\t\t\t// peer retracting a value we would otherwise hold forever.\n\t\t\t\tconst prev = this.#probe.peek();\n\t\t\t\tconst rtt = probe.rtt !== undefined ? Time.Milli(probe.rtt) : undefined;\n\t\t\t\tthis.#probe.set({\n\t\t\t\t\t// `undefined` is the peer reporting \"unknown\", not an estimate of\n\t\t\t\t\t// zero; letting it through would become a real 0 bps ABR target.\n\t\t\t\t\testimatedRecvRate: probe.bitrate,\n\t\t\t\t\trtt: hasProbeRtt(this.version) ? rtt : (rtt ?? prev.rtt),\n\t\t\t\t});\n\t\t\t}\n\t\t} catch (err: unknown) {\n\t\t\tif (!this.#closed.signal.aborted) {\n\t\t\t\tconsole.warn(\"probe stream error\", err);\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.#probe.set({});\n\t\t}\n\t}\n\n\t/**\n\t * Ends every subscribed track: cleanly for a deliberate close, or with `err` when the\n\t * session died, since those tracks were cut off rather than ended.\n\t */\n\tclose(err?: Error) {\n\t\t// A fetch or setup exchange cut off by the session is incomplete even on a deliberate\n\t\t// close, so it always ends with an error.\n\t\tconst cut = err ?? new StreamError(StreamCode.SessionClosed, { message: \"session closed\" });\n\t\tthis.#closed.abort(cut);\n\n\t\tfor (const { track } of this.#subscribes.values()) {\n\t\t\ttrack.close(err);\n\t\t}\n\n\t\tthis.#subscribes.clear();\n\n\t\t// This also releases callers still awaiting acceptance.\n\t\tfor (const { group } of this.#fetches.values()) {\n\t\t\tgroup.close(cut);\n\t\t}\n\t}\n}\n\n// Settles with `step`, or rejects with the group's error once it closes first. A publisher\n// may never answer a FETCH, so Subscriber.close() closing the group is what releases it.\nasync function untilClosed<T>(group: netGroup.Producer, step: Promise<T>): Promise<T> {\n\tconst value = await race([step, group.closed]);\n\tconst closed = group.closed.peek();\n\tif (closed !== undefined) throw closed ?? new Error(\"fetch closed before it was accepted\");\n\treturn value as T;\n}\n\n// Like untilClosed, but also cancels once every reader has left. Demand is level-triggered, so a\n// caller that coalesces onto the group before the check re-arms it.\nasync function untilAbandoned<T>(group: netGroup.Producer, step: Promise<T>): Promise<T> {\n\tconst idle: unique symbol = Symbol(\"idle\");\n\tfor (;;) {\n\t\tconst value = await untilClosed(group, race([step, group.unused().then((): typeof idle => idle)]));\n\t\tif (value !== idle) return value as T;\n\t\tif (!group.used.peek()) throw new StreamError(StreamCode.Cancel, { message: \"cancel\" });\n\t}\n}\n\n/**\n * A broadcast consumed from a lite session. It resolves `track.Consumer.query()` and\n * `.fetchGroup()` over the wire (lite-05+ TRACK / FETCH streams) by reaching into the\n * {@link Subscriber} it was opened from, the way the Rust `BroadcastConsumer` holds its\n * session. Live subscribes still flow through the inherited requested() queue.\n */\nclass ConsumeBroadcast extends broadcast.Consumer {\n\t#subscriber: Subscriber;\n\t#path: Path.Valid;\n\n\tconstructor(subscriber: Subscriber, path: Path.Valid, state?: never) {\n\t\tsuper(state);\n\t\toverrideBroadcastWire(this, {\n\t\t\tresolveTrackInfo: (name) => subscriber.resolveTrackInfo(path, name),\n\t\t\tfetchGroup: (name, sequence, options) => subscriber.fetchGroup(path, name, sequence, options),\n\t\t});\n\t\tthis.#subscriber = subscriber;\n\t\tthis.#path = path;\n\t}\n\n\t// Preserve the subclass (and its wire-backed info/fetchGroup) when the consume cache shares\n\t// this broadcast across callers.\n\toverride clone(): ConsumeBroadcast {\n\t\treturn new ConsumeBroadcast(this.#subscriber, this.#path, this.shareState());\n\t}\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@moq/net",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.4.
|
|
4
|
+
"version": "0.4.5",
|
|
5
5
|
"description": "The networking layer for Media over QUIC: real-time pub/sub with built-in caching, fan-out, and prioritization.",
|
|
6
6
|
"license": "(MIT OR Apache-2.0)",
|
|
7
7
|
"repository": {
|
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
"dependencies": {
|
|
24
24
|
"@moq/pattern": "^0.2.1",
|
|
25
25
|
"@moq/qmux": "^0.3.3",
|
|
26
|
-
"@moq/signals": "^0.2.
|
|
26
|
+
"@moq/signals": "^0.2.6",
|
|
27
27
|
"async-mutex": "^0.5.0",
|
|
28
28
|
"bowser": "^2.14.1"
|
|
29
29
|
},
|
package/path.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"path.d.ts","sourceRoot":"","sources":["../src/path.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,MAAM,MAAM,KAAK,GAAG,MAAM,GAAG;IAAE,OAAO,EAAE,MAAM,CAAA;CAAE,CAAC;AAEjD;;;;;;GAMG;AACH,MAAM,MAAM,QAAQ,GAAG,MAAM,GAAG;IAAE,OAAO,EAAE,UAAU,CAAA;CAAE,CAAC;AAExD;;;;;GAKG;AACH,eAAO,MAAM,SAAS,KAAK,CAAC;AAE5B,iGAAiG;AACjG,wBAAgB,IAAI,CAAC,GAAG,KAAK,EAAE,MAAM,EAAE,GAAG,KAAK,CAI9C;AAED,gFAAgF;AAChF,wBAAgB,KAAK,CAAC,IAAI,EAAE,KAAK,GAAG,MAAM,EAAE,CAE3C;AAED;;;;GAIG;AACH,wBAAgB,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,KAAK,CAGzC;AAED;;;;;GAKG;AACH,wBAAgB,MAAM,CAAC,IAAI,EAAE,KAAK,GAAG,KAAK,
|
|
1
|
+
{"version":3,"file":"path.d.ts","sourceRoot":"","sources":["../src/path.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,MAAM,MAAM,KAAK,GAAG,MAAM,GAAG;IAAE,OAAO,EAAE,MAAM,CAAA;CAAE,CAAC;AAEjD;;;;;;GAMG;AACH,MAAM,MAAM,QAAQ,GAAG,MAAM,GAAG;IAAE,OAAO,EAAE,UAAU,CAAA;CAAE,CAAC;AAExD;;;;;GAKG;AACH,eAAO,MAAM,SAAS,KAAK,CAAC;AAE5B,iGAAiG;AACjG,wBAAgB,IAA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AO,EACP,QAAQ,EACR,KAAK,OAAO,EACZ,KAAK,WAAW,GAChB,MAAM,cAAc,CAAC"}
|
package/path.js
CHANGED
|
@@ -32,8 +32,12 @@ export function decode(raw) {
|
|
|
32
32
|
* emit a path the remote side is required to reject.
|
|
33
33
|
*/
|
|
34
34
|
export function encode(path) {
|
|
35
|
-
|
|
36
|
-
|
|
35
|
+
// Count separators with an early exit instead of splitting, so a hostile path never allocates per part.
|
|
36
|
+
let count = path === "" ? 0 : 1;
|
|
37
|
+
for (let i = path.indexOf("/"); i !== -1; i = path.indexOf("/", i + 1)) {
|
|
38
|
+
if (++count > MAX_PARTS) {
|
|
39
|
+
throw new Error(`path exceeds ${MAX_PARTS} parts`);
|
|
40
|
+
}
|
|
37
41
|
}
|
|
38
42
|
return path;
|
|
39
43
|
}
|
package/path.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"path.js","sourceRoot":"","sources":["../src/path.ts"],"names":[],"mappings":"AA+CA;;;;;GAKG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG,EAAE,CAAC;AAE5B,iGAAiG;AACjG,MAAM,UAAU,IAAI,CAAC,GAAG,KAAe;IACtC,4GAA4G;IAC5G,MAAM,MAAM,GAAG,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAC/B,OAAO,MAAM,CAAC,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAU,CAAC;AACrF,CAAC;AAED,gFAAgF;AAChF,MAAM,UAAU,KAAK,CAAC,IAAW;IAChC,OAAO,IAAI,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;AAC3C,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,MAAM,CAAC,GAAW;IACjC,MAAM,IAAI,GAAG,IAA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AAO,EAAc,CAAC;IAE3C,wEAAwE;IACxE,MAAM,GAAG,GAAG,IAAI,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAC/C,GAAG,CAAC,GAAG,EAAE,CAAC;IAEV,MAAM,KAAK,GAAG,MAAM,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAErD,IAAI,MAAM,GAAG,CAAC,CAAC;IACf,OAAO,MAAM,GAAG,GAAG,CAAC,MAAM,IAAI,MAAM,GAAG,KAAK,CAAC,MAAM,IAAI,GAAG,CAAC,MAAM,CAAC,KAAK,KAAK,CAAC,MAAM,CAAC,EAAE,CAAC;QACtF,MAAM,IAAI,CAAC,CAAC;IACb,CAAC;IAED,MAAM,IAAI,GAAG,KAAK,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;IACjC,yDAAyD;IACzD,IAAI,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,KAAK,GAAG,IAAI,IAAI,KAAK,IAAI,CAAC;QAAE,OAAO,SAAS,CAAC;IAEzE,MAAM,GAAG,GAAG,KAAK,CAAC,GAAG,CAAC,MAAM,GAAG,MAAM,CAAC;SACpC,IAAI,CAAC,IAAI,CAAC;SACV,MAAM,CAAC,IAAI,CAAC,CAAC;IAEf,iFAAiF;IACjF,OAAO,CAAC,GAAG,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAa,CAAC;AAC7D,CAAC;AAED,kEAAkE;AAClE,OAAO,EACN,kBAAkB,EAClB,cAAc,EACd,OAAO,EACP,QAAQ,GAGR,MAAM,cAAc,CAAC","sourcesContent":["/**\n * A broadcast path that provides safe prefix matching operations.\n *\n * This module provides path-aware operations that respect delimiter boundaries,\n * preventing issues like \"foo\" matching \"foobar\".\n *\n * Paths are automatically trimmed of leading and trailing slashes on creation,\n * making all slashes implicit at boundaries. A path names a point in the origin's\n * tree from its root; a leading slash never escapes that root. The same type names\n * an exact broadcast and the prefix a route or announcement covers, so a broadcast's\n * own path is the prefix it announces. See {@link Relative} for `..`-style references.\n *\n * {@link Pattern} and {@link Patterns} are re-exported from `@moq/pattern`, the owner of\n * the v1 grammar and algebra. Literal path construction and wire decoding retain\n * their existing behavior.\n *\n * @example\n * ```typescript\n * // Creation automatically trims slashes\n * const path1 = Path.from(\"/foo/bar/\");\n * const path2 = Path.from(\"foo/bar\");\n * console.log(path1 === path2); // true\n *\n * // Multiple arguments are joined with \"/\"\n * const path3 = Path.from(\"api\", \"v1\", \"users\");\n * console.log(path3); // \"api/v1/users\"\n *\n * // Safe prefix matching\n * const base = Path.from(\"api/v1\");\n * console.log(Path.hasPrefix(Path.from(\"api\"), base)); // true\n * console.log(Path.hasPrefix(Path.from(\"api/v1\"), base)); // true\n *\n * const joined = Path.join(base, Path.from(\"users\"));\n * console.log(joined); // \"api/v1/users\"\n * ```\n */\nexport type Valid = string & { __brand: \"Name\" };\n\n/**\n * A relative reference from one broadcast to another, as a hang catalog carries it.\n *\n * It may contain `..` and is meaningful only once {@link resolve}d against a base\n * {@link Valid} path. It never crosses the wire on its own. Build one with\n * {@link normalizeRelative} or {@link relative}.\n */\nexport type Relative = string & { __brand: \"Relative\" };\n\n/**\n * Maximum number of slash-separated parts in a path.\n *\n * Matches the IETF moq-transport limit of 32 fields in a namespace tuple.\n * moq-lite enforces the same bound when decoding paths off the wire.\n */\nexport const MAX_PARTS = 32;\n\n/** Build a path from one or more components, joining with \"/\" and trimming redundant slashes. */\nexport function from(...paths: string[]): Valid {\n\t// Join paths with \"/\" and then remove leading and trailing slashes, and collapse multiple slashes into one.\n\tconst joined = paths.join(\"/\");\n\treturn joined.replace(/\\/+/g, \"/\").replace(/^\\/+/, \"\").replace(/\\/+$/, \"\") as Valid;\n}\n\n/** Split a path into its slash-separated parts. The empty path has no parts. */\nexport function parts(path: Valid): string[] {\n\treturn path === \"\" ? [] : path.split(\"/\");\n}\n\n/**\n * Validate an untrusted wire string as a path, enforcing {@link MAX_PARTS}.\n *\n * Throws when the path has too many parts; use at wire decode sites.\n */\nexport function decode(raw: string): Valid {\n\tconst path = from(raw);\n\treturn encode(path);\n}\n\n/**\n * Validate a path before writing it to the wire, enforcing {@link MAX_PARTS}.\n *\n * Throws when the path has too many parts; use at wire encode sites so we never\n * emit a path the remote side is required to reject.\n */\nexport function encode(path: Valid): Valid {\n\tif (parts(path).length > MAX_PARTS) {\n\t\tthrow new Error(`path exceeds ${MAX_PARTS} parts`);\n\t}\n\treturn path;\n}\n\n/**\n * Check if a path has the given prefix, respecting path boundaries.\n *\n * Unlike String.startsWith, this ensures that \"foo\" does not match \"foobar\".\n * The prefix must either:\n * - Be exactly equal to the path\n * - Be followed by a '/' delimiter in the original path\n * - Be empty (matches everything)\n *\n * @example\n * ```typescript\n * const path = Path.from(\"foo/bar\");\n * console.log(Path.hasPrefix(Path.from(\"foo\"), path)); // true\n * console.log(Path.hasPrefix(Path.from(\"foo/\"), path)); // true (trailing slash ignored)\n * console.log(Path.hasPrefix(Path.from(\"fo\"), path)); // false\n *\n * const path2 = Path.from(\"foobar\");\n * console.log(Path.hasPrefix(Path.from(\"foo\"), path2)); // false\n * ```\n */\nexport function hasPrefix(prefix: Valid, path: Valid): boolean {\n\tif (prefix === \"\") {\n\t\treturn true;\n\t}\n\n\tif (!path.startsWith(prefix)) {\n\t\treturn false;\n\t}\n\n\t// Check if the prefix is the exact match\n\tif (path.length === prefix.length) {\n\t\treturn true;\n\t}\n\n\t// Otherwise, ensure the character after the prefix is a delimiter\n\treturn path[prefix.length] === \"/\";\n}\n\n/**\n * Strip the given prefix from a path, returning the suffix.\n *\n * Returns null if the prefix doesn't match according to hasPrefix rules.\n *\n * @example\n * ```typescript\n * const path = Path.from(\"foo/bar/baz\");\n * const suffix = Path.stripPrefix(Path.from(\"foo\"), path);\n * console.log(suffix); // \"bar/baz\"\n *\n * const suffix2 = Path.stripPrefix(Path.from(\"foo/\"), path);\n * console.log(suffix2); // \"bar/baz\"\n *\n * const noMatch = Path.stripPrefix(Path.from(\"notfound\"), path);\n * console.log(noMatch); // null\n * ```\n */\nexport function stripPrefix(prefix: Valid, path: Valid): Valid | null {\n\tif (!hasPrefix(prefix, path)) {\n\t\treturn null;\n\t}\n\n\t// Handle empty prefix case\n\tif (prefix === \"\") {\n\t\treturn path;\n\t}\n\n\t// If prefix matches exactly, return empty\n\tif (path.length === prefix.length) {\n\t\treturn \"\" as Valid;\n\t}\n\n\t// For non-empty prefix that's shorter, skip the prefix and the following slash\n\treturn path.slice(prefix.length + 1) as Valid;\n}\n\n/**\n * Join two path components together.\n *\n * @example\n * ```typescript\n * const base = Path.from(\"foo\");\n * const joined = Path.join(base, Path.from(\"bar\"));\n * console.log(joined); // \"foo/bar\"\n * ```\n */\nexport function join(path: Valid, other: Valid): Valid {\n\tif (path === \"\") {\n\t\treturn other;\n\t} else if (other === \"\") {\n\t\treturn path;\n\t} else {\n\t\t// Since paths are trimmed, we always need to add a slash\n\t\treturn `${path}/${other}` as Valid;\n\t}\n}\n\n/** The empty path, which is a prefix of every path. */\nexport function empty(): Valid {\n\treturn \"\" as Valid;\n}\n\n/**\n * Normalize a relative path reference: trim leading/trailing slashes, drop empty\n * segments, and drop redundant `.` segments. A reference made only of `.` segments\n * normalizes to `.` because it names the base's parent, while empty names the base.\n * `..` is preserved and only interpreted by {@link resolve}.\n *\n * Mirrors the Rust `path::Relative::new` normalization, so JS and Rust agree\n * byte-for-byte on the stored form. Two callers comparing normalized strings can\n * detect equivalent references while preserving the distinction between `\"\"` and `\".\"`.\n */\nexport function normalizeRelative(rel: string): Relative {\n\tconst raw = rel.split(\"/\");\n\tconst normalized = raw.filter((s) => s !== \"\" && s !== \".\").join(\"/\");\n\n\treturn (normalized === \"\" && raw.includes(\".\") ? \".\" : normalized) as Relative;\n}\n\n/**\n * Resolve a relative path reference against a base path.\n *\n * A non-empty reference replaces the last segment of the base, matching relative URL\n * resolution. `..` segments then pop another segment; other segments are appended.\n * `.` and empty segments are no-ops. Excess `..` once the base is empty is also a no-op\n * (subsequent named segments still append). An empty `rel` returns the base unchanged.\n *\n * Mirrors the Rust `Path::resolve`, used by hang catalogs to express\n * cross-broadcast track references (a rendition's `broadcast` field).\n *\n * @example\n * ```typescript\n * Path.resolve(Path.from(\"a/b/c\"), \"./source\"); // \"a/b/source\"\n * Path.resolve(Path.from(\"a/b\"), \".\"); // \"a\"\n * Path.resolve(Path.from(\"a/b/c\"), \"../source\"); // \"a/source\"\n * ```\n */\nexport function resolve(base: Valid, rel: Relative): Valid {\n\tif (rel === \"\") return base;\n\n\tconst segments = base === \"\" ? [] : base.split(\"/\");\n\tsegments.pop();\n\n\tfor (const seg of rel.split(\"/\")) {\n\t\tif (seg === \"\" || seg === \".\") {\n\t\t\tcontinue;\n\t\t}\n\t\tif (seg === \"..\") {\n\t\t\tsegments.pop();\n\t\t} else {\n\t\t\tsegments.push(seg);\n\t\t}\n\t}\n\n\treturn segments.join(\"/\") as Valid;\n}\n\n/**\n * Resolve a relative path, returning `undefined` if it escapes above the root.\n *\n * Unlike {@link resolve}, this distinguishes a valid reference to the empty root\n * path from excess `..` segments. Use it for untrusted catalog references that\n * must not be clamped to the root.\n */\nexport function tryResolve(base: Valid, rel: Relative): Valid | undefined {\n\tif (rel === \"\") return base;\n\n\tconst segments = base === \"\" ? [] : base.split(\"/\");\n\tsegments.pop();\n\n\tfor (const seg of rel.split(\"/\")) {\n\t\tif (seg === \"\" || seg === \".\") {\n\t\t\tcontinue;\n\t\t}\n\t\tif (seg === \"..\") {\n\t\t\tif (segments.pop() === undefined) return undefined;\n\t\t} else {\n\t\t\tsegments.push(seg);\n\t\t}\n\t}\n\n\treturn segments.join(\"/\") as Valid;\n}\n\n/**\n * Express `target` relative to `base`: the inverse of {@link resolve}.\n *\n * The result round-trips (`resolve(base, relative(target, base)) === target`) and never\n * walks above the root, so {@link tryResolve} accepts it too.\n *\n * A relative reference replaces the last segment of the base, matching relative URL\n * resolution, so a target nested under the base repeats the base's own last segment.\n *\n * The empty reference names the base itself, so that is what a self-reference returns.\n *\n * Returns `undefined` for a target no reference can name: a path segment may literally be\n * `.` or `..`, which resolution reads as navigation instead of as a name. Only the segments\n * past the shared prefix matter, since the rest are never emitted.\n *\n * Mirrors the Rust `Path::relative`, used to author the cross-broadcast track\n * references a hang catalog carries. Note the argument order: the target comes first,\n * the opposite of Node's `path.relative(from, to)`.\n *\n * @example\n * ```typescript\n * Path.relative(Path.from(\"a/b/c\"), Path.from(\"a/b\")); // \"b/c\"\n * Path.relative(Path.from(\"a/c\"), Path.from(\"a/b\")); // \"c\"\n * Path.relative(Path.from(\"a\"), Path.from(\"a/b\")); // \".\"\n * Path.relative(Path.from(\"a/b\"), Path.from(\"a/b\")); // \"\"\n * Path.relative(Path.from(\"a/..\"), Path.from(\"a/b\")); // undefined\n * ```\n */\nexport function relative(target: Valid, base: Valid): Relative | undefined {\n\t// Only the empty reference can name a base whose last segment is itself `.` or `..`,\n\t// since resolution replaces that segment rather than emitting it.\n\tif (target === base) return \"\" as Relative;\n\n\t// Resolution replaces the base's last segment, so walk from its parent.\n\tconst dir = base === \"\" ? [] : base.split(\"/\");\n\tdir.pop();\n\n\tconst parts = target === \"\" ? [] : target.split(\"/\");\n\n\tlet common = 0;\n\twhile (common < dir.length && common < parts.length && dir[common] === parts[common]) {\n\t\tcommon += 1;\n\t}\n\n\tconst down = parts.slice(common);\n\t// Resolution would walk on these instead of naming them.\n\tif (down.some((part) => part === \".\" || part === \"..\")) return undefined;\n\n\tconst rel = Array(dir.length - common)\n\t\t.fill(\"..\")\n\t\t.concat(down);\n\n\t// An empty reference resolves to the base itself, so name the parent explicitly.\n\treturn (rel.length === 0 ? \".\" : rel.join(\"/\")) as Relative;\n}\n\n/** Path patterns: grammar and algebra owned by `@moq/pattern`. */\nexport {\n\tcompareSpecificity,\n\tInvalidPattern,\n\tPattern,\n\tPatterns,\n\ttype Segment,\n\ttype Specificity,\n} from \"@moq/pattern\";\n"]}
|
|
1
|
+
{"version":3,"file":"path.js","sourceRoot":"","sources":["../src/path.ts"],"names":[],"mappings":"AA+CA;;;;;GAKG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG,EAAE,CAAC;AAE5B,iGAAiG;AACjG,MAAM,UAAU,IAAI,CAAC,GAAG,KAAe;IACtC,4GAA4G;IAC5G,MAAM,MAAM,GAAG,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAC/B,OAAO,MAAM,CAAC,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAU,CAAC;AACrF,CAAC;AAED,gFAAgF;AAChF,MAAM,UAAU,KAAK,CAAC,IAAW;IAChC,OAAO,IAAI,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;AAC3C,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,MAAM,CAAC,GAAW;IACjC,MAAM,IAAI,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC;IACvB,OAAO,MAAM,CAAC,IAAI,CAAC,CAAC;AACrB,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,MAAM,CAAC,IAAW;IACjC,wGAAwG;IACxG,IAAI,KAAK,GAAG,IAAI,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAChC,KAAK,IAAI,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC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AG,CAAC,CAAC;IAC/C,GAAG,CAAC,GAAG,EAAE,CAAC;IAEV,MAAM,KAAK,GAAG,MAAM,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAErD,IAAI,MAAM,GAAG,CAAC,CAAC;IACf,OAAO,MAAM,GAAG,GAAG,CAAC,MAAM,IAAI,MAAM,GAAG,KAAK,CAAC,MAAM,IAAI,GAAG,CAAC,MAAM,CAAC,KAAK,KAAK,CAAC,MAAM,CAAC,EAAE,CAAC;QACtF,MAAM,IAAI,CAAC,CAAC;IACb,CAAC;IAED,MAAM,IAAI,GAAG,KAAK,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;IACjC,yDAAyD;IACzD,IAAI,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,KAAK,GAAG,IAAI,IAAI,KAAK,IAAI,CAAC;QAAE,OAAO,SAAS,CAAC;IAEzE,MAAM,GAAG,GAAG,KAAK,CAAC,GAAG,CAAC,MAAM,GAAG,MAAM,CAAC;SACpC,IAAI,CAAC,IAAI,CAAC;SACV,MAAM,CAAC,IAAI,CAAC,CAAC;IAEf,iFAAiF;IACjF,OAAO,CAAC,GAAG,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAa,CAAC;AAC7D,CAAC;AAED,kEAAkE;AAClE,OAAO,EACN,kBAAkB,EAClB,cAAc,EACd,OAAO,EACP,QAAQ,GAGR,MAAM,cAAc,CAAC","sourcesContent":["/**\n * A broadcast path that provides safe prefix matching operations.\n *\n * This module provides path-aware operations that respect delimiter boundaries,\n * preventing issues like \"foo\" matching \"foobar\".\n *\n * Paths are automatically trimmed of leading and trailing slashes on creation,\n * making all slashes implicit at boundaries. A path names a point in the origin's\n * tree from its root; a leading slash never escapes that root. The same type names\n * an exact broadcast and the prefix a route or announcement covers, so a broadcast's\n * own path is the prefix it announces. See {@link Relative} for `..`-style references.\n *\n * {@link Pattern} and {@link Patterns} are re-exported from `@moq/pattern`, the owner of\n * the v1 grammar and algebra. Literal path construction and wire decoding retain\n * their existing behavior.\n *\n * @example\n * ```typescript\n * // Creation automatically trims slashes\n * const path1 = Path.from(\"/foo/bar/\");\n * const path2 = Path.from(\"foo/bar\");\n * console.log(path1 === path2); // true\n *\n * // Multiple arguments are joined with \"/\"\n * const path3 = Path.from(\"api\", \"v1\", \"users\");\n * console.log(path3); // \"api/v1/users\"\n *\n * // Safe prefix matching\n * const base = Path.from(\"api/v1\");\n * console.log(Path.hasPrefix(Path.from(\"api\"), base)); // true\n * console.log(Path.hasPrefix(Path.from(\"api/v1\"), base)); // true\n *\n * const joined = Path.join(base, Path.from(\"users\"));\n * console.log(joined); // \"api/v1/users\"\n * ```\n */\nexport type Valid = string & { __brand: \"Name\" };\n\n/**\n * A relative reference from one broadcast to another, as a hang catalog carries it.\n *\n * It may contain `..` and is meaningful only once {@link resolve}d against a base\n * {@link Valid} path. It never crosses the wire on its own. Build one with\n * {@link normalizeRelative} or {@link relative}.\n */\nexport type Relative = string & { __brand: \"Relative\" };\n\n/**\n * Maximum number of slash-separated parts in a path.\n *\n * Matches the IETF moq-transport limit of 32 fields in a namespace tuple.\n * moq-lite enforces the same bound when decoding paths off the wire.\n */\nexport const MAX_PARTS = 32;\n\n/** Build a path from one or more components, joining with \"/\" and trimming redundant slashes. */\nexport function from(...paths: string[]): Valid {\n\t// Join paths with \"/\" and then remove leading and trailing slashes, and collapse multiple slashes into one.\n\tconst joined = paths.join(\"/\");\n\treturn joined.replace(/\\/+/g, \"/\").replace(/^\\/+/, \"\").replace(/\\/+$/, \"\") as Valid;\n}\n\n/** Split a path into its slash-separated parts. The empty path has no parts. */\nexport function parts(path: Valid): string[] {\n\treturn path === \"\" ? [] : path.split(\"/\");\n}\n\n/**\n * Validate an untrusted wire string as a path, enforcing {@link MAX_PARTS}.\n *\n * Throws when the path has too many parts; use at wire decode sites.\n */\nexport function decode(raw: string): Valid {\n\tconst path = from(raw);\n\treturn encode(path);\n}\n\n/**\n * Validate a path before writing it to the wire, enforcing {@link MAX_PARTS}.\n *\n * Throws when the path has too many parts; use at wire encode sites so we never\n * emit a path the remote side is required to reject.\n */\nexport function encode(path: Valid): Valid {\n\t// Count separators with an early exit instead of splitting, so a hostile path never allocates per part.\n\tlet count = path === \"\" ? 0 : 1;\n\tfor (let i = path.indexOf(\"/\"); i !== -1; i = path.indexOf(\"/\", i + 1)) {\n\t\tif (++count > MAX_PARTS) {\n\t\t\tthrow new Error(`path exceeds ${MAX_PARTS} parts`);\n\t\t}\n\t}\n\treturn path;\n}\n\n/**\n * Check if a path has the given prefix, respecting path boundaries.\n *\n * Unlike String.startsWith, this ensures that \"foo\" does not match \"foobar\".\n * The prefix must either:\n * - Be exactly equal to the path\n * - Be followed by a '/' delimiter in the original path\n * - Be empty (matches everything)\n *\n * @example\n * ```typescript\n * const path = Path.from(\"foo/bar\");\n * console.log(Path.hasPrefix(Path.from(\"foo\"), path)); // true\n * console.log(Path.hasPrefix(Path.from(\"foo/\"), path)); // true (trailing slash ignored)\n * console.log(Path.hasPrefix(Path.from(\"fo\"), path)); // false\n *\n * const path2 = Path.from(\"foobar\");\n * console.log(Path.hasPrefix(Path.from(\"foo\"), path2)); // false\n * ```\n */\nexport function hasPrefix(prefix: Valid, path: Valid): boolean {\n\tif (prefix === \"\") {\n\t\treturn true;\n\t}\n\n\tif (!path.startsWith(prefix)) {\n\t\treturn false;\n\t}\n\n\t// Check if the prefix is the exact match\n\tif (path.length === prefix.length) {\n\t\treturn true;\n\t}\n\n\t// Otherwise, ensure the character after the prefix is a delimiter\n\treturn path[prefix.length] === \"/\";\n}\n\n/**\n * Strip the given prefix from a path, returning the suffix.\n *\n * Returns null if the prefix doesn't match according to hasPrefix rules.\n *\n * @example\n * ```typescript\n * const path = Path.from(\"foo/bar/baz\");\n * const suffix = Path.stripPrefix(Path.from(\"foo\"), path);\n * console.log(suffix); // \"bar/baz\"\n *\n * const suffix2 = Path.stripPrefix(Path.from(\"foo/\"), path);\n * console.log(suffix2); // \"bar/baz\"\n *\n * const noMatch = Path.stripPrefix(Path.from(\"notfound\"), path);\n * console.log(noMatch); // null\n * ```\n */\nexport function stripPrefix(prefix: Valid, path: Valid): Valid | null {\n\tif (!hasPrefix(prefix, path)) {\n\t\treturn null;\n\t}\n\n\t// Handle empty prefix case\n\tif (prefix === \"\") {\n\t\treturn path;\n\t}\n\n\t// If prefix matches exactly, return empty\n\tif (path.length === prefix.length) {\n\t\treturn \"\" as Valid;\n\t}\n\n\t// For non-empty prefix that's shorter, skip the prefix and the following slash\n\treturn path.slice(prefix.length + 1) as Valid;\n}\n\n/**\n * Join two path components together.\n *\n * @example\n * ```typescript\n * const base = Path.from(\"foo\");\n * const joined = Path.join(base, Path.from(\"bar\"));\n * console.log(joined); // \"foo/bar\"\n * ```\n */\nexport function join(path: Valid, other: Valid): Valid {\n\tif (path === \"\") {\n\t\treturn other;\n\t} else if (other === \"\") {\n\t\treturn path;\n\t} else {\n\t\t// Since paths are trimmed, we always need to add a slash\n\t\treturn `${path}/${other}` as Valid;\n\t}\n}\n\n/** The empty path, which is a prefix of every path. */\nexport function empty(): Valid {\n\treturn \"\" as Valid;\n}\n\n/**\n * Normalize a relative path reference: trim leading/trailing slashes, drop empty\n * segments, and drop redundant `.` segments. A reference made only of `.` segments\n * normalizes to `.` because it names the base's parent, while empty names the base.\n * `..` is preserved and only interpreted by {@link resolve}.\n *\n * Mirrors the Rust `path::Relative::new` normalization, so JS and Rust agree\n * byte-for-byte on the stored form. Two callers comparing normalized strings can\n * detect equivalent references while preserving the distinction between `\"\"` and `\".\"`.\n */\nexport function normalizeRelative(rel: string): Relative {\n\tconst raw = rel.split(\"/\");\n\tconst normalized = raw.filter((s) => s !== \"\" && s !== \".\").join(\"/\");\n\n\treturn (normalized === \"\" && raw.includes(\".\") ? \".\" : normalized) as Relative;\n}\n\n/**\n * Resolve a relative path reference against a base path.\n *\n * A non-empty reference replaces the last segment of the base, matching relative URL\n * resolution. `..` segments then pop another segment; other segments are appended.\n * `.` and empty segments are no-ops. Excess `..` once the base is empty is also a no-op\n * (subsequent named segments still append). An empty `rel` returns the base unchanged.\n *\n * Mirrors the Rust `Path::resolve`, used by hang catalogs to express\n * cross-broadcast track references (a rendition's `broadcast` field).\n *\n * @example\n * ```typescript\n * Path.resolve(Path.from(\"a/b/c\"), \"./source\"); // \"a/b/source\"\n * Path.resolve(Path.from(\"a/b\"), \".\"); // \"a\"\n * Path.resolve(Path.from(\"a/b/c\"), \"../source\"); // \"a/source\"\n * ```\n */\nexport function resolve(base: Valid, rel: Relative): Valid {\n\tif (rel === \"\") return base;\n\n\tconst segments = base === \"\" ? [] : base.split(\"/\");\n\tsegments.pop();\n\n\tfor (const seg of rel.split(\"/\")) {\n\t\tif (seg === \"\" || seg === \".\") {\n\t\t\tcontinue;\n\t\t}\n\t\tif (seg === \"..\") {\n\t\t\tsegments.pop();\n\t\t} else {\n\t\t\tsegments.push(seg);\n\t\t}\n\t}\n\n\treturn segments.join(\"/\") as Valid;\n}\n\n/**\n * Resolve a relative path, returning `undefined` if it escapes above the root.\n *\n * Unlike {@link resolve}, this distinguishes a valid reference to the empty root\n * path from excess `..` segments. Use it for untrusted catalog references that\n * must not be clamped to the root.\n */\nexport function tryResolve(base: Valid, rel: Relative): Valid | undefined {\n\tif (rel === \"\") return base;\n\n\tconst segments = base === \"\" ? [] : base.split(\"/\");\n\tsegments.pop();\n\n\tfor (const seg of rel.split(\"/\")) {\n\t\tif (seg === \"\" || seg === \".\") {\n\t\t\tcontinue;\n\t\t}\n\t\tif (seg === \"..\") {\n\t\t\tif (segments.pop() === undefined) return undefined;\n\t\t} else {\n\t\t\tsegments.push(seg);\n\t\t}\n\t}\n\n\treturn segments.join(\"/\") as Valid;\n}\n\n/**\n * Express `target` relative to `base`: the inverse of {@link resolve}.\n *\n * The result round-trips (`resolve(base, relative(target, base)) === target`) and never\n * walks above the root, so {@link tryResolve} accepts it too.\n *\n * A relative reference replaces the last segment of the base, matching relative URL\n * resolution, so a target nested under the base repeats the base's own last segment.\n *\n * The empty reference names the base itself, so that is what a self-reference returns.\n *\n * Returns `undefined` for a target no reference can name: a path segment may literally be\n * `.` or `..`, which resolution reads as navigation instead of as a name. Only the segments\n * past the shared prefix matter, since the rest are never emitted.\n *\n * Mirrors the Rust `Path::relative`, used to author the cross-broadcast track\n * references a hang catalog carries. Note the argument order: the target comes first,\n * the opposite of Node's `path.relative(from, to)`.\n *\n * @example\n * ```typescript\n * Path.relative(Path.from(\"a/b/c\"), Path.from(\"a/b\")); // \"b/c\"\n * Path.relative(Path.from(\"a/c\"), Path.from(\"a/b\")); // \"c\"\n * Path.relative(Path.from(\"a\"), Path.from(\"a/b\")); // \".\"\n * Path.relative(Path.from(\"a/b\"), Path.from(\"a/b\")); // \"\"\n * Path.relative(Path.from(\"a/..\"), Path.from(\"a/b\")); // undefined\n * ```\n */\nexport function relative(target: Valid, base: Valid): Relative | undefined {\n\t// Only the empty reference can name a base whose last segment is itself `.` or `..`,\n\t// since resolution replaces that segment rather than emitting it.\n\tif (target === base) return \"\" as Relative;\n\n\t// Resolution replaces the base's last segment, so walk from its parent.\n\tconst dir = base === \"\" ? [] : base.split(\"/\");\n\tdir.pop();\n\n\tconst parts = target === \"\" ? [] : target.split(\"/\");\n\n\tlet common = 0;\n\twhile (common < dir.length && common < parts.length && dir[common] === parts[common]) {\n\t\tcommon += 1;\n\t}\n\n\tconst down = parts.slice(common);\n\t// Resolution would walk on these instead of naming them.\n\tif (down.some((part) => part === \".\" || part === \"..\")) return undefined;\n\n\tconst rel = Array(dir.length - common)\n\t\t.fill(\"..\")\n\t\t.concat(down);\n\n\t// An empty reference resolves to the base itself, so name the parent explicitly.\n\treturn (rel.length === 0 ? \".\" : rel.join(\"/\")) as Relative;\n}\n\n/** Path patterns: grammar and algebra owned by `@moq/pattern`. */\nexport {\n\tcompareSpecificity,\n\tInvalidPattern,\n\tPattern,\n\tPatterns,\n\ttype Segment,\n\ttype Specificity,\n} from \"@moq/pattern\";\n"]}
|