stinky-moq-js 0.1.20 → 0.1.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,3 +1,3 @@
1
1
  "use strict";var ru=Object.defineProperty;var Za=t=>{throw TypeError(t)};var nu=(t,e,s)=>e in t?ru(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s;var E=(t,e,s)=>nu(t,typeof e!="symbol"?e+"":e,s),_r=(t,e,s)=>e.has(t)||Za("Cannot "+s);var c=(t,e,s)=>(_r(t,e,"read from private field"),s?s.call(t):e.get(t)),f=(t,e,s)=>e.has(t)?Za("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),m=(t,e,s,r)=>(_r(t,e,"write to private field"),r?r.call(t,s):e.set(t,s),s),p=(t,e,s)=>(_r(t,e,"access private method"),s);var br=(t,e,s,r)=>({set _(n){m(t,e,n,s)},get _(){return c(t,e,r)}});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});var Ya=Object.prototype.hasOwnProperty;function ja(t,e,s){for(s of t.keys())if(Mt(s,e))return s}function Mt(t,e){var s,r,n;if(t===e)return!0;if(t&&e&&(s=t.constructor)===e.constructor){if(s===Date)return t.getTime()===e.getTime();if(s===RegExp)return t.toString()===e.toString();if(s===Array){if((r=t.length)===e.length)for(;r--&&Mt(t[r],e[r]););return r===-1}if(s===Set){if(t.size!==e.size)return!1;for(r of t)if(n=r,n&&typeof n=="object"&&(n=ja(e,n),!n)||!e.has(n))return!1;return!0}if(s===Map){if(t.size!==e.size)return!1;for(r of t)if(n=r[0],n&&typeof n=="object"&&(n=ja(e,n),!n)||!Mt(r[1],e.get(n)))return!1;return!0}if(s===ArrayBuffer)t=new Uint8Array(t),e=new Uint8Array(e);else if(s===DataView){if((r=t.byteLength)===e.byteLength)for(;r--&&t.getInt8(r)===e.getInt8(r););return r===-1}if(ArrayBuffer.isView(t)){if((r=t.byteLength)===e.byteLength)for(;r--&&t[r]===e[r];);return r===-1}if(!s||typeof t=="object"){r=0;for(s in t)if(Ya.call(t,s)&&++r&&!Ya.call(e,s)||!(s in e)||!Mt(t[s],e[s]))return!1;return Object.keys(e).length===r}}return t!==t&&e!==e}const au={},iu=typeof au<"u"&&!1,ei=Symbol.for("@kixelated/signals");var mi,F,Ke,ce;mi=ei;const za=class za{constructor(e){f(this,F);f(this,Ke,new Set);f(this,ce,new Set);E(this,mi,!0);m(this,F,e)}static from(e){return typeof e=="object"&&e!==null&&ei in e?e:new za(e)}peek(){return c(this,F)}set(e,s){const r=c(this,F);if(m(this,F,e),s===!1||s===void 0&&r===c(this,F)||c(this,Ke).size===0&&c(this,ce).size===0)return;const n=c(this,Ke),a=c(this,ce);m(this,ce,new Set),queueMicrotask(()=>{if(s===void 0&&Mt(r,c(this,F))){for(const i of a)c(this,ce).add(i);return}for(const i of n)try{i(e)}catch(o){console.error("signal subscriber error",o)}for(const i of a)try{i(e)}catch(o){console.error("signal changed error",o)}})}update(e,s=!0){const r=e(c(this,F));this.set(r,s)}mutate(e,s=!0){const r=e(c(this,F));return this.set(c(this,F),s),r}subscribe(e){return c(this,Ke).add(e),()=>c(this,Ke).delete(e)}changed(e){return c(this,ce).add(e),()=>c(this,ce).delete(e)}watch(e){const s=this.subscribe(e);return queueMicrotask(()=>e(c(this,F))),s}static async race(...e){const s=[],r=await new Promise(n=>{for(const a of e)s.push(a.changed(n))});for(const n of s)n();return r}};F=new WeakMap,Ke=new WeakMap,ce=new WeakMap;let $=za;var Rn,pt,g,be,ye,_t,bt,Qe,yt,Ht,zt,$e,ss,Si;const Lt=class Lt{constructor(e){f(this,$e);f(this,pt);f(this,g,[]);f(this,be,[]);f(this,ye,[]);f(this,_t);f(this,bt,!1);f(this,Qe);f(this,yt);f(this,Ht);f(this,zt);m(this,pt,e),m(this,yt,new Promise(s=>{m(this,Qe,s)})),m(this,zt,new Promise(s=>{m(this,Ht,s)})),e&&p(this,$e,ss).call(this)}get(e){if(c(this,g)===void 0)return e.peek();const s=e.peek(),r=e.changed(()=>p(this,$e,ss).call(this));return c(this,be).push(r),s}set(e,s,...r){if(c(this,g)===void 0)return;e.set(s);const n=r[0],a=n===void 0?void 0:n;this.cleanup(()=>e.set(a))}spawn(e){const s=e().catch(r=>{console.error("spawn error",r)});c(this,g)!==void 0&&c(this,ye).push(s)}timer(e,s){if(c(this,g)===void 0)return;let r;r=setTimeout(()=>{r=void 0,e()},s),this.cleanup(()=>r&&clearTimeout(r))}timeout(e,s){if(c(this,g)===void 0)return;const r=new Lt(e);let n=setTimeout(()=>{r.close(),n=void 0},s);c(this,g).push(()=>{n&&(clearTimeout(n),r.close())})}animate(e){if(c(this,g)===void 0)return;let s=requestAnimationFrame(r=>{e(r),s=void 0});this.cleanup(()=>{s&&cancelAnimationFrame(s)})}interval(e,s){if(c(this,g)===void 0)return;const r=setInterval(()=>{e()},s);this.cleanup(()=>clearInterval(r))}effect(e){if(c(this,g)===void 0)return;const s=new Lt(e);c(this,g).push(()=>s.close())}subscribe(e,s){if(c(this,g)===void 0){s(e.peek());return}this.effect(r=>{const n=r.get(e);s(n)})}event(e,s,r,n){c(this,g)!==void 0&&(e.addEventListener(s,r,n),this.cleanup(()=>e.removeEventListener(s,r,n)))}reload(){p(this,$e,ss).call(this)}cleanup(e){if(c(this,g)===void 0){e();return}c(this,g).push(e)}close(){if(c(this,g)!==void 0){c(this,Ht).call(this),c(this,Qe).call(this);for(const e of c(this,g))e();m(this,g,void 0);for(const e of c(this,be))e();c(this,be).length=0,c(this,ye).length=0}}get closed(){return c(this,zt)}get cancel(){return c(this,yt)}};Rn=new WeakMap,pt=new WeakMap,g=new WeakMap,be=new WeakMap,ye=new WeakMap,_t=new WeakMap,bt=new WeakMap,Qe=new WeakMap,yt=new WeakMap,Ht=new WeakMap,zt=new WeakMap,$e=new WeakSet,ss=function(){c(this,bt)||(m(this,bt,!0),queueMicrotask(()=>p(this,$e,Si).call(this).catch(e=>{console.error("effect error",e,c(this,_t))})))},Si=async function(){if(c(this,g)!==void 0){c(this,Qe).call(this),m(this,yt,new Promise(e=>{m(this,Qe,e)}));for(const e of c(this,be))e();c(this,be).length=0;for(const e of c(this,g))e();if(c(this,g).length=0,c(this,ye).length>0)try{let e;const s=new Promise(r=>{e=setTimeout(()=>{r()},5e3)});await Promise.race([Promise.all(c(this,ye)),s]),e&&clearTimeout(e),c(this,ye).length=0}catch(e){console.error("async effect error",e),c(this,_t)&&console.error("stack",c(this,_t))}c(this,g)!==void 0&&(m(this,bt,!1),c(this,pt)&&c(this,pt).call(this,this))}},f(Lt,Rn,new FinalizationRegistry(e=>{console.warn(`Signals was garbage collected without being closed:
2
- ${e}`)}));let ti=Lt;function Y(...t){return t.join("/").replace(/\/+/g,"/").replace(/^\/+/,"").replace(/\/+$/,"")}function cu(t,e){return t===""?!0:e.startsWith(t)?e.length===t.length?!0:e[t.length]==="/":!1}function si(t,e){return cu(t,e)?t===""?e:e.length===t.length?"":e.slice(t.length+1):null}function ri(t,e){return t===""?e:e===""?t:`${t}/${e}`}function Qt(){return""}var ou=Object.defineProperty,hu=(t,e,s)=>e in t?ou(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Tt=(t,e,s)=>hu(t,typeof e!="symbol"?e+"":e,s);class uu{constructor(){Tt(this,"queue",new $([])),Tt(this,"closed",new $(!1))}}class ki{constructor(e=Qt()){Tt(this,"state",new uu),Tt(this,"prefix"),Tt(this,"closed"),this.prefix=e,this.closed=new Promise(s=>{const r=this.state.closed.subscribe(n=>{n&&(s(n instanceof Error?n:void 0),r())})})}append(e){if(this.state.closed.peek())throw new Error("announced is closed");this.state.queue.mutate(s=>{s.push(e)})}close(e){this.state.closed.set(e??!0),this.state.queue.mutate(s=>{s.length=0})}async next(){for(;;){const e=this.state.queue.peek().shift();if(e)return e;const s=this.state.closed.peek();if(s instanceof Error)throw s;if(s)return;await $.race(this.state.queue,this.state.closed)}}}var du=Object.defineProperty,lu=(t,e,s)=>e in t?du(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ut=(t,e,s)=>lu(t,typeof e!="symbol"?e+"":e,s);class fu{constructor(){ut(this,"frames",new $([])),ut(this,"closed",new $(!1)),ut(this,"total",new $(0))}}let Fn=class{constructor(e){ut(this,"sequence"),ut(this,"state",new fu),ut(this,"closed"),this.sequence=e,this.closed=new Promise(s=>{const r=this.state.closed.subscribe(n=>{n&&(s(n instanceof Error?n:void 0),r())})})}writeFrame(e){if(this.state.closed.peek())throw new Error("group is closed");this.state.frames.mutate(s=>{s.push(e)}),this.state.total.update(s=>s+1)}writeString(e){this.writeFrame(new TextEncoder().encode(e))}writeJson(e){this.writeString(JSON.stringify(e))}writeBool(e){this.writeFrame(new Uint8Array([e?1:0]))}async readFrame(){for(;;){const s=this.state.frames.peek().shift();if(s)return s;const r=this.state.closed.peek();if(r instanceof Error)throw r;if(r)return;await $.race(this.state.frames,this.state.closed)}}async readFrameSequence(){for(;;){const e=this.state.frames.peek(),s=e.shift();if(s)return{sequence:this.state.total.peek()-e.length-1,data:s};const r=this.state.closed.peek();if(r instanceof Error)throw r;if(r)return;await $.race(this.state.frames,this.state.closed)}}async readString(){const e=await this.readFrame();return e?new TextDecoder().decode(e):void 0}async readJson(){const e=await this.readString();return e?JSON.parse(e):void 0}async readBool(){const e=await this.readFrame();return e?e[0]===1:void 0}close(e){this.state.closed.set(e??!0)}};var wu=Object.defineProperty,$i=t=>{throw TypeError(t)},pu=(t,e,s)=>e in t?wu(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ot=(t,e,s)=>pu(t,typeof e!="symbol"?e+"":e,s),Ei=(t,e,s)=>e.has(t)||$i("Cannot "+s),ni=(t,e,s)=>(Ei(t,e,"read from private field"),s?s.call(t):e.get(t)),_u=(t,e,s)=>e.has(t)?$i("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),ai=(t,e,s,r)=>(Ei(t,e,"write to private field"),e.set(t,s),s),at;class bu{constructor(){Ot(this,"groups",new $([])),Ot(this,"closed",new $(!1))}}class Pi{constructor(e){Ot(this,"name"),Ot(this,"state",new bu),_u(this,at),Ot(this,"closed"),this.name=e,this.closed=new Promise(s=>{const r=this.state.closed.subscribe(n=>{n&&(s(n instanceof Error?n:void 0),r())})})}appendGroup(){if(this.state.closed.peek())throw new Error("track is closed");const e=new Fn(ni(this,at)??0);return ai(this,at,e.sequence+1),this.state.groups.mutate(s=>{s.push(e),s.sort((r,n)=>r.sequence-n.sequence)}),e}writeGroup(e){if(this.state.closed.peek())throw new Error("track is closed");if(e.sequence<(ni(this,at)??0)){e.close();return}ai(this,at,e.sequence+1),this.state.groups.mutate(s=>{s.push(e),s.sort((r,n)=>r.sequence-n.sequence)})}writeFrame(e){const s=this.appendGroup();s.writeFrame(e),s.close()}writeString(e){const s=this.appendGroup();s.writeString(e),s.close()}writeJson(e){const s=this.appendGroup();s.writeJson(e),s.close()}writeBool(e){const s=this.appendGroup();s.writeBool(e),s.close()}async nextGroup(){for(;;){const e=this.state.groups.peek();if(e.length>0)return e.shift();const s=this.state.closed.peek();if(s instanceof Error)throw s;if(s)return;await $.race(this.state.groups,this.state.closed)}}async readFrame(){var e;return(e=await this.readFrameSequence())==null?void 0:e.data}async readFrameSequence(){var e;for(;;){const s=this.state.groups.peek();for(;s.length>1;){const o=s[0].state.frames.peek(),h=o.shift();if(h){const v=s[0].state.total.peek()-o.length-1;return{group:s[0].sequence,frame:v,data:h}}(e=s.shift())==null||e.close()}if(s.length===0){const o=this.state.closed.peek();if(o instanceof Error)throw o;if(o)return;await $.race(this.state.groups,this.state.closed);continue}const r=s[0],n=r.state.frames.peek(),a=n.shift();if(a){const o=r.state.total.peek()-n.length-1;return{group:r.sequence,frame:o,data:a}}const i=this.state.closed.peek();if(i instanceof Error)throw i;if(i)return;await $.race(this.state.groups,this.state.closed,r.state.frames)}}async readString(){const e=await this.readFrame();if(e)return new TextDecoder().decode(e)}async readJson(){const e=await this.readString();if(e)return JSON.parse(e)}async readBool(){const e=await this.readFrame();if(e){if(e.byteLength!==1||!(e[0]===0||e[0]===1))throw new Error("invalid bool frame");return e[0]===1}}close(e){this.state.closed.set(e??!0);for(const s of this.state.groups.peek())s.close(e)}}at=new WeakMap;var yu=Object.defineProperty,vu=(t,e,s)=>e in t?yu(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,os=(t,e,s)=>vu(t,typeof e!="symbol"?e+"":e,s);let gu=class{constructor(){os(this,"requested",new $([])),os(this,"closed",new $(!1))}};class Ln{constructor(){os(this,"state",new gu),os(this,"closed"),this.closed=new Promise(e=>{const s=this.state.closed.subscribe(r=>{r&&(e(r instanceof Error?r:void 0),s())})})}async requested(){for(;;){const e=this.state.requested.peek().pop();if(e)return e;const s=this.state.closed.peek();if(s instanceof Error)throw s;if(s)return;await $.race(this.state.requested,this.state.closed)}}subscribe(e,s){const r=new Pi(e);if(this.state.closed.peek())throw new Error(`broadcast is closed: ${this.state.closed.peek()}`);return this.state.requested.mutate(n=>{n.push({track:r,priority:s}),n.sort((a,i)=>a.priority-i.priority)}),r}close(e){this.state.closed.set(e??!0);for(const{track:s}of this.state.requested.peek())s.close(e);this.state.requested.mutate(s=>{s.length=0})}}const Ve=class Ve{constructor(e){E(this,"value");if(e<0n||e>Ve.MAX)throw new Error(`VarInt value out of range: ${e}`);this.value=e}static from(e){return new Ve(BigInt(e))}size(){const e=this.value;if(e<2n**6n)return 1;if(e<2n**14n)return 2;if(e<2n**30n)return 4;if(e<2n**62n)return 8;throw new Error("VarInt value too large")}encode(e){const s=this.value,r=this.size();if(e.buffer.byteLength<e.byteLength+r)throw new Error("destination buffer too small");const n=new DataView(e.buffer,e.byteOffset+e.byteLength,r);if(r===1)n.setUint8(0,Number(s));else if(r===2)n.setUint16(0,16384|Number(s),!1);else if(r===4)n.setUint32(0,2<<30|Number(s),!1);else if(r===8)n.setBigUint64(0,3n<<62n|s,!1);else throw new Error("VarInt value too large");return new Uint8Array(e.buffer,e.byteOffset,e.byteLength+r)}static decode(e){if(e.byteLength<1)throw new Error("Unexpected end of buffer");const s=new DataView(e.buffer,e.byteOffset),r=s.getUint8(0),n=r>>6;let a,i;switch(n){case 0:a=BigInt(r&63),i=1;break;case 1:if(2>e.length)throw new Error("Unexpected end of buffer");a=BigInt(s.getUint16(0,!1)&16383),i=2;break;case 2:if(4>e.length)throw new Error("Unexpected end of buffer");a=BigInt(s.getUint32(0,!1)&1073741823),i=4;break;case 3:if(8>e.length)throw new Error("Unexpected end of buffer");a=s.getBigUint64(0,!1)&0x3fffffffffffffffn,i=8;break;default:throw new Error("Invalid VarInt tag")}const o=new Uint8Array(e.buffer,e.byteOffset+i,e.byteLength-i);return[new Ve(a),o]}};E(Ve,"MAX",(1n<<62n)-1n),E(Ve,"MAX_SIZE",8);let O=Ve;const pe={Bi:0,Uni:1};class Ze{constructor(e){E(this,"value");this.value=e}static create(e,s,r){let n=e<<2n;return s===pe.Uni&&(n|=0x02n),r&&(n|=0x01n),new Ze(O.from(n))}get dir(){return(this.value.value&0x02n)!==0n?pe.Uni:pe.Bi}get serverInitiated(){return(this.value.value&0x01n)!==0n}canRecv(e){return this.dir===pe.Uni?this.serverInitiated!==e:!0}canSend(e){return this.dir===pe.Uni?this.serverInitiated===e:!0}}const Ii=4,Ci=5,Ni=8,gr=9,qi=29;function ii(t){switch(t.type){case"stream":{let e=new Uint8Array(new ArrayBuffer(9+t.data.length),0,1);return e[0]=t.fin?gr:Ni,e=t.id.value.encode(e),e=new Uint8Array(e.buffer,e.byteOffset,e.byteLength+t.data.length),e.set(t.data,e.byteLength-t.data.length),e}case"reset_stream":{let e=new Uint8Array(new ArrayBuffer(17),0,1);return e[0]=Ii,e=t.id.value.encode(e),e=t.code.encode(e),e}case"stop_sending":{let e=new Uint8Array(new ArrayBuffer(17),0,1);return e[0]=Ci,e=t.id.value.encode(e),e=t.code.encode(e),e}case"connection_close":{const e=new TextEncoder().encode(t.reason);let s=new Uint8Array(new ArrayBuffer(9+e.length),0,1);return s[0]=qi,s=t.code.encode(s),s=new Uint8Array(s.buffer,s.byteOffset,s.byteLength+e.length),s.set(e,s.byteLength-e.length),s}}}function mu(t){if(t.length===0)throw new Error("Invalid frame: empty buffer");const e=t[0];t=t.slice(1);let s;if(e===Ii){[s,t]=O.decode(t);const r=new Ze(s);return[s,t]=O.decode(t),{type:"reset_stream",id:r,code:s}}if(e===Ci){[s,t]=O.decode(t);const r=new Ze(s);return[s,t]=O.decode(t),{type:"stop_sending",id:r,code:s}}if(e===qi){[s,t]=O.decode(t);const r=s,n=new TextDecoder().decode(t);return{type:"connection_close",code:r,reason:n}}if(e===Ni||e===gr)return[s,t]=O.decode(t),{type:"stream",id:new Ze(s),data:t,fin:e===gr};throw new Error(`Invalid frame type: ${e}`)}var x,ve,L,Xt,q,D,xs,Rs,Jt,Kt,vt,gt,Fs,Ai,u,Wi,Mi,Ti,Oi,Ui,xi,Ri,xe,de,rs;const Ls=class Ls{constructor(e,s){f(this,u);f(this,x);f(this,ve,!1);f(this,L);f(this,Xt);f(this,q,new Map);f(this,D,new Map);f(this,xs,0n);f(this,Rs,0n);E(this,"ready");f(this,Jt);E(this,"closed");f(this,Kt);E(this,"incomingBidirectionalStreams");f(this,vt);E(this,"incomingUnidirectionalStreams");f(this,gt);E(this,"datagrams",new Su);var r;if(s!=null&&s.requireUnreliable)throw new Error("not allowed to use WebSocket; requireUnreliable is true");s!=null&&s.serverCertificateHashes&&console.warn("serverCertificateHashes is not supported; trying anyway"),e=p(r=Ls,Fs,Ai).call(r,e),m(this,x,new WebSocket(e,["webtransport"])),this.ready=new Promise(n=>{m(this,Jt,n)}),this.closed=new Promise(n=>{m(this,Kt,n)}),c(this,x).binaryType="arraybuffer",c(this,x).onopen=()=>c(this,Jt).call(this),c(this,x).onmessage=n=>p(this,u,Wi).call(this,n),c(this,x).onerror=n=>p(this,u,Mi).call(this,n),c(this,x).onclose=n=>p(this,u,Ti).call(this,n),this.incomingBidirectionalStreams=new ReadableStream({start:n=>{m(this,vt,n)}}),this.incomingUnidirectionalStreams=new ReadableStream({start:n=>{m(this,gt,n)}})}async createBidirectionalStream(){if(await this.ready,c(this,L))throw c(this,Xt)||new Error("Connection closed");const e=Ze.create(br(this,Rs)._++,pe.Bi,c(this,ve)),s=new WritableStream({start:n=>{c(this,q).set(e.value.value,n)},write:async n=>{await Promise.race([p(this,u,xe).call(this,{type:"stream",id:e,data:n,fin:!1}),this.closed])},abort:n=>{console.warn("abort",n),p(this,u,de).call(this,{type:"reset_stream",id:e,code:O.from(0)}),c(this,q).delete(e.value.value)},close:async()=>{await Promise.race([p(this,u,xe).call(this,{type:"stream",id:e,data:new Uint8Array,fin:!0}),this.closed]),c(this,q).delete(e.value.value)}});return{readable:new ReadableStream({start:n=>{c(this,D).set(e.value.value,n)},cancel:async()=>{p(this,u,de).call(this,{type:"stop_sending",id:e,code:O.from(0)}),c(this,D).delete(e.value.value)}}),writable:s}}async createUnidirectionalStream(){if(await this.ready,c(this,L))throw c(this,L);const e=Ze.create(br(this,xs)._++,pe.Uni,c(this,ve)),s=this;return new WritableStream({start:n=>{c(s,q).set(e.value.value,n)},async write(n){var a;await Promise.race([p(a=s,u,xe).call(a,{type:"stream",id:e,data:n,fin:!1}),s.closed])},abort(n){var a;console.warn("abort",n),p(a=s,u,de).call(a,{type:"reset_stream",id:e,code:O.from(0)}),c(s,q).delete(e.value.value)},async close(){var n;await Promise.race([p(n=s,u,xe).call(n,{type:"stream",id:e,data:new Uint8Array,fin:!0}),s.closed]),c(s,q).delete(e.value.value)}})}close(e){if(c(this,L))return;const s=(e==null?void 0:e.closeCode)??0,r=(e==null?void 0:e.reason)??"";p(this,u,de).call(this,{type:"connection_close",code:O.from(s),reason:r}),setTimeout(()=>{c(this,x).close()},100),p(this,u,rs).call(this,s,r)}get congestionControl(){return"default"}};x=new WeakMap,ve=new WeakMap,L=new WeakMap,Xt=new WeakMap,q=new WeakMap,D=new WeakMap,xs=new WeakMap,Rs=new WeakMap,Jt=new WeakMap,Kt=new WeakMap,vt=new WeakMap,gt=new WeakMap,Fs=new WeakSet,Ai=function(e){const s=typeof e=="string"?new URL(e):e;let r=s.protocol;if(r==="https:")r="wss:";else if(r==="http:")r="ws:";else if(r!=="ws:"&&r!=="wss:")throw new Error(`Unsupported protocol: ${r}`);return`${r}//${s.host}${s.pathname}${s.search}`},u=new WeakSet,Wi=function(e){if(!(e.data instanceof ArrayBuffer))return;const s=new Uint8Array(e.data);try{const r=mu(s);p(this,u,Oi).call(this,r)}catch(r){console.error("Failed to decode frame:",r),this.close({closeCode:1002,reason:"Protocol violation"})}},Mi=function(e){c(this,L)||(m(this,L,new Error(`WebSocket error: ${e.type}`)),p(this,u,rs).call(this,1006,"WebSocket error"))},Ti=function(e){c(this,L)||(m(this,L,new Error(`Connection closed: ${e.code} ${e.reason}`)),p(this,u,rs).call(this,e.code,e.reason))},Oi=function(e){if(e.type==="stream")p(this,u,Ui).call(this,e);else if(e.type==="reset_stream")p(this,u,xi).call(this,e);else if(e.type==="stop_sending")p(this,u,Ri).call(this,e);else if(e.type==="connection_close")m(this,Xt,new Error(`Connection closed: ${e.code.value}: ${e.reason}`)),c(this,x).close();else{const s=e;throw new Error(`Unknown frame type: ${s}`)}},Ui=async function(e){const s=e.id.value.value;if(!e.id.canRecv(c(this,ve)))throw new Error("Invalid stream ID direction");let r=c(this,D).get(s);if(!r){if(e.id.serverInitiated===c(this,ve))return;if(!e.id.canRecv(c(this,ve)))throw new Error("received write-only stream");const n=new ReadableStream({start:a=>{r=a,c(this,D).set(s,a)},cancel:()=>{p(this,u,de).call(this,{type:"stop_sending",id:e.id,code:O.from(0)}),c(this,D).delete(s)}});if(e.id.dir===pe.Bi){const a=new WritableStream({start:i=>{c(this,q).set(s,i)},write:async i=>{await Promise.race([p(this,u,xe).call(this,{type:"stream",id:e.id,data:i,fin:!1}),this.closed])},abort:i=>{console.warn("abort",i),p(this,u,de).call(this,{type:"reset_stream",id:e.id,code:O.from(0)}),c(this,q).delete(s)},close:async()=>{await Promise.race([p(this,u,xe).call(this,{type:"stream",id:e.id,data:new Uint8Array,fin:!0}),this.closed]),c(this,q).delete(s)}});c(this,vt).enqueue({readable:n,writable:a})}else c(this,gt).enqueue(n)}e.data.byteLength>0&&(r==null||r.enqueue(e.data)),e.fin&&(r==null||r.close(),c(this,D).delete(s))},xi=function(e){const s=e.id.value.value,r=c(this,D).get(s);r&&(r.error(new Error(`RESET_STREAM: ${e.code.value}`)),c(this,D).delete(s))},Ri=function(e){const s=e.id.value.value,r=c(this,q).get(s);r&&(r.error(new Error(`STOP_SENDING: ${e.code.value}`)),c(this,q).delete(s),p(this,u,de).call(this,{type:"reset_stream",id:e.id,code:e.code}))},xe=async function(e){for(;c(this,x).bufferedAmount>64*1024;)await new Promise(r=>setTimeout(r,10));const s=ii(e);c(this,x).send(s)},de=function(e){const s=ii(e);c(this,x).send(s)},rs=function(e,s){c(this,Kt).call(this,{closeCode:e,reason:s});try{c(this,vt).close()}catch{}try{c(this,gt).close()}catch{}for(const r of c(this,q).values())try{r.error(c(this,L))}catch{}for(const r of c(this,D).values())try{r.error(c(this,L))}catch{}c(this,q).clear(),c(this,D).clear()},f(Ls,Fs);let hs=Ls;class Su{constructor(){E(this,"incomingHighWaterMark");E(this,"incomingMaxAge");E(this,"maxDatagramSize");E(this,"outgoingHighWaterMark");E(this,"outgoingMaxAge");E(this,"readable");E(this,"writable");this.incomingHighWaterMark=1024,this.incomingMaxAge=null,this.maxDatagramSize=1200,this.outgoingHighWaterMark=1024,this.outgoingMaxAge=null,this.readable=new ReadableStream({}),this.writable=new WritableStream({})}}var ku=Object.defineProperty,Fi=t=>{throw TypeError(t)},$u=(t,e,s)=>e in t?ku(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ci=(t,e,s)=>$u(t,typeof e!="symbol"?e+"":e,s),Dn=(t,e,s)=>e.has(t)||Fi("Cannot "+s),d=(t,e,s)=>(Dn(t,e,"read from private field"),s?s.call(t):e.get(t)),ge=(t,e,s)=>e.has(t)?Fi("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),j=(t,e,s,r)=>(Dn(t,e,"write to private field"),e.set(t,s),s),P=(t,e,s)=>(Dn(t,e,"access private method"),s),S,ns,He,k,us,le,ne,Re,as,ae,At;const Li=2**6-1,Di=2**14-1,Bi=2**30-1,Eu=2**31-1,Bn=Number.MAX_SAFE_INTEGER,oi=1024*1024*64;let Ds=class mr{constructor(e){ci(this,"reader"),ci(this,"writer"),this.writer=new Zt(e.writable),this.reader=new Bs(e.readable)}static async accept(e){for(;;){const s=e.incomingBidirectionalStreams.getReader(),r=await s.read();return s.releaseLock(),r.done?void 0:new mr(r.value)}}static async open(e,s){return new mr(await e.createBidirectionalStream({sendOrder:s}))}close(){this.writer.close(),this.reader.stop(new Error("cancel"))}abort(e){this.writer.reset(e),this.reader.stop(e)}};class Bs{constructor(e,s){var r;ge(this,k),ge(this,S),ge(this,ns),ge(this,He),j(this,S,s??new Uint8Array),j(this,ns,e),j(this,He,(r=d(this,ns))==null?void 0:r.getReader())}async read(e){return e===0?new Uint8Array:(await P(this,k,le).call(this,e),P(this,k,ne).call(this,e))}async readAll(){for(;await P(this,k,us).call(this););return P(this,k,ne).call(this,d(this,S).byteLength)}async string(){const e=await this.u53(),s=await this.read(e);return new TextDecoder().decode(s)}async bool(){const e=await this.u8();if(e===0)return!1;if(e===1)return!0;throw new Error("invalid bool value")}async u8(){return await P(this,k,le).call(this,1),P(this,k,ne).call(this,1)[0]}async u16(){await P(this,k,le).call(this,2);const s=new DataView(d(this,S).buffer,d(this,S).byteOffset,2).getUint16(0);return P(this,k,ne).call(this,2),s}async u53(){const e=await this.u62();if(e>Bn)throw new Error("value larger than 53-bits; use v62 instead");return Number(e)}async u62(){await P(this,k,le).call(this,1);const e=(d(this,S)[0]&192)>>6;if(e===0){const n=P(this,k,ne).call(this,1)[0];return BigInt(n)&0x3fn}if(e===1){await P(this,k,le).call(this,2);const n=P(this,k,ne).call(this,2),a=new DataView(n.buffer,n.byteOffset,n.byteLength);return BigInt(a.getUint16(0))&0x3fffn}if(e===2){await P(this,k,le).call(this,4);const n=P(this,k,ne).call(this,4),a=new DataView(n.buffer,n.byteOffset,n.byteLength);return BigInt(a.getUint32(0))&0x3fffffffn}await P(this,k,le).call(this,8);const s=P(this,k,ne).call(this,8);return new DataView(s.buffer,s.byteOffset,s.byteLength).getBigUint64(0)&0x3fffffffffffffffn}async done(){return d(this,S).byteLength>0?!1:!await P(this,k,us).call(this)}stop(e){var s;(s=d(this,He))==null||s.cancel(e).catch(()=>{})}get closed(){var e;return((e=d(this,He))==null?void 0:e.closed)??Promise.resolve()}}S=new WeakMap;ns=new WeakMap;He=new WeakMap;k=new WeakSet;us=async function(){if(!d(this,He))return!1;const t=await d(this,He).read();if(t.done)return!1;if(t.value.byteLength===0)throw new Error("unexpected empty chunk");const e=new Uint8Array(t.value);if(d(this,S).byteLength===0)j(this,S,e);else{const s=new Uint8Array(d(this,S).byteLength+e.byteLength);s.set(d(this,S)),s.set(e,d(this,S).byteLength),j(this,S,s)}return!0};le=async function(t){if(t>oi)throw new Error(`read size ${t} exceeds max size ${oi}`);for(;d(this,S).byteLength<t;)if(!await P(this,k,us).call(this))throw new Error("unexpected end of stream")};ne=function(t){const e=new Uint8Array(d(this,S).buffer,d(this,S).byteOffset,t);return j(this,S,new Uint8Array(d(this,S).buffer,d(this,S).byteOffset+t,d(this,S).byteLength-t)),e};const Pu=class Gi{constructor(e){ge(this,Re),ge(this,as),ge(this,ae),j(this,as,e),j(this,ae,new ArrayBuffer(8)),j(this,Re,d(this,as).getWriter())}async bool(e){await this.write(ds(d(this,ae),e?1:0))}async u8(e){await this.write(ds(d(this,ae),e))}async u16(e){await this.write(Gn(d(this,ae),e))}async i32(e){if(Math.abs(e)>Eu)throw new Error(`overflow, value larger than 32-bits: ${e.toString()}`);await this.write(Iu(d(this,ae),e))}async u53(e){if(e<0)throw new Error(`underflow, value is negative: ${e.toString()}`);if(e>Bn)throw new Error(`overflow, value larger than 53-bits: ${e.toString()}`);await this.write(Cu(d(this,ae),e))}async u62(e){if(e<0)throw new Error(`underflow, value is negative: ${e.toString()}`);await this.write(Nu(d(this,ae),e))}async write(e){await d(this,Re).write(e)}async string(e){const s=new TextEncoder().encode(e);await this.u53(s.byteLength),await this.write(s)}close(){d(this,Re).close().catch(()=>{})}get closed(){return d(this,Re).closed}reset(e){d(this,Re).abort(e).catch(()=>{})}static async open(e){const s=await e.createUnidirectionalStream();return new Gi(s)}};Re=new WeakMap;as=new WeakMap;ae=new WeakMap;let Zt=Pu;function ds(t,e){const s=new Uint8Array(t,0,1);return s[0]=e,s}function Gn(t,e){const s=new DataView(t,0,2);return s.setUint16(0,e),new Uint8Array(s.buffer,s.byteOffset,s.byteLength)}function Iu(t,e){const s=new DataView(t,0,4);return s.setInt32(0,e),new Uint8Array(s.buffer,s.byteOffset,s.byteLength)}function Vi(t,e){const s=new DataView(t,0,4);return s.setUint32(0,e),new Uint8Array(s.buffer,s.byteOffset,s.byteLength)}function Cu(t,e){if(e<=Li)return ds(t,e);if(e<=Di)return Gn(t,e|16384);if(e<=Bi)return Vi(t,e|2147483648);if(e<=Bn)return Hi(t,BigInt(e)|0xc000000000000000n);throw new Error(`overflow, value larger than 53-bits: ${e.toString()}`)}function Nu(t,e){return e<Li?ds(t,Number(e)):e<Di?Gn(t,Number(e)|16384):e<=Bi?Vi(t,Number(e)|2147483648):Hi(t,BigInt(e)|0xc000000000000000n)}function Hi(t,e){const s=new DataView(t,0,8);return s.setBigUint64(0,e),new Uint8Array(s.buffer,s.byteOffset,s.byteLength)}class zi{constructor(e){ge(this,At),j(this,At,e.incomingUnidirectionalStreams.getReader())}async next(){const e=await d(this,At).read();if(!e.done)return new Bs(e.value)}close(){d(this,At).cancel()}}At=new WeakMap;function z(t){return t instanceof Error?t:new Error(String(t))}function qu(t){throw new Error(`unreachable: ${t}`)}const Au=new Error("request for lock canceled");var Wu=function(t,e,s,r){function n(a){return a instanceof s?a:new s(function(i){i(a)})}return new(s||(s=Promise))(function(a,i){function o(w){try{v(r.next(w))}catch(M){i(M)}}function h(w){try{v(r.throw(w))}catch(M){i(M)}}function v(w){w.done?a(w.value):n(w.value).then(o,h)}v((r=r.apply(t,e||[])).next())})};class Mu{constructor(e,s=Au){this._value=e,this._cancelError=s,this._queue=[],this._weightedWaiters=[]}acquire(e=1,s=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return new Promise((r,n)=>{const a={resolve:r,reject:n,weight:e,priority:s},i=Xi(this._queue,o=>s<=o.priority);i===-1&&e<=this._value?this._dispatchItem(a):this._queue.splice(i+1,0,a)})}runExclusive(e){return Wu(this,arguments,void 0,function*(s,r=1,n=0){const[a,i]=yield this.acquire(r,n);try{return yield s(a)}finally{i()}})}waitForUnlock(e=1,s=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,s)?Promise.resolve():new Promise(r=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),Tu(this._weightedWaiters[e-1],{resolve:r,priority:s})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatchQueue()}release(e=1){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);this._value+=e,this._dispatchQueue()}cancel(){this._queue.forEach(e=>e.reject(this._cancelError)),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(e){const s=this._value;this._value-=e.weight,e.resolve([s,this._newReleaser(e.weight)])}_newReleaser(e){let s=!1;return()=>{s||(s=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){const s=this._weightedWaiters[e-1];s&&(s.forEach(r=>r.resolve()),this._weightedWaiters[e-1]=[])}else{const e=this._queue[0].priority;for(let s=this._value;s>0;s--){const r=this._weightedWaiters[s-1];if(!r)continue;const n=r.findIndex(a=>a.priority<=e);(n===-1?r:r.splice(0,n)).forEach(a=>a.resolve())}}}_couldLockImmediately(e,s){return(this._queue.length===0||this._queue[0].priority<s)&&e<=this._value}}function Tu(t,e){const s=Xi(t,r=>e.priority<=r.priority);t.splice(s+1,0,e)}function Xi(t,e){for(let s=t.length-1;s>=0;s--)if(e(t[s]))return s;return-1}var Ou=function(t,e,s,r){function n(a){return a instanceof s?a:new s(function(i){i(a)})}return new(s||(s=Promise))(function(a,i){function o(w){try{v(r.next(w))}catch(M){i(M)}}function h(w){try{v(r.throw(w))}catch(M){i(M)}}function v(w){w.done?a(w.value):n(w.value).then(o,h)}v((r=r.apply(t,e||[])).next())})};class hi{constructor(e){this._semaphore=new Mu(1,e)}acquire(){return Ou(this,arguments,void 0,function*(e=0){const[,s]=yield this._semaphore.acquire(1,e);return s})}runExclusive(e,s=0){return this._semaphore.runExclusive(()=>e(),1,s)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(e=0){return this._semaphore.waitForUnlock(1,e)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}}async function b(t,e){let s=new Uint8Array;const r=new Zt(new WritableStream({write(n){const a=s.byteLength+n.byteLength;if(a>s.buffer.byteLength){const i=Math.max(a,s.buffer.byteLength*2),o=new ArrayBuffer(i),h=new Uint8Array(o,0,a);h.set(s),h.set(n,s.byteLength),s=h}else s=new Uint8Array(s.buffer,0,a),s.set(n,a-n.byteLength)}}));try{await e(r)}finally{r.close()}if(await r.closed,s.byteLength>65535)throw new Error(`Message too large: ${s.byteLength} bytes (max 65535)`);await t.u16(s.byteLength),await t.write(s)}async function y(t,e){const s=await t.u16(),r=await t.read(s),n=new Bs(void 0,r),a=await e(n);if(!await n.done())throw new Error("Message decoding consumed too few bytes");return a}var Uu=Object.defineProperty,Ji=t=>{throw TypeError(t)},xu=(t,e,s)=>e in t?Uu(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,I=(t,e,s)=>xu(t,typeof e!="symbol"?e+"":e,s),Ru=(t,e,s)=>e.has(t)||Ji("Cannot "+s),Ne=(t,e,s)=>e.has(t)?Ji("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),Ee=(t,e,s)=>(Ru(t,e,"access private method"),s),Sr,Ki,Vn,Qi,kr,Zi,Hn,Yi,$r,ji,zn,ec,Er,tc,Xn,sc;const Jn=class rc{constructor(e,s,r,n,a,i,o,h,v){Ne(this,Sr),I(this,"requestId"),I(this,"trackNamespace"),I(this,"trackName"),I(this,"subscriberPriority"),I(this,"groupOrder"),I(this,"startGroup"),I(this,"startObject"),I(this,"endGroup"),I(this,"endObject"),this.requestId=e,this.trackNamespace=s,this.trackName=r,this.subscriberPriority=n,this.groupOrder=a,this.startGroup=i,this.startObject=o,this.endGroup=h,this.endObject=v}async encode(e){return b(e,Ee(this,Sr,Ki).bind(this))}static async decode(e){return y(e,Ee(rc,Vn,Qi))}};Sr=new WeakSet;Ki=async function(t){throw new Error("FETCH messages are not supported")};Vn=new WeakSet;Qi=async function(t){throw new Error("FETCH messages are not supported")};Ne(Jn,Vn);I(Jn,"id",22);let Pr=Jn;const Kn=class nc{constructor(e){Ne(this,kr),I(this,"requestId"),this.requestId=e}async encode(e){return b(e,Ee(this,kr,Zi).bind(this))}static async decode(e){return y(e,Ee(nc,Hn,Yi))}};kr=new WeakSet;Zi=async function(t){throw new Error("FETCH_OK messages are not supported")};Hn=new WeakSet;Yi=async function(t){throw new Error("FETCH_OK messages are not supported")};Ne(Kn,Hn);I(Kn,"id",24);let Ir=Kn;const Qn=class ac{constructor(e,s,r){Ne(this,$r),I(this,"requestId"),I(this,"errorCode"),I(this,"reasonPhrase"),this.requestId=e,this.errorCode=s,this.reasonPhrase=r}async encode(e){return b(e,Ee(this,$r,ji).bind(this))}static async decode(e){return y(e,Ee(ac,zn,ec))}};$r=new WeakSet;ji=async function(t){throw new Error("FETCH_ERROR messages are not supported")};zn=new WeakSet;ec=async function(t){throw new Error("FETCH_ERROR messages are not supported")};Ne(Qn,zn);I(Qn,"id",25);let Cr=Qn;const Zn=class ic{constructor(e){Ne(this,Er),I(this,"requestId"),this.requestId=e}async encode(e){return b(e,Ee(this,Er,tc).bind(this))}static async decode(e){return y(e,Ee(ic,Xn,sc))}};Er=new WeakSet;tc=async function(t){throw new Error("FETCH_CANCEL messages are not supported")};Xn=new WeakSet;sc=async function(t){throw new Error("FETCH_CANCEL messages are not supported")};Ne(Zn,Xn);I(Zn,"id",23);let Nr=Zn;var Fu=Object.defineProperty,cc=t=>{throw TypeError(t)},Lu=(t,e,s)=>e in t?Fu(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,oc=(t,e,s)=>Lu(t,typeof e!="symbol"?e+"":e,s),Du=(t,e,s)=>e.has(t)||cc("Cannot "+s),hc=(t,e,s)=>e.has(t)?cc("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),ui=(t,e,s)=>(Du(t,e,"access private method"),s),qr,uc,Yn,dc;const Gs=class lc{constructor(e){hc(this,qr),oc(this,"newSessionUri"),this.newSessionUri=e}async encode(e){return b(e,ui(this,qr,uc).bind(this))}static async decode(e){return y(e,ui(lc,Yn,dc))}};qr=new WeakSet;uc=async function(t){await t.string(this.newSessionUri)};Yn=new WeakSet;dc=async function(t){const e=await t.string();return new Gs(e)};hc(Gs,Yn);oc(Gs,"id",16);let Ar=Gs;async function qe(t,e){const s=e.split("/");await t.u53(s.length);for(const r of s)await t.string(r)}async function Ae(t){const e=[],s=await t.u53();for(let r=0;r<s;r++)e.push(await t.string());return Y(...e)}var Bu=Object.defineProperty,Gu=(t,e,s)=>e in t?Bu(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,di=(t,e,s)=>Gu(t,typeof e!="symbol"?e+"":e,s);const yr={MaxRequestId:2n,Implementation:7n};class X{constructor(){di(this,"vars"),di(this,"bytes"),this.vars=new Map,this.bytes=new Map}get size(){return this.vars.size+this.bytes.size}setBytes(e,s){if(e%2n!==1n)throw new Error(`invalid parameter id: ${e.toString()}, must be odd`);this.bytes.set(e,s)}setVarint(e,s){if(e%2n!==0n)throw new Error(`invalid parameter id: ${e.toString()}, must be even`);this.vars.set(e,s)}getBytes(e){if(e%2n!==1n)throw new Error(`invalid parameter id: ${e.toString()}, must be odd`);return this.bytes.get(e)}getVarint(e){if(e%2n!==0n)throw new Error(`invalid parameter id: ${e.toString()}, must be even`);return this.vars.get(e)}removeBytes(e){if(e%2n!==1n)throw new Error(`invalid parameter id: ${e.toString()}, must be odd`);return this.bytes.delete(e)}removeVarint(e){if(e%2n!==0n)throw new Error(`invalid parameter id: ${e.toString()}, must be even`);return this.vars.delete(e)}async encode(e){await e.u53(this.vars.size+this.bytes.size);for(const[s,r]of this.vars)await e.u62(s),await e.u62(r);for(const[s,r]of this.bytes)await e.u62(s),await e.u53(r.length),await e.write(r)}static async decode(e){const s=await e.u53(),r=new X;for(let n=0;n<s;n++){const a=await e.u62();if(a%2n===0n){if(r.vars.has(a))throw new Error(`duplicate parameter id: ${a.toString()}`);const i=await e.u62();r.setVarint(a,i)}else{if(r.bytes.has(a))throw new Error(`duplicate parameter id: ${a.toString()}`);const i=await e.u53(),o=await e.read(i);r.setBytes(a,o)}}return r}}var Vu=Object.defineProperty,fc=t=>{throw TypeError(t)},Hu=(t,e,s)=>e in t?Vu(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,C=(t,e,s)=>Hu(t,typeof e!="symbol"?e+"":e,s),zu=(t,e,s)=>e.has(t)||fc("Cannot "+s),We=(t,e,s)=>e.has(t)?fc("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),Pe=(t,e,s)=>(zu(t,e,"access private method"),s),Wr,wc,jn,pc,Mr,_c,ea,bc,Tr,yc,ta,vc,Or,gc,sa,mc;const Vs=class Sc{constructor(e,s,r,n,a,i,o,h){We(this,Wr),C(this,"requestId"),C(this,"trackNamespace"),C(this,"trackName"),C(this,"trackAlias"),C(this,"groupOrder"),C(this,"contentExists"),C(this,"largest"),C(this,"forward"),this.requestId=e,this.trackNamespace=s,this.trackName=r,this.trackAlias=n,this.groupOrder=a,this.contentExists=i,this.largest=o,this.forward=h}async encode(e){return b(e,Pe(this,Wr,wc).bind(this))}static async decode(e){return y(e,Pe(Sc,jn,pc))}};Wr=new WeakSet;wc=async function(t){if(await t.u62(this.requestId),await qe(t,this.trackNamespace),await t.string(this.trackName),await t.u62(this.trackAlias),await t.u8(this.groupOrder),await t.bool(this.contentExists),this.contentExists!==!!this.largest)throw new Error("contentExists and largest must both be true or false");this.largest&&(await t.u62(this.largest.groupId),await t.u62(this.largest.objectId)),await t.bool(this.forward),await t.u53(0)};jn=new WeakSet;pc=async function(t){const e=await t.u62(),s=await Ae(t),r=await t.string(),n=await t.u62(),a=await t.u8(),i=await t.bool(),o=i?{groupId:await t.u62(),objectId:await t.u62()}:void 0,h=await t.bool();return await X.decode(t),new Vs(e,s,r,n,a,i,o,h)};We(Vs,jn);C(Vs,"id",29);let Ur=Vs;const ra=class kc{constructor(){We(this,Mr)}async encode(e){return b(e,Pe(this,Mr,_c).bind(this))}static async decode(e){return y(e,Pe(kc,ea,bc))}};Mr=new WeakSet;_c=async function(t){throw new Error("PUBLISH_OK messages are not supported")};ea=new WeakSet;bc=async function(t){throw new Error("PUBLISH_OK messages are not supported")};We(ra,ea);C(ra,"id",30);let xr=ra;const Hs=class $c{constructor(e,s,r){We(this,Tr),C(this,"requestId"),C(this,"errorCode"),C(this,"reasonPhrase"),this.requestId=e,this.errorCode=s,this.reasonPhrase=r}async encode(e){return b(e,Pe(this,Tr,yc).bind(this))}static async decode(e){return y(e,Pe($c,ta,vc))}};Tr=new WeakSet;yc=async function(t){await t.u62(this.requestId),await t.u62(BigInt(this.errorCode)),await t.string(this.reasonPhrase)};ta=new WeakSet;vc=async function(t){const e=await t.u62(),s=Number(await t.u62()),r=await t.string();return new Hs(e,s,r)};We(Hs,ta);C(Hs,"id",31);let ls=Hs;const zs=class Ec{constructor(e,s,r){We(this,Or),C(this,"requestId"),C(this,"statusCode"),C(this,"reasonPhrase"),this.requestId=e,this.statusCode=s,this.reasonPhrase=r}async encode(e){return b(e,Pe(this,Or,gc).bind(this))}static async decode(e){return y(e,Pe(Ec,sa,mc))}};Or=new WeakSet;gc=async function(t){await t.u62(this.requestId),await t.u62(BigInt(this.statusCode)),await t.u62(BigInt(0)),await t.string(this.reasonPhrase)};sa=new WeakSet;mc=async function(t){const e=await t.u62(),s=Number(await t.u62());await t.u62();const r=await t.string();return new zs(e,s,r)};We(zs,sa);C(zs,"id",11);let Dt=zs;var Xu=Object.defineProperty,Pc=t=>{throw TypeError(t)},Ju=(t,e,s)=>e in t?Xu(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,U=(t,e,s)=>Ju(t,typeof e!="symbol"?e+"":e,s),Ku=(t,e,s)=>e.has(t)||Pc("Cannot "+s),se=(t,e,s)=>e.has(t)?Pc("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),te=(t,e,s)=>(Ku(t,e,"access private method"),s),Rr,Ic,na,Cc,Fr,Nc,aa,qc,Lr,Ac,ia,Wc,Dr,Mc,ca,Tc,Br,Oc,oa,Uc;const Xs=class xc{constructor(e,s){se(this,Rr),U(this,"requestId"),U(this,"trackNamespace"),this.requestId=e,this.trackNamespace=s}async encode(e){return b(e,te(this,Rr,Ic).bind(this))}static async decode(e){return y(e,te(xc,na,Cc))}};Rr=new WeakSet;Ic=async function(t){await t.u62(this.requestId),await qe(t,this.trackNamespace),await t.u53(0)};na=new WeakSet;Cc=async function(t){const e=await t.u62(),s=await Ae(t);return await X.decode(t),new Xs(e,s)};se(Xs,na);U(Xs,"id",6);let fs=Xs;const Js=class Rc{constructor(e){se(this,Fr),U(this,"requestId"),this.requestId=e}async encode(e){return b(e,te(this,Fr,Nc).bind(this))}static async decode(e){return y(e,te(Rc,aa,qc))}};Fr=new WeakSet;Nc=async function(t){await t.u62(this.requestId)};aa=new WeakSet;qc=async function(t){const e=await t.u62();return new Js(e)};se(Js,aa);U(Js,"id",7);let Gr=Js;const Ks=class Fc{constructor(e,s,r){se(this,Lr),U(this,"requestId"),U(this,"errorCode"),U(this,"reasonPhrase"),this.requestId=e,this.errorCode=s,this.reasonPhrase=r}async encode(e){return b(e,te(this,Lr,Ac).bind(this))}static async decode(e){return y(e,te(Fc,ia,Wc))}};Lr=new WeakSet;Ac=async function(t){await t.u62(this.requestId),await t.u62(BigInt(this.errorCode)),await t.string(this.reasonPhrase)};ia=new WeakSet;Wc=async function(t){const e=await t.u62(),s=Number(await t.u62()),r=await t.string();return new Ks(e,s,r)};se(Ks,ia);U(Ks,"id",8);let Vr=Ks;const Qs=class Lc{constructor(e,s=0,r=""){se(this,Dr),U(this,"trackNamespace"),U(this,"errorCode"),U(this,"reasonPhrase"),this.trackNamespace=e,this.errorCode=s,this.reasonPhrase=r}async encode(e){return b(e,te(this,Dr,Mc).bind(this))}static async decode(e){return y(e,te(Lc,ca,Tc))}};Dr=new WeakSet;Mc=async function(t){await qe(t,this.trackNamespace),await t.u62(BigInt(this.errorCode)),await t.string(this.reasonPhrase)};ca=new WeakSet;Tc=async function(t){const e=await Ae(t),s=Number(await t.u62()),r=await t.string();return new Qs(e,s,r)};se(Qs,ca);U(Qs,"id",12);let Hr=Qs;const Zs=class Dc{constructor(e){se(this,Br),U(this,"trackNamespace"),this.trackNamespace=e}async encode(e){return b(e,te(this,Br,Oc).bind(this))}static async decode(e){return y(e,te(Dc,oa,Uc))}};Br=new WeakSet;Oc=async function(t){await qe(t,this.trackNamespace)};oa=new WeakSet;Uc=async function(t){const e=await Ae(t);return new Zs(e)};se(Zs,oa);U(Zs,"id",9);let ws=Zs;var Qu=Object.defineProperty,Bc=t=>{throw TypeError(t)},Zu=(t,e,s)=>e in t?Qu(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ys=(t,e,s)=>Zu(t,typeof e!="symbol"?e+"":e,s),Yu=(t,e,s)=>e.has(t)||Bc("Cannot "+s),js=(t,e,s)=>e.has(t)?Bc("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),ps=(t,e,s)=>(Yu(t,e,"access private method"),s),zr,Gc,ha,Vc,Xr,Hc,ua,zc;const er=class Xc{constructor(e){js(this,zr),Ys(this,"requestId"),this.requestId=e}async encode(e){return b(e,ps(this,zr,Gc).bind(this))}static async decode(e){return y(e,ps(Xc,ha,Vc))}};zr=new WeakSet;Gc=async function(t){await t.u62(this.requestId)};ha=new WeakSet;Vc=async function(t){return new er(await t.u62())};js(er,ha);Ys(er,"id",21);let Jr=er;const tr=class Jc{constructor(e){js(this,Xr),Ys(this,"requestId"),this.requestId=e}async encode(e){return b(e,ps(this,Xr,Hc).bind(this))}static async decode(e){return y(e,ps(Jc,ua,zc))}};Xr=new WeakSet;Hc=async function(t){await t.u62(this.requestId)};ua=new WeakSet;zc=async function(t){return new tr(await t.u62())};js(tr,ua);Ys(tr,"id",26);let Kr=tr;var ju=Object.defineProperty,Kc=t=>{throw TypeError(t)},ed=(t,e,s)=>e in t?ju(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,mt=(t,e,s)=>ed(t,typeof e!="symbol"?e+"":e,s),td=(t,e,s)=>e.has(t)||Kc("Cannot "+s),sr=(t,e,s)=>e.has(t)?Kc("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),_s=(t,e,s)=>(td(t,e,"access private method"),s),Qr,Qc,da,Zc,Zr,Yc,la,jc;const sd=128,rr=class eo{constructor(e,s=new X){sr(this,Qr),mt(this,"versions"),mt(this,"parameters"),this.versions=e,this.parameters=s}async encode(e){return b(e,_s(this,Qr,Qc).bind(this))}static async decode(e){return y(e,_s(eo,da,Zc))}};Qr=new WeakSet;Qc=async function(t){await t.u53(this.versions.length);for(const e of this.versions)await t.u53(e);await this.parameters.encode(t)};da=new WeakSet;Zc=async function(t){const e=await t.u53();if(e>sd)throw new Error(`too many versions: ${e}`);const s=[];for(let n=0;n<e;n++){const a=await t.u53();s.push(a)}const r=await X.decode(t);return new rr(s,r)};sr(rr,da);mt(rr,"id",32);let bs=rr;const nr=class to{constructor(e,s=new X){sr(this,Zr),mt(this,"version"),mt(this,"parameters"),this.version=e,this.parameters=s}async encode(e){return b(e,_s(this,Zr,Yc).bind(this))}static async decode(e){return y(e,_s(to,la,jc))}};Zr=new WeakSet;Yc=async function(t){await t.u53(this.version),await this.parameters.encode(t)};la=new WeakSet;jc=async function(t){const e=await t.u53(),s=await X.decode(t);return new nr(e,s)};sr(nr,la);mt(nr,"id",33);let ys=nr;var rd=Object.defineProperty,so=t=>{throw TypeError(t)},nd=(t,e,s)=>e in t?rd(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,R=(t,e,s)=>nd(t,typeof e!="symbol"?e+"":e,s),ad=(t,e,s)=>e.has(t)||so("Cannot "+s),Me=(t,e,s)=>e.has(t)?so("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),Ie=(t,e,s)=>(ad(t,e,"access private method"),s),Yr,ro,fa,no,jr,ao,wa,io,en,co,pa,oo,tn,ho,_a,uo;const lo=2,ar=class fo{constructor(e,s,r,n){Me(this,Yr),R(this,"requestId"),R(this,"trackNamespace"),R(this,"trackName"),R(this,"subscriberPriority"),this.requestId=e,this.trackNamespace=s,this.trackName=r,this.subscriberPriority=n}async encode(e){return b(e,Ie(this,Yr,ro).bind(this))}static async decode(e){return y(e,Ie(fo,fa,no))}};Yr=new WeakSet;ro=async function(t){await t.u62(this.requestId),await qe(t,this.trackNamespace),await t.string(this.trackName),await t.u8(this.subscriberPriority),await t.u8(lo),await t.bool(!0),await t.u53(2),await t.u53(0)};fa=new WeakSet;no=async function(t){const e=await t.u62(),s=await Ae(t),r=await t.string(),n=await t.u8(),a=await t.u8();if(a>2)throw new Error(`unknown group order: ${a}`);const i=await t.bool();if(!i)throw new Error(`unsupported forward value: ${i}`);const o=await t.u53();if(o!==1&&o!==2)throw new Error(`unsupported filter type: ${o}`);return await X.decode(t),new ar(e,s,r,n)};Me(ar,fa);R(ar,"id",3);let vs=ar;const ir=class wo{constructor(e,s){Me(this,jr),R(this,"requestId"),R(this,"trackAlias"),this.requestId=e,this.trackAlias=s}async encode(e){return b(e,Ie(this,jr,ao).bind(this))}static async decode(e){return y(e,Ie(wo,wa,io))}};jr=new WeakSet;ao=async function(t){await t.u62(this.requestId),await t.u62(this.trackAlias),await t.u62(0n),await t.u8(lo),await t.bool(!1),await t.u53(0)};wa=new WeakSet;io=async function(t){const e=await t.u62(),s=await t.u62(),r=await t.u62();if(r!==BigInt(0))throw new Error(`unsupported expires: ${r}`);return await t.u8(),await t.bool()&&(await t.u62(),await t.u62()),await X.decode(t),new ir(e,s)};Me(ir,wa);R(ir,"id",4);let gs=ir;const cr=class po{constructor(e,s,r){Me(this,en),R(this,"requestId"),R(this,"errorCode"),R(this,"reasonPhrase"),this.requestId=e,this.errorCode=s,this.reasonPhrase=r}async encode(e){return b(e,Ie(this,en,co).bind(this))}static async decode(e){return y(e,Ie(po,pa,oo))}};en=new WeakSet;co=async function(t){await t.u62(this.requestId),await t.u62(BigInt(this.errorCode)),await t.string(this.reasonPhrase)};pa=new WeakSet;oo=async function(t){const e=await t.u62(),s=Number(await t.u62()),r=await t.string();return new cr(e,s,r)};Me(cr,pa);R(cr,"id",5);let ms=cr;const or=class _o{constructor(e){Me(this,tn),R(this,"requestId"),this.requestId=e}async encode(e){return b(e,Ie(this,tn,ho).bind(this))}static async decode(e){return y(e,Ie(_o,_a,uo))}};tn=new WeakSet;ho=async function(t){await t.u62(this.requestId)};_a=new WeakSet;uo=async function(t){const e=await t.u62();return new or(e)};Me(or,_a);R(or,"id",10);let Ss=or;var id=Object.defineProperty,bo=t=>{throw TypeError(t)},cd=(t,e,s)=>e in t?id(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Z=(t,e,s)=>cd(t,typeof e!="symbol"?e+"":e,s),od=(t,e,s)=>e.has(t)||bo("Cannot "+s),Te=(t,e,s)=>e.has(t)?bo("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),Ce=(t,e,s)=>(od(t,e,"access private method"),s),sn,yo,ba,vo,rn,go,ya,mo,nn,So,va,ko,an,$o,ga,Eo;const hr=class Po{constructor(e,s){Te(this,sn),Z(this,"namespace"),Z(this,"requestId"),this.namespace=e,this.requestId=s}async encode(e){return b(e,Ce(this,sn,yo).bind(this))}static async decode(e){return y(e,Ce(Po,ba,vo))}};sn=new WeakSet;yo=async function(t){await t.u62(this.requestId),await qe(t,this.namespace),await t.u53(0)};ba=new WeakSet;vo=async function(t){const e=await t.u62(),s=await Ae(t);return await X.decode(t),new hr(s,e)};Te(hr,ba);Z(hr,"id",17);let ks=hr;const ur=class Io{constructor(e){Te(this,rn),Z(this,"requestId"),this.requestId=e}async encode(e){return b(e,Ce(this,rn,go).bind(this))}static async decode(e){return y(e,Ce(Io,ya,mo))}};rn=new WeakSet;go=async function(t){await t.u62(this.requestId)};ya=new WeakSet;mo=async function(t){const e=await t.u62();return new ur(e)};Te(ur,ya);Z(ur,"id",18);let cn=ur;const dr=class Co{constructor(e,s,r){Te(this,nn),Z(this,"requestId"),Z(this,"errorCode"),Z(this,"reasonPhrase"),this.requestId=e,this.errorCode=s,this.reasonPhrase=r}async encode(e){return b(e,Ce(this,nn,So).bind(this))}static async decode(e){return y(e,Ce(Co,va,ko))}};nn=new WeakSet;So=async function(t){await t.u62(this.requestId),await t.u62(BigInt(this.errorCode)),await t.string(this.reasonPhrase)};va=new WeakSet;ko=async function(t){const e=await t.u62(),s=Number(await t.u62()),r=await t.string();return new dr(e,s,r)};Te(dr,va);Z(dr,"id",19);let on=dr;const lr=class No{constructor(e){Te(this,an),Z(this,"requestId"),this.requestId=e}async encode(e){return b(e,Ce(this,an,$o).bind(this))}static async decode(e){return y(e,Ce(No,ga,Eo))}};an=new WeakSet;$o=async function(t){await t.u62(this.requestId)};ga=new WeakSet;Eo=async function(t){const e=await t.u62();return new lr(e)};Te(lr,ga);Z(lr,"id",20);let $s=lr;var hd=Object.defineProperty,qo=t=>{throw TypeError(t)},ud=(t,e,s)=>e in t?hd(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,B=(t,e,s)=>ud(t,typeof e!="symbol"?e+"":e,s),dd=(t,e,s)=>e.has(t)||qo("Cannot "+s),fr=(t,e,s)=>e.has(t)?qo("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),Es=(t,e,s)=>(dd(t,e,"access private method"),s),hn,Ao,ma,Wo,un,Mo,Sa,To;const wr=class Oo{constructor(e,s){fr(this,hn),B(this,"trackNamespace"),B(this,"trackName"),this.trackNamespace=e,this.trackName=s}async encode(e){return b(e,Es(this,hn,Ao).bind(this))}static async decode(e){return y(e,Es(Oo,ma,Wo))}};hn=new WeakSet;Ao=async function(t){await qe(t,this.trackNamespace),await t.string(this.trackName)};ma=new WeakSet;Wo=async function(t){const e=await Ae(t),s=await t.string();return new wr(e,s)};fr(wr,ma);B(wr,"id",13);let dn=wr;const Oe=class Uo{constructor(e,s,r,n,a){fr(this,un),B(this,"trackNamespace"),B(this,"trackName"),B(this,"statusCode"),B(this,"lastGroupId"),B(this,"lastObjectId"),this.trackNamespace=e,this.trackName=s,this.statusCode=r,this.lastGroupId=n,this.lastObjectId=a}async encode(e){return b(e,Es(this,un,Mo).bind(this))}static async decode(e){return y(e,Es(Uo,Sa,To))}};un=new WeakSet;Mo=async function(t){await qe(t,this.trackNamespace),await t.string(this.trackName),await t.u62(BigInt(this.statusCode)),await t.u62(this.lastGroupId),await t.u62(this.lastObjectId)};Sa=new WeakSet;To=async function(t){const e=await Ae(t),s=await t.string(),r=Number(await t.u62()),n=await t.u62(),a=await t.u62();return new Oe(e,s,r,n,a)};fr(Oe,Sa);B(Oe,"id",14);B(Oe,"STATUS_IN_PROGRESS",0);B(Oe,"STATUS_NOT_FOUND",1);B(Oe,"STATUS_NOT_AUTHORIZED",2);B(Oe,"STATUS_ENDED",3);let Bt=Oe;var ld=Object.defineProperty,xo=t=>{throw TypeError(t)},fd=(t,e,s)=>e in t?ld(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,wd=(t,e,s)=>fd(t,e+"",s),Ro=(t,e,s)=>e.has(t)||xo("Cannot "+s),K=(t,e,s)=>(Ro(t,e,"read from private field"),s?s.call(t):e.get(t)),rt=(t,e,s)=>e.has(t)?xo("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),ue=(t,e,s,r)=>(Ro(t,e,"write to private field"),e.set(t,s),s),Wt,Fe,Le,it,ln,fn;const li={[bs.id]:bs,[ys.id]:ys,[vs.id]:vs,[gs.id]:gs,[ms.id]:ms,[fs.id]:fs,[Gr.id]:Gr,[Vr.id]:Vr,[ws.id]:ws,[Ss.id]:Ss,[Dt.id]:Dt,[Hr.id]:Hr,[dn.id]:dn,[Bt.id]:Bt,[Ar.id]:Ar,[Pr.id]:Pr,[Nr.id]:Nr,[Ir.id]:Ir,[Cr.id]:Cr,[ks.id]:ks,[cn.id]:cn,[on.id]:on,[$s.id]:$s,[Ur.id]:Ur,[xr.id]:xr,[ls.id]:ls,[Jr.id]:Jr,[Kr.id]:Kr};class pd{constructor(e,s){wd(this,"stream"),rt(this,Wt,0n),rt(this,Fe),rt(this,Le),rt(this,it),rt(this,ln,new hi),rt(this,fn,new hi),this.stream=e,ue(this,Fe,s),ue(this,Le,new Promise(r=>{ue(this,it,r)}))}async write(e){console.debug("message write",e),await K(this,ln).runExclusive(async()=>{await this.stream.writer.u53(e.constructor.id),await e.encode(this.stream.writer)})}async read(){return await K(this,fn).runExclusive(async()=>{const e=await this.stream.reader.u53();if(!(e in li))throw new Error(`Unknown control message type: ${e}`);try{const s=await li[e].decode(this.stream.reader);return console.debug("message read",s),s}catch(s){throw console.error("failed to decode message",e,s),s}})}maxRequestId(e){if(e<=K(this,Fe))throw new Error(`max request id must be greater than current max request id: max=${e} current=${K(this,Fe)}`);ue(this,Fe,e),K(this,it).call(this),ue(this,Le,new Promise(s=>{ue(this,it,s)}))}async nextRequestId(){for(;;){const e=K(this,Wt);if(e<K(this,Fe))return ue(this,Wt,K(this,Wt)+2n),e;if(!K(this,Le))return;await K(this,Le)}}close(){K(this,it).call(this),ue(this,Le,void 0)}}Wt=new WeakMap;Fe=new WeakMap;Le=new WeakMap;it=new WeakMap;ln=new WeakMap;fn=new WeakMap;var _d=Object.defineProperty,bd=(t,e,s)=>e in t?_d(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ct=(t,e,s)=>bd(t,typeof e!="symbol"?e+"":e,s);const fi=3;let Fo=class Lo{constructor(e,s,r,n,a){ct(this,"flags"),ct(this,"trackAlias"),ct(this,"groupId"),ct(this,"subGroupId"),ct(this,"publisherPriority"),this.flags=a,this.trackAlias=e,this.groupId=s,this.subGroupId=r,this.publisherPriority=n}async encode(e){if(!this.flags.hasSubgroup&&this.subGroupId!==0)throw new Error(`Subgroup ID must be 0 if hasSubgroup is false: ${this.subGroupId}`);let s=16;this.flags.hasExtensions&&(s|=1),this.flags.hasSubgroupObject&&(s|=2),this.flags.hasSubgroup&&(s|=4),this.flags.hasEnd&&(s|=8),await e.u53(s),await e.u62(this.trackAlias),await e.u53(this.groupId),this.flags.hasSubgroup&&await e.u53(this.subGroupId),await e.u8(0)}static async decode(e){const s=await e.u53();if(s<16||s>31)throw new Error(`Unsupported group type: ${s}`);const r={hasExtensions:(s&1)!==0,hasSubgroupObject:(s&2)!==0,hasSubgroup:(s&4)!==0,hasEnd:(s&8)!==0},n=await e.u62(),a=await e.u53(),i=r.hasSubgroup?await e.u53():0,o=await e.u8();return new Lo(n,a,i,o,r)}};class dt{constructor(e){ct(this,"payload"),this.payload=e}async encode(e,s){await e.u53(0),s.hasExtensions&&await e.u53(0),this.payload!==void 0?(await e.u53(this.payload.byteLength),this.payload.byteLength===0?await e.u53(0):await e.write(this.payload)):(await e.u53(0),await e.u53(fi))}static async decode(e,s){const r=await e.u53();if(r!==0&&console.warn(`object ID delta is not supported, ignoring: ${r}`),s.hasExtensions){const i=await e.u53();await e.read(i)}const n=await e.u53();if(n>0){const i=await e.read(n);return new dt(i)}const a=await e.u53();if(s.hasEnd){if(a===0)return new dt(new Uint8Array(0))}else if(a===0||a===fi)return new dt;throw new Error(`Unsupported object status: ${a}`)}}var Do=t=>{throw TypeError(t)},ka=(t,e,s)=>e.has(t)||Do("Cannot "+s),H=(t,e,s)=>(ka(t,e,"read from private field"),s?s.call(t):e.get(t)),jt=(t,e,s)=>e.has(t)?Do("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),wi=(t,e,s,r)=>(ka(t,e,"write to private field"),e.set(t,s),s),wn=(t,e,s)=>(ka(t,e,"access private method"),s),Ps,Q,Ut,xt,Bo,Go,Vo;let yd=class{constructor(e,s){jt(this,xt),jt(this,Ps),jt(this,Q),jt(this,Ut,new Map),wi(this,Ps,e),wi(this,Q,s)}publish(e,s){H(this,Ut).set(e,s),wn(this,xt,Bo).call(this,e,s)}async handleSubscribe(e){const s=e.trackNamespace,r=H(this,Ut).get(s);if(!r){const i=new ms(e.requestId,404,"Broadcast not found");await H(this,Q).write(i);return}const n=r.subscribe(e.trackName,e.subscriberPriority),a=new gs(e.requestId,e.requestId);await H(this,Q).write(a),wn(this,xt,Go).call(this,e.requestId,n)}async handleTrackStatusRequest(e){const s=new Bt(e.trackNamespace,e.trackName,Bt.STATUS_NOT_FOUND,0n,0n);await H(this,Q).write(s)}async handleUnsubscribe(e){}async handlePublishNamespaceOk(e){}async handlePublishNamespaceError(e){}async handlePublishNamespaceCancel(e){}async handleSubscribeNamespace(e){}async handleUnsubscribeNamespace(e){}};Ps=new WeakMap;Q=new WeakMap;Ut=new WeakMap;xt=new WeakSet;Bo=async function(t,e){try{const s=await H(this,Q).nextRequestId();if(s===void 0)return;const r=new fs(s,t);await H(this,Q).write(r),await e.closed;const n=new ws(t);await H(this,Q).write(n)}catch(s){const r=z(s);console.warn(`announce failed: broadcast=${t} error=${r.message}`)}finally{e.close(),H(this,Ut).delete(t)}};Go=async function(t,e){try{for(;;){const r=await e.nextGroup();if(!r)break;wn(this,xt,Vo).call(this,t,r)}const s=new Dt(t,200,"OK");await H(this,Q).write(s)}catch(s){const r=z(s),n=new Dt(t,500,r.message);await H(this,Q).write(n)}finally{e.close()}};Vo=async function(t,e){try{const s=await Zt.open(H(this,Ps)),r=new Fo(t,e.sequence,0,0,{hasExtensions:!1,hasSubgroup:!1,hasSubgroupObject:!1,hasEnd:!0});console.debug("sending group header",r),await r.encode(s);try{for(;;){const n=await Promise.race([e.readFrame(),s.closed]);if(!n)break;await new dt(n).encode(s,r.flags)}s.close()}catch(n){s.reset(z(n))}}finally{e.close()}};var Ho=t=>{throw TypeError(t)},$a=(t,e,s)=>e.has(t)||Ho("Cannot "+s),_=(t,e,s)=>($a(t,e,"read from private field"),s?s.call(t):e.get(t)),Ue=(t,e,s)=>e.has(t)?Ho("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),vd=(t,e,s,r)=>($a(t,e,"write to private field"),e.set(t,s),s),pi=(t,e,s)=>($a(t,e,"access private method"),s),ee,De,ot,Gt,lt,ze,is,zo,Xo;let gd=class{constructor(e){Ue(this,is),Ue(this,ee),Ue(this,De,new Set),Ue(this,ot,new Set),Ue(this,Gt,new Map),Ue(this,lt,new Map),Ue(this,ze,new Map),vd(this,ee,e)}announced(e=Qt()){const s=new ki(e);for(const r of _(this,De))r.startsWith(e)&&s.append({path:r,active:!0});return _(this,ot).add(s),pi(this,is,zo).call(this,s,e).finally(()=>{_(this,ot).delete(s)}),s}consume(e){const s=new Ln;return(async()=>{for(;;){const r=await s.requested();if(!r)break;pi(this,is,Xo).call(this,e,r)}})(),s}async handleSubscribeOk(e){const s=_(this,ze).get(e.requestId);s?s.resolve(e):console.warn("handleSubscribeOk unknown requestId",e.requestId)}async handleSubscribeError(e){const s=_(this,ze).get(e.requestId);s?s.reject(new Error(`SUBSCRIBE_ERROR: code=${e.errorCode} reason=${e.reasonPhrase}`)):console.warn("handleSubscribeError unknown requestId",e.requestId)}async handleGroup(e,s){const r=new Fn(e.groupId);e.subGroupId!==0&&console.warn("subgroup ID is not supported, ignoring");try{let n=_(this,lt).get(e.trackAlias);n===void 0&&(n=e.trackAlias,console.warn("unknown track alias, using request ID"));const a=_(this,Gt).get(n);if(!a)throw new Error(`unknown track: trackAlias=${e.trackAlias} requestId=${_(this,lt).get(e.trackAlias)}`);for(a.writeGroup(r);await Promise.race([s.done(),r.closed,a.closed])===!1;){const o=await dt.decode(s,e.flags);if(o.payload===void 0)break;r.writeFrame(o.payload)}r.close()}catch(n){const a=z(n);r.close(a),s.stop(a)}}async handlePublish(e){const s=new ls(e.requestId,500,"publish not supported");await _(this,ee).write(s)}async handlePublishDone(e){const s=_(this,ze).get(e.requestId);s&&s.reject(new Error(`PUBLISH_DONE: code=${e.statusCode} reason=${e.reasonPhrase}`))}async handlePublishNamespace(e){if(_(this,De).has(e.trackNamespace)){console.warn("duplicate PUBLISH_NAMESPACE message");return}_(this,De).add(e.trackNamespace);for(const s of _(this,ot))s.append({path:e.trackNamespace,active:!0})}async handlePublishNamespaceDone(e){if(!_(this,De).has(e.trackNamespace)){console.warn("unknown PUBLISH_NAMESPACE_DONE message");return}_(this,De).delete(e.trackNamespace);for(const s of _(this,ot))s.append({path:e.trackNamespace,active:!1})}async handleSubscribeNamespaceOk(e){}async handleSubscribeNamespaceError(e){throw new Error("SUBSCRIBE_NAMESPACE_ERROR messages are not supported")}async handleTrackStatus(e){throw new Error("TRACK_STATUS messages are not supported")}};ee=new WeakMap;De=new WeakMap;ot=new WeakMap;Gt=new WeakMap;lt=new WeakMap;ze=new WeakMap;is=new WeakSet;zo=async function(t,e){const s=await _(this,ee).nextRequestId();if(s!==void 0)try{_(this,ee).write(new ks(e,s)),await t.closed}finally{_(this,ee).write(new $s(s))}};Xo=async function(t,e){const s=await _(this,ee).nextRequestId();if(s===void 0)return;_(this,Gt).set(s,e.track);const r=new vs(s,t,e.track.name,e.priority),n=new Promise((a,i)=>{_(this,ze).set(s,{resolve:a,reject:i})});await _(this,ee).write(r);try{const a=await n;_(this,lt).set(a.trackAlias,s);try{await e.track.closed;const i=new Ss(s);await _(this,ee).write(i)}finally{_(this,lt).delete(a.trackAlias)}}catch(a){const i=z(a);e.track.close(i)}finally{_(this,Gt).delete(s),_(this,ze).delete(s)}};var md=Object.defineProperty,Jo=t=>{throw TypeError(t)},Sd=(t,e,s)=>e in t?md(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,kd=(t,e,s)=>Sd(t,e+"",s),Ea=(t,e,s)=>e.has(t)||Jo("Cannot "+s),l=(t,e,s)=>(Ea(t,e,"read from private field"),s?s.call(t):e.get(t)),Nt=(t,e,s)=>e.has(t)?Jo("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),es=(t,e,s,r)=>(Ea(t,e,"write to private field"),e.set(t,s),s),Ye=(t,e,s)=>(Ea(t,e,"access private method"),s),we,_e,V,T,he,Ko,Qo,Zo,Yo,jo,eh,th;let $d=class{constructor(e,s,r,n){Nt(this,he),kd(this,"url"),Nt(this,we),Nt(this,_e),Nt(this,V),Nt(this,T),this.url=e,es(this,we,s),es(this,_e,new pd(r,n)),l(this,we).closed.finally(()=>{l(this,_e).close()}),es(this,V,new yd(l(this,we),l(this,_e))),es(this,T,new gd(l(this,_e))),Ye(this,he,Ko).call(this)}close(){try{l(this,we).close()}catch{}}publish(e,s){l(this,V).publish(e,s)}announced(e=Qt()){return l(this,T).announced(e)}consume(e){return l(this,T).consume(e)}get closed(){return l(this,we).closed.then(()=>{})}};we=new WeakMap;_e=new WeakMap;V=new WeakMap;T=new WeakMap;he=new WeakSet;Ko=async function(){const t=Ye(this,he,Qo).call(this),e=Ye(this,he,eh).call(this);try{await Promise.all([t,e])}catch(s){console.error("fatal error running connection",s)}finally{this.close()}};Qo=async function(){for(;;)try{const t=await l(this,_e).read();if(t instanceof vs)await l(this,V).handleSubscribe(t);else if(t instanceof Ss)await l(this,V).handleUnsubscribe(t);else if(t instanceof dn)await l(this,V).handleTrackStatusRequest(t);else if(t instanceof Gr)await l(this,V).handlePublishNamespaceOk(t);else if(t instanceof Vr)await l(this,V).handlePublishNamespaceError(t);else if(t instanceof Hr)await l(this,V).handlePublishNamespaceCancel(t);else if(t instanceof fs)await l(this,T).handlePublishNamespace(t);else if(t instanceof ws)await l(this,T).handlePublishNamespaceDone(t);else if(t instanceof gs)await l(this,T).handleSubscribeOk(t);else if(t instanceof ms)await l(this,T).handleSubscribeError(t);else if(t instanceof Dt)await l(this,T).handlePublishDone(t);else if(t instanceof Bt)await l(this,T).handleTrackStatus(t);else if(t instanceof Ar)await Ye(this,he,Zo).call(this,t);else if(t instanceof bs)await Ye(this,he,Yo).call(this,t);else if(t instanceof ys)await Ye(this,he,jo).call(this,t);else if(t instanceof ks)await l(this,V).handleSubscribeNamespace(t);else if(t instanceof cn)await l(this,T).handleSubscribeNamespaceOk(t);else if(t instanceof on)await l(this,T).handleSubscribeNamespaceError(t);else if(t instanceof $s)await l(this,V).handleUnsubscribeNamespace(t);else if(t instanceof Ur)await l(this,T).handlePublish(t);else{if(t instanceof xr)throw new Error("PUBLISH_OK messages are not supported");if(t instanceof ls)throw new Error("PUBLISH_ERROR messages are not supported");if(t instanceof Pr)throw new Error("FETCH messages are not supported");if(t instanceof Ir)throw new Error("FETCH_OK messages are not supported");if(t instanceof Cr)throw new Error("FETCH_ERROR messages are not supported");if(t instanceof Nr)throw new Error("FETCH_CANCEL messages are not supported");t instanceof Jr?l(this,_e).maxRequestId(t.requestId):t instanceof Kr?console.warn("ignoring REQUESTS_BLOCKED message"):qu(t)}}catch(t){console.error("error processing control message",t);break}console.warn("control stream closed")};Zo=async function(t){console.warn(`MOQLITE_INCOMPATIBLE: Received GOAWAY with redirect URI: ${t.newSessionUri}`),this.close()};Yo=async function(t){console.error("Unexpected CLIENT_SETUP message received after connection established"),this.close()};jo=async function(t){console.error("Unexpected SERVER_SETUP message received after connection established"),this.close()};eh=async function(){const t=new zi(l(this,we));for(;;){const e=await t.next();if(!e)break;Ye(this,he,th).call(this,e).then(()=>{e.stop(new Error("cancel"))}).catch(s=>{e.stop(s)})}};th=async function(t){try{const e=await Fo.decode(t);console.debug("received group header",e),await l(this,T).handleGroup(e,t)}catch(e){console.error("error processing object stream",e)}};const Ed={DRAFT_14:4278190094},_i=Ed.DRAFT_14;async function J(t,e){let s=new Uint8Array;const r=new Zt(new WritableStream({write(n){const a=s.byteLength+n.byteLength;if(a>s.buffer.byteLength){const i=Math.max(a,s.buffer.byteLength*2),o=new ArrayBuffer(i),h=new Uint8Array(o,0,a);h.set(s),h.set(n,s.byteLength),s=h}else s=new Uint8Array(s.buffer,0,a),s.set(n,a-n.byteLength)}}));await e(r),r.close(),await r.closed,await t.u53(s.byteLength),await t.write(s)}async function G(t,e){const s=await t.u53(),r=await t.read(s),n=new Bs(void 0,r),a=await e(n);if(!await n.done())throw new Error("Message decoding consumed too few bytes");return a}async function Yt(t,e){if(!await t.done())return await G(t,e)}var Pd=Object.defineProperty,sh=t=>{throw TypeError(t)},Id=(t,e,s)=>e in t?Pd(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Is=(t,e,s)=>Id(t,typeof e!="symbol"?e+"":e,s),Cd=(t,e,s)=>e.has(t)||sh("Cannot "+s),kt=(t,e,s)=>e.has(t)?sh("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),je=(t,e,s)=>(Cd(t,e,"access private method"),s),pn,rh,Cs,_n,bn,nh,Pa,ah,yn,ih,Ia,ch;const Ca=class vn{constructor(e,s){kt(this,pn),Is(this,"suffix"),Is(this,"active"),this.suffix=e,this.active=s}async encode(e){return J(e,je(this,pn,rh).bind(this))}static async decode(e){return G(e,je(vn,Cs,_n))}static async decodeMaybe(e){return Yt(e,je(vn,Cs,_n))}};pn=new WeakSet;rh=async function(t){await t.bool(this.active),await t.string(this.suffix)};Cs=new WeakSet;_n=async function(t){const e=await t.bool(),s=Y(await t.string());return new Ca(s,e)};kt(Ca,Cs);let gn=Ca;const Na=class oh{constructor(e){kt(this,bn),Is(this,"prefix"),this.prefix=e}async encode(e){return J(e,je(this,bn,nh).bind(this))}static async decode(e){return G(e,je(oh,Pa,ah))}};bn=new WeakSet;nh=async function(t){await t.string(this.prefix)};Pa=new WeakSet;ah=async function(t){const e=Y(await t.string());return new Na(e)};kt(Na,Pa);let hh=Na;const qa=class uh{constructor(e){kt(this,yn),Is(this,"suffixes"),this.suffixes=e}async encode(e){return J(e,je(this,yn,ih).bind(this))}static async decode(e){return G(e,je(uh,Ia,ch))}};yn=new WeakSet;ih=async function(t){await t.u53(this.suffixes.length);for(const e of this.suffixes)await t.string(e)};Ia=new WeakSet;ch=async function(t){const e=await t.u53(),s=[];for(let r=0;r<e;r++)s.push(Y(await t.string()));return new qa(s)};kt(qa,Ia);let dh=qa;var Nd=Object.defineProperty,lh=t=>{throw TypeError(t)},qd=(t,e,s)=>e in t?Nd(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ft=(t,e,s)=>qd(t,typeof e!="symbol"?e+"":e,s),Ad=(t,e,s)=>e.has(t)||lh("Cannot "+s),$t=(t,e,s)=>e.has(t)?lh("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),Se=(t,e,s)=>(Ad(t,e,"access private method"),s),mn,fh,Ns,Sn,kn,wh,qs,$n,En,ph,Aa,_h;const Wa=class Pn{constructor(e,s){$t(this,mn),ft(this,"subscribe"),ft(this,"sequence"),this.subscribe=e,this.sequence=s}async encode(e){return J(e,Se(this,mn,fh).bind(this))}static async decode(e){return G(e,Se(Pn,Ns,Sn))}static async decodeMaybe(e){return Yt(e,Se(Pn,Ns,Sn))}};mn=new WeakSet;fh=async function(t){await t.u62(this.subscribe),await t.u53(this.sequence)};Ns=new WeakSet;Sn=async function(t){return new Wa(await t.u62(),await t.u53())};$t(Wa,Ns);let bh=Wa;const yh=class In{constructor(e,s,r){$t(this,kn),ft(this,"sequence"),ft(this,"count"),ft(this,"error"),this.sequence=e,this.count=s,this.error=r}async encode(e){return J(e,Se(this,kn,wh).bind(this))}static async decode(e){return G(e,Se(In,qs,$n))}static async decodeMaybe(e){return Yt(e,Se(In,qs,$n))}};kn=new WeakSet;wh=async function(t){await t.u53(this.sequence),await t.u53(this.count),await t.u53(this.error)};qs=new WeakSet;$n=async function(t){return new yh(await t.u53(),await t.u53(),await t.u53())};$t(yh,qs);const vh=class gh{constructor(e){$t(this,En),ft(this,"payload"),this.payload=e}async encode(e){return J(e,Se(this,En,ph).bind(this))}static async decode(e){return G(e,Se(gh,Aa,_h))}};En=new WeakSet;ph=async function(t){await t.write(this.payload)};Aa=new WeakSet;_h=async function(t){const e=await t.readAll();return new vh(e)};$t(vh,Aa);var Wd=Object.defineProperty,mh=t=>{throw TypeError(t)},Md=(t,e,s)=>e in t?Wd(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ht=(t,e,s)=>Md(t,typeof e!="symbol"?e+"":e,s),Td=(t,e,s)=>e.has(t)||mh("Cannot "+s),Et=(t,e,s)=>e.has(t)?mh("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),et=(t,e,s)=>(Td(t,e,"access private method"),s),Cn,Sh,As,Nn,qn,kh,Ma,$h,An,Eh,Ta,Ph;const Oa=class Wn{constructor(e){Et(this,Cn),ht(this,"priority"),this.priority=e}async encode(e){return J(e,et(this,Cn,Sh).bind(this))}static async decode(e){return G(e,et(Wn,As,Nn))}static async decodeMaybe(e){return Yt(e,et(Wn,As,Nn))}};Cn=new WeakSet;Sh=async function(t){await t.u8(this.priority)};As=new WeakSet;Nn=async function(t){const e=await t.u8();return new Oa(e)};Et(Oa,As);let bi=Oa;const Ua=class Ih{constructor(e,s,r,n){Et(this,qn),ht(this,"id"),ht(this,"broadcast"),ht(this,"track"),ht(this,"priority"),this.id=e,this.broadcast=s,this.track=r,this.priority=n}async encode(e){return J(e,et(this,qn,kh).bind(this))}static async decode(e){return G(e,et(Ih,Ma,$h))}};qn=new WeakSet;kh=async function(t){await t.u62(this.id),await t.string(this.broadcast),await t.string(this.track),await t.u8(this.priority)};Ma=new WeakSet;$h=async function(t){const e=await t.u62(),s=Y(await t.string()),r=await t.string(),n=await t.u8();return new Ua(e,s,r,n)};Et(Ua,Ma);let Ch=Ua;const xa=class Nh{constructor(e){Et(this,An),ht(this,"priority"),this.priority=e}async encode(e){return J(e,et(this,An,Eh).bind(this))}static async decode(e){return G(e,et(Nh,Ta,Ph))}};An=new WeakSet;Eh=async function(t){await t.u8(this.priority)};Ta=new WeakSet;Ph=async function(t){const e=await t.u8();return new xa(e)};Et(xa,Ta);let qh=xa;var Ah=t=>{throw TypeError(t)},Ra=(t,e,s)=>e.has(t)||Ah("Cannot "+s),Be=(t,e,s)=>(Ra(t,e,"read from private field"),s?s.call(t):e.get(t)),vr=(t,e,s)=>e.has(t)?Ah("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),Od=(t,e,s,r)=>(Ra(t,e,"write to private field"),e.set(t,s),s),Wh=(t,e,s)=>(Ra(t,e,"access private method"),s),Ws,fe,Ms,Mh,Th;class Ud{constructor(e){vr(this,Ms),vr(this,Ws),vr(this,fe,new $(new Map)),Od(this,Ws,e)}publish(e,s){Be(this,fe).mutate(r=>{if(!r)throw new Error("closed");r.set(e,s)}),s.closed.finally(()=>{Be(this,fe).mutate(r=>{r==null||r.delete(e)})})}async runAnnounce(e,s){console.debug(`announce: prefix=${e.prefix}`);let r=new Set;const n=Be(this,fe).peek();if(!n)return;for(const i of n.keys()){const o=si(e.prefix,i);o!==null&&(console.debug(`announce: broadcast=${i} active=true`),r.add(o))}for(await new dh(r.values().toArray()).encode(s.writer);;){let i;const o=new Promise(w=>{i=Be(this,fe).changed(w)}),h=await Promise.race([o,s.reader.closed]);if(i(),!h)break;const v=new Set;for(const w of h.keys()){const M=si(e.prefix,w);M!==null&&v.add(M)}for(const w of v.difference(r))console.debug(`announce: broadcast=${w} active=true`),await new gn(w,!0).encode(s.writer);for(const w of r.difference(v))console.debug(`announce: broadcast=${w} active=false`),await new gn(w,!1).encode(s.writer);r=v}}async runSubscribe(e,s){var a;const r=(a=Be(this,fe).peek())==null?void 0:a.get(e.broadcast);if(!r){console.debug(`publish unknown: broadcast=${e.broadcast}`),s.writer.reset(new Error("not found"));return}const n=r.subscribe(e.track,e.priority);try{await new qh(e.priority).encode(s.writer),console.debug(`publish ok: broadcast=${e.broadcast} track=${n.name}`);const o=Wh(this,Ms,Mh).call(this,e.id,e.broadcast,n,s.writer);for(;;){const h=bi.decodeMaybe(s.reader),v=await Promise.any([o,h]);if(!v)break;v instanceof bi&&console.warn("subscribe update not supported",v)}console.debug(`publish done: broadcast=${e.broadcast} track=${n.name}`),s.close(),n.close()}catch(i){const o=z(i);console.warn(`publish error: broadcast=${e.broadcast} track=${n.name} error=${o.message}`),n.close(o),s.abort(o)}}close(){Be(this,fe).update(e=>{for(const s of(e==null?void 0:e.values())??[])s.close()})}}Ws=new WeakMap;fe=new WeakMap;Ms=new WeakSet;Mh=async function(t,e,s,r){try{for(;;){const n=s.nextGroup(),a=await Promise.race([n,r.closed]);if(!a){n.then(i=>i==null?void 0:i.close()).catch(()=>{});break}Wh(this,Ms,Th).call(this,t,a)}console.debug(`publish close: broadcast=${e} track=${s.name}`),s.close(),r.close()}catch(n){const a=z(n);console.warn(`publish error: broadcast=${e} track=${s.name} error=${a.message}`),s.close(a),r.reset(a)}};Th=async function(t,e){const s=new bh(t,e.sequence);try{const r=await Zt.open(Be(this,Ws));await r.u8(0),await s.encode(r);try{for(;;){const n=await Promise.race([e.readFrame(),r.closed]);if(!n)break;await r.u53(n.byteLength),await r.write(n)}r.close(),e.close()}catch(n){const a=z(n);r.reset(a),e.close(a)}}catch(r){const n=z(r);e.close(n)}};var xd=Object.defineProperty,Oh=t=>{throw TypeError(t)},Rd=(t,e,s)=>e in t?xd(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,St=(t,e,s)=>Rd(t,typeof e!="symbol"?e+"":e,s),Fd=(t,e,s)=>e.has(t)||Oh("Cannot "+s),Pt=(t,e,s)=>e.has(t)?Oh("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),tt=(t,e,s)=>(Fd(t,e,"access private method"),s),Mn,Uh,Fa,xh,Tn,Rh,La,Fh,On,Lh,Ts,Un;const Ld={LITE_01:4279086337},yi=Ld.LITE_01;class It{constructor(){St(this,"entries"),this.entries=new Map}set(e,s){this.entries.set(e,s)}get(e){return this.entries.get(e)}remove(e){const s=this.entries.get(e);return this.entries.delete(e),s}async encode(e){await e.u53(this.entries.size);for(const[s,r]of this.entries)await e.u62(s),await e.u53(r.length),await e.write(r)}static async decode(e){const s=await e.u53(),r=new It;for(let n=0;n<s;n++){const a=await e.u62(),i=await e.u53(),o=await e.read(i);if(r.entries.has(a))throw new Error(`duplicate parameter id: ${a.toString()}`);r.entries.set(a,o)}return r}}const Dh=class Bh{constructor(e,s=new It){Pt(this,Mn),St(this,"versions"),St(this,"extensions"),this.versions=e,this.extensions=s}async encode(e){return J(e,tt(this,Mn,Uh).bind(this))}static async decode(e){return G(e,tt(Bh,Fa,xh))}};Mn=new WeakSet;Uh=async function(t){await t.u53(this.versions.length);for(const e of this.versions)await t.u53(e);await this.extensions.encode(t)};Fa=new WeakSet;xh=async function(t){const e=[],s=await t.u53();for(let n=0;n<s;n++)e.push(await t.u53());const r=await It.decode(t);return new Dh(e,r)};Pt(Dh,Fa);const Gh=class Vh{constructor(e,s=new It){Pt(this,Tn),St(this,"version"),St(this,"extensions"),this.version=e,this.extensions=s}async encode(e){return J(e,tt(this,Tn,Rh).bind(this))}static async decode(e){return G(e,tt(Vh,La,Fh))}};Tn=new WeakSet;Rh=async function(t){await t.u53(this.version),await this.extensions.encode(t)};La=new WeakSet;Fh=async function(t){const e=await t.u53(),s=await It.decode(t);return new Gh(e,s)};Pt(Gh,La);const Da=class xn{constructor(e){Pt(this,On),St(this,"bitrate"),this.bitrate=e}async encode(e){return J(e,tt(this,On,Lh).bind(this))}static async decode(e){return G(e,tt(xn,Ts,Un))}static async decodeMaybe(e){return Yt(e,tt(xn,Ts,Un))}};On=new WeakSet;Lh=async function(t){await t.u53(this.bitrate)};Ts=new WeakSet;Un=async function(t){const e=await t.u53();return new Da(e)};Pt(Da,Ts);let Dd=Da;const st={Session:0,Announce:1,Subscribe:2,ClientCompat:32,ServerCompat:33};var Hh=t=>{throw TypeError(t)},Ba=(t,e,s)=>e.has(t)||Hh("Cannot "+s),oe=(t,e,s)=>(Ba(t,e,"read from private field"),s?s.call(t):e.get(t)),ts=(t,e,s)=>e.has(t)?Hh("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),zh=(t,e,s,r)=>(Ba(t,e,"write to private field"),e.set(t,s),s),vi=(t,e,s)=>(Ba(t,e,"access private method"),s),Bd=(t,e,s,r)=>({set _(n){zh(t,e,n)},get _(){return oe(t,e,r)}}),Vt,Xe,Os,cs,Xh,Jh;class Gd{constructor(e){ts(this,cs),ts(this,Vt),ts(this,Xe,new Map),ts(this,Os,0n),zh(this,Vt,e)}announced(e=Qt()){const s=new ki;return vi(this,cs,Xh).call(this,s,e),s}consume(e){const s=new Ln;return(async()=>{for(;;){const r=await s.requested();if(!r)break;vi(this,cs,Jh).call(this,e,r)}})(),s}async runGroup(e,s){const r=oe(this,Xe).get(e.subscribe);if(!r){if(e.subscribe>=oe(this,Os))throw new Error(`unknown subscription: id=${e.subscribe}`);return}const n=new Fn(e.sequence);r.writeGroup(n);try{for(;await Promise.race([s.done(),r.closed,n.closed])===!1;){const i=await s.u53(),o=await s.read(i);if(!o)break;n.writeFrame(o)}n.close(),s.stop(new Error("cancel"))}catch(a){const i=z(a);n.close(i),s.stop(i)}}close(){for(const e of oe(this,Xe).values())e.close();oe(this,Xe).clear()}}Vt=new WeakMap;Xe=new WeakMap;Os=new WeakMap;cs=new WeakSet;Xh=async function(t,e){console.debug(`announced: prefix=${e}`);const s=new hh(e);try{const r=await Ds.open(oe(this,Vt));await r.writer.u53(st.Announce),await s.encode(r.writer);const n=await dh.decode(r.reader);for(const a of n.suffixes){const i=ri(e,a);console.debug(`announced: broadcast=${i} active=true`),t.append({path:i,active:!0})}for(;;){const a=await Promise.race([gn.decodeMaybe(r.reader),t.closed]);if(!a)break;if(a instanceof Error)throw a;const i=ri(e,a.suffix);console.debug(`announced: broadcast=${i} active=${a.active}`),t.append({path:i,active:a.active})}t.close()}catch(r){t.close(z(r))}};Jh=async function(t,e){const s=Bd(this,Os)._++;oe(this,Xe).set(s,e.track),console.debug(`subscribe start: id=${s} broadcast=${t} track=${e.track.name}`);const r=new Ch(s,t,e.track.name,e.priority),n=await Ds.open(oe(this,Vt));await n.writer.u53(st.Subscribe),await r.encode(n.writer);try{await qh.decode(n.reader),console.debug(`subscribe ok: id=${s} broadcast=${t} track=${e.track.name}`),await Promise.race([n.reader.closed,e.track.closed]),e.track.close(),n.close(),console.debug(`subscribe close: id=${s} broadcast=${t} track=${e.track.name}`)}catch(a){const i=z(a);e.track.close(i),console.warn(`subscribe error: id=${s} broadcast=${t} track=${e.track.name} error=${i.message}`),n.abort(i)}finally{oe(this,Xe).delete(s)}};var Vd=Object.defineProperty,Kh=t=>{throw TypeError(t)},Hd=(t,e,s)=>e in t?Vd(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,zd=(t,e,s)=>Hd(t,e+"",s),Ga=(t,e,s)=>e.has(t)||Kh("Cannot "+s),N=(t,e,s)=>(Ga(t,e,"read from private field"),s?s.call(t):e.get(t)),nt=(t,e,s)=>e.has(t)?Kh("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),qt=(t,e,s,r)=>(Ga(t,e,"write to private field"),e.set(t,s),s),wt=(t,e,s)=>(Ga(t,e,"access private method"),s),ie,Us,Je,Ge,Rt,ke,Qh,Zh,Yh,jh,eu,tu;class Xd{constructor(e,s,r){nt(this,ke),zd(this,"url"),nt(this,ie),nt(this,Us),nt(this,Je),nt(this,Ge),nt(this,Rt,!1),this.url=e,qt(this,ie,s),qt(this,Us,r),qt(this,Je,new Ud(N(this,ie))),qt(this,Ge,new Gd(N(this,ie))),wt(this,ke,Qh).call(this)}close(){if(!N(this,Rt)){qt(this,Rt,!0),N(this,Je).close(),N(this,Ge).close();try{N(this,ie).close()}catch{}}}publish(e,s){N(this,Je).publish(e,s)}announced(e=Qt()){return N(this,Ge).announced(e)}consume(e){return N(this,Ge).consume(e)}get closed(){return N(this,ie).closed.then(()=>{})}}ie=new WeakMap;Us=new WeakMap;Je=new WeakMap;Ge=new WeakMap;Rt=new WeakMap;ke=new WeakSet;Qh=async function(){const t=wt(this,ke,Zh).call(this),e=wt(this,ke,Yh).call(this),s=wt(this,ke,eu).call(this);try{await Promise.all([t,e,s])}catch(r){N(this,Rt)||console.error("fatal error running connection",r)}finally{this.close()}};Zh=async function(){try{for(;await Dd.decodeMaybe(N(this,Us).reader););}finally{console.warn("session stream closed")}};Yh=async function(){for(;;){const t=await Ds.accept(N(this,ie));if(!t)break;wt(this,ke,jh).call(this,t).catch(e=>{t.writer.reset(e)}).finally(()=>{t.writer.close()})}};jh=async function(t){const e=await t.reader.u53();if(e===st.Session)throw new Error("duplicate session stream");if(e===st.Announce){const s=await hh.decode(t.reader);await N(this,Je).runAnnounce(s,t);return}else if(e===st.Subscribe){const s=await Ch.decode(t.reader);await N(this,Je).runSubscribe(s,t);return}else throw new Error(`unknown stream type: ${e.toString()}`)};eu=async function(){const t=new zi(N(this,ie));for(;;){const e=await t.next();if(!e)break;wt(this,ke,tu).call(this,e).then(()=>{e.stop(new Error("cancel"))}).catch(s=>{e.stop(s)})}};tu=async function(t){const e=await t.u8();if(e===0){const s=await bh.decode(t);await N(this,Ge).runGroup(s,t)}else throw new Error(`unknown stream type: ${e.toString()}`)};function Jd(t){if(t=t.startsWith("0x")?t.slice(2):t,t.length%2)throw new Error("invalid hex string length");const e=t.match(/.{2}/g);if(!e)throw new Error("invalid hex string format");return new Uint8Array(e.map(s=>parseInt(s,16)))}const gi=new Set;async function Kd(t,e){var Ja,Ka,Qa;let s;const r=new Promise(pr=>{s=pr}),n=globalThis.WebTransport?Qd(t,r,e==null?void 0:e.webtransport):void 0,a=!n||gi.has(t.toString())?0:((Ja=e==null?void 0:e.websocket)==null?void 0:Ja.delay)??200,i=((Ka=e==null?void 0:e.websocket)==null?void 0:Ka.enabled)!==!1?Zd(((Qa=e==null?void 0:e.websocket)==null?void 0:Qa.url)??t,a,r):void 0;if(!i&&!n)throw new Error("no transport available; WebTransport not supported and WebSocket is disabled");const o=await Promise.any(n?i?[i,n]:[n]:[i]);if(s&&s(),!o)throw new Error("no transport available");o instanceof hs&&(console.warn(t.toString(),"using WebSocket fallback; the user experience may be degraded"),gi.add(t.toString()));const h=await Ds.open(o);await h.writer.u53(st.ClientCompat);const v=new TextEncoder,w=new X;w.setVarint(yr.MaxRequestId,42069n),w.setBytes(yr.Implementation,v.encode("moq-lite-js"));const M=new bs([yi,_i],w);console.debug(t.toString(),"sending client setup",M),await M.encode(h.writer);const Xa=await h.reader.u53();if(Xa!==st.ServerCompat)throw new Error(`unsupported server message type: ${Xa.toString()}`);const Ct=await ys.decode(h.reader);if(console.debug(t.toString(),"received server setup",Ct),Ct.version===yi)return console.debug(t.toString(),"moq-lite session established"),new Xd(t,o,h);if(Ct.version===_i){const pr=Ct.parameters.getVarint(yr.MaxRequestId)??0n;return console.debug(t.toString(),"moq-ietf session established"),new $d(t,o,h,pr)}else throw new Error(`unsupported server version: ${Ct.version.toString()}`)}async function Qd(t,e,s){let r=t;const n={allowPooling:!1,congestionControl:"low-latency",...s};if(t.protocol==="http:"){const o=new URL(t);o.pathname="/certificate.sha256",o.search="",console.warn(o.toString(),"performing an insecure fingerprint fetch; use https:// in production");const h=await Promise.race([fetch(o),e]);if(!h)return;const v=await Promise.race([h.text(),e]);if(v===void 0)return;n.serverCertificateHashes=(n.serverCertificateHashes||[]).concat([{algorithm:"sha-256",value:Jd(v)}]),r=new URL(t),r.protocol="https:"}const a=new WebTransport(r,n);if(!await Promise.race([a.ready.then(()=>!0),e])){a.close();return}return a}async function Zd(t,e,s){const r=new Promise(o=>setTimeout(o,e));if(!await Promise.race([s,r.then(()=>!0)]))return;e&&console.debug(t.toString(),`no WebTransport after ${e}ms, attempting WebSocket fallback`);const a=new hs(t);if(!await Promise.race([a.ready.then(()=>!0),s])){a.close();return}return a}var Yd=Object.defineProperty,jd=(t,e,s)=>e in t?Yd(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,el=(t,e,s)=>jd(t,e+"",s);class Va{constructor(){el(this,"listeners",new Map)}emit(e,...s){const r=this.listeners.get(e);if(!r||r.size===0)return!1;for(const n of r)try{n(...s)}catch(a){console.error("Error in event listener:",a)}return!0}on(e,s){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(s),this}once(e,s){const r=(...n)=>{this.off(e,r),s(...n)};return this.on(e,r)}off(e,s){const r=this.listeners.get(e);return r&&(r.delete(s),r.size===0&&this.listeners.delete(e)),this}removeListener(e,s){return this.off(e,s)}addListener(e,s){return this.on(e,s)}removeAllListeners(e){return e===void 0?this.listeners.clear():this.listeners.delete(e),this}listenerCount(e){var s;return((s=this.listeners.get(e))==null?void 0:s.size)||0}eventNames(){return Array.from(this.listeners.keys())}}var tl=Object.defineProperty,sl=(t,e,s)=>e in t?tl(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,me=(t,e,s)=>sl(t,typeof e!="symbol"?e+"":e,s);class rl{constructor(e,s){me(this,"group"),me(this,"track"),me(this,"bytesSent",0),me(this,"config"),this.track=e,this.config=s}send(e,s){var r;try{(s||!this.group)&&((r=this.group)==null||r.close(),this.group=this.track.appendGroup()),this.group.writeFrame(e),this.bytesSent+=e.byteLength}catch{}}updateTrack(e){this.track=e}dispose(){var e;(e=this.group)==null||e.close(),this.track.close()}}class nl extends Va{constructor(e,s,r){super(),me(this,"connection"),me(this,"broadcast"),me(this,"broadcasts",new Map),me(this,"catalogTrack"),this.connection=s,this.broadcast=new Ln,this.connection.publish(e,this.broadcast),this.runTrackRequests().catch(n=>{this.emit("error",n)});for(const n of r)this.addBroadcast(n);this.updateCatalog()}dispose(){this.removeAllListeners();for(const e of this.broadcasts.values())e.dispose();this.broadcasts.clear(),this.broadcast.close()}addBroadcast(e){const s=new rl(new Pi(e.trackName),e);this.broadcasts.set(e.trackName,s)}async runTrackRequests(){for(;;){const e=await this.broadcast.requested();if(!e)return;if(e.track.name==="catalog.json"){this.catalogTrack=e.track,this.updateCatalog();continue}const s=this.broadcasts.get(e.track.name);s&&(s.updateTrack(e.track),this.emit("trackRequested",e.track.name))}}updateCatalog(){var s;const e={tracks:[]};e.tracks=[...this.broadcasts.values()].map(r=>({trackName:r.config.trackName,type:r.config.type,priority:r.config.priority||0})),(s=this.catalogTrack)==null||s.writeJson(e)}async send(e,s,r){const n=this.broadcasts.get(e);return n==null?void 0:n.send(s,r)}}var A=(t=>(t.DISCONNECTED="disconnected",t.CONNECTING="connecting",t.CONNECTED="connected",t.RECONNECTING="reconnecting",t.FAILED="failed",t))(A||{}),su=(t=>(t.IDLE="idle",t.BROADCASTING="broadcasting",t.ERROR="error",t))(su||{}),Ft=(t=>(t.IDLE="idle",t.SUBSCRIBED="subscribed",t.FAILED="failed",t))(Ft||{}),al=Object.defineProperty,il=(t,e,s)=>e in t?al(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,re=(t,e,s)=>il(t,typeof e!="symbol"?e+"":e,s);class cl extends Va{constructor(e,s,r=[],n){super(),re(this,"connection"),re(this,"broadcast"),re(this,"namespace"),re(this,"catalogTrack"),re(this,"catalog",{tracks:[]}),re(this,"enabled_",!1),re(this,"requestedSubscriptions",new Map),re(this,"subscriptions",new Map),re(this,"dataCallback"),this.connection=s,this.namespace=e,this.dataCallback=n,this.broadcast=this.connection.consume(this.namespace),console.log("Subscription manager created for namespace:",this.namespace,r);for(const a of r)this.requestedSubscriptions.set(a.trackName,a)}set enabled(e){this.enabled_!==e&&(this.enabled_=e,e&&this.runCatalog().catch(s=>{this.emit("error",s)}))}get enabled(){return this.enabled_}async runCatalog(){if(this.catalogTrack=await this.broadcast.subscribe("catalog.json",0),!this.catalogTrack)throw new Error("Failed to subscribe to catalog track");for(;;){console.log("Waiting for catalog update...");const e=await this.catalogTrack.readJson();if(e)console.log("Received catalog update:",e),this.updateCatalog(e);else return}}updateCatalog(e){this.catalog=e,this.checkSubscriptions()}setDataCallback(e){this.dataCallback=e}dispose(){var e,s;this.removeAllListeners();for(const r of this.subscriptions.values())r.track.close();(e=this.catalogTrack)==null||e.close(),(s=this.broadcast)==null||s.close()}checkSubscriptions(){const e=new Set(this.requestedSubscriptions.keys()),s=new Set(this.subscriptions.keys()),r=this.catalog.tracks.map(n=>n.trackName);console.log("Checking subscriptions. Desired:",e,"Current:",s,"Available:",r);for(const n of s)(!e.has(n)||!r.includes(n))&&this.removeSubscription(n);for(const n of e)if(!s.has(n)&&r.includes(n)){const a=this.requestedSubscriptions.get(n);this.addSubscription(n,a).catch(i=>{this.emit("error",i)})}}removeSubscription(e){const s=this.subscriptions.get(e);s&&(s.track.close(),this.subscriptions.delete(e),this.emit("stateChange",{state:Ft.IDLE,trackName:e,bytesReceived:0}))}async addSubscription(e,s){const r=this.broadcast.subscribe(e,s.priority??0);let n=-1;if(r)for(this.subscriptions.set(e,{track:r,config:s}),this.emit("stateChange",{state:Ft.SUBSCRIBED,trackName:e,bytesReceived:0});;){const a=await r.nextGroup();if(!a)return;try{if(a.sequence<=n){console.log(`Skipping out-of-order group on track "${e}": ${a.sequence} <= ${n}`),a.close();continue}for(;;){const i=await a.readFrame();if(!i)break;n=a.sequence,this.dataCallback&&this.dataCallback(e,i)}}catch(i){console.log("Error processing group on track:",e,i)}finally{a.close()}}else console.warn(`Failed to subscribe to track: ${e}`),this.emit("stateChange",{state:Ft.FAILED,trackName:e,bytesReceived:0,lastError:new Error(`Failed to subscribe to track: ${e}`)})}}var ol=Object.defineProperty,hl=(t,e,s)=>e in t?ol(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,W=(t,e,s)=>hl(t,typeof e!="symbol"?e+"":e,s);class Ha extends Va{constructor(e){var s;super(),W(this,"url"),W(this,"reconnectAttempts",0),W(this,"lastError"),W(this,"connectedAt"),W(this,"reconnectTimer"),W(this,"doReconnect",!0),W(this,"disposed",!1),W(this,"state",A.DISCONNECTED),W(this,"connection"),W(this,"config"),this.config={...e,reconnection:{delay:Math.max(((s=e.reconnection)==null?void 0:s.delay)||1e3,1e3)},connectionTimeout:e.connectionTimeout||1e4},this.url=new URL(this.config.relayUrl)}get status(){return{state:this.state,reconnectAttempts:this.reconnectAttempts,lastError:this.lastError,connectedAt:this.connectedAt}}async connect(){if(this.disposed)throw new Error("Cannot connect a disposed session");if(!(this.state===A.CONNECTING||this.state===A.CONNECTED)){this.setState(A.CONNECTING);try{this.doReconnect=!0,this.connection=await Kd(this.url,{websocket:{enabled:!1}}),this.setState(A.CONNECTED),this.connectedAt=new Date,this.reconnectAttempts=0,this.connection.closed.then(()=>{this.handleDisconnected()}),this.startAnnouncementDiscovery(),this.handleConnected()}catch(e){const s=new Error(`Failed to connect to relay: ${e.message}`);throw this.handleError(s),this.scheduleReconnect(),s}}}disconnect(){if(this.state!==A.DISCONNECTED){if(this.doReconnect=!1,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.connection){try{this.connection.close()}catch(e){console.warn("Error closing connection:",e)}this.connection=void 0}this.setState(A.DISCONNECTED),this.connectedAt=void 0}}async startAnnouncementDiscovery(){if(this.connection)try{const e=Y(this.config.namespace),s=this.connection.announced(e);this.processAnnouncements(s)}catch(e){console.error("Failed to start announcement discovery:",e)}}async processAnnouncements(e){try{for(;!this.disposed;){const s=await e.next();if(!s||this.disposed)break;s.active?this.handleAnnounced(s.path):this.handleUnannounced(s.path)}}catch{}}handleDisconnected(){this.disposed||(this.setState(A.DISCONNECTED),this.scheduleReconnect())}scheduleReconnect(){var s;if(this.disposed||!this.config.reconnection||!this.doReconnect)return;const e=((s=this.config.reconnection)==null?void 0:s.delay)||1e3;this.setState(A.RECONNECTING),this.reconnectAttempts++,this.reconnectTimer=setTimeout(()=>{this.disposed||!this.doReconnect||this.state===A.RECONNECTING&&this.connect().catch(r=>{console.error("Reconnection failed:",r)})},e)}setState(e){this.disposed||this.state!==e&&(this.state=e,this.emit("stateChange",this.status))}handleError(e){this.disposed||(this.lastError=e,this.emit("error",e))}dispose(){this.disposed=!0,this.doReconnect=!1,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0);try{this.disconnect()}catch(e){console.warn("Error during disconnect in dispose:",e)}this.removeAllListeners()}}class ul extends Ha{constructor(e,s){super(e),W(this,"subscriptionManager"),W(this,"subscriptions",[]),W(this,"wasUnannounced",!1),W(this,"discoveryOnly"),this.subscriptions=s,this.discoveryOnly=e.discoveryOnly??!1}dispose(){var e;super.dispose(),(e=this.subscriptionManager)==null||e.dispose()}updateSubscriptions(e){this.subscriptions=e,this.subscriptionManager&&this.state===A.CONNECTED&&this.setupSubscriptionManager()}addSubscription(e){const s=this.subscriptions.findIndex(r=>r.trackName===e.trackName);s>=0?this.subscriptions[s]=e:this.subscriptions.push(e),this.subscriptionManager&&this.state===A.CONNECTED&&this.setupSubscriptionManager()}removeSubscription(e){this.subscriptions=this.subscriptions.filter(s=>s.trackName!==e),this.subscriptionManager&&this.state===A.CONNECTED&&this.setupSubscriptionManager()}handleConnected(){}setupSubscriptionManager(){this.subscriptionManager&&this.subscriptionManager.dispose();const e=(s,r)=>{this.emit("data",s,r)};this.subscriptionManager=new cl(Y(this.config.namespace),this.connection,this.subscriptions,e),this.subscriptionManager.on("error",s=>this.emit("error",s)),this.subscriptionManager.on("stateChange",s=>this.emit("subscriptionStateChange",s.trackName,s)),this.subscriptionManager.enabled=!0}handleDisconnected(){var e;super.handleDisconnected(),(e=this.subscriptionManager)==null||e.dispose()}handleAnnounced(e){if(this.emit("broadcastAnnounced",{path:e,active:!0}),this.discoveryOnly)return;const s=Y(this.config.namespace);e.startsWith(s)&&setTimeout(()=>{this.setupSubscriptionManager(),this.wasUnannounced=!1},this.wasUnannounced?3e3:100)}handleUnannounced(e){var r;if(this.emit("broadcastAnnounced",{path:e,active:!1}),this.discoveryOnly)return;const s=Y(this.config.namespace);e.startsWith(s)&&((r=this.subscriptionManager)==null||r.dispose(),this.subscriptionManager=void 0,this.wasUnannounced=!0)}}class dl extends Ha{constructor(e,s){super(e),W(this,"broadcastManager"),W(this,"broadcasts",[]),this.broadcasts=s}dispose(){var e;super.dispose(),(e=this.broadcastManager)==null||e.dispose()}setupBroadcastManager(){this.broadcastManager&&this.broadcastManager.dispose(),this.broadcastManager=new nl(Y(this.config.namespace),this.connection,this.broadcasts),this.broadcastManager.on("error",e=>this.emit("error",e))}handleConnected(){this.setupBroadcastManager()}handleDisconnected(){var e;super.handleDisconnected(),(e=this.broadcastManager)==null||e.dispose()}handleAnnounced(e){}handleUnannounced(e){}send(e,s,r){if(!this.broadcastManager)throw new Error("Broadcast manager not initialized");if(this.state!==A.CONNECTED)throw new Error("Cannot send data when session is not connected");this.broadcastManager.send(e,s,r)}}exports.BroadcastState=su;exports.MoQSession=Ha;exports.MoqSessionBroadcaster=dl;exports.MoqSessionSubscriber=ul;exports.SessionState=A;exports.SubscriptionState=Ft;
2
+ ${e}`)}));let ti=Lt;function Y(...t){return t.join("/").replace(/\/+/g,"/").replace(/^\/+/,"").replace(/\/+$/,"")}function cu(t,e){return t===""?!0:e.startsWith(t)?e.length===t.length?!0:e[t.length]==="/":!1}function si(t,e){return cu(t,e)?t===""?e:e.length===t.length?"":e.slice(t.length+1):null}function ri(t,e){return t===""?e:e===""?t:`${t}/${e}`}function Qt(){return""}var ou=Object.defineProperty,hu=(t,e,s)=>e in t?ou(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ot=(t,e,s)=>hu(t,typeof e!="symbol"?e+"":e,s);class uu{constructor(){Ot(this,"queue",new $([])),Ot(this,"closed",new $(!1))}}class ki{constructor(e=Qt()){Ot(this,"state",new uu),Ot(this,"prefix"),Ot(this,"closed"),this.prefix=e,this.closed=new Promise(s=>{const r=this.state.closed.subscribe(n=>{n&&(s(n instanceof Error?n:void 0),r())})})}append(e){if(this.state.closed.peek())throw new Error("announced is closed");this.state.queue.mutate(s=>{s.push(e)})}close(e){this.state.closed.set(e??!0),this.state.queue.mutate(s=>{s.length=0})}async next(){for(;;){const e=this.state.queue.peek().shift();if(e)return e;const s=this.state.closed.peek();if(s instanceof Error)throw s;if(s)return;await $.race(this.state.queue,this.state.closed)}}}var du=Object.defineProperty,lu=(t,e,s)=>e in t?du(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ut=(t,e,s)=>lu(t,typeof e!="symbol"?e+"":e,s);class fu{constructor(){ut(this,"frames",new $([])),ut(this,"closed",new $(!1)),ut(this,"total",new $(0))}}let Fn=class{constructor(e){ut(this,"sequence"),ut(this,"state",new fu),ut(this,"closed"),this.sequence=e,this.closed=new Promise(s=>{const r=this.state.closed.subscribe(n=>{n&&(s(n instanceof Error?n:void 0),r())})})}writeFrame(e){if(this.state.closed.peek())throw new Error("group is closed");this.state.frames.mutate(s=>{s.push(e)}),this.state.total.update(s=>s+1)}writeString(e){this.writeFrame(new TextEncoder().encode(e))}writeJson(e){this.writeString(JSON.stringify(e))}writeBool(e){this.writeFrame(new Uint8Array([e?1:0]))}async readFrame(){for(;;){const s=this.state.frames.peek().shift();if(s)return s;const r=this.state.closed.peek();if(r instanceof Error)throw r;if(r)return;await $.race(this.state.frames,this.state.closed)}}async readFrameSequence(){for(;;){const e=this.state.frames.peek(),s=e.shift();if(s)return{sequence:this.state.total.peek()-e.length-1,data:s};const r=this.state.closed.peek();if(r instanceof Error)throw r;if(r)return;await $.race(this.state.frames,this.state.closed)}}async readString(){const e=await this.readFrame();return e?new TextDecoder().decode(e):void 0}async readJson(){const e=await this.readString();return e?JSON.parse(e):void 0}async readBool(){const e=await this.readFrame();return e?e[0]===1:void 0}close(e){this.state.closed.set(e??!0)}};var wu=Object.defineProperty,$i=t=>{throw TypeError(t)},pu=(t,e,s)=>e in t?wu(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Tt=(t,e,s)=>pu(t,typeof e!="symbol"?e+"":e,s),Ei=(t,e,s)=>e.has(t)||$i("Cannot "+s),ni=(t,e,s)=>(Ei(t,e,"read from private field"),s?s.call(t):e.get(t)),_u=(t,e,s)=>e.has(t)?$i("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),ai=(t,e,s,r)=>(Ei(t,e,"write to private field"),e.set(t,s),s),at;class bu{constructor(){Tt(this,"groups",new $([])),Tt(this,"closed",new $(!1))}}class Pi{constructor(e){Tt(this,"name"),Tt(this,"state",new bu),_u(this,at),Tt(this,"closed"),this.name=e,this.closed=new Promise(s=>{const r=this.state.closed.subscribe(n=>{n&&(s(n instanceof Error?n:void 0),r())})})}appendGroup(){if(this.state.closed.peek())throw new Error("track is closed");const e=new Fn(ni(this,at)??0);return ai(this,at,e.sequence+1),this.state.groups.mutate(s=>{s.push(e),s.sort((r,n)=>r.sequence-n.sequence)}),e}writeGroup(e){if(this.state.closed.peek())throw new Error("track is closed");if(e.sequence<(ni(this,at)??0)){e.close();return}ai(this,at,e.sequence+1),this.state.groups.mutate(s=>{s.push(e),s.sort((r,n)=>r.sequence-n.sequence)})}writeFrame(e){const s=this.appendGroup();s.writeFrame(e),s.close()}writeString(e){const s=this.appendGroup();s.writeString(e),s.close()}writeJson(e){const s=this.appendGroup();s.writeJson(e),s.close()}writeBool(e){const s=this.appendGroup();s.writeBool(e),s.close()}async nextGroup(){for(;;){const e=this.state.groups.peek();if(e.length>0)return e.shift();const s=this.state.closed.peek();if(s instanceof Error)throw s;if(s)return;await $.race(this.state.groups,this.state.closed)}}async readFrame(){var e;return(e=await this.readFrameSequence())==null?void 0:e.data}async readFrameSequence(){var e;for(;;){const s=this.state.groups.peek();for(;s.length>1;){const o=s[0].state.frames.peek(),h=o.shift();if(h){const v=s[0].state.total.peek()-o.length-1;return{group:s[0].sequence,frame:v,data:h}}(e=s.shift())==null||e.close()}if(s.length===0){const o=this.state.closed.peek();if(o instanceof Error)throw o;if(o)return;await $.race(this.state.groups,this.state.closed);continue}const r=s[0],n=r.state.frames.peek(),a=n.shift();if(a){const o=r.state.total.peek()-n.length-1;return{group:r.sequence,frame:o,data:a}}const i=this.state.closed.peek();if(i instanceof Error)throw i;if(i)return;await $.race(this.state.groups,this.state.closed,r.state.frames)}}async readString(){const e=await this.readFrame();if(e)return new TextDecoder().decode(e)}async readJson(){const e=await this.readString();if(e)return JSON.parse(e)}async readBool(){const e=await this.readFrame();if(e){if(e.byteLength!==1||!(e[0]===0||e[0]===1))throw new Error("invalid bool frame");return e[0]===1}}close(e){this.state.closed.set(e??!0);for(const s of this.state.groups.peek())s.close(e)}}at=new WeakMap;var yu=Object.defineProperty,vu=(t,e,s)=>e in t?yu(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,os=(t,e,s)=>vu(t,typeof e!="symbol"?e+"":e,s);let gu=class{constructor(){os(this,"requested",new $([])),os(this,"closed",new $(!1))}};class Ln{constructor(){os(this,"state",new gu),os(this,"closed"),this.closed=new Promise(e=>{const s=this.state.closed.subscribe(r=>{r&&(e(r instanceof Error?r:void 0),s())})})}async requested(){for(;;){const e=this.state.requested.peek().pop();if(e)return e;const s=this.state.closed.peek();if(s instanceof Error)throw s;if(s)return;await $.race(this.state.requested,this.state.closed)}}subscribe(e,s){const r=new Pi(e);if(this.state.closed.peek())throw new Error(`broadcast is closed: ${this.state.closed.peek()}`);return this.state.requested.mutate(n=>{n.push({track:r,priority:s}),n.sort((a,i)=>a.priority-i.priority)}),r}close(e){this.state.closed.set(e??!0);for(const{track:s}of this.state.requested.peek())s.close(e);this.state.requested.mutate(s=>{s.length=0})}}const Ve=class Ve{constructor(e){E(this,"value");if(e<0n||e>Ve.MAX)throw new Error(`VarInt value out of range: ${e}`);this.value=e}static from(e){return new Ve(BigInt(e))}size(){const e=this.value;if(e<2n**6n)return 1;if(e<2n**14n)return 2;if(e<2n**30n)return 4;if(e<2n**62n)return 8;throw new Error("VarInt value too large")}encode(e){const s=this.value,r=this.size();if(e.buffer.byteLength<e.byteLength+r)throw new Error("destination buffer too small");const n=new DataView(e.buffer,e.byteOffset+e.byteLength,r);if(r===1)n.setUint8(0,Number(s));else if(r===2)n.setUint16(0,16384|Number(s),!1);else if(r===4)n.setUint32(0,2<<30|Number(s),!1);else if(r===8)n.setBigUint64(0,3n<<62n|s,!1);else throw new Error("VarInt value too large");return new Uint8Array(e.buffer,e.byteOffset,e.byteLength+r)}static decode(e){if(e.byteLength<1)throw new Error("Unexpected end of buffer");const s=new DataView(e.buffer,e.byteOffset),r=s.getUint8(0),n=r>>6;let a,i;switch(n){case 0:a=BigInt(r&63),i=1;break;case 1:if(2>e.length)throw new Error("Unexpected end of buffer");a=BigInt(s.getUint16(0,!1)&16383),i=2;break;case 2:if(4>e.length)throw new Error("Unexpected end of buffer");a=BigInt(s.getUint32(0,!1)&1073741823),i=4;break;case 3:if(8>e.length)throw new Error("Unexpected end of buffer");a=s.getBigUint64(0,!1)&0x3fffffffffffffffn,i=8;break;default:throw new Error("Invalid VarInt tag")}const o=new Uint8Array(e.buffer,e.byteOffset+i,e.byteLength-i);return[new Ve(a),o]}};E(Ve,"MAX",(1n<<62n)-1n),E(Ve,"MAX_SIZE",8);let T=Ve;const pe={Bi:0,Uni:1};class Ze{constructor(e){E(this,"value");this.value=e}static create(e,s,r){let n=e<<2n;return s===pe.Uni&&(n|=0x02n),r&&(n|=0x01n),new Ze(T.from(n))}get dir(){return(this.value.value&0x02n)!==0n?pe.Uni:pe.Bi}get serverInitiated(){return(this.value.value&0x01n)!==0n}canRecv(e){return this.dir===pe.Uni?this.serverInitiated!==e:!0}canSend(e){return this.dir===pe.Uni?this.serverInitiated===e:!0}}const Ii=4,Ci=5,Ni=8,gr=9,qi=29;function ii(t){switch(t.type){case"stream":{let e=new Uint8Array(new ArrayBuffer(9+t.data.length),0,1);return e[0]=t.fin?gr:Ni,e=t.id.value.encode(e),e=new Uint8Array(e.buffer,e.byteOffset,e.byteLength+t.data.length),e.set(t.data,e.byteLength-t.data.length),e}case"reset_stream":{let e=new Uint8Array(new ArrayBuffer(17),0,1);return e[0]=Ii,e=t.id.value.encode(e),e=t.code.encode(e),e}case"stop_sending":{let e=new Uint8Array(new ArrayBuffer(17),0,1);return e[0]=Ci,e=t.id.value.encode(e),e=t.code.encode(e),e}case"connection_close":{const e=new TextEncoder().encode(t.reason);let s=new Uint8Array(new ArrayBuffer(9+e.length),0,1);return s[0]=qi,s=t.code.encode(s),s=new Uint8Array(s.buffer,s.byteOffset,s.byteLength+e.length),s.set(e,s.byteLength-e.length),s}}}function mu(t){if(t.length===0)throw new Error("Invalid frame: empty buffer");const e=t[0];t=t.slice(1);let s;if(e===Ii){[s,t]=T.decode(t);const r=new Ze(s);return[s,t]=T.decode(t),{type:"reset_stream",id:r,code:s}}if(e===Ci){[s,t]=T.decode(t);const r=new Ze(s);return[s,t]=T.decode(t),{type:"stop_sending",id:r,code:s}}if(e===qi){[s,t]=T.decode(t);const r=s,n=new TextDecoder().decode(t);return{type:"connection_close",code:r,reason:n}}if(e===Ni||e===gr)return[s,t]=T.decode(t),{type:"stream",id:new Ze(s),data:t,fin:e===gr};throw new Error(`Invalid frame type: ${e}`)}var x,ve,L,Xt,q,D,xs,Rs,Jt,Kt,vt,gt,Fs,Ai,u,Wi,Mi,Oi,Ti,Ui,xi,Ri,xe,de,rs;const Ls=class Ls{constructor(e,s){f(this,u);f(this,x);f(this,ve,!1);f(this,L);f(this,Xt);f(this,q,new Map);f(this,D,new Map);f(this,xs,0n);f(this,Rs,0n);E(this,"ready");f(this,Jt);E(this,"closed");f(this,Kt);E(this,"incomingBidirectionalStreams");f(this,vt);E(this,"incomingUnidirectionalStreams");f(this,gt);E(this,"datagrams",new Su);var r;if(s!=null&&s.requireUnreliable)throw new Error("not allowed to use WebSocket; requireUnreliable is true");s!=null&&s.serverCertificateHashes&&console.warn("serverCertificateHashes is not supported; trying anyway"),e=p(r=Ls,Fs,Ai).call(r,e),m(this,x,new WebSocket(e,["webtransport"])),this.ready=new Promise(n=>{m(this,Jt,n)}),this.closed=new Promise(n=>{m(this,Kt,n)}),c(this,x).binaryType="arraybuffer",c(this,x).onopen=()=>c(this,Jt).call(this),c(this,x).onmessage=n=>p(this,u,Wi).call(this,n),c(this,x).onerror=n=>p(this,u,Mi).call(this,n),c(this,x).onclose=n=>p(this,u,Oi).call(this,n),this.incomingBidirectionalStreams=new ReadableStream({start:n=>{m(this,vt,n)}}),this.incomingUnidirectionalStreams=new ReadableStream({start:n=>{m(this,gt,n)}})}async createBidirectionalStream(){if(await this.ready,c(this,L))throw c(this,Xt)||new Error("Connection closed");const e=Ze.create(br(this,Rs)._++,pe.Bi,c(this,ve)),s=new WritableStream({start:n=>{c(this,q).set(e.value.value,n)},write:async n=>{await Promise.race([p(this,u,xe).call(this,{type:"stream",id:e,data:n,fin:!1}),this.closed])},abort:n=>{console.warn("abort",n),p(this,u,de).call(this,{type:"reset_stream",id:e,code:T.from(0)}),c(this,q).delete(e.value.value)},close:async()=>{await Promise.race([p(this,u,xe).call(this,{type:"stream",id:e,data:new Uint8Array,fin:!0}),this.closed]),c(this,q).delete(e.value.value)}});return{readable:new ReadableStream({start:n=>{c(this,D).set(e.value.value,n)},cancel:async()=>{p(this,u,de).call(this,{type:"stop_sending",id:e,code:T.from(0)}),c(this,D).delete(e.value.value)}}),writable:s}}async createUnidirectionalStream(){if(await this.ready,c(this,L))throw c(this,L);const e=Ze.create(br(this,xs)._++,pe.Uni,c(this,ve)),s=this;return new WritableStream({start:n=>{c(s,q).set(e.value.value,n)},async write(n){var a;await Promise.race([p(a=s,u,xe).call(a,{type:"stream",id:e,data:n,fin:!1}),s.closed])},abort(n){var a;console.warn("abort",n),p(a=s,u,de).call(a,{type:"reset_stream",id:e,code:T.from(0)}),c(s,q).delete(e.value.value)},async close(){var n;await Promise.race([p(n=s,u,xe).call(n,{type:"stream",id:e,data:new Uint8Array,fin:!0}),s.closed]),c(s,q).delete(e.value.value)}})}close(e){if(c(this,L))return;const s=(e==null?void 0:e.closeCode)??0,r=(e==null?void 0:e.reason)??"";p(this,u,de).call(this,{type:"connection_close",code:T.from(s),reason:r}),setTimeout(()=>{c(this,x).close()},100),p(this,u,rs).call(this,s,r)}get congestionControl(){return"default"}};x=new WeakMap,ve=new WeakMap,L=new WeakMap,Xt=new WeakMap,q=new WeakMap,D=new WeakMap,xs=new WeakMap,Rs=new WeakMap,Jt=new WeakMap,Kt=new WeakMap,vt=new WeakMap,gt=new WeakMap,Fs=new WeakSet,Ai=function(e){const s=typeof e=="string"?new URL(e):e;let r=s.protocol;if(r==="https:")r="wss:";else if(r==="http:")r="ws:";else if(r!=="ws:"&&r!=="wss:")throw new Error(`Unsupported protocol: ${r}`);return`${r}//${s.host}${s.pathname}${s.search}`},u=new WeakSet,Wi=function(e){if(!(e.data instanceof ArrayBuffer))return;const s=new Uint8Array(e.data);try{const r=mu(s);p(this,u,Ti).call(this,r)}catch(r){console.error("Failed to decode frame:",r),this.close({closeCode:1002,reason:"Protocol violation"})}},Mi=function(e){c(this,L)||(m(this,L,new Error(`WebSocket error: ${e.type}`)),p(this,u,rs).call(this,1006,"WebSocket error"))},Oi=function(e){c(this,L)||(m(this,L,new Error(`Connection closed: ${e.code} ${e.reason}`)),p(this,u,rs).call(this,e.code,e.reason))},Ti=function(e){if(e.type==="stream")p(this,u,Ui).call(this,e);else if(e.type==="reset_stream")p(this,u,xi).call(this,e);else if(e.type==="stop_sending")p(this,u,Ri).call(this,e);else if(e.type==="connection_close")m(this,Xt,new Error(`Connection closed: ${e.code.value}: ${e.reason}`)),c(this,x).close();else{const s=e;throw new Error(`Unknown frame type: ${s}`)}},Ui=async function(e){const s=e.id.value.value;if(!e.id.canRecv(c(this,ve)))throw new Error("Invalid stream ID direction");let r=c(this,D).get(s);if(!r){if(e.id.serverInitiated===c(this,ve))return;if(!e.id.canRecv(c(this,ve)))throw new Error("received write-only stream");const n=new ReadableStream({start:a=>{r=a,c(this,D).set(s,a)},cancel:()=>{p(this,u,de).call(this,{type:"stop_sending",id:e.id,code:T.from(0)}),c(this,D).delete(s)}});if(e.id.dir===pe.Bi){const a=new WritableStream({start:i=>{c(this,q).set(s,i)},write:async i=>{await Promise.race([p(this,u,xe).call(this,{type:"stream",id:e.id,data:i,fin:!1}),this.closed])},abort:i=>{console.warn("abort",i),p(this,u,de).call(this,{type:"reset_stream",id:e.id,code:T.from(0)}),c(this,q).delete(s)},close:async()=>{await Promise.race([p(this,u,xe).call(this,{type:"stream",id:e.id,data:new Uint8Array,fin:!0}),this.closed]),c(this,q).delete(s)}});c(this,vt).enqueue({readable:n,writable:a})}else c(this,gt).enqueue(n)}e.data.byteLength>0&&(r==null||r.enqueue(e.data)),e.fin&&(r==null||r.close(),c(this,D).delete(s))},xi=function(e){const s=e.id.value.value,r=c(this,D).get(s);r&&(r.error(new Error(`RESET_STREAM: ${e.code.value}`)),c(this,D).delete(s))},Ri=function(e){const s=e.id.value.value,r=c(this,q).get(s);r&&(r.error(new Error(`STOP_SENDING: ${e.code.value}`)),c(this,q).delete(s),p(this,u,de).call(this,{type:"reset_stream",id:e.id,code:e.code}))},xe=async function(e){for(;c(this,x).bufferedAmount>64*1024;)await new Promise(r=>setTimeout(r,10));const s=ii(e);c(this,x).send(s)},de=function(e){const s=ii(e);c(this,x).send(s)},rs=function(e,s){c(this,Kt).call(this,{closeCode:e,reason:s});try{c(this,vt).close()}catch{}try{c(this,gt).close()}catch{}for(const r of c(this,q).values())try{r.error(c(this,L))}catch{}for(const r of c(this,D).values())try{r.error(c(this,L))}catch{}c(this,q).clear(),c(this,D).clear()},f(Ls,Fs);let hs=Ls;class Su{constructor(){E(this,"incomingHighWaterMark");E(this,"incomingMaxAge");E(this,"maxDatagramSize");E(this,"outgoingHighWaterMark");E(this,"outgoingMaxAge");E(this,"readable");E(this,"writable");this.incomingHighWaterMark=1024,this.incomingMaxAge=null,this.maxDatagramSize=1200,this.outgoingHighWaterMark=1024,this.outgoingMaxAge=null,this.readable=new ReadableStream({}),this.writable=new WritableStream({})}}var ku=Object.defineProperty,Fi=t=>{throw TypeError(t)},$u=(t,e,s)=>e in t?ku(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ci=(t,e,s)=>$u(t,typeof e!="symbol"?e+"":e,s),Dn=(t,e,s)=>e.has(t)||Fi("Cannot "+s),d=(t,e,s)=>(Dn(t,e,"read from private field"),s?s.call(t):e.get(t)),ge=(t,e,s)=>e.has(t)?Fi("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),j=(t,e,s,r)=>(Dn(t,e,"write to private field"),e.set(t,s),s),P=(t,e,s)=>(Dn(t,e,"access private method"),s),S,ns,He,k,us,le,ne,Re,as,ae,At;const Li=2**6-1,Di=2**14-1,Bi=2**30-1,Eu=2**31-1,Bn=Number.MAX_SAFE_INTEGER,oi=1024*1024*64;let Ds=class mr{constructor(e){ci(this,"reader"),ci(this,"writer"),this.writer=new Zt(e.writable),this.reader=new Bs(e.readable)}static async accept(e){for(;;){const s=e.incomingBidirectionalStreams.getReader(),r=await s.read();return s.releaseLock(),r.done?void 0:new mr(r.value)}}static async open(e,s){return new mr(await e.createBidirectionalStream({sendOrder:s}))}close(){this.writer.close(),this.reader.stop(new Error("cancel"))}abort(e){this.writer.reset(e),this.reader.stop(e)}};class Bs{constructor(e,s){var r;ge(this,k),ge(this,S),ge(this,ns),ge(this,He),j(this,S,s??new Uint8Array),j(this,ns,e),j(this,He,(r=d(this,ns))==null?void 0:r.getReader())}async read(e){return e===0?new Uint8Array:(await P(this,k,le).call(this,e),P(this,k,ne).call(this,e))}async readAll(){for(;await P(this,k,us).call(this););return P(this,k,ne).call(this,d(this,S).byteLength)}async string(){const e=await this.u53(),s=await this.read(e);return new TextDecoder().decode(s)}async bool(){const e=await this.u8();if(e===0)return!1;if(e===1)return!0;throw new Error("invalid bool value")}async u8(){return await P(this,k,le).call(this,1),P(this,k,ne).call(this,1)[0]}async u16(){await P(this,k,le).call(this,2);const s=new DataView(d(this,S).buffer,d(this,S).byteOffset,2).getUint16(0);return P(this,k,ne).call(this,2),s}async u53(){const e=await this.u62();if(e>Bn)throw new Error("value larger than 53-bits; use v62 instead");return Number(e)}async u62(){await P(this,k,le).call(this,1);const e=(d(this,S)[0]&192)>>6;if(e===0){const n=P(this,k,ne).call(this,1)[0];return BigInt(n)&0x3fn}if(e===1){await P(this,k,le).call(this,2);const n=P(this,k,ne).call(this,2),a=new DataView(n.buffer,n.byteOffset,n.byteLength);return BigInt(a.getUint16(0))&0x3fffn}if(e===2){await P(this,k,le).call(this,4);const n=P(this,k,ne).call(this,4),a=new DataView(n.buffer,n.byteOffset,n.byteLength);return BigInt(a.getUint32(0))&0x3fffffffn}await P(this,k,le).call(this,8);const s=P(this,k,ne).call(this,8);return new DataView(s.buffer,s.byteOffset,s.byteLength).getBigUint64(0)&0x3fffffffffffffffn}async done(){return d(this,S).byteLength>0?!1:!await P(this,k,us).call(this)}stop(e){var s;(s=d(this,He))==null||s.cancel(e).catch(()=>{})}get closed(){var e;return((e=d(this,He))==null?void 0:e.closed)??Promise.resolve()}}S=new WeakMap;ns=new WeakMap;He=new WeakMap;k=new WeakSet;us=async function(){if(!d(this,He))return!1;const t=await d(this,He).read();if(t.done)return!1;if(t.value.byteLength===0)throw new Error("unexpected empty chunk");const e=new Uint8Array(t.value);if(d(this,S).byteLength===0)j(this,S,e);else{const s=new Uint8Array(d(this,S).byteLength+e.byteLength);s.set(d(this,S)),s.set(e,d(this,S).byteLength),j(this,S,s)}return!0};le=async function(t){if(t>oi)throw new Error(`read size ${t} exceeds max size ${oi}`);for(;d(this,S).byteLength<t;)if(!await P(this,k,us).call(this))throw new Error("unexpected end of stream")};ne=function(t){const e=new Uint8Array(d(this,S).buffer,d(this,S).byteOffset,t);return j(this,S,new Uint8Array(d(this,S).buffer,d(this,S).byteOffset+t,d(this,S).byteLength-t)),e};const Pu=class Gi{constructor(e){ge(this,Re),ge(this,as),ge(this,ae),j(this,as,e),j(this,ae,new ArrayBuffer(8)),j(this,Re,d(this,as).getWriter())}async bool(e){await this.write(ds(d(this,ae),e?1:0))}async u8(e){await this.write(ds(d(this,ae),e))}async u16(e){await this.write(Gn(d(this,ae),e))}async i32(e){if(Math.abs(e)>Eu)throw new Error(`overflow, value larger than 32-bits: ${e.toString()}`);await this.write(Iu(d(this,ae),e))}async u53(e){if(e<0)throw new Error(`underflow, value is negative: ${e.toString()}`);if(e>Bn)throw new Error(`overflow, value larger than 53-bits: ${e.toString()}`);await this.write(Cu(d(this,ae),e))}async u62(e){if(e<0)throw new Error(`underflow, value is negative: ${e.toString()}`);await this.write(Nu(d(this,ae),e))}async write(e){await d(this,Re).write(e)}async string(e){const s=new TextEncoder().encode(e);await this.u53(s.byteLength),await this.write(s)}close(){d(this,Re).close().catch(()=>{})}get closed(){return d(this,Re).closed}reset(e){d(this,Re).abort(e).catch(()=>{})}static async open(e){const s=await e.createUnidirectionalStream();return new Gi(s)}};Re=new WeakMap;as=new WeakMap;ae=new WeakMap;let Zt=Pu;function ds(t,e){const s=new Uint8Array(t,0,1);return s[0]=e,s}function Gn(t,e){const s=new DataView(t,0,2);return s.setUint16(0,e),new Uint8Array(s.buffer,s.byteOffset,s.byteLength)}function Iu(t,e){const s=new DataView(t,0,4);return s.setInt32(0,e),new Uint8Array(s.buffer,s.byteOffset,s.byteLength)}function Vi(t,e){const s=new DataView(t,0,4);return s.setUint32(0,e),new Uint8Array(s.buffer,s.byteOffset,s.byteLength)}function Cu(t,e){if(e<=Li)return ds(t,e);if(e<=Di)return Gn(t,e|16384);if(e<=Bi)return Vi(t,e|2147483648);if(e<=Bn)return Hi(t,BigInt(e)|0xc000000000000000n);throw new Error(`overflow, value larger than 53-bits: ${e.toString()}`)}function Nu(t,e){return e<Li?ds(t,Number(e)):e<Di?Gn(t,Number(e)|16384):e<=Bi?Vi(t,Number(e)|2147483648):Hi(t,BigInt(e)|0xc000000000000000n)}function Hi(t,e){const s=new DataView(t,0,8);return s.setBigUint64(0,e),new Uint8Array(s.buffer,s.byteOffset,s.byteLength)}class zi{constructor(e){ge(this,At),j(this,At,e.incomingUnidirectionalStreams.getReader())}async next(){const e=await d(this,At).read();if(!e.done)return new Bs(e.value)}close(){d(this,At).cancel()}}At=new WeakMap;function z(t){return t instanceof Error?t:new Error(String(t))}function qu(t){throw new Error(`unreachable: ${t}`)}const Au=new Error("request for lock canceled");var Wu=function(t,e,s,r){function n(a){return a instanceof s?a:new s(function(i){i(a)})}return new(s||(s=Promise))(function(a,i){function o(w){try{v(r.next(w))}catch(M){i(M)}}function h(w){try{v(r.throw(w))}catch(M){i(M)}}function v(w){w.done?a(w.value):n(w.value).then(o,h)}v((r=r.apply(t,e||[])).next())})};class Mu{constructor(e,s=Au){this._value=e,this._cancelError=s,this._queue=[],this._weightedWaiters=[]}acquire(e=1,s=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return new Promise((r,n)=>{const a={resolve:r,reject:n,weight:e,priority:s},i=Xi(this._queue,o=>s<=o.priority);i===-1&&e<=this._value?this._dispatchItem(a):this._queue.splice(i+1,0,a)})}runExclusive(e){return Wu(this,arguments,void 0,function*(s,r=1,n=0){const[a,i]=yield this.acquire(r,n);try{return yield s(a)}finally{i()}})}waitForUnlock(e=1,s=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,s)?Promise.resolve():new Promise(r=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),Ou(this._weightedWaiters[e-1],{resolve:r,priority:s})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatchQueue()}release(e=1){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);this._value+=e,this._dispatchQueue()}cancel(){this._queue.forEach(e=>e.reject(this._cancelError)),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(e){const s=this._value;this._value-=e.weight,e.resolve([s,this._newReleaser(e.weight)])}_newReleaser(e){let s=!1;return()=>{s||(s=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){const s=this._weightedWaiters[e-1];s&&(s.forEach(r=>r.resolve()),this._weightedWaiters[e-1]=[])}else{const e=this._queue[0].priority;for(let s=this._value;s>0;s--){const r=this._weightedWaiters[s-1];if(!r)continue;const n=r.findIndex(a=>a.priority<=e);(n===-1?r:r.splice(0,n)).forEach(a=>a.resolve())}}}_couldLockImmediately(e,s){return(this._queue.length===0||this._queue[0].priority<s)&&e<=this._value}}function Ou(t,e){const s=Xi(t,r=>e.priority<=r.priority);t.splice(s+1,0,e)}function Xi(t,e){for(let s=t.length-1;s>=0;s--)if(e(t[s]))return s;return-1}var Tu=function(t,e,s,r){function n(a){return a instanceof s?a:new s(function(i){i(a)})}return new(s||(s=Promise))(function(a,i){function o(w){try{v(r.next(w))}catch(M){i(M)}}function h(w){try{v(r.throw(w))}catch(M){i(M)}}function v(w){w.done?a(w.value):n(w.value).then(o,h)}v((r=r.apply(t,e||[])).next())})};class hi{constructor(e){this._semaphore=new Mu(1,e)}acquire(){return Tu(this,arguments,void 0,function*(e=0){const[,s]=yield this._semaphore.acquire(1,e);return s})}runExclusive(e,s=0){return this._semaphore.runExclusive(()=>e(),1,s)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(e=0){return this._semaphore.waitForUnlock(1,e)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}}async function b(t,e){let s=new Uint8Array;const r=new Zt(new WritableStream({write(n){const a=s.byteLength+n.byteLength;if(a>s.buffer.byteLength){const i=Math.max(a,s.buffer.byteLength*2),o=new ArrayBuffer(i),h=new Uint8Array(o,0,a);h.set(s),h.set(n,s.byteLength),s=h}else s=new Uint8Array(s.buffer,0,a),s.set(n,a-n.byteLength)}}));try{await e(r)}finally{r.close()}if(await r.closed,s.byteLength>65535)throw new Error(`Message too large: ${s.byteLength} bytes (max 65535)`);await t.u16(s.byteLength),await t.write(s)}async function y(t,e){const s=await t.u16(),r=await t.read(s),n=new Bs(void 0,r),a=await e(n);if(!await n.done())throw new Error("Message decoding consumed too few bytes");return a}var Uu=Object.defineProperty,Ji=t=>{throw TypeError(t)},xu=(t,e,s)=>e in t?Uu(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,I=(t,e,s)=>xu(t,typeof e!="symbol"?e+"":e,s),Ru=(t,e,s)=>e.has(t)||Ji("Cannot "+s),Ne=(t,e,s)=>e.has(t)?Ji("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),Ee=(t,e,s)=>(Ru(t,e,"access private method"),s),Sr,Ki,Vn,Qi,kr,Zi,Hn,Yi,$r,ji,zn,ec,Er,tc,Xn,sc;const Jn=class rc{constructor(e,s,r,n,a,i,o,h,v){Ne(this,Sr),I(this,"requestId"),I(this,"trackNamespace"),I(this,"trackName"),I(this,"subscriberPriority"),I(this,"groupOrder"),I(this,"startGroup"),I(this,"startObject"),I(this,"endGroup"),I(this,"endObject"),this.requestId=e,this.trackNamespace=s,this.trackName=r,this.subscriberPriority=n,this.groupOrder=a,this.startGroup=i,this.startObject=o,this.endGroup=h,this.endObject=v}async encode(e){return b(e,Ee(this,Sr,Ki).bind(this))}static async decode(e){return y(e,Ee(rc,Vn,Qi))}};Sr=new WeakSet;Ki=async function(t){throw new Error("FETCH messages are not supported")};Vn=new WeakSet;Qi=async function(t){throw new Error("FETCH messages are not supported")};Ne(Jn,Vn);I(Jn,"id",22);let Pr=Jn;const Kn=class nc{constructor(e){Ne(this,kr),I(this,"requestId"),this.requestId=e}async encode(e){return b(e,Ee(this,kr,Zi).bind(this))}static async decode(e){return y(e,Ee(nc,Hn,Yi))}};kr=new WeakSet;Zi=async function(t){throw new Error("FETCH_OK messages are not supported")};Hn=new WeakSet;Yi=async function(t){throw new Error("FETCH_OK messages are not supported")};Ne(Kn,Hn);I(Kn,"id",24);let Ir=Kn;const Qn=class ac{constructor(e,s,r){Ne(this,$r),I(this,"requestId"),I(this,"errorCode"),I(this,"reasonPhrase"),this.requestId=e,this.errorCode=s,this.reasonPhrase=r}async encode(e){return b(e,Ee(this,$r,ji).bind(this))}static async decode(e){return y(e,Ee(ac,zn,ec))}};$r=new WeakSet;ji=async function(t){throw new Error("FETCH_ERROR messages are not supported")};zn=new WeakSet;ec=async function(t){throw new Error("FETCH_ERROR messages are not supported")};Ne(Qn,zn);I(Qn,"id",25);let Cr=Qn;const Zn=class ic{constructor(e){Ne(this,Er),I(this,"requestId"),this.requestId=e}async encode(e){return b(e,Ee(this,Er,tc).bind(this))}static async decode(e){return y(e,Ee(ic,Xn,sc))}};Er=new WeakSet;tc=async function(t){throw new Error("FETCH_CANCEL messages are not supported")};Xn=new WeakSet;sc=async function(t){throw new Error("FETCH_CANCEL messages are not supported")};Ne(Zn,Xn);I(Zn,"id",23);let Nr=Zn;var Fu=Object.defineProperty,cc=t=>{throw TypeError(t)},Lu=(t,e,s)=>e in t?Fu(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,oc=(t,e,s)=>Lu(t,typeof e!="symbol"?e+"":e,s),Du=(t,e,s)=>e.has(t)||cc("Cannot "+s),hc=(t,e,s)=>e.has(t)?cc("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),ui=(t,e,s)=>(Du(t,e,"access private method"),s),qr,uc,Yn,dc;const Gs=class lc{constructor(e){hc(this,qr),oc(this,"newSessionUri"),this.newSessionUri=e}async encode(e){return b(e,ui(this,qr,uc).bind(this))}static async decode(e){return y(e,ui(lc,Yn,dc))}};qr=new WeakSet;uc=async function(t){await t.string(this.newSessionUri)};Yn=new WeakSet;dc=async function(t){const e=await t.string();return new Gs(e)};hc(Gs,Yn);oc(Gs,"id",16);let Ar=Gs;async function qe(t,e){const s=e.split("/");await t.u53(s.length);for(const r of s)await t.string(r)}async function Ae(t){const e=[],s=await t.u53();for(let r=0;r<s;r++)e.push(await t.string());return Y(...e)}var Bu=Object.defineProperty,Gu=(t,e,s)=>e in t?Bu(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,di=(t,e,s)=>Gu(t,typeof e!="symbol"?e+"":e,s);const yr={MaxRequestId:2n,Implementation:7n};class X{constructor(){di(this,"vars"),di(this,"bytes"),this.vars=new Map,this.bytes=new Map}get size(){return this.vars.size+this.bytes.size}setBytes(e,s){if(e%2n!==1n)throw new Error(`invalid parameter id: ${e.toString()}, must be odd`);this.bytes.set(e,s)}setVarint(e,s){if(e%2n!==0n)throw new Error(`invalid parameter id: ${e.toString()}, must be even`);this.vars.set(e,s)}getBytes(e){if(e%2n!==1n)throw new Error(`invalid parameter id: ${e.toString()}, must be odd`);return this.bytes.get(e)}getVarint(e){if(e%2n!==0n)throw new Error(`invalid parameter id: ${e.toString()}, must be even`);return this.vars.get(e)}removeBytes(e){if(e%2n!==1n)throw new Error(`invalid parameter id: ${e.toString()}, must be odd`);return this.bytes.delete(e)}removeVarint(e){if(e%2n!==0n)throw new Error(`invalid parameter id: ${e.toString()}, must be even`);return this.vars.delete(e)}async encode(e){await e.u53(this.vars.size+this.bytes.size);for(const[s,r]of this.vars)await e.u62(s),await e.u62(r);for(const[s,r]of this.bytes)await e.u62(s),await e.u53(r.length),await e.write(r)}static async decode(e){const s=await e.u53(),r=new X;for(let n=0;n<s;n++){const a=await e.u62();if(a%2n===0n){if(r.vars.has(a))throw new Error(`duplicate parameter id: ${a.toString()}`);const i=await e.u62();r.setVarint(a,i)}else{if(r.bytes.has(a))throw new Error(`duplicate parameter id: ${a.toString()}`);const i=await e.u53(),o=await e.read(i);r.setBytes(a,o)}}return r}}var Vu=Object.defineProperty,fc=t=>{throw TypeError(t)},Hu=(t,e,s)=>e in t?Vu(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,C=(t,e,s)=>Hu(t,typeof e!="symbol"?e+"":e,s),zu=(t,e,s)=>e.has(t)||fc("Cannot "+s),We=(t,e,s)=>e.has(t)?fc("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),Pe=(t,e,s)=>(zu(t,e,"access private method"),s),Wr,wc,jn,pc,Mr,_c,ea,bc,Or,yc,ta,vc,Tr,gc,sa,mc;const Vs=class Sc{constructor(e,s,r,n,a,i,o,h){We(this,Wr),C(this,"requestId"),C(this,"trackNamespace"),C(this,"trackName"),C(this,"trackAlias"),C(this,"groupOrder"),C(this,"contentExists"),C(this,"largest"),C(this,"forward"),this.requestId=e,this.trackNamespace=s,this.trackName=r,this.trackAlias=n,this.groupOrder=a,this.contentExists=i,this.largest=o,this.forward=h}async encode(e){return b(e,Pe(this,Wr,wc).bind(this))}static async decode(e){return y(e,Pe(Sc,jn,pc))}};Wr=new WeakSet;wc=async function(t){if(await t.u62(this.requestId),await qe(t,this.trackNamespace),await t.string(this.trackName),await t.u62(this.trackAlias),await t.u8(this.groupOrder),await t.bool(this.contentExists),this.contentExists!==!!this.largest)throw new Error("contentExists and largest must both be true or false");this.largest&&(await t.u62(this.largest.groupId),await t.u62(this.largest.objectId)),await t.bool(this.forward),await t.u53(0)};jn=new WeakSet;pc=async function(t){const e=await t.u62(),s=await Ae(t),r=await t.string(),n=await t.u62(),a=await t.u8(),i=await t.bool(),o=i?{groupId:await t.u62(),objectId:await t.u62()}:void 0,h=await t.bool();return await X.decode(t),new Vs(e,s,r,n,a,i,o,h)};We(Vs,jn);C(Vs,"id",29);let Ur=Vs;const ra=class kc{constructor(){We(this,Mr)}async encode(e){return b(e,Pe(this,Mr,_c).bind(this))}static async decode(e){return y(e,Pe(kc,ea,bc))}};Mr=new WeakSet;_c=async function(t){throw new Error("PUBLISH_OK messages are not supported")};ea=new WeakSet;bc=async function(t){throw new Error("PUBLISH_OK messages are not supported")};We(ra,ea);C(ra,"id",30);let xr=ra;const Hs=class $c{constructor(e,s,r){We(this,Or),C(this,"requestId"),C(this,"errorCode"),C(this,"reasonPhrase"),this.requestId=e,this.errorCode=s,this.reasonPhrase=r}async encode(e){return b(e,Pe(this,Or,yc).bind(this))}static async decode(e){return y(e,Pe($c,ta,vc))}};Or=new WeakSet;yc=async function(t){await t.u62(this.requestId),await t.u62(BigInt(this.errorCode)),await t.string(this.reasonPhrase)};ta=new WeakSet;vc=async function(t){const e=await t.u62(),s=Number(await t.u62()),r=await t.string();return new Hs(e,s,r)};We(Hs,ta);C(Hs,"id",31);let ls=Hs;const zs=class Ec{constructor(e,s,r){We(this,Tr),C(this,"requestId"),C(this,"statusCode"),C(this,"reasonPhrase"),this.requestId=e,this.statusCode=s,this.reasonPhrase=r}async encode(e){return b(e,Pe(this,Tr,gc).bind(this))}static async decode(e){return y(e,Pe(Ec,sa,mc))}};Tr=new WeakSet;gc=async function(t){await t.u62(this.requestId),await t.u62(BigInt(this.statusCode)),await t.u62(BigInt(0)),await t.string(this.reasonPhrase)};sa=new WeakSet;mc=async function(t){const e=await t.u62(),s=Number(await t.u62());await t.u62();const r=await t.string();return new zs(e,s,r)};We(zs,sa);C(zs,"id",11);let Dt=zs;var Xu=Object.defineProperty,Pc=t=>{throw TypeError(t)},Ju=(t,e,s)=>e in t?Xu(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,U=(t,e,s)=>Ju(t,typeof e!="symbol"?e+"":e,s),Ku=(t,e,s)=>e.has(t)||Pc("Cannot "+s),se=(t,e,s)=>e.has(t)?Pc("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),te=(t,e,s)=>(Ku(t,e,"access private method"),s),Rr,Ic,na,Cc,Fr,Nc,aa,qc,Lr,Ac,ia,Wc,Dr,Mc,ca,Oc,Br,Tc,oa,Uc;const Xs=class xc{constructor(e,s){se(this,Rr),U(this,"requestId"),U(this,"trackNamespace"),this.requestId=e,this.trackNamespace=s}async encode(e){return b(e,te(this,Rr,Ic).bind(this))}static async decode(e){return y(e,te(xc,na,Cc))}};Rr=new WeakSet;Ic=async function(t){await t.u62(this.requestId),await qe(t,this.trackNamespace),await t.u53(0)};na=new WeakSet;Cc=async function(t){const e=await t.u62(),s=await Ae(t);return await X.decode(t),new Xs(e,s)};se(Xs,na);U(Xs,"id",6);let fs=Xs;const Js=class Rc{constructor(e){se(this,Fr),U(this,"requestId"),this.requestId=e}async encode(e){return b(e,te(this,Fr,Nc).bind(this))}static async decode(e){return y(e,te(Rc,aa,qc))}};Fr=new WeakSet;Nc=async function(t){await t.u62(this.requestId)};aa=new WeakSet;qc=async function(t){const e=await t.u62();return new Js(e)};se(Js,aa);U(Js,"id",7);let Gr=Js;const Ks=class Fc{constructor(e,s,r){se(this,Lr),U(this,"requestId"),U(this,"errorCode"),U(this,"reasonPhrase"),this.requestId=e,this.errorCode=s,this.reasonPhrase=r}async encode(e){return b(e,te(this,Lr,Ac).bind(this))}static async decode(e){return y(e,te(Fc,ia,Wc))}};Lr=new WeakSet;Ac=async function(t){await t.u62(this.requestId),await t.u62(BigInt(this.errorCode)),await t.string(this.reasonPhrase)};ia=new WeakSet;Wc=async function(t){const e=await t.u62(),s=Number(await t.u62()),r=await t.string();return new Ks(e,s,r)};se(Ks,ia);U(Ks,"id",8);let Vr=Ks;const Qs=class Lc{constructor(e,s=0,r=""){se(this,Dr),U(this,"trackNamespace"),U(this,"errorCode"),U(this,"reasonPhrase"),this.trackNamespace=e,this.errorCode=s,this.reasonPhrase=r}async encode(e){return b(e,te(this,Dr,Mc).bind(this))}static async decode(e){return y(e,te(Lc,ca,Oc))}};Dr=new WeakSet;Mc=async function(t){await qe(t,this.trackNamespace),await t.u62(BigInt(this.errorCode)),await t.string(this.reasonPhrase)};ca=new WeakSet;Oc=async function(t){const e=await Ae(t),s=Number(await t.u62()),r=await t.string();return new Qs(e,s,r)};se(Qs,ca);U(Qs,"id",12);let Hr=Qs;const Zs=class Dc{constructor(e){se(this,Br),U(this,"trackNamespace"),this.trackNamespace=e}async encode(e){return b(e,te(this,Br,Tc).bind(this))}static async decode(e){return y(e,te(Dc,oa,Uc))}};Br=new WeakSet;Tc=async function(t){await qe(t,this.trackNamespace)};oa=new WeakSet;Uc=async function(t){const e=await Ae(t);return new Zs(e)};se(Zs,oa);U(Zs,"id",9);let ws=Zs;var Qu=Object.defineProperty,Bc=t=>{throw TypeError(t)},Zu=(t,e,s)=>e in t?Qu(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Ys=(t,e,s)=>Zu(t,typeof e!="symbol"?e+"":e,s),Yu=(t,e,s)=>e.has(t)||Bc("Cannot "+s),js=(t,e,s)=>e.has(t)?Bc("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),ps=(t,e,s)=>(Yu(t,e,"access private method"),s),zr,Gc,ha,Vc,Xr,Hc,ua,zc;const er=class Xc{constructor(e){js(this,zr),Ys(this,"requestId"),this.requestId=e}async encode(e){return b(e,ps(this,zr,Gc).bind(this))}static async decode(e){return y(e,ps(Xc,ha,Vc))}};zr=new WeakSet;Gc=async function(t){await t.u62(this.requestId)};ha=new WeakSet;Vc=async function(t){return new er(await t.u62())};js(er,ha);Ys(er,"id",21);let Jr=er;const tr=class Jc{constructor(e){js(this,Xr),Ys(this,"requestId"),this.requestId=e}async encode(e){return b(e,ps(this,Xr,Hc).bind(this))}static async decode(e){return y(e,ps(Jc,ua,zc))}};Xr=new WeakSet;Hc=async function(t){await t.u62(this.requestId)};ua=new WeakSet;zc=async function(t){return new tr(await t.u62())};js(tr,ua);Ys(tr,"id",26);let Kr=tr;var ju=Object.defineProperty,Kc=t=>{throw TypeError(t)},ed=(t,e,s)=>e in t?ju(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,mt=(t,e,s)=>ed(t,typeof e!="symbol"?e+"":e,s),td=(t,e,s)=>e.has(t)||Kc("Cannot "+s),sr=(t,e,s)=>e.has(t)?Kc("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),_s=(t,e,s)=>(td(t,e,"access private method"),s),Qr,Qc,da,Zc,Zr,Yc,la,jc;const sd=128,rr=class eo{constructor(e,s=new X){sr(this,Qr),mt(this,"versions"),mt(this,"parameters"),this.versions=e,this.parameters=s}async encode(e){return b(e,_s(this,Qr,Qc).bind(this))}static async decode(e){return y(e,_s(eo,da,Zc))}};Qr=new WeakSet;Qc=async function(t){await t.u53(this.versions.length);for(const e of this.versions)await t.u53(e);await this.parameters.encode(t)};da=new WeakSet;Zc=async function(t){const e=await t.u53();if(e>sd)throw new Error(`too many versions: ${e}`);const s=[];for(let n=0;n<e;n++){const a=await t.u53();s.push(a)}const r=await X.decode(t);return new rr(s,r)};sr(rr,da);mt(rr,"id",32);let bs=rr;const nr=class to{constructor(e,s=new X){sr(this,Zr),mt(this,"version"),mt(this,"parameters"),this.version=e,this.parameters=s}async encode(e){return b(e,_s(this,Zr,Yc).bind(this))}static async decode(e){return y(e,_s(to,la,jc))}};Zr=new WeakSet;Yc=async function(t){await t.u53(this.version),await this.parameters.encode(t)};la=new WeakSet;jc=async function(t){const e=await t.u53(),s=await X.decode(t);return new nr(e,s)};sr(nr,la);mt(nr,"id",33);let ys=nr;var rd=Object.defineProperty,so=t=>{throw TypeError(t)},nd=(t,e,s)=>e in t?rd(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,R=(t,e,s)=>nd(t,typeof e!="symbol"?e+"":e,s),ad=(t,e,s)=>e.has(t)||so("Cannot "+s),Me=(t,e,s)=>e.has(t)?so("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),Ie=(t,e,s)=>(ad(t,e,"access private method"),s),Yr,ro,fa,no,jr,ao,wa,io,en,co,pa,oo,tn,ho,_a,uo;const lo=2,ar=class fo{constructor(e,s,r,n){Me(this,Yr),R(this,"requestId"),R(this,"trackNamespace"),R(this,"trackName"),R(this,"subscriberPriority"),this.requestId=e,this.trackNamespace=s,this.trackName=r,this.subscriberPriority=n}async encode(e){return b(e,Ie(this,Yr,ro).bind(this))}static async decode(e){return y(e,Ie(fo,fa,no))}};Yr=new WeakSet;ro=async function(t){await t.u62(this.requestId),await qe(t,this.trackNamespace),await t.string(this.trackName),await t.u8(this.subscriberPriority),await t.u8(lo),await t.bool(!0),await t.u53(2),await t.u53(0)};fa=new WeakSet;no=async function(t){const e=await t.u62(),s=await Ae(t),r=await t.string(),n=await t.u8(),a=await t.u8();if(a>2)throw new Error(`unknown group order: ${a}`);const i=await t.bool();if(!i)throw new Error(`unsupported forward value: ${i}`);const o=await t.u53();if(o!==1&&o!==2)throw new Error(`unsupported filter type: ${o}`);return await X.decode(t),new ar(e,s,r,n)};Me(ar,fa);R(ar,"id",3);let vs=ar;const ir=class wo{constructor(e,s){Me(this,jr),R(this,"requestId"),R(this,"trackAlias"),this.requestId=e,this.trackAlias=s}async encode(e){return b(e,Ie(this,jr,ao).bind(this))}static async decode(e){return y(e,Ie(wo,wa,io))}};jr=new WeakSet;ao=async function(t){await t.u62(this.requestId),await t.u62(this.trackAlias),await t.u62(0n),await t.u8(lo),await t.bool(!1),await t.u53(0)};wa=new WeakSet;io=async function(t){const e=await t.u62(),s=await t.u62(),r=await t.u62();if(r!==BigInt(0))throw new Error(`unsupported expires: ${r}`);return await t.u8(),await t.bool()&&(await t.u62(),await t.u62()),await X.decode(t),new ir(e,s)};Me(ir,wa);R(ir,"id",4);let gs=ir;const cr=class po{constructor(e,s,r){Me(this,en),R(this,"requestId"),R(this,"errorCode"),R(this,"reasonPhrase"),this.requestId=e,this.errorCode=s,this.reasonPhrase=r}async encode(e){return b(e,Ie(this,en,co).bind(this))}static async decode(e){return y(e,Ie(po,pa,oo))}};en=new WeakSet;co=async function(t){await t.u62(this.requestId),await t.u62(BigInt(this.errorCode)),await t.string(this.reasonPhrase)};pa=new WeakSet;oo=async function(t){const e=await t.u62(),s=Number(await t.u62()),r=await t.string();return new cr(e,s,r)};Me(cr,pa);R(cr,"id",5);let ms=cr;const or=class _o{constructor(e){Me(this,tn),R(this,"requestId"),this.requestId=e}async encode(e){return b(e,Ie(this,tn,ho).bind(this))}static async decode(e){return y(e,Ie(_o,_a,uo))}};tn=new WeakSet;ho=async function(t){await t.u62(this.requestId)};_a=new WeakSet;uo=async function(t){const e=await t.u62();return new or(e)};Me(or,_a);R(or,"id",10);let Ss=or;var id=Object.defineProperty,bo=t=>{throw TypeError(t)},cd=(t,e,s)=>e in t?id(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Z=(t,e,s)=>cd(t,typeof e!="symbol"?e+"":e,s),od=(t,e,s)=>e.has(t)||bo("Cannot "+s),Oe=(t,e,s)=>e.has(t)?bo("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),Ce=(t,e,s)=>(od(t,e,"access private method"),s),sn,yo,ba,vo,rn,go,ya,mo,nn,So,va,ko,an,$o,ga,Eo;const hr=class Po{constructor(e,s){Oe(this,sn),Z(this,"namespace"),Z(this,"requestId"),this.namespace=e,this.requestId=s}async encode(e){return b(e,Ce(this,sn,yo).bind(this))}static async decode(e){return y(e,Ce(Po,ba,vo))}};sn=new WeakSet;yo=async function(t){await t.u62(this.requestId),await qe(t,this.namespace),await t.u53(0)};ba=new WeakSet;vo=async function(t){const e=await t.u62(),s=await Ae(t);return await X.decode(t),new hr(s,e)};Oe(hr,ba);Z(hr,"id",17);let ks=hr;const ur=class Io{constructor(e){Oe(this,rn),Z(this,"requestId"),this.requestId=e}async encode(e){return b(e,Ce(this,rn,go).bind(this))}static async decode(e){return y(e,Ce(Io,ya,mo))}};rn=new WeakSet;go=async function(t){await t.u62(this.requestId)};ya=new WeakSet;mo=async function(t){const e=await t.u62();return new ur(e)};Oe(ur,ya);Z(ur,"id",18);let cn=ur;const dr=class Co{constructor(e,s,r){Oe(this,nn),Z(this,"requestId"),Z(this,"errorCode"),Z(this,"reasonPhrase"),this.requestId=e,this.errorCode=s,this.reasonPhrase=r}async encode(e){return b(e,Ce(this,nn,So).bind(this))}static async decode(e){return y(e,Ce(Co,va,ko))}};nn=new WeakSet;So=async function(t){await t.u62(this.requestId),await t.u62(BigInt(this.errorCode)),await t.string(this.reasonPhrase)};va=new WeakSet;ko=async function(t){const e=await t.u62(),s=Number(await t.u62()),r=await t.string();return new dr(e,s,r)};Oe(dr,va);Z(dr,"id",19);let on=dr;const lr=class No{constructor(e){Oe(this,an),Z(this,"requestId"),this.requestId=e}async encode(e){return b(e,Ce(this,an,$o).bind(this))}static async decode(e){return y(e,Ce(No,ga,Eo))}};an=new WeakSet;$o=async function(t){await t.u62(this.requestId)};ga=new WeakSet;Eo=async function(t){const e=await t.u62();return new lr(e)};Oe(lr,ga);Z(lr,"id",20);let $s=lr;var hd=Object.defineProperty,qo=t=>{throw TypeError(t)},ud=(t,e,s)=>e in t?hd(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,B=(t,e,s)=>ud(t,typeof e!="symbol"?e+"":e,s),dd=(t,e,s)=>e.has(t)||qo("Cannot "+s),fr=(t,e,s)=>e.has(t)?qo("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),Es=(t,e,s)=>(dd(t,e,"access private method"),s),hn,Ao,ma,Wo,un,Mo,Sa,Oo;const wr=class To{constructor(e,s){fr(this,hn),B(this,"trackNamespace"),B(this,"trackName"),this.trackNamespace=e,this.trackName=s}async encode(e){return b(e,Es(this,hn,Ao).bind(this))}static async decode(e){return y(e,Es(To,ma,Wo))}};hn=new WeakSet;Ao=async function(t){await qe(t,this.trackNamespace),await t.string(this.trackName)};ma=new WeakSet;Wo=async function(t){const e=await Ae(t),s=await t.string();return new wr(e,s)};fr(wr,ma);B(wr,"id",13);let dn=wr;const Te=class Uo{constructor(e,s,r,n,a){fr(this,un),B(this,"trackNamespace"),B(this,"trackName"),B(this,"statusCode"),B(this,"lastGroupId"),B(this,"lastObjectId"),this.trackNamespace=e,this.trackName=s,this.statusCode=r,this.lastGroupId=n,this.lastObjectId=a}async encode(e){return b(e,Es(this,un,Mo).bind(this))}static async decode(e){return y(e,Es(Uo,Sa,Oo))}};un=new WeakSet;Mo=async function(t){await qe(t,this.trackNamespace),await t.string(this.trackName),await t.u62(BigInt(this.statusCode)),await t.u62(this.lastGroupId),await t.u62(this.lastObjectId)};Sa=new WeakSet;Oo=async function(t){const e=await Ae(t),s=await t.string(),r=Number(await t.u62()),n=await t.u62(),a=await t.u62();return new Te(e,s,r,n,a)};fr(Te,Sa);B(Te,"id",14);B(Te,"STATUS_IN_PROGRESS",0);B(Te,"STATUS_NOT_FOUND",1);B(Te,"STATUS_NOT_AUTHORIZED",2);B(Te,"STATUS_ENDED",3);let Bt=Te;var ld=Object.defineProperty,xo=t=>{throw TypeError(t)},fd=(t,e,s)=>e in t?ld(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,wd=(t,e,s)=>fd(t,e+"",s),Ro=(t,e,s)=>e.has(t)||xo("Cannot "+s),K=(t,e,s)=>(Ro(t,e,"read from private field"),s?s.call(t):e.get(t)),rt=(t,e,s)=>e.has(t)?xo("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),ue=(t,e,s,r)=>(Ro(t,e,"write to private field"),e.set(t,s),s),Wt,Fe,Le,it,ln,fn;const li={[bs.id]:bs,[ys.id]:ys,[vs.id]:vs,[gs.id]:gs,[ms.id]:ms,[fs.id]:fs,[Gr.id]:Gr,[Vr.id]:Vr,[ws.id]:ws,[Ss.id]:Ss,[Dt.id]:Dt,[Hr.id]:Hr,[dn.id]:dn,[Bt.id]:Bt,[Ar.id]:Ar,[Pr.id]:Pr,[Nr.id]:Nr,[Ir.id]:Ir,[Cr.id]:Cr,[ks.id]:ks,[cn.id]:cn,[on.id]:on,[$s.id]:$s,[Ur.id]:Ur,[xr.id]:xr,[ls.id]:ls,[Jr.id]:Jr,[Kr.id]:Kr};class pd{constructor(e,s){wd(this,"stream"),rt(this,Wt,0n),rt(this,Fe),rt(this,Le),rt(this,it),rt(this,ln,new hi),rt(this,fn,new hi),this.stream=e,ue(this,Fe,s),ue(this,Le,new Promise(r=>{ue(this,it,r)}))}async write(e){console.debug("message write",e),await K(this,ln).runExclusive(async()=>{await this.stream.writer.u53(e.constructor.id),await e.encode(this.stream.writer)})}async read(){return await K(this,fn).runExclusive(async()=>{const e=await this.stream.reader.u53();if(!(e in li))throw new Error(`Unknown control message type: ${e}`);try{const s=await li[e].decode(this.stream.reader);return console.debug("message read",s),s}catch(s){throw console.error("failed to decode message",e,s),s}})}maxRequestId(e){if(e<=K(this,Fe))throw new Error(`max request id must be greater than current max request id: max=${e} current=${K(this,Fe)}`);ue(this,Fe,e),K(this,it).call(this),ue(this,Le,new Promise(s=>{ue(this,it,s)}))}async nextRequestId(){for(;;){const e=K(this,Wt);if(e<K(this,Fe))return ue(this,Wt,K(this,Wt)+2n),e;if(!K(this,Le))return;await K(this,Le)}}close(){K(this,it).call(this),ue(this,Le,void 0)}}Wt=new WeakMap;Fe=new WeakMap;Le=new WeakMap;it=new WeakMap;ln=new WeakMap;fn=new WeakMap;var _d=Object.defineProperty,bd=(t,e,s)=>e in t?_d(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ct=(t,e,s)=>bd(t,typeof e!="symbol"?e+"":e,s);const fi=3;let Fo=class Lo{constructor(e,s,r,n,a){ct(this,"flags"),ct(this,"trackAlias"),ct(this,"groupId"),ct(this,"subGroupId"),ct(this,"publisherPriority"),this.flags=a,this.trackAlias=e,this.groupId=s,this.subGroupId=r,this.publisherPriority=n}async encode(e){if(!this.flags.hasSubgroup&&this.subGroupId!==0)throw new Error(`Subgroup ID must be 0 if hasSubgroup is false: ${this.subGroupId}`);let s=16;this.flags.hasExtensions&&(s|=1),this.flags.hasSubgroupObject&&(s|=2),this.flags.hasSubgroup&&(s|=4),this.flags.hasEnd&&(s|=8),await e.u53(s),await e.u62(this.trackAlias),await e.u53(this.groupId),this.flags.hasSubgroup&&await e.u53(this.subGroupId),await e.u8(0)}static async decode(e){const s=await e.u53();if(s<16||s>31)throw new Error(`Unsupported group type: ${s}`);const r={hasExtensions:(s&1)!==0,hasSubgroupObject:(s&2)!==0,hasSubgroup:(s&4)!==0,hasEnd:(s&8)!==0},n=await e.u62(),a=await e.u53(),i=r.hasSubgroup?await e.u53():0,o=await e.u8();return new Lo(n,a,i,o,r)}};class dt{constructor(e){ct(this,"payload"),this.payload=e}async encode(e,s){await e.u53(0),s.hasExtensions&&await e.u53(0),this.payload!==void 0?(await e.u53(this.payload.byteLength),this.payload.byteLength===0?await e.u53(0):await e.write(this.payload)):(await e.u53(0),await e.u53(fi))}static async decode(e,s){const r=await e.u53();if(r!==0&&console.warn(`object ID delta is not supported, ignoring: ${r}`),s.hasExtensions){const i=await e.u53();await e.read(i)}const n=await e.u53();if(n>0){const i=await e.read(n);return new dt(i)}const a=await e.u53();if(s.hasEnd){if(a===0)return new dt(new Uint8Array(0))}else if(a===0||a===fi)return new dt;throw new Error(`Unsupported object status: ${a}`)}}var Do=t=>{throw TypeError(t)},ka=(t,e,s)=>e.has(t)||Do("Cannot "+s),H=(t,e,s)=>(ka(t,e,"read from private field"),s?s.call(t):e.get(t)),jt=(t,e,s)=>e.has(t)?Do("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),wi=(t,e,s,r)=>(ka(t,e,"write to private field"),e.set(t,s),s),wn=(t,e,s)=>(ka(t,e,"access private method"),s),Ps,Q,Ut,xt,Bo,Go,Vo;let yd=class{constructor(e,s){jt(this,xt),jt(this,Ps),jt(this,Q),jt(this,Ut,new Map),wi(this,Ps,e),wi(this,Q,s)}publish(e,s){H(this,Ut).set(e,s),wn(this,xt,Bo).call(this,e,s)}async handleSubscribe(e){const s=e.trackNamespace,r=H(this,Ut).get(s);if(!r){const i=new ms(e.requestId,404,"Broadcast not found");await H(this,Q).write(i);return}const n=r.subscribe(e.trackName,e.subscriberPriority),a=new gs(e.requestId,e.requestId);await H(this,Q).write(a),wn(this,xt,Go).call(this,e.requestId,n)}async handleTrackStatusRequest(e){const s=new Bt(e.trackNamespace,e.trackName,Bt.STATUS_NOT_FOUND,0n,0n);await H(this,Q).write(s)}async handleUnsubscribe(e){}async handlePublishNamespaceOk(e){}async handlePublishNamespaceError(e){}async handlePublishNamespaceCancel(e){}async handleSubscribeNamespace(e){}async handleUnsubscribeNamespace(e){}};Ps=new WeakMap;Q=new WeakMap;Ut=new WeakMap;xt=new WeakSet;Bo=async function(t,e){try{const s=await H(this,Q).nextRequestId();if(s===void 0)return;const r=new fs(s,t);await H(this,Q).write(r),await e.closed;const n=new ws(t);await H(this,Q).write(n)}catch(s){const r=z(s);console.warn(`announce failed: broadcast=${t} error=${r.message}`)}finally{e.close(),H(this,Ut).delete(t)}};Go=async function(t,e){try{for(;;){const r=await e.nextGroup();if(!r)break;wn(this,xt,Vo).call(this,t,r)}const s=new Dt(t,200,"OK");await H(this,Q).write(s)}catch(s){const r=z(s),n=new Dt(t,500,r.message);await H(this,Q).write(n)}finally{e.close()}};Vo=async function(t,e){try{const s=await Zt.open(H(this,Ps)),r=new Fo(t,e.sequence,0,0,{hasExtensions:!1,hasSubgroup:!1,hasSubgroupObject:!1,hasEnd:!0});console.debug("sending group header",r),await r.encode(s);try{for(;;){const n=await Promise.race([e.readFrame(),s.closed]);if(!n)break;await new dt(n).encode(s,r.flags)}s.close()}catch(n){s.reset(z(n))}}finally{e.close()}};var Ho=t=>{throw TypeError(t)},$a=(t,e,s)=>e.has(t)||Ho("Cannot "+s),_=(t,e,s)=>($a(t,e,"read from private field"),s?s.call(t):e.get(t)),Ue=(t,e,s)=>e.has(t)?Ho("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),vd=(t,e,s,r)=>($a(t,e,"write to private field"),e.set(t,s),s),pi=(t,e,s)=>($a(t,e,"access private method"),s),ee,De,ot,Gt,lt,ze,is,zo,Xo;let gd=class{constructor(e){Ue(this,is),Ue(this,ee),Ue(this,De,new Set),Ue(this,ot,new Set),Ue(this,Gt,new Map),Ue(this,lt,new Map),Ue(this,ze,new Map),vd(this,ee,e)}announced(e=Qt()){const s=new ki(e);for(const r of _(this,De))r.startsWith(e)&&s.append({path:r,active:!0});return _(this,ot).add(s),pi(this,is,zo).call(this,s,e).finally(()=>{_(this,ot).delete(s)}),s}consume(e){const s=new Ln;return(async()=>{for(;;){const r=await s.requested();if(!r)break;pi(this,is,Xo).call(this,e,r)}})(),s}async handleSubscribeOk(e){const s=_(this,ze).get(e.requestId);s?s.resolve(e):console.warn("handleSubscribeOk unknown requestId",e.requestId)}async handleSubscribeError(e){const s=_(this,ze).get(e.requestId);s?s.reject(new Error(`SUBSCRIBE_ERROR: code=${e.errorCode} reason=${e.reasonPhrase}`)):console.warn("handleSubscribeError unknown requestId",e.requestId)}async handleGroup(e,s){const r=new Fn(e.groupId);e.subGroupId!==0&&console.warn("subgroup ID is not supported, ignoring");try{let n=_(this,lt).get(e.trackAlias);n===void 0&&(n=e.trackAlias,console.warn("unknown track alias, using request ID"));const a=_(this,Gt).get(n);if(!a)throw new Error(`unknown track: trackAlias=${e.trackAlias} requestId=${_(this,lt).get(e.trackAlias)}`);for(a.writeGroup(r);await Promise.race([s.done(),r.closed,a.closed])===!1;){const o=await dt.decode(s,e.flags);if(o.payload===void 0)break;r.writeFrame(o.payload)}r.close()}catch(n){const a=z(n);r.close(a),s.stop(a)}}async handlePublish(e){const s=new ls(e.requestId,500,"publish not supported");await _(this,ee).write(s)}async handlePublishDone(e){const s=_(this,ze).get(e.requestId);s&&s.reject(new Error(`PUBLISH_DONE: code=${e.statusCode} reason=${e.reasonPhrase}`))}async handlePublishNamespace(e){if(_(this,De).has(e.trackNamespace)){console.warn("duplicate PUBLISH_NAMESPACE message");return}_(this,De).add(e.trackNamespace);for(const s of _(this,ot))s.append({path:e.trackNamespace,active:!0})}async handlePublishNamespaceDone(e){if(!_(this,De).has(e.trackNamespace)){console.warn("unknown PUBLISH_NAMESPACE_DONE message");return}_(this,De).delete(e.trackNamespace);for(const s of _(this,ot))s.append({path:e.trackNamespace,active:!1})}async handleSubscribeNamespaceOk(e){}async handleSubscribeNamespaceError(e){throw new Error("SUBSCRIBE_NAMESPACE_ERROR messages are not supported")}async handleTrackStatus(e){throw new Error("TRACK_STATUS messages are not supported")}};ee=new WeakMap;De=new WeakMap;ot=new WeakMap;Gt=new WeakMap;lt=new WeakMap;ze=new WeakMap;is=new WeakSet;zo=async function(t,e){const s=await _(this,ee).nextRequestId();if(s!==void 0)try{_(this,ee).write(new ks(e,s)),await t.closed}finally{_(this,ee).write(new $s(s))}};Xo=async function(t,e){const s=await _(this,ee).nextRequestId();if(s===void 0)return;_(this,Gt).set(s,e.track);const r=new vs(s,t,e.track.name,e.priority),n=new Promise((a,i)=>{_(this,ze).set(s,{resolve:a,reject:i})});await _(this,ee).write(r);try{const a=await n;_(this,lt).set(a.trackAlias,s);try{await e.track.closed;const i=new Ss(s);await _(this,ee).write(i)}finally{_(this,lt).delete(a.trackAlias)}}catch(a){const i=z(a);e.track.close(i)}finally{_(this,Gt).delete(s),_(this,ze).delete(s)}};var md=Object.defineProperty,Jo=t=>{throw TypeError(t)},Sd=(t,e,s)=>e in t?md(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,kd=(t,e,s)=>Sd(t,e+"",s),Ea=(t,e,s)=>e.has(t)||Jo("Cannot "+s),l=(t,e,s)=>(Ea(t,e,"read from private field"),s?s.call(t):e.get(t)),Nt=(t,e,s)=>e.has(t)?Jo("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),es=(t,e,s,r)=>(Ea(t,e,"write to private field"),e.set(t,s),s),Ye=(t,e,s)=>(Ea(t,e,"access private method"),s),we,_e,V,O,he,Ko,Qo,Zo,Yo,jo,eh,th;let $d=class{constructor(e,s,r,n){Nt(this,he),kd(this,"url"),Nt(this,we),Nt(this,_e),Nt(this,V),Nt(this,O),this.url=e,es(this,we,s),es(this,_e,new pd(r,n)),l(this,we).closed.finally(()=>{l(this,_e).close()}),es(this,V,new yd(l(this,we),l(this,_e))),es(this,O,new gd(l(this,_e))),Ye(this,he,Ko).call(this)}close(){try{l(this,we).close()}catch{}}publish(e,s){l(this,V).publish(e,s)}announced(e=Qt()){return l(this,O).announced(e)}consume(e){return l(this,O).consume(e)}get closed(){return l(this,we).closed.then(()=>{})}};we=new WeakMap;_e=new WeakMap;V=new WeakMap;O=new WeakMap;he=new WeakSet;Ko=async function(){const t=Ye(this,he,Qo).call(this),e=Ye(this,he,eh).call(this);try{await Promise.all([t,e])}catch(s){console.error("fatal error running connection",s)}finally{this.close()}};Qo=async function(){for(;;)try{const t=await l(this,_e).read();if(t instanceof vs)await l(this,V).handleSubscribe(t);else if(t instanceof Ss)await l(this,V).handleUnsubscribe(t);else if(t instanceof dn)await l(this,V).handleTrackStatusRequest(t);else if(t instanceof Gr)await l(this,V).handlePublishNamespaceOk(t);else if(t instanceof Vr)await l(this,V).handlePublishNamespaceError(t);else if(t instanceof Hr)await l(this,V).handlePublishNamespaceCancel(t);else if(t instanceof fs)await l(this,O).handlePublishNamespace(t);else if(t instanceof ws)await l(this,O).handlePublishNamespaceDone(t);else if(t instanceof gs)await l(this,O).handleSubscribeOk(t);else if(t instanceof ms)await l(this,O).handleSubscribeError(t);else if(t instanceof Dt)await l(this,O).handlePublishDone(t);else if(t instanceof Bt)await l(this,O).handleTrackStatus(t);else if(t instanceof Ar)await Ye(this,he,Zo).call(this,t);else if(t instanceof bs)await Ye(this,he,Yo).call(this,t);else if(t instanceof ys)await Ye(this,he,jo).call(this,t);else if(t instanceof ks)await l(this,V).handleSubscribeNamespace(t);else if(t instanceof cn)await l(this,O).handleSubscribeNamespaceOk(t);else if(t instanceof on)await l(this,O).handleSubscribeNamespaceError(t);else if(t instanceof $s)await l(this,V).handleUnsubscribeNamespace(t);else if(t instanceof Ur)await l(this,O).handlePublish(t);else{if(t instanceof xr)throw new Error("PUBLISH_OK messages are not supported");if(t instanceof ls)throw new Error("PUBLISH_ERROR messages are not supported");if(t instanceof Pr)throw new Error("FETCH messages are not supported");if(t instanceof Ir)throw new Error("FETCH_OK messages are not supported");if(t instanceof Cr)throw new Error("FETCH_ERROR messages are not supported");if(t instanceof Nr)throw new Error("FETCH_CANCEL messages are not supported");t instanceof Jr?l(this,_e).maxRequestId(t.requestId):t instanceof Kr?console.warn("ignoring REQUESTS_BLOCKED message"):qu(t)}}catch(t){console.error("error processing control message",t);break}console.warn("control stream closed")};Zo=async function(t){console.warn(`MOQLITE_INCOMPATIBLE: Received GOAWAY with redirect URI: ${t.newSessionUri}`),this.close()};Yo=async function(t){console.error("Unexpected CLIENT_SETUP message received after connection established"),this.close()};jo=async function(t){console.error("Unexpected SERVER_SETUP message received after connection established"),this.close()};eh=async function(){const t=new zi(l(this,we));for(;;){const e=await t.next();if(!e)break;Ye(this,he,th).call(this,e).then(()=>{e.stop(new Error("cancel"))}).catch(s=>{e.stop(s)})}};th=async function(t){try{const e=await Fo.decode(t);console.debug("received group header",e),await l(this,O).handleGroup(e,t)}catch(e){console.error("error processing object stream",e)}};const Ed={DRAFT_14:4278190094},_i=Ed.DRAFT_14;async function J(t,e){let s=new Uint8Array;const r=new Zt(new WritableStream({write(n){const a=s.byteLength+n.byteLength;if(a>s.buffer.byteLength){const i=Math.max(a,s.buffer.byteLength*2),o=new ArrayBuffer(i),h=new Uint8Array(o,0,a);h.set(s),h.set(n,s.byteLength),s=h}else s=new Uint8Array(s.buffer,0,a),s.set(n,a-n.byteLength)}}));await e(r),r.close(),await r.closed,await t.u53(s.byteLength),await t.write(s)}async function G(t,e){const s=await t.u53(),r=await t.read(s),n=new Bs(void 0,r),a=await e(n);if(!await n.done())throw new Error("Message decoding consumed too few bytes");return a}async function Yt(t,e){if(!await t.done())return await G(t,e)}var Pd=Object.defineProperty,sh=t=>{throw TypeError(t)},Id=(t,e,s)=>e in t?Pd(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,Is=(t,e,s)=>Id(t,typeof e!="symbol"?e+"":e,s),Cd=(t,e,s)=>e.has(t)||sh("Cannot "+s),kt=(t,e,s)=>e.has(t)?sh("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),je=(t,e,s)=>(Cd(t,e,"access private method"),s),pn,rh,Cs,_n,bn,nh,Pa,ah,yn,ih,Ia,ch;const Ca=class vn{constructor(e,s){kt(this,pn),Is(this,"suffix"),Is(this,"active"),this.suffix=e,this.active=s}async encode(e){return J(e,je(this,pn,rh).bind(this))}static async decode(e){return G(e,je(vn,Cs,_n))}static async decodeMaybe(e){return Yt(e,je(vn,Cs,_n))}};pn=new WeakSet;rh=async function(t){await t.bool(this.active),await t.string(this.suffix)};Cs=new WeakSet;_n=async function(t){const e=await t.bool(),s=Y(await t.string());return new Ca(s,e)};kt(Ca,Cs);let gn=Ca;const Na=class oh{constructor(e){kt(this,bn),Is(this,"prefix"),this.prefix=e}async encode(e){return J(e,je(this,bn,nh).bind(this))}static async decode(e){return G(e,je(oh,Pa,ah))}};bn=new WeakSet;nh=async function(t){await t.string(this.prefix)};Pa=new WeakSet;ah=async function(t){const e=Y(await t.string());return new Na(e)};kt(Na,Pa);let hh=Na;const qa=class uh{constructor(e){kt(this,yn),Is(this,"suffixes"),this.suffixes=e}async encode(e){return J(e,je(this,yn,ih).bind(this))}static async decode(e){return G(e,je(uh,Ia,ch))}};yn=new WeakSet;ih=async function(t){await t.u53(this.suffixes.length);for(const e of this.suffixes)await t.string(e)};Ia=new WeakSet;ch=async function(t){const e=await t.u53(),s=[];for(let r=0;r<e;r++)s.push(Y(await t.string()));return new qa(s)};kt(qa,Ia);let dh=qa;var Nd=Object.defineProperty,lh=t=>{throw TypeError(t)},qd=(t,e,s)=>e in t?Nd(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ft=(t,e,s)=>qd(t,typeof e!="symbol"?e+"":e,s),Ad=(t,e,s)=>e.has(t)||lh("Cannot "+s),$t=(t,e,s)=>e.has(t)?lh("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),Se=(t,e,s)=>(Ad(t,e,"access private method"),s),mn,fh,Ns,Sn,kn,wh,qs,$n,En,ph,Aa,_h;const Wa=class Pn{constructor(e,s){$t(this,mn),ft(this,"subscribe"),ft(this,"sequence"),this.subscribe=e,this.sequence=s}async encode(e){return J(e,Se(this,mn,fh).bind(this))}static async decode(e){return G(e,Se(Pn,Ns,Sn))}static async decodeMaybe(e){return Yt(e,Se(Pn,Ns,Sn))}};mn=new WeakSet;fh=async function(t){await t.u62(this.subscribe),await t.u53(this.sequence)};Ns=new WeakSet;Sn=async function(t){return new Wa(await t.u62(),await t.u53())};$t(Wa,Ns);let bh=Wa;const yh=class In{constructor(e,s,r){$t(this,kn),ft(this,"sequence"),ft(this,"count"),ft(this,"error"),this.sequence=e,this.count=s,this.error=r}async encode(e){return J(e,Se(this,kn,wh).bind(this))}static async decode(e){return G(e,Se(In,qs,$n))}static async decodeMaybe(e){return Yt(e,Se(In,qs,$n))}};kn=new WeakSet;wh=async function(t){await t.u53(this.sequence),await t.u53(this.count),await t.u53(this.error)};qs=new WeakSet;$n=async function(t){return new yh(await t.u53(),await t.u53(),await t.u53())};$t(yh,qs);const vh=class gh{constructor(e){$t(this,En),ft(this,"payload"),this.payload=e}async encode(e){return J(e,Se(this,En,ph).bind(this))}static async decode(e){return G(e,Se(gh,Aa,_h))}};En=new WeakSet;ph=async function(t){await t.write(this.payload)};Aa=new WeakSet;_h=async function(t){const e=await t.readAll();return new vh(e)};$t(vh,Aa);var Wd=Object.defineProperty,mh=t=>{throw TypeError(t)},Md=(t,e,s)=>e in t?Wd(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,ht=(t,e,s)=>Md(t,typeof e!="symbol"?e+"":e,s),Od=(t,e,s)=>e.has(t)||mh("Cannot "+s),Et=(t,e,s)=>e.has(t)?mh("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),et=(t,e,s)=>(Od(t,e,"access private method"),s),Cn,Sh,As,Nn,qn,kh,Ma,$h,An,Eh,Oa,Ph;const Ta=class Wn{constructor(e){Et(this,Cn),ht(this,"priority"),this.priority=e}async encode(e){return J(e,et(this,Cn,Sh).bind(this))}static async decode(e){return G(e,et(Wn,As,Nn))}static async decodeMaybe(e){return Yt(e,et(Wn,As,Nn))}};Cn=new WeakSet;Sh=async function(t){await t.u8(this.priority)};As=new WeakSet;Nn=async function(t){const e=await t.u8();return new Ta(e)};Et(Ta,As);let bi=Ta;const Ua=class Ih{constructor(e,s,r,n){Et(this,qn),ht(this,"id"),ht(this,"broadcast"),ht(this,"track"),ht(this,"priority"),this.id=e,this.broadcast=s,this.track=r,this.priority=n}async encode(e){return J(e,et(this,qn,kh).bind(this))}static async decode(e){return G(e,et(Ih,Ma,$h))}};qn=new WeakSet;kh=async function(t){await t.u62(this.id),await t.string(this.broadcast),await t.string(this.track),await t.u8(this.priority)};Ma=new WeakSet;$h=async function(t){const e=await t.u62(),s=Y(await t.string()),r=await t.string(),n=await t.u8();return new Ua(e,s,r,n)};Et(Ua,Ma);let Ch=Ua;const xa=class Nh{constructor(e){Et(this,An),ht(this,"priority"),this.priority=e}async encode(e){return J(e,et(this,An,Eh).bind(this))}static async decode(e){return G(e,et(Nh,Oa,Ph))}};An=new WeakSet;Eh=async function(t){await t.u8(this.priority)};Oa=new WeakSet;Ph=async function(t){const e=await t.u8();return new xa(e)};Et(xa,Oa);let qh=xa;var Ah=t=>{throw TypeError(t)},Ra=(t,e,s)=>e.has(t)||Ah("Cannot "+s),Be=(t,e,s)=>(Ra(t,e,"read from private field"),s?s.call(t):e.get(t)),vr=(t,e,s)=>e.has(t)?Ah("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),Td=(t,e,s,r)=>(Ra(t,e,"write to private field"),e.set(t,s),s),Wh=(t,e,s)=>(Ra(t,e,"access private method"),s),Ws,fe,Ms,Mh,Oh;class Ud{constructor(e){vr(this,Ms),vr(this,Ws),vr(this,fe,new $(new Map)),Td(this,Ws,e)}publish(e,s){Be(this,fe).mutate(r=>{if(!r)throw new Error("closed");r.set(e,s)}),s.closed.finally(()=>{Be(this,fe).mutate(r=>{r==null||r.delete(e)})})}async runAnnounce(e,s){console.debug(`announce: prefix=${e.prefix}`);let r=new Set;const n=Be(this,fe).peek();if(!n)return;for(const i of n.keys()){const o=si(e.prefix,i);o!==null&&(console.debug(`announce: broadcast=${i} active=true`),r.add(o))}for(await new dh(r.values().toArray()).encode(s.writer);;){let i;const o=new Promise(w=>{i=Be(this,fe).changed(w)}),h=await Promise.race([o,s.reader.closed]);if(i(),!h)break;const v=new Set;for(const w of h.keys()){const M=si(e.prefix,w);M!==null&&v.add(M)}for(const w of v.difference(r))console.debug(`announce: broadcast=${w} active=true`),await new gn(w,!0).encode(s.writer);for(const w of r.difference(v))console.debug(`announce: broadcast=${w} active=false`),await new gn(w,!1).encode(s.writer);r=v}}async runSubscribe(e,s){var a;const r=(a=Be(this,fe).peek())==null?void 0:a.get(e.broadcast);if(!r){console.debug(`publish unknown: broadcast=${e.broadcast}`),s.writer.reset(new Error("not found"));return}const n=r.subscribe(e.track,e.priority);try{await new qh(e.priority).encode(s.writer),console.debug(`publish ok: broadcast=${e.broadcast} track=${n.name}`);const o=Wh(this,Ms,Mh).call(this,e.id,e.broadcast,n,s.writer);for(;;){const h=bi.decodeMaybe(s.reader),v=await Promise.any([o,h]);if(!v)break;v instanceof bi&&console.warn("subscribe update not supported",v)}console.debug(`publish done: broadcast=${e.broadcast} track=${n.name}`),s.close(),n.close()}catch(i){const o=z(i);console.warn(`publish error: broadcast=${e.broadcast} track=${n.name} error=${o.message}`),n.close(o),s.abort(o)}}close(){Be(this,fe).update(e=>{for(const s of(e==null?void 0:e.values())??[])s.close()})}}Ws=new WeakMap;fe=new WeakMap;Ms=new WeakSet;Mh=async function(t,e,s,r){try{for(;;){const n=s.nextGroup(),a=await Promise.race([n,r.closed]);if(!a){n.then(i=>i==null?void 0:i.close()).catch(()=>{});break}Wh(this,Ms,Oh).call(this,t,a)}console.debug(`publish close: broadcast=${e} track=${s.name}`),s.close(),r.close()}catch(n){const a=z(n);console.warn(`publish error: broadcast=${e} track=${s.name} error=${a.message}`),s.close(a),r.reset(a)}};Oh=async function(t,e){const s=new bh(t,e.sequence);try{const r=await Zt.open(Be(this,Ws));await r.u8(0),await s.encode(r);try{for(;;){const n=await Promise.race([e.readFrame(),r.closed]);if(!n)break;await r.u53(n.byteLength),await r.write(n)}r.close(),e.close()}catch(n){const a=z(n);r.reset(a),e.close(a)}}catch(r){const n=z(r);e.close(n)}};var xd=Object.defineProperty,Th=t=>{throw TypeError(t)},Rd=(t,e,s)=>e in t?xd(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,St=(t,e,s)=>Rd(t,typeof e!="symbol"?e+"":e,s),Fd=(t,e,s)=>e.has(t)||Th("Cannot "+s),Pt=(t,e,s)=>e.has(t)?Th("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),tt=(t,e,s)=>(Fd(t,e,"access private method"),s),Mn,Uh,Fa,xh,On,Rh,La,Fh,Tn,Lh,Os,Un;const Ld={LITE_01:4279086337},yi=Ld.LITE_01;class It{constructor(){St(this,"entries"),this.entries=new Map}set(e,s){this.entries.set(e,s)}get(e){return this.entries.get(e)}remove(e){const s=this.entries.get(e);return this.entries.delete(e),s}async encode(e){await e.u53(this.entries.size);for(const[s,r]of this.entries)await e.u62(s),await e.u53(r.length),await e.write(r)}static async decode(e){const s=await e.u53(),r=new It;for(let n=0;n<s;n++){const a=await e.u62(),i=await e.u53(),o=await e.read(i);if(r.entries.has(a))throw new Error(`duplicate parameter id: ${a.toString()}`);r.entries.set(a,o)}return r}}const Dh=class Bh{constructor(e,s=new It){Pt(this,Mn),St(this,"versions"),St(this,"extensions"),this.versions=e,this.extensions=s}async encode(e){return J(e,tt(this,Mn,Uh).bind(this))}static async decode(e){return G(e,tt(Bh,Fa,xh))}};Mn=new WeakSet;Uh=async function(t){await t.u53(this.versions.length);for(const e of this.versions)await t.u53(e);await this.extensions.encode(t)};Fa=new WeakSet;xh=async function(t){const e=[],s=await t.u53();for(let n=0;n<s;n++)e.push(await t.u53());const r=await It.decode(t);return new Dh(e,r)};Pt(Dh,Fa);const Gh=class Vh{constructor(e,s=new It){Pt(this,On),St(this,"version"),St(this,"extensions"),this.version=e,this.extensions=s}async encode(e){return J(e,tt(this,On,Rh).bind(this))}static async decode(e){return G(e,tt(Vh,La,Fh))}};On=new WeakSet;Rh=async function(t){await t.u53(this.version),await this.extensions.encode(t)};La=new WeakSet;Fh=async function(t){const e=await t.u53(),s=await It.decode(t);return new Gh(e,s)};Pt(Gh,La);const Da=class xn{constructor(e){Pt(this,Tn),St(this,"bitrate"),this.bitrate=e}async encode(e){return J(e,tt(this,Tn,Lh).bind(this))}static async decode(e){return G(e,tt(xn,Os,Un))}static async decodeMaybe(e){return Yt(e,tt(xn,Os,Un))}};Tn=new WeakSet;Lh=async function(t){await t.u53(this.bitrate)};Os=new WeakSet;Un=async function(t){const e=await t.u53();return new Da(e)};Pt(Da,Os);let Dd=Da;const st={Session:0,Announce:1,Subscribe:2,ClientCompat:32,ServerCompat:33};var Hh=t=>{throw TypeError(t)},Ba=(t,e,s)=>e.has(t)||Hh("Cannot "+s),oe=(t,e,s)=>(Ba(t,e,"read from private field"),s?s.call(t):e.get(t)),ts=(t,e,s)=>e.has(t)?Hh("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),zh=(t,e,s,r)=>(Ba(t,e,"write to private field"),e.set(t,s),s),vi=(t,e,s)=>(Ba(t,e,"access private method"),s),Bd=(t,e,s,r)=>({set _(n){zh(t,e,n)},get _(){return oe(t,e,r)}}),Vt,Xe,Ts,cs,Xh,Jh;class Gd{constructor(e){ts(this,cs),ts(this,Vt),ts(this,Xe,new Map),ts(this,Ts,0n),zh(this,Vt,e)}announced(e=Qt()){const s=new ki;return vi(this,cs,Xh).call(this,s,e),s}consume(e){const s=new Ln;return(async()=>{for(;;){const r=await s.requested();if(!r)break;vi(this,cs,Jh).call(this,e,r)}})(),s}async runGroup(e,s){const r=oe(this,Xe).get(e.subscribe);if(!r){if(e.subscribe>=oe(this,Ts))throw new Error(`unknown subscription: id=${e.subscribe}`);return}const n=new Fn(e.sequence);r.writeGroup(n);try{for(;await Promise.race([s.done(),r.closed,n.closed])===!1;){const i=await s.u53(),o=await s.read(i);if(!o)break;n.writeFrame(o)}n.close(),s.stop(new Error("cancel"))}catch(a){const i=z(a);n.close(i),s.stop(i)}}close(){for(const e of oe(this,Xe).values())e.close();oe(this,Xe).clear()}}Vt=new WeakMap;Xe=new WeakMap;Ts=new WeakMap;cs=new WeakSet;Xh=async function(t,e){console.debug(`announced: prefix=${e}`);const s=new hh(e);try{const r=await Ds.open(oe(this,Vt));await r.writer.u53(st.Announce),await s.encode(r.writer);const n=await dh.decode(r.reader);for(const a of n.suffixes){const i=ri(e,a);console.debug(`announced: broadcast=${i} active=true`),t.append({path:i,active:!0})}for(;;){const a=await Promise.race([gn.decodeMaybe(r.reader),t.closed]);if(!a)break;if(a instanceof Error)throw a;const i=ri(e,a.suffix);console.debug(`announced: broadcast=${i} active=${a.active}`),t.append({path:i,active:a.active})}t.close()}catch(r){t.close(z(r))}};Jh=async function(t,e){const s=Bd(this,Ts)._++;oe(this,Xe).set(s,e.track),console.debug(`subscribe start: id=${s} broadcast=${t} track=${e.track.name}`);const r=new Ch(s,t,e.track.name,e.priority),n=await Ds.open(oe(this,Vt));await n.writer.u53(st.Subscribe),await r.encode(n.writer);try{await qh.decode(n.reader),console.debug(`subscribe ok: id=${s} broadcast=${t} track=${e.track.name}`),await Promise.race([n.reader.closed,e.track.closed]),e.track.close(),n.close(),console.debug(`subscribe close: id=${s} broadcast=${t} track=${e.track.name}`)}catch(a){const i=z(a);e.track.close(i),console.warn(`subscribe error: id=${s} broadcast=${t} track=${e.track.name} error=${i.message}`),n.abort(i)}finally{oe(this,Xe).delete(s)}};var Vd=Object.defineProperty,Kh=t=>{throw TypeError(t)},Hd=(t,e,s)=>e in t?Vd(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,zd=(t,e,s)=>Hd(t,e+"",s),Ga=(t,e,s)=>e.has(t)||Kh("Cannot "+s),N=(t,e,s)=>(Ga(t,e,"read from private field"),s?s.call(t):e.get(t)),nt=(t,e,s)=>e.has(t)?Kh("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,s),qt=(t,e,s,r)=>(Ga(t,e,"write to private field"),e.set(t,s),s),wt=(t,e,s)=>(Ga(t,e,"access private method"),s),ie,Us,Je,Ge,Rt,ke,Qh,Zh,Yh,jh,eu,tu;class Xd{constructor(e,s,r){nt(this,ke),zd(this,"url"),nt(this,ie),nt(this,Us),nt(this,Je),nt(this,Ge),nt(this,Rt,!1),this.url=e,qt(this,ie,s),qt(this,Us,r),qt(this,Je,new Ud(N(this,ie))),qt(this,Ge,new Gd(N(this,ie))),wt(this,ke,Qh).call(this)}close(){if(!N(this,Rt)){qt(this,Rt,!0),N(this,Je).close(),N(this,Ge).close();try{N(this,ie).close()}catch{}}}publish(e,s){N(this,Je).publish(e,s)}announced(e=Qt()){return N(this,Ge).announced(e)}consume(e){return N(this,Ge).consume(e)}get closed(){return N(this,ie).closed.then(()=>{})}}ie=new WeakMap;Us=new WeakMap;Je=new WeakMap;Ge=new WeakMap;Rt=new WeakMap;ke=new WeakSet;Qh=async function(){const t=wt(this,ke,Zh).call(this),e=wt(this,ke,Yh).call(this),s=wt(this,ke,eu).call(this);try{await Promise.all([t,e,s])}catch(r){N(this,Rt)||console.error("fatal error running connection",r)}finally{this.close()}};Zh=async function(){try{for(;await Dd.decodeMaybe(N(this,Us).reader););}finally{console.warn("session stream closed")}};Yh=async function(){for(;;){const t=await Ds.accept(N(this,ie));if(!t)break;wt(this,ke,jh).call(this,t).catch(e=>{t.writer.reset(e)}).finally(()=>{t.writer.close()})}};jh=async function(t){const e=await t.reader.u53();if(e===st.Session)throw new Error("duplicate session stream");if(e===st.Announce){const s=await hh.decode(t.reader);await N(this,Je).runAnnounce(s,t);return}else if(e===st.Subscribe){const s=await Ch.decode(t.reader);await N(this,Je).runSubscribe(s,t);return}else throw new Error(`unknown stream type: ${e.toString()}`)};eu=async function(){const t=new zi(N(this,ie));for(;;){const e=await t.next();if(!e)break;wt(this,ke,tu).call(this,e).then(()=>{e.stop(new Error("cancel"))}).catch(s=>{e.stop(s)})}};tu=async function(t){const e=await t.u8();if(e===0){const s=await bh.decode(t);await N(this,Ge).runGroup(s,t)}else throw new Error(`unknown stream type: ${e.toString()}`)};function Jd(t){if(t=t.startsWith("0x")?t.slice(2):t,t.length%2)throw new Error("invalid hex string length");const e=t.match(/.{2}/g);if(!e)throw new Error("invalid hex string format");return new Uint8Array(e.map(s=>parseInt(s,16)))}const gi=new Set;async function Kd(t,e){var Ja,Ka,Qa;let s;const r=new Promise(pr=>{s=pr}),n=globalThis.WebTransport?Qd(t,r,e==null?void 0:e.webtransport):void 0,a=!n||gi.has(t.toString())?0:((Ja=e==null?void 0:e.websocket)==null?void 0:Ja.delay)??200,i=((Ka=e==null?void 0:e.websocket)==null?void 0:Ka.enabled)!==!1?Zd(((Qa=e==null?void 0:e.websocket)==null?void 0:Qa.url)??t,a,r):void 0;if(!i&&!n)throw new Error("no transport available; WebTransport not supported and WebSocket is disabled");const o=await Promise.any(n?i?[i,n]:[n]:[i]);if(s&&s(),!o)throw new Error("no transport available");o instanceof hs&&(console.warn(t.toString(),"using WebSocket fallback; the user experience may be degraded"),gi.add(t.toString()));const h=await Ds.open(o);await h.writer.u53(st.ClientCompat);const v=new TextEncoder,w=new X;w.setVarint(yr.MaxRequestId,42069n),w.setBytes(yr.Implementation,v.encode("moq-lite-js"));const M=new bs([yi,_i],w);console.debug(t.toString(),"sending client setup",M),await M.encode(h.writer);const Xa=await h.reader.u53();if(Xa!==st.ServerCompat)throw new Error(`unsupported server message type: ${Xa.toString()}`);const Ct=await ys.decode(h.reader);if(console.debug(t.toString(),"received server setup",Ct),Ct.version===yi)return console.debug(t.toString(),"moq-lite session established"),new Xd(t,o,h);if(Ct.version===_i){const pr=Ct.parameters.getVarint(yr.MaxRequestId)??0n;return console.debug(t.toString(),"moq-ietf session established"),new $d(t,o,h,pr)}else throw new Error(`unsupported server version: ${Ct.version.toString()}`)}async function Qd(t,e,s){let r=t;const n={allowPooling:!1,congestionControl:"low-latency",...s};if(t.protocol==="http:"){const o=new URL(t);o.pathname="/certificate.sha256",o.search="",console.warn(o.toString(),"performing an insecure fingerprint fetch; use https:// in production");const h=await Promise.race([fetch(o),e]);if(!h)return;const v=await Promise.race([h.text(),e]);if(v===void 0)return;n.serverCertificateHashes=(n.serverCertificateHashes||[]).concat([{algorithm:"sha-256",value:Jd(v)}]),r=new URL(t),r.protocol="https:"}const a=new WebTransport(r,n);if(!await Promise.race([a.ready.then(()=>!0),e])){a.close();return}return a}async function Zd(t,e,s){const r=new Promise(o=>setTimeout(o,e));if(!await Promise.race([s,r.then(()=>!0)]))return;e&&console.debug(t.toString(),`no WebTransport after ${e}ms, attempting WebSocket fallback`);const a=new hs(t);if(!await Promise.race([a.ready.then(()=>!0),s])){a.close();return}return a}var Yd=Object.defineProperty,jd=(t,e,s)=>e in t?Yd(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,el=(t,e,s)=>jd(t,e+"",s);class Va{constructor(){el(this,"listeners",new Map)}emit(e,...s){const r=this.listeners.get(e);if(!r||r.size===0)return!1;for(const n of r)try{n(...s)}catch(a){console.error("Error in event listener:",a)}return!0}on(e,s){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(s),this}once(e,s){const r=(...n)=>{this.off(e,r),s(...n)};return this.on(e,r)}off(e,s){const r=this.listeners.get(e);return r&&(r.delete(s),r.size===0&&this.listeners.delete(e)),this}removeListener(e,s){return this.off(e,s)}addListener(e,s){return this.on(e,s)}removeAllListeners(e){return e===void 0?this.listeners.clear():this.listeners.delete(e),this}listenerCount(e){var s;return((s=this.listeners.get(e))==null?void 0:s.size)||0}eventNames(){return Array.from(this.listeners.keys())}}var tl=Object.defineProperty,sl=(t,e,s)=>e in t?tl(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,me=(t,e,s)=>sl(t,typeof e!="symbol"?e+"":e,s);class rl{constructor(e,s){me(this,"group"),me(this,"track"),me(this,"bytesSent",0),me(this,"config"),this.track=e,this.config=s}send(e,s){var r;try{(s||!this.group)&&((r=this.group)==null||r.close(),this.group=this.track.appendGroup()),this.group.writeFrame(e),this.bytesSent+=e.byteLength}catch{}}updateTrack(e){this.track=e}dispose(){var e;(e=this.group)==null||e.close(),this.track.close()}}class nl extends Va{constructor(e,s,r){super(),me(this,"connection"),me(this,"broadcast"),me(this,"broadcasts",new Map),me(this,"catalogTrack"),this.connection=s,this.broadcast=new Ln,this.connection.publish(e,this.broadcast),this.runTrackRequests().catch(n=>{this.emit("error",n)});for(const n of r)this.addBroadcast(n);this.updateCatalog()}dispose(){this.removeAllListeners();for(const e of this.broadcasts.values())e.dispose();this.broadcasts.clear(),this.broadcast.close()}addBroadcast(e){const s=new rl(new Pi(e.trackName),e);this.broadcasts.set(e.trackName,s)}async runTrackRequests(){for(;;){const e=await this.broadcast.requested();if(!e)return;if(e.track.name==="catalog.json"){this.catalogTrack=e.track,this.updateCatalog();continue}const s=this.broadcasts.get(e.track.name);s&&(s.updateTrack(e.track),this.emit("trackRequested",e.track.name))}}updateCatalog(){var s;const e={tracks:[]};e.tracks=[...this.broadcasts.values()].map(r=>({trackName:r.config.trackName,type:r.config.type,priority:r.config.priority||0})),(s=this.catalogTrack)==null||s.writeJson(e)}async send(e,s,r){const n=this.broadcasts.get(e);return n==null?void 0:n.send(s,r)}}var A=(t=>(t.DISCONNECTED="disconnected",t.CONNECTING="connecting",t.CONNECTED="connected",t.RECONNECTING="reconnecting",t.FAILED="failed",t))(A||{}),su=(t=>(t.IDLE="idle",t.BROADCASTING="broadcasting",t.ERROR="error",t))(su||{}),Ft=(t=>(t.IDLE="idle",t.SUBSCRIBED="subscribed",t.FAILED="failed",t))(Ft||{}),al=Object.defineProperty,il=(t,e,s)=>e in t?al(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,re=(t,e,s)=>il(t,typeof e!="symbol"?e+"":e,s);class cl extends Va{constructor(e,s,r=[],n){super(),re(this,"connection"),re(this,"broadcast"),re(this,"namespace"),re(this,"catalogTrack"),re(this,"catalog",{tracks:[]}),re(this,"enabled_",!1),re(this,"requestedSubscriptions",new Map),re(this,"subscriptions",new Map),re(this,"dataCallback"),this.connection=s,this.namespace=e,this.dataCallback=n,this.broadcast=this.connection.consume(this.namespace),console.log("Subscription manager created for namespace:",this.namespace,r);for(const a of r)this.requestedSubscriptions.set(a.trackName,a)}set enabled(e){this.enabled_!==e&&(this.enabled_=e,e&&this.runCatalog().catch(s=>{this.emit("error",s)}))}get enabled(){return this.enabled_}async runCatalog(){if(this.catalogTrack=await this.broadcast.subscribe("catalog.json",0),!this.catalogTrack)throw new Error("Failed to subscribe to catalog track");for(;;){console.log("Waiting for catalog update...");const e=await this.catalogTrack.readJson();if(e)console.log("Received catalog update:",e),this.updateCatalog(e);else return}}updateCatalog(e){this.catalog=e,this.checkSubscriptions()}setDataCallback(e){this.dataCallback=e}dispose(){var e,s;this.removeAllListeners();for(const r of this.subscriptions.values())r.track.close();(e=this.catalogTrack)==null||e.close(),(s=this.broadcast)==null||s.close()}checkSubscriptions(){const e=new Set(this.requestedSubscriptions.keys()),s=new Set(this.subscriptions.keys()),r=this.catalog.tracks.map(n=>n.trackName);console.log("Checking subscriptions. Desired:",e,"Current:",s,"Available:",r);for(const n of s)(!e.has(n)||!r.includes(n))&&this.removeSubscription(n);for(const n of e)if(!s.has(n)&&r.includes(n)){const a=this.requestedSubscriptions.get(n);this.addSubscription(n,a).catch(i=>{this.emit("error",i)})}}removeSubscription(e){const s=this.subscriptions.get(e);s&&(s.track.close(),this.subscriptions.delete(e),this.emit("stateChange",{state:Ft.IDLE,trackName:e,bytesReceived:0}))}async addSubscription(e,s){const r=this.broadcast.subscribe(e,s.priority??0);let n=-1;if(r)for(this.subscriptions.set(e,{track:r,config:s}),this.emit("stateChange",{state:Ft.SUBSCRIBED,trackName:e,bytesReceived:0});;){const a=await r.nextGroup();if(!a)return;try{if(a.sequence<=n){console.log(`Skipping out-of-order group on track "${e}": ${a.sequence} <= ${n}`),a.close();continue}for(;;){const i=await a.readFrame();if(!i)break;n=a.sequence,this.dataCallback&&this.dataCallback(e,i)}}catch(i){console.log("Error processing group on track:",e,i)}finally{a.close()}}else console.warn(`Failed to subscribe to track: ${e}`),this.emit("stateChange",{state:Ft.FAILED,trackName:e,bytesReceived:0,lastError:new Error(`Failed to subscribe to track: ${e}`)})}}var ol=Object.defineProperty,hl=(t,e,s)=>e in t?ol(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,W=(t,e,s)=>hl(t,typeof e!="symbol"?e+"":e,s);class Ha extends Va{constructor(e){var s;super(),W(this,"url"),W(this,"reconnectAttempts",0),W(this,"lastError"),W(this,"connectedAt"),W(this,"reconnectTimer"),W(this,"doReconnect",!0),W(this,"disposed",!1),W(this,"state",A.DISCONNECTED),W(this,"connection"),W(this,"config"),this.config={...e,reconnection:{delay:Math.max(((s=e.reconnection)==null?void 0:s.delay)||1e3,1e3)},connectionTimeout:e.connectionTimeout||1e4},this.url=new URL(this.config.relayUrl)}get status(){return{state:this.state,reconnectAttempts:this.reconnectAttempts,lastError:this.lastError,connectedAt:this.connectedAt}}async connect(){if(this.disposed)throw new Error("Cannot connect a disposed session");if(!(this.state===A.CONNECTING||this.state===A.CONNECTED)){this.setState(A.CONNECTING);try{this.doReconnect=!0,this.connection=await Kd(this.url,{websocket:{enabled:!1}}),this.setState(A.CONNECTED),this.connectedAt=new Date,this.reconnectAttempts=0,this.connection.closed.then(()=>{this.handleDisconnected()}),this.startAnnouncementDiscovery(),this.handleConnected()}catch(e){const s=new Error(`Failed to connect to relay: ${e.message}`);throw this.handleError(s),this.scheduleReconnect(),s}}}disconnect(){if(this.state!==A.DISCONNECTED){if(this.doReconnect=!1,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0),this.connection){try{this.connection.close()}catch(e){console.warn("Error closing connection:",e)}this.connection=void 0}this.setState(A.DISCONNECTED),this.connectedAt=void 0}}async startAnnouncementDiscovery(){if(this.connection)try{const e=Y(this.config.namespace),s=this.connection.announced(e);this.processAnnouncements(s)}catch(e){console.error("Failed to start announcement discovery:",e)}}async processAnnouncements(e){try{for(;!this.disposed;){const s=await e.next();if(!s||this.disposed)break;s.active?this.handleAnnounced(s.path):this.handleUnannounced(s.path)}}catch{}}handleDisconnected(){this.disposed||(this.setState(A.DISCONNECTED),this.scheduleReconnect())}scheduleReconnect(){var s;if(this.disposed||!this.config.reconnection||!this.doReconnect)return;const e=((s=this.config.reconnection)==null?void 0:s.delay)||1e3;this.setState(A.RECONNECTING),this.reconnectAttempts++,this.reconnectTimer=setTimeout(()=>{this.disposed||!this.doReconnect||this.state===A.RECONNECTING&&this.connect().catch(r=>{console.error("Reconnection failed:",r)})},e)}setState(e){this.disposed||this.state!==e&&(this.state=e,this.emit("stateChange",this.status))}handleError(e){this.disposed||(this.lastError=e,this.emit("error",e))}dispose(){this.disposed=!0,this.doReconnect=!1,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0);try{this.disconnect()}catch(e){console.warn("Error during disconnect in dispose:",e)}this.removeAllListeners()}}class ul extends Ha{constructor(e,s){super(e),W(this,"subscriptionManager"),W(this,"subscriptions",[]),W(this,"wasUnannounced",!1),W(this,"discoveryOnly"),this.subscriptions=s,this.discoveryOnly=e.discoveryOnly??!1}dispose(){var e;super.dispose(),(e=this.subscriptionManager)==null||e.dispose()}updateSubscriptions(e){this.subscriptions=e,!this.discoveryOnly&&this.subscriptionManager&&this.state===A.CONNECTED&&this.setupSubscriptionManager()}addSubscription(e){if(this.discoveryOnly)return;const s=this.subscriptions.findIndex(r=>r.trackName===e.trackName);s>=0?this.subscriptions[s]=e:this.subscriptions.push(e),this.subscriptionManager&&this.state===A.CONNECTED&&this.setupSubscriptionManager()}removeSubscription(e){this.discoveryOnly||(this.subscriptions=this.subscriptions.filter(s=>s.trackName!==e),this.subscriptionManager&&this.state===A.CONNECTED&&this.setupSubscriptionManager())}handleConnected(){}setupSubscriptionManager(){this.subscriptionManager&&this.subscriptionManager.dispose();const e=(s,r)=>{this.emit("data",s,r)};this.subscriptionManager=new cl(Y(this.config.namespace),this.connection,this.subscriptions,e),this.subscriptionManager.on("error",s=>this.emit("error",s)),this.subscriptionManager.on("stateChange",s=>this.emit("subscriptionStateChange",s.trackName,s)),this.subscriptionManager.enabled=!0}handleDisconnected(){var e;super.handleDisconnected(),(e=this.subscriptionManager)==null||e.dispose()}handleAnnounced(e){if(this.emit("broadcastAnnounced",{path:e,active:!0}),this.discoveryOnly)return;const s=Y(this.config.namespace);e.startsWith(s)&&setTimeout(()=>{this.setupSubscriptionManager(),this.wasUnannounced=!1},this.wasUnannounced?3e3:100)}handleUnannounced(e){var r;if(this.emit("broadcastAnnounced",{path:e,active:!1}),this.discoveryOnly)return;const s=Y(this.config.namespace);e.startsWith(s)&&((r=this.subscriptionManager)==null||r.dispose(),this.subscriptionManager=void 0,this.wasUnannounced=!0)}}class dl extends Ha{constructor(e,s){super(e),W(this,"broadcastManager"),W(this,"broadcasts",[]),this.broadcasts=s}dispose(){var e;super.dispose(),(e=this.broadcastManager)==null||e.dispose()}setupBroadcastManager(){this.broadcastManager&&this.broadcastManager.dispose(),this.broadcastManager=new nl(Y(this.config.namespace),this.connection,this.broadcasts),this.broadcastManager.on("error",e=>this.emit("error",e))}handleConnected(){this.setupBroadcastManager()}handleDisconnected(){var e;super.handleDisconnected(),(e=this.broadcastManager)==null||e.dispose()}handleAnnounced(e){}handleUnannounced(e){}send(e,s,r){if(!this.broadcastManager)throw new Error("Broadcast manager not initialized");if(this.state!==A.CONNECTED)throw new Error("Cannot send data when session is not connected");this.broadcastManager.send(e,s,r)}}exports.BroadcastState=su;exports.MoQSession=Ha;exports.MoqSessionBroadcaster=dl;exports.MoqSessionSubscriber=ul;exports.SessionState=A;exports.SubscriptionState=Ft;
3
3
  //# sourceMappingURL=index.cjs.map