openrtc 2.8.9 → 2.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/BrowserManagedBroadcastHost-FTKYCKLF.js +1 -0
- package/dist/{IpcRuntimeAdapter-Cp2QsHX2.d.ts → IpcRuntimeAdapter-BVTYrfIe.d.ts} +2 -0
- package/dist/{NativeManagedBroadcastHost-WCQ6TPUU.js → NativeManagedBroadcastHost-6A2QP3A7.js} +1 -1
- package/dist/NativeProjectionBroker-2OH2SCPF.js +1 -0
- package/dist/WasmBridge-QUACJ7JY.js +1 -0
- package/dist/chunk-3B4IDT2M.js +1 -0
- package/dist/{chunk-T3G55YPI.js → chunk-3PDMPSVP.js} +1 -1
- package/dist/{chunk-H4XCP4Z4.js → chunk-6CHYSTXL.js} +1 -1
- package/dist/chunk-7KWWA3M6.js +2 -0
- package/dist/{chunk-EUVLZSGT.js → chunk-BG7VCJ5V.js} +1 -1
- package/dist/chunk-COXQYBTI.js +1 -0
- package/dist/chunk-FIWTJQJA.js +2 -0
- package/dist/{chunk-LLZT3MR6.js → chunk-FKAQDDUM.js} +1 -1
- package/dist/chunk-ONV44QWS.js +1 -0
- package/dist/{chunk-RCQ6MLBL.js → chunk-Q7ZKAI5S.js} +1 -1
- package/dist/chunk-RT7YTAXU.js +1 -0
- package/dist/chunk-WALOTASO.js +2 -0
- package/dist/chunk-XK2JESZY.js +2 -0
- package/dist/chunk-ZFSJ2LEF.js +1 -0
- package/dist/controlPlane-HPGXZDDD.js +1 -0
- package/dist/deviceEnrollment-ZRMFBH5R.js +2 -0
- package/dist/deviceHandle-R7WWNAG7.js +1 -0
- package/dist/index.js +1 -1
- package/dist/ipcFactory-FYLQKIJ2.js +1 -0
- package/dist/native.js +1 -1
- package/dist/node.js +2 -2
- package/dist/{openrtc-H2DETG65.js → openrtc-K6B3ZZIG.js} +1 -1
- package/dist/openrtc_bg.wasm +0 -0
- package/dist/room-QWTKWEAZ.js +1 -0
- package/dist/runtime/WasmRuntimeAdapter.js +1 -1
- package/dist/runtime/factories.d.ts +1 -1
- package/dist/runtime/factories.js +1 -1
- package/dist/runtime/index.d.ts +1 -1
- package/dist/runtime/index.js +1 -1
- package/dist/server.js +1 -1
- package/dist/service-node.js +1 -1
- package/dist/testing/native.js +1 -1
- package/dist/testing.d.ts +20 -1
- package/dist/testing.js +1 -1
- package/native/darwin-arm64/openrtc-node-host +0 -0
- package/native/darwin-arm64/openrtc-node-host.manifest.json +4 -4
- package/native/darwin-x64/openrtc-node-host +0 -0
- package/native/darwin-x64/openrtc-node-host.manifest.json +4 -4
- package/native/linux-x64/openrtc-node-host +0 -0
- package/native/linux-x64/openrtc-node-host.manifest.json +4 -4
- package/package.json +1 -1
- package/dist/BrowserManagedBroadcastHost-ARCP5MGJ.js +0 -1
- package/dist/WasmBridge-QNS6SWNZ.js +0 -1
- package/dist/chunk-577A77JB.js +0 -2
- package/dist/chunk-67RYEH6T.js +0 -1
- package/dist/chunk-ESBROG6S.js +0 -2
- package/dist/chunk-IR5VXG3N.js +0 -1
- package/dist/chunk-LAL63F6X.js +0 -2
- package/dist/chunk-OC4VXLX7.js +0 -1
- package/dist/chunk-WD2FZUOM.js +0 -1
- package/dist/chunk-WD47V4PK.js +0 -2
- package/dist/controlPlane-C5RUPLAM.js +0 -1
- package/dist/deviceEnrollment-27EVK3E3.js +0 -2
- package/dist/deviceHandle-2T6HQ253.js +0 -1
- package/dist/ipcFactory-DOEPQPOP.js +0 -1
- package/dist/room-JIU2XJZX.js +0 -1
|
@@ -115,4 +115,4 @@ class OpenRtcAudioCaptureProcessor extends AudioWorkletProcessor {
|
|
|
115
115
|
}
|
|
116
116
|
}
|
|
117
117
|
registerProcessor('openrtc-audio-capture', OpenRtcAudioCaptureProcessor);
|
|
118
|
-
`;function ne(i){return URL.createObjectURL(new Blob([i],{type:"text/javascript"}))}function ie(i){if(typeof Worker!="function")throw new Error("[OpenRTC] Dedicated workers are unavailable for the browser video edge.");let e=ne(i);try{return {worker:new Worker(e),url:e}}catch(t){throw URL.revokeObjectURL(e),t}}async function we(i){if(typeof i.clone!="function")throw new Error("[OpenRTC] The browser cannot clone a video track for its worker media edge.");let{worker:e,url:t}=ie(fe),r=null,l,s,a=new Promise((o,c)=>{l=o,s=c;}),n=new ReadableStream({start(o){r=o;},pull(){e.postMessage({type:"read"});},cancel(o){e.postMessage({type:"cancel",reason:String(o??"")}),e.terminate();}},{highWaterMark:0});e.onmessage=({data:o})=>{if(o?.type==="ready")l();else if(o?.type==="frame")r?.enqueue(o.frame);else if(o?.type==="done")r?.close(),e.terminate();else if(o?.type==="error"){let c=new Error(`[OpenRTC] Browser video worker failed: ${o.message}`);s(c),r?.error(c),e.terminate();}},e.onerror=o=>{let c=new Error(`[OpenRTC] Browser video worker failed: ${o.message}`);s(c),r?.error(c),e.terminate();};let d=i.clone();e.postMessage({type:"start",track:d},[d]);try{await a;}finally{URL.revokeObjectURL(t);}return {readable:n}}async function ve(i){let e=globalThis,t=e.AudioContext??e.webkitAudioContext,r=e.AudioData;if(typeof t!="function"||typeof r!="function")throw new Error("[OpenRTC] Web Audio and AudioData are required for browser audio capture.");let l=i.getSettings?.()??{},s=Number(l.sampleRate??48e3),a=Math.max(1,Math.min(2,Number(l.channelCount??1))),n=new t({sampleRate:s}),d=Number(n.sampleRate??s),o=ne(ye);try{await n.audioWorklet.addModule(o);}catch(f){throw await n.close(),f}finally{URL.revokeObjectURL(o);}await n.resume();let c=n.createMediaStreamSource(new MediaStream([i])),m=new AudioWorkletNode(n,"openrtc-audio-capture",{numberOfInputs:1,numberOfOutputs:1,channelCount:a,channelCountMode:"explicit",channelInterpretation:"speakers",outputChannelCount:[a],processorOptions:{channels:a,framesPerChunk:Math.max(1,Math.round(d/50))}}),y=n.createGain();y.gain.value=0,c.connect(m).connect(y).connect(n.destination);let k=false,w=async()=>{k||(k=true,m.port.onmessage=null,c.disconnect(),m.disconnect(),y.disconnect(),i.removeEventListener?.("ended",v),await n.close());},A=null,v=()=>{A?.close(),w();};return i.addEventListener?.("ended",v,{once:true}),{readable:new ReadableStream({start(f){A=f,m.port.onmessage=({data:u})=>{if(!(f.desiredSize!==null&&f.desiredSize<=0))try{f.enqueue(new r({format:"f32-planar",sampleRate:d,numberOfFrames:u.frames,numberOfChannels:a,timestamp:Math.round(u.timestampFrames*1e6/d),data:u.planar}));}catch(O){f.error(O);}};},cancel:w},{highWaterMark:2})}}async function ae(i){let e=globalThis.MediaStreamTrackProcessor;return typeof e=="function"?he(i,e):i.kind==="video"?we(i):ve(i)}async function ge(){let{worker:i,url:e}=ie(be),t,r,l=new Promise((c,m)=>{t=c,r=m;}),s=0,a=new Map,n=null;i.onmessage=({data:c})=>{if(c?.type==="ready"){t(c.track);return}if(c?.type==="written"){a.get(c.id)?.resolve(),a.delete(c.id);return}if(c?.type==="closed"||c?.type==="aborted"){n?.resolve(),n=null,i.terminate();return}if(c?.type==="error"){let m=new Error(`[OpenRTC] Browser video renderer failed: ${c.message}`);r(m),a.get(c.id)?.reject(m),a.delete(c.id),n?.reject(m),n=null,i.terminate();}},i.onerror=c=>{let m=new Error(`[OpenRTC] Browser video renderer failed: ${c.message}`);r(m);for(let y of a.values())y.reject(m);a.clear(),n?.reject(m),n=null,i.terminate();},i.postMessage({type:"start"});let d;try{d=await l;}finally{URL.revokeObjectURL(e);}let o=(c,m)=>new Promise((y,k)=>{n={resolve:y,reject:k},i.postMessage({type:c,reason:String(m??"")});});return {track:d,writable:new WritableStream({write(c){let m=++s;return new Promise((y,k)=>{a.set(m,{resolve:y,reject:k}),i.postMessage({type:"write",id:m,frame:c},[c]);})},close:()=>o("close"),abort:c=>o("abort",c)},{highWaterMark:1})}}async function Me(i,e,t){let r=globalThis,l=r.AudioContext??r.webkitAudioContext;if(typeof l!="function")throw new Error("[OpenRTC] Web Audio is required for browser audio rendering.");let s=new l({sampleRate:i});await s.resume();let a=s.createMediaStreamDestination(),n=a.stream.getAudioTracks()[0];if(!n)throw await s.close(),new Error("[OpenRTC] Web Audio did not create a renderable media track.");let d=new Set,o=s.currentTime,c=async()=>{for(let m of d)try{m.stop();}catch{}d.clear(),n.stop(),await s.close();};return {track:n,writable:new WritableStream({async write(m){for(;o-s.currentTime>.5;){if(t?.aborted)throw new Error("[OpenRTC] browser audio rendering was cancelled.");await new Promise(f=>{let u,O=()=>{clearTimeout(u),t?.removeEventListener("abort",O),f();};u=setTimeout(()=>{t?.removeEventListener("abort",O),f();},10),t?.addEventListener("abort",O,{once:true});});}let y=Number(m.numberOfChannels??e),k=Number(m.sampleRate??i),w=Number(m.numberOfFrames??0),A=s.createBuffer(y,w,k);for(let f=0;f<y;f+=1){let u=new Float32Array(w);m.copyTo(u,{planeIndex:f,format:"f32-planar"}),A.copyToChannel(u,f);}let v=s.createBufferSource();v.buffer=A,v.connect(a),v.onended=()=>d.delete(v),d.add(v),o<s.currentTime-.05&&(o=s.currentTime),v.start(o),o+=A.duration;},close:c,abort:c},{highWaterMark:2})}}async function oe(i){let e=globalThis.MediaStreamTrackGenerator;if(typeof e=="function"){let t=new e({kind:i.kind});return {track:t.track??t,writable:t.writable}}return i.kind==="video"?ge():Me(i.sampleRate,i.channels,i.signal)}var ce="openrtc-media/1",le=2*1024*1024+72,Re=32,ke=8,Se=2*1024*1024,Te=8*1024*1024,J=1e3,Pe=30,Ee=32,Ce=8,Ae=8,Oe=16,ue=1e4,Le=512;function We(i){if(!i||typeof i!="object")return false;let e=i;return e.name==="OpenRtcPeerStreamStopped"&&e.openrtcPeerStopCode===0}function Ie(i){if(!Number.isSafeInteger(i.transportStableId)||i.transportStableId<=0||!Number.isSafeInteger(i.transportGeneration)||i.transportGeneration<=0||!Number.isSafeInteger(i.routeGeneration)||i.routeGeneration<0)throw new RangeError("[OpenRTC] media physical generation requires a safe positive transport identity and generation.")}function C(){return globalThis.performance?.now?.()??Date.now()}var B=class{constructor(){this.values=[];}observe(e){!Number.isFinite(e)||e<0||(this.values.length===Le&&this.values.shift(),this.values.push(e));}snapshot(){if(this.values.length===0)return {samples:0,p50Ms:0,p95Ms:0,p99Ms:0,maxMs:0};let e=[...this.values].sort((r,l)=>r-l),t=r=>e[Math.ceil(r*e.length)-1]??0;return {samples:e.length,p50Ms:t(.5),p95Ms:t(.95),p99Ms:t(.99),maxMs:e[e.length-1]}}};function se(i){if(i.byteLength>le)throw new Error("[OpenRTC] encoded media frame exceeds the portable media limit.");let e=new Uint8Array(4+i.byteLength);return new DataView(e.buffer).setUint32(0,i.byteLength,false),e.set(i,4),e}async function*xe(i,e){let t=i.getReader(),r=()=>{t.cancel("media-publication-cancelled");};e?.addEventListener("abort",r,{once:true});let l=new Uint8Array(4),s=0,a=null,n=0;try{for(;;){let d=await t.read();if(d.done)break;if(!d.value?.byteLength)continue;let o=0;for(;o<d.value.byteLength;){if(!a){let m=Math.min(l.byteLength-s,d.value.byteLength-o);if(l.set(d.value.subarray(o,o+m),s),s+=m,o+=m,s<l.byteLength)continue;let y=new DataView(l.buffer).getUint32(0,!1);if(y>le)throw new Error("[OpenRTC] incoming media frame exceeds the portable media limit.");s=0,a=new Uint8Array(y),n=0,y===0&&(yield a,a=null);continue}let c=Math.min(a.byteLength-n,d.value.byteLength-o);a.set(d.value.subarray(o,o+c),n),n+=c,o+=c,n===a.byteLength&&(yield a,a=null,n=0);}}if(s!==0||a!==null)throw new Error("[OpenRTC] incoming media stream ended with a truncated frame.")}finally{e?.removeEventListener("abort",r),t.releaseLock();}}function H(i){switch(i){case "h264":return "avc1.42001e";case "av1":return "av01.0.04M.08";default:return i}}function Ge(i){let e=Number(i.numberOfFrames),t=Number(i.numberOfChannels);if(!Number.isSafeInteger(e)||e<1||!Number.isSafeInteger(t)||t<1||typeof i.copyTo!="function")throw new Error("[OpenRTC] PCM audio requires copyable AudioData frames.");let r=new Uint8Array(e*t*2),l=new DataView(r.buffer),s=new Float32Array(e);for(let a=0;a<t;a+=1){s.fill(0),i.copyTo(s,{planeIndex:a,format:"f32-planar"});for(let n=0;n<e;n+=1){let d=Math.max(-1,Math.min(1,s[n])),o=d<0?Math.round(d*32768):Math.round(d*32767);l.setInt16((a*e+n)*2,o,true);}}return r}var Z=class{constructor(e,t,r,l){this.options=t;this.streams=r;this.runtime=l;this.publicationId="";this.stopped=false;this.abort=null;this.run=null;this.encodeLatency=new B;this.protectedWriteLatency=new B;this.pendingWrites=new Map;this.nextPendingWriteId=0;this.currentTrack=e,this.stats={publicationId:"",mediaGeneration:0,accepted:0,queued:0,queuedBytes:0,queuedAgeMs:0,transmitted:0,dropped:0,bytes:0,maxQueued:0,maxQueuedBytes:0,maxQueuedAgeMs:0,lastError:void 0,encodeLatency:this.encodeLatency.snapshot(),protectedWriteLatency:this.protectedWriteLatency.snapshot()};}get id(){return this.publicationId}get track(){return this.currentTrack}async start(){if(!this.currentTrack)return;this.stats.lastError=void 0;let e=new AbortController;this.abort=e;let t,r,l=new Promise((s,a)=>{t=s,r=a;});this.run=this.encode(this.currentTrack,e.signal,t).catch(s=>{throw e.signal.aborted||(this.stats.lastError=s instanceof Error?s.message:String(s)),r(s),s}),this.run.catch(()=>{});try{await l;}catch(s){throw e.abort(),await this.run.catch(()=>{}),s}}async replaceTrack(e){if(this.stopped)throw new Error("[OpenRTC] media sender is stopped.");this.abort?.abort(),await this.run?.catch(()=>{}),this.publicationId&&await this.runtime.pauseOpenRtcMediaPublication(this.publicationId),this.currentTrack=e,e&&await this.start();}async setEnabled(e){if(this.stopped)throw new Error("[OpenRTC] media sender is stopped.");this.currentTrack&&(this.currentTrack.enabled=e);}async stop(){this.stopped||(this.stopped=true,this.abort?.abort(),await this.run?.catch(()=>{}),this.currentTrack=null,this.publicationId&&await this.runtime.retireOpenRtcMediaPublication(this.publicationId));}async restartForPhysicalGeneration(){this.stopped||!this.currentTrack||(this.abort?.abort(),await this.run?.catch(()=>{}),this.publicationId&&await this.runtime.pauseOpenRtcMediaPublication(this.publicationId),!this.stopped&&this.currentTrack&&await this.start());}async getStats(){return this.updatePendingWriteStats(),{...this.stats,encodeLatency:this.encodeLatency.snapshot(),protectedWriteLatency:this.protectedWriteLatency.snapshot()}}updatePendingWriteStats(e=C()){for(let[r,l]of this.pendingWrites)e-l.acceptedAtMs<=J||(this.pendingWrites.delete(r),this.stats.dropped+=1);this.stats.queued=this.pendingWrites.size,this.stats.queuedBytes=[...this.pendingWrites.values()].reduce((r,l)=>r+l.bytes,0);let t=[...this.pendingWrites.values()].reduce((r,l)=>r===null||l.acceptedAtMs<r?l.acceptedAtMs:r,null);this.stats.queuedAgeMs=t===null?0:Math.max(0,e-t),this.stats.maxQueued=Math.max(this.stats.maxQueued,this.stats.queued),this.stats.maxQueuedBytes=Math.max(this.stats.maxQueuedBytes,this.stats.queuedBytes),this.stats.maxQueuedAgeMs=Math.max(this.stats.maxQueuedAgeMs,this.stats.queuedAgeMs);}async encode(e,t,r){let l=globalThis;if(e.kind!=="audio"&&e.kind!=="video")throw new Error(`[OpenRTC] Unsupported media track kind '${e.kind}'.`);let s=await ae(e),a=s.readable.getReader(),n=async()=>{await s.close?.();},d=()=>{a.cancel("media-generation-replaced");},o,c=new Promise(h=>{o=h;}),m=()=>o();t.addEventListener("abort",d,{once:true}),t.addEventListener("abort",m,{once:true});let y=null,k;try{k=await Promise.race([a.read(),new Promise((h,E)=>{y=setTimeout(()=>{E(new Error("[OpenRTC] media encoder startup timed out."));},ue);})]);}catch(h){throw await a.cancel("media-encoder-startup-failed").catch(()=>{}),a.releaseLock(),await n().catch(()=>{}),t.removeEventListener("abort",d),t.removeEventListener("abort",m),h}finally{y&&clearTimeout(y);}if(k.done||!k.value||t.aborted)throw a.releaseLock(),await n().catch(()=>{}),t.removeEventListener("abort",d),t.removeEventListener("abort",m),new Error("[OpenRTC] media track ended before its encoder became ready.");let w=k.value,A=e.kind==="video"?"vp8":typeof l.AudioEncoder=="function"?"opus":"pcm",v=(this.options.codec??A).toLowerCase(),f=v.startsWith("avc1")?"h264":v.startsWith("av01")?"av1":v,u=e.kind==="audio"&&f==="pcm";if(f==="pcm"&&e.kind!=="audio")throw w.close?.(),a.releaseLock(),await n().catch(()=>{}),t.removeEventListener("abort",d),new Error("[OpenRTC] PCM is supported only for audio tracks.");let O=e.kind==="video"?l.VideoEncoder:l.AudioEncoder;if(!u&&typeof O!="function")throw w.close?.(),a.releaseLock(),await n().catch(()=>{}),t.removeEventListener("abort",d),new Error("[OpenRTC] WebCodecs encode support is required for compressed browser media.");let D={publicationId:this.publicationId,kind:e.kind,codec:f,clockRate:e.kind==="audio"?Number(w.sampleRate??48e3):1e6,codedWidth:e.kind==="video"?Number(w.displayWidth??w.codedWidth):void 0,codedHeight:e.kind==="video"?Number(w.displayHeight??w.codedHeight):void 0,channels:e.kind==="audio"?Number(w.numberOfChannels??2):void 0},G=Promise.resolve(),S=null,L=false,I=null,N=null,F=null,q=0,V=false,W=false,z=false,_=new Map,U=h=>N?(F??(F=N(h)),F):Promise.resolve(),Q=()=>{U("media-generation-replaced").catch(()=>{});},x=h=>{S===null&&(S=h),o(),a.cancel("media-sender-failed").catch(()=>{}),U("media-sender-failed").catch(()=>{});},K=()=>{L=true,o(),a.cancel("media-peer-receiver-stopped").catch(()=>{});},X=h=>{try{if(t.aborted||S){this.stats.dropped+=1;return}let E=Number(h.timestamp??0),T=_.get(E);T!==void 0&&(this.encodeLatency.observe(C()-T),_.delete(E));let b=e.kind==="video"?ke:Re,P=e.kind==="video"?Te:Se,M=new Uint8Array(h.byteLength);if(this.pendingWrites.size>=b||this.stats.queuedBytes+M.byteLength>P||!I){this.stats.dropped+=1;return}h.copyTo(M),this.stats.accepted+=1;let R=++this.nextPendingWriteId,te=C();this.pendingWrites.set(R,{bytes:M.byteLength,acceptedAtMs:te}),this.updatePendingWriteStats(te),G=G.then(async()=>{let $=this.pendingWrites.get(R);if(!$||t.aborted)return;if(C()-$.acceptedAtMs>J){this.pendingWrites.delete(R),this.stats.dropped+=1;return}if(this.updatePendingWriteStats(),!this.pendingWrites.has(R))return;let pe=await this.runtime.encodeOpenRtcMediaSample({publicationId:this.id,timestampUs:Number(h.timestamp??0),durationUs:Number(h.duration??0),keyframe:h.type==="key",discardable:e.kind==="video"&&h.type!=="key",payload:M});if(t.aborted||S)return;let Y=this.pendingWrites.get(R);if(!Y||C()-Y.acceptedAtMs>J){Y&&(this.pendingWrites.delete(R),this.stats.dropped+=1);return}this.pendingWrites.delete(R),this.updatePendingWriteStats();let me=C();await I.write(se(pe)),!(t.aborted||S)&&(this.protectedWriteLatency.observe(C()-me),this.stats.transmitted+=1,this.stats.bytes+=M.byteLength);}).catch($=>{We($)?K():x($);}).finally(()=>{this.pendingWrites.delete(R),this.updatePendingWriteStats();});}catch(E){x(E),this.stats.dropped+=1;}},g=u?null:new O({output:X,error:h=>{x(h);}}),j=e.kind==="video"?{codec:H(f),width:D.codedWidth,height:D.codedHeight,bitrate:this.options.bitrate??15e5,framerate:30,latencyMode:"realtime"}:{codec:H(f),sampleRate:D.clockRate,numberOfChannels:D.channels,bitrate:this.options.bitrate??96e3},p=h=>{try{if(t.aborted)return;if(u){let P=Number(h.timestamp??0);_.set(P,C());let M=Ge(h);X({timestamp:P,duration:Number(h.duration??0),type:"key",byteLength:M.byteLength,copyTo(R){R.set(M);}});return}let E=e.kind==="video"?4:8;if(g.encodeQueueSize>=E){this.stats.dropped+=1;return}let T=e.kind==="video"&&q%Pe===0;q+=1;let b=Number(h.timestamp??0);if(_.size>=64){let P=_.keys().next().value;P!==void 0&&_.delete(P);}_.set(b,C()),g.encode(h,e.kind==="video"?{keyFrame:T}:void 0);}finally{h.close?.();}};try{if(!u&&typeof O.isConfigSupported!="function")throw new Error("[OpenRTC] The browser cannot verify WebCodecs encoder support.");let h=u?null:await O.isConfigSupported(j);if(!u&&!h?.supported)throw new Error(`[OpenRTC] The browser cannot encode '${f}' for this track.`);let E=h?.config??j,T=await this.runtime.beginOpenRtcMediaPublication(D);V=!0,this.publicationId=T.publicationId,this.stats.publicationId=T.publicationId,this.stats.mediaGeneration=T.mediaGeneration;let b$1=await this.streams.createBidirectionalStream({protocol:ce});for(N=b(b$1.writable),I=b$1.writable.getWriter(),t.addEventListener("abort",Q,{once:!0}),t.aborted&&Q(),b$1.readable.cancel("media-v1-has-no-reverse-control").catch(()=>{}),await I.write(se(T.control)),g?.configure(E),r(),z=!0,p(w);!t.aborted&&!S&&!L;){let P=await a.read();if(P.done)break;P.value&&p(P.value);}if(!t.aborted&&!S&&!L&&(g&&await Promise.race([g.flush(),c]),!t.aborted&&!S&&!L&&await Promise.race([G,c])),S)throw S;if(L)await this.runtime.pauseOpenRtcMediaPublication(this.publicationId);else if(!t.aborted){let P=I.close();await Promise.race([P,c]),W=!t.aborted&&!S;}}catch(h){throw V&&!t.aborted&&await this.runtime.pauseOpenRtcMediaPublication(this.publicationId),h}finally{if(t.removeEventListener("abort",d),t.removeEventListener("abort",m),t.removeEventListener("abort",Q),z||w.close?.(),a.releaseLock(),await n().catch(()=>{}),g&&g.state!=="closed")try{g.close?.();}catch{}if(I&&!W){let h=t.aborted?"media-generation-replaced":L?"media-peer-receiver-stopped":"media-sender-failed";await U(h).catch(()=>{}),await I.abort(h).catch(()=>{});}await G.catch(()=>{});try{I?.releaseLock();}catch{}}}},ee=class{constructor(e,t,r,l,s){this.id=e;this.track=t;this.stats=r;this.receiveToDecodeLatency=l;this.renderWriteLatency=s;}async getStats(){return {...this.stats,receiveToDecodeLatency:this.receiveToDecodeLatency.snapshot(),renderWriteLatency:this.renderWriteLatency.snapshot()}}},de=class{constructor(e,t,r,l=()=>({registered:true,peers:1,boundConnections:0,observed:0,accepted:0,declined:0,lastResolution:"none"})){this.streams=e;this.runtime=t;this.incomingDemux=l;this.senderMap=new Map;this.receiverMap=new Map;this.listeners=new Set;this.incomingRuns=new Map;this.receiverRuns=new Map;this.incomingFailures=[];this.incomingProtocolStreams=0;this.stopped=false;this.physicalGeneration=null;this.recoveryTail=Promise.resolve();this.stopIncoming=r(ce,s=>{if(this.incomingProtocolStreams+=1,this.stopped||this.incomingRuns.size>=Ae){s.readable.cancel("incoming-media-publication-limit").catch(()=>{}),s.writable.abort("incoming-media-publication-limit").catch(()=>{});return}let a=new AbortController,n=this.receivePublication(s.readable,s.writable,a);this.incomingRuns.set(a,n),n.catch(d=>{let o=d instanceof Error?d.message:String(d);this.incomingFailures.length===Oe&&this.incomingFailures.shift(),this.incomingFailures.push(o),console.error("[OpenRTC][media] incoming publication failed",{message:o});}).finally(()=>this.incomingRuns.delete(a));});}async addTrack(e,t={}){if(this.stopped)throw new Error("[OpenRTC] media connection is closed.");if(e.kind!=="audio"&&e.kind!=="video")throw new Error(`[OpenRTC] Unsupported media track kind '${e.kind}'.`);let r=new Z(e,t,this.streams,this.runtime);try{return await r.start(),this.senderMap.set(r.id,r),r}catch(l){throw await r.stop().catch(()=>{}),l}}async removeTrack(e){let t=this.senderMap.get(e.id);!t||t!==e||(this.senderMap.delete(e.id),await t.stop());}onTrack(e){return this.listeners.add(e),()=>this.listeners.delete(e)}senders(){return [...this.senderMap.values()]}receivers(){return [...this.receiverMap.values()]}async getStats(){return {senders:await Promise.all([...this.senderMap.values()].map(e=>e.getStats())),receivers:await Promise.all([...this.receiverMap.values()].map(e=>e.getStats())),incomingFailures:[...this.incomingFailures],incomingProtocolStreams:this.incomingProtocolStreams,incomingDemux:this.incomingDemux()}}async observePhysicalGeneration(e){if(this.stopped)return;if(Ie(e),this.physicalGeneration===null){this.physicalGeneration={...e};return}let t=this.physicalGeneration;if(!(e.transportGeneration<t.transportGeneration)){if(e.transportGeneration===t.transportGeneration){if(e.transportStableId!==t.transportStableId)throw new Error("[OpenRTC] media rejected an inconsistent physical generation tuple.");e.routeGeneration>t.routeGeneration&&(this.physicalGeneration={...e});return}if(e.transportStableId===t.transportStableId)throw new Error("[OpenRTC] media rejected a reused physical transport identity.");this.physicalGeneration={...e},this.recoveryTail=this.recoveryTail.catch(()=>{}).then(async()=>{if(!this.stopped)for(let r of this.senderMap.values())await r.restartForPhysicalGeneration();}),await this.recoveryTail;}}async close(){if(this.stopped)return;this.stopped=true,this.stopIncoming(),await this.recoveryTail.catch(()=>{}),await Promise.all([...this.senderMap.values()].map(t=>t.stop())),this.senderMap.clear(),this.listeners.clear();let e=[...this.incomingRuns.entries()];for(let[t]of e)t.abort();await Promise.allSettled(e.map(([,t])=>t)),this.incomingRuns.clear(),this.receiverRuns.clear();for(let t of this.receiverMap.values())t.track.stop();this.receiverMap.clear(),this.incomingFailures.splice(0);}async receivePublication(e,t,r){if(this.stopped){await e.cancel("media-connection-closed").catch(()=>{}),await t.abort("media-connection-closed").catch(()=>{});return}let l=xe(e,r.signal),s=null,a;try{a=await Promise.race([l.next(),new Promise((p,h)=>{s=setTimeout(()=>{h(new Error("[OpenRTC] incoming media control timed out."));},ue);})]);}catch(p){throw r.abort(),await l.return(void 0).catch(()=>{}),await e.cancel("incoming-media-control-failed").catch(()=>{}),await t.abort("incoming-media-control-failed").catch(()=>{}),p}finally{s&&clearTimeout(s);}if(a.done){await t.close().catch(()=>{});return}let n;try{let p=await this.runtime.decodeOpenRtcMediaControl(a.value);if(p.type!=="publish")throw new Error("[OpenRTC] media stream did not begin with publish control.");n=p;}catch(p){throw r.abort(),await l.return(void 0).catch(()=>{}),await e.cancel("incoming-media-control-invalid").catch(()=>{}),await t.abort("incoming-media-control-invalid").catch(()=>{}),p}let d=n.publicationId,o=async(p,h)=>{throw r.abort(),await l.return(void 0).catch(()=>{}),await this.runtime.retireOpenRtcMediaReceiver(d,n.mediaGeneration),await t.abort(p).catch(()=>{}),h},c=globalThis,m=n.kind==="audio"&&n.codec==="pcm",y=n.kind==="video"?c.VideoDecoder:c.AudioDecoder,k=n.kind==="video"?c.EncodedVideoChunk:c.EncodedAudioChunk;if(!m&&(typeof y!="function"||typeof k!="function"))return o("media-decoder-api-unavailable",new Error("[OpenRTC] WebCodecs decode support is required for browser media."));if(m&&typeof c.AudioData!="function")return o("media-pcm-api-unavailable",new Error("[OpenRTC] AudioData is required for PCM browser media."));let w=n.kind==="video"?{codec:H(n.codec),codedWidth:n.codedWidth,codedHeight:n.codedHeight,optimizeForLatency:true}:{codec:H(n.codec),sampleRate:n.clockRate,numberOfChannels:n.channels??2};if(!m&&typeof y.isConfigSupported!="function")return o("media-decoder-support-unverifiable",new Error("[OpenRTC] The browser cannot verify WebCodecs decoder support."));let A=null;try{m||(A=await y.isConfigSupported(w));}catch(p){return o("media-decoder-support-check-failed",p)}if(!m&&!A?.supported)return o("media-decoder-unsupported",new Error(`[OpenRTC] The browser cannot decode '${n.codec}'.`));let v,f;try{let p=await oe({kind:n.kind,sampleRate:n.clockRate,channels:n.channels??2,signal:r.signal});v=p.track,f=p.writable.getWriter();}catch(p){return o("media-renderer-setup-failed",p)}let u={publicationId:d,mediaGeneration:n.mediaGeneration,received:0,decoded:0,rendered:0,dropped:0,integrityFailures:0,malformedFrames:0,replayDrops:0,videoRecoveries:0,awaitingKeyframe:n.kind==="video",maxVideoRecoveryMs:0,bytes:0,decoderQueued:0,maxDecoderQueued:0,renderQueued:0,maxRenderQueued:0,receiveToDecodeLatency:new B().snapshot(),renderWriteLatency:new B().snapshot()},O=new B,D=new B,G=new Map,S=[],L=n.kind==="video",I=L,N=null,F=null,q=()=>{L&&(I=true,u.awaitingKeyframe=true,N===null&&(N=C()));},V=Promise.resolve(),W=null,z,_=new Promise(p=>{z=p;}),U=()=>{z(),f.abort("media-receiver-cancelled").catch(()=>{});};r.signal.addEventListener("abort",U,{once:true}),r.signal.aborted&&U();let Q=p=>{W===null&&(W=p),r.abort();},x=0,K=n.kind==="video"?Ce:Ee,X=(p,h=0)=>{if(r.signal.aborted||W){p.close?.();return}u.decoderQueued=h;let E=Number(p.timestamp??0),T=L?G.get(E):S.shift();if(T!==void 0&&(O.observe(C()-T),L&&G.delete(E)),x>=K){u.dropped+=1,p.close?.();return}x+=1,u.renderQueued=x,u.maxRenderQueued=Math.max(u.maxRenderQueued,x),V=V.then(async()=>{if(r.signal.aborted)return;let b=C();await f.write(p),D.observe(C()-b),u.decoded+=1,u.rendered+=1;}).catch(b=>{r.signal.aborted||Q(b);}).finally(()=>{p.close?.(),x-=1,u.renderQueued=x;});},g=null;try{m||(g=new y({output:p=>{X(p,Number(g?.decodeQueueSize??0));},error:p=>{r.signal.aborted||Q(p);}})),g?.configure(A?.config??w);}catch(p){r.signal.removeEventListener("abort",U),f.abort("media-decoder-setup-failed").catch(()=>{});try{f.releaseLock();}catch{}return v.stop(),o("media-decoder-setup-failed",p)}let j=new ee(d,v,u,O,D);try{let p=this.receiverRuns.get(d);if(p&&p.abort!==r&&p.mediaGeneration>=n.mediaGeneration)throw new Error(`[OpenRTC] stale media generation ${n.mediaGeneration} cannot replace ${p.mediaGeneration} for '${d}'.`);if(this.receiverRuns.set(d,{mediaGeneration:n.mediaGeneration,abort:r}),p&&p.abort!==r&&(p.abort.abort(),await this.incomingRuns.get(p.abort)?.catch(()=>{})),this.stopped||r.signal.aborted)return;let h=this.receiverMap.get(d);h&&h.track.stop(),this.receiverMap.set(d,j);let E=new MediaStream([v]);for(let T of this.listeners)try{T({track:v,receiver:j,streams:[E]});}catch{}for await(let T of l){if(r.signal.aborted||W||this.stopped)break;let b;try{b=await this.runtime.decodeOpenRtcMediaChunk(T);}catch(M){let R=String(M);/integrity/i.test(R)?(u.integrityFailures+=1,q()):/replay|retired/i.test(R)?u.replayDrops+=1:/truncated|invalidmagic|unsupported|chunktoolarge|too large|lengthmismatch/i.test(R)?(u.malformedFrames+=1,q()):u.dropped+=1;continue}if(r.signal.aborted||this.stopped)break;if(b.publicationId!==d||b.mediaGeneration!==n.mediaGeneration){u.dropped+=1;continue}if(F!==null&&b.sequence>F+1&&q(),F=F===null?b.sequence:Math.max(F,b.sequence),u.received+=1,u.bytes+=b.payload.byteLength,L&&I){if(!b.keyframe){u.dropped+=1;continue}if(N!==null){let M=C()-N;u.videoRecoveries+=1,u.maxVideoRecoveryMs=Math.max(u.maxVideoRecoveryMs,M),g?.reset?.(),g?.configure(A?.config??w);}I=!1,N=null,u.awaitingKeyframe=!1;}if((g?.decodeQueueSize??x)>=K){u.dropped+=1;continue}let P=C();if(L){if(G.size>=64){let M=G.keys().next().value;M!==void 0&&G.delete(M);}G.set(b.timestampUs,P);}else S.length>=64&&S.shift(),S.push(P);if(m){let M=n.channels??2,R=M*2;if(b.payload.byteLength===0||b.payload.byteLength%R!==0){u.dropped+=1;continue}X(new c.AudioData({format:"s16-planar",sampleRate:n.clockRate,numberOfFrames:b.payload.byteLength/R,numberOfChannels:M,timestamp:b.timestampUs,data:b.payload}));}else try{g.decode(new k({type:b.keyframe?"key":"delta",timestamp:b.timestampUs,duration:b.durationUs||void 0,data:b.payload}));}catch(M){Q(M);break}u.decoderQueued=Number(g?.decodeQueueSize??x),u.maxDecoderQueued=Math.max(u.maxDecoderQueued,u.decoderQueued);}if(!r.signal.aborted&&!W&&g&&await Promise.race([g.flush(),_]),!r.signal.aborted&&!W&&await Promise.race([V,_]),W)throw W}finally{r.signal.removeEventListener("abort",U);try{g?.close?.();}catch{}r.signal.aborted||W?f.abort("media-receiver-finished").catch(()=>{}):f.close().catch(()=>{});try{f.releaseLock();}catch{}this.receiverRuns.get(d)?.abort===r&&this.receiverRuns.delete(d),this.receiverMap.get(d)===j&&this.receiverMap.delete(d),await this.runtime.retireOpenRtcMediaReceiver(d,u.mediaGeneration),v.stop(),r.signal.aborted||W?t.abort("media-receiver-finished").catch(()=>{}):t.close().catch(()=>{});}}};export{se as a,de as b};
|
|
118
|
+
`;function ne(i){return URL.createObjectURL(new Blob([i],{type:"text/javascript"}))}function ie(i){if(typeof Worker!="function")throw new Error("[OpenRTC] Dedicated workers are unavailable for the browser video edge.");let e=ne(i);try{return {worker:new Worker(e),url:e}}catch(t){throw URL.revokeObjectURL(e),t}}async function we(i){if(typeof i.clone!="function")throw new Error("[OpenRTC] The browser cannot clone a video track for its worker media edge.");let{worker:e,url:t}=ie(fe),r=null,l,s,a=new Promise((o,c)=>{l=o,s=c;}),n=new ReadableStream({start(o){r=o;},pull(){e.postMessage({type:"read"});},cancel(o){e.postMessage({type:"cancel",reason:String(o??"")}),e.terminate();}},{highWaterMark:0});e.onmessage=({data:o})=>{if(o?.type==="ready")l();else if(o?.type==="frame")r?.enqueue(o.frame);else if(o?.type==="done")r?.close(),e.terminate();else if(o?.type==="error"){let c=new Error(`[OpenRTC] Browser video worker failed: ${o.message}`);s(c),r?.error(c),e.terminate();}},e.onerror=o=>{let c=new Error(`[OpenRTC] Browser video worker failed: ${o.message}`);s(c),r?.error(c),e.terminate();};let d=i.clone();e.postMessage({type:"start",track:d},[d]);try{await a;}finally{URL.revokeObjectURL(t);}return {readable:n}}async function ve(i){let e=globalThis,t=e.AudioContext??e.webkitAudioContext,r=e.AudioData;if(typeof t!="function"||typeof r!="function")throw new Error("[OpenRTC] Web Audio and AudioData are required for browser audio capture.");let l=i.getSettings?.()??{},s=Number(l.sampleRate??48e3),a=Math.max(1,Math.min(2,Number(l.channelCount??1))),n=new t({sampleRate:s}),d=Number(n.sampleRate??s),o=ne(ye);try{await n.audioWorklet.addModule(o);}catch(f){throw await n.close(),f}finally{URL.revokeObjectURL(o);}await n.resume();let c=n.createMediaStreamSource(new MediaStream([i])),m=new AudioWorkletNode(n,"openrtc-audio-capture",{numberOfInputs:1,numberOfOutputs:1,channelCount:a,channelCountMode:"explicit",channelInterpretation:"speakers",outputChannelCount:[a],processorOptions:{channels:a,framesPerChunk:Math.max(1,Math.round(d/50))}}),y=n.createGain();y.gain.value=0,c.connect(m).connect(y).connect(n.destination);let k=false,w=async()=>{k||(k=true,m.port.onmessage=null,c.disconnect(),m.disconnect(),y.disconnect(),i.removeEventListener?.("ended",v),await n.close());},A=null,v=()=>{A?.close(),w();};return i.addEventListener?.("ended",v,{once:true}),{readable:new ReadableStream({start(f){A=f,m.port.onmessage=({data:u})=>{if(!(f.desiredSize!==null&&f.desiredSize<=0))try{f.enqueue(new r({format:"f32-planar",sampleRate:d,numberOfFrames:u.frames,numberOfChannels:a,timestamp:Math.round(u.timestampFrames*1e6/d),data:u.planar}));}catch(O){f.error(O);}};},cancel:w},{highWaterMark:2})}}async function ae(i){let e=globalThis.MediaStreamTrackProcessor;return typeof e=="function"?he(i,e):i.kind==="video"?we(i):ve(i)}async function ge(){let{worker:i,url:e}=ie(be),t,r,l=new Promise((c,m)=>{t=c,r=m;}),s=0,a=new Map,n=null;i.onmessage=({data:c})=>{if(c?.type==="ready"){t(c.track);return}if(c?.type==="written"){a.get(c.id)?.resolve(),a.delete(c.id);return}if(c?.type==="closed"||c?.type==="aborted"){n?.resolve(),n=null,i.terminate();return}if(c?.type==="error"){let m=new Error(`[OpenRTC] Browser video renderer failed: ${c.message}`);r(m),a.get(c.id)?.reject(m),a.delete(c.id),n?.reject(m),n=null,i.terminate();}},i.onerror=c=>{let m=new Error(`[OpenRTC] Browser video renderer failed: ${c.message}`);r(m);for(let y of a.values())y.reject(m);a.clear(),n?.reject(m),n=null,i.terminate();},i.postMessage({type:"start"});let d;try{d=await l;}finally{URL.revokeObjectURL(e);}let o=(c,m)=>new Promise((y,k)=>{n={resolve:y,reject:k},i.postMessage({type:c,reason:String(m??"")});});return {track:d,writable:new WritableStream({write(c){let m=++s;return new Promise((y,k)=>{a.set(m,{resolve:y,reject:k}),i.postMessage({type:"write",id:m,frame:c},[c]);})},close:()=>o("close"),abort:c=>o("abort",c)},{highWaterMark:1})}}async function Me(i,e,t){let r=globalThis,l=r.AudioContext??r.webkitAudioContext;if(typeof l!="function")throw new Error("[OpenRTC] Web Audio is required for browser audio rendering.");let s=new l({sampleRate:i});await s.resume();let a=s.createMediaStreamDestination(),n=a.stream.getAudioTracks()[0];if(!n)throw await s.close(),new Error("[OpenRTC] Web Audio did not create a renderable media track.");let d=new Set,o=s.currentTime,c=async()=>{for(let m of d)try{m.stop();}catch{}d.clear(),n.stop(),await s.close();};return {track:n,writable:new WritableStream({async write(m){for(;o-s.currentTime>.5;){if(t?.aborted)throw new Error("[OpenRTC] browser audio rendering was cancelled.");await new Promise(f=>{let u,O=()=>{clearTimeout(u),t?.removeEventListener("abort",O),f();};u=setTimeout(()=>{t?.removeEventListener("abort",O),f();},10),t?.addEventListener("abort",O,{once:true});});}let y=Number(m.numberOfChannels??e),k=Number(m.sampleRate??i),w=Number(m.numberOfFrames??0),A=s.createBuffer(y,w,k);for(let f=0;f<y;f+=1){let u=new Float32Array(w);m.copyTo(u,{planeIndex:f,format:"f32-planar"}),A.copyToChannel(u,f);}let v=s.createBufferSource();v.buffer=A,v.connect(a),v.onended=()=>d.delete(v),d.add(v),o<s.currentTime-.05&&(o=s.currentTime),v.start(o),o+=A.duration;},close:c,abort:c},{highWaterMark:2})}}async function oe(i){let e=globalThis.MediaStreamTrackGenerator;if(typeof e=="function"){let t=new e({kind:i.kind});return {track:t.track??t,writable:t.writable}}return i.kind==="video"?ge():Me(i.sampleRate,i.channels,i.signal)}var ce="openrtc-media/1",le=2*1024*1024+72,Re=32,ke=8,Se=2*1024*1024,Te=8*1024*1024,J=1e3,Pe=30,Ee=32,Ce=8,Ae=8,Oe=16,ue=1e4,Le=512;function We(i){if(!i||typeof i!="object")return false;let e=i;return e.name==="OpenRtcPeerStreamStopped"&&e.openrtcPeerStopCode===0}function Ie(i){if(!Number.isSafeInteger(i.transportStableId)||i.transportStableId<=0||!Number.isSafeInteger(i.transportGeneration)||i.transportGeneration<=0||!Number.isSafeInteger(i.routeGeneration)||i.routeGeneration<0)throw new RangeError("[OpenRTC] media physical generation requires a safe positive transport identity and generation.")}function C(){return globalThis.performance?.now?.()??Date.now()}var B=class{constructor(){this.values=[];}observe(e){!Number.isFinite(e)||e<0||(this.values.length===Le&&this.values.shift(),this.values.push(e));}snapshot(){if(this.values.length===0)return {samples:0,p50Ms:0,p95Ms:0,p99Ms:0,maxMs:0};let e=[...this.values].sort((r,l)=>r-l),t=r=>e[Math.ceil(r*e.length)-1]??0;return {samples:e.length,p50Ms:t(.5),p95Ms:t(.95),p99Ms:t(.99),maxMs:e[e.length-1]}}};function se(i){if(i.byteLength>le)throw new Error("[OpenRTC] encoded media frame exceeds the portable media limit.");let e=new Uint8Array(4+i.byteLength);return new DataView(e.buffer).setUint32(0,i.byteLength,false),e.set(i,4),e}async function*xe(i,e){let t=i.getReader(),r=()=>{t.cancel("media-publication-cancelled");};e?.addEventListener("abort",r,{once:true});let l=new Uint8Array(4),s=0,a=null,n=0;try{for(;;){let d=await t.read();if(d.done)break;if(!d.value?.byteLength)continue;let o=0;for(;o<d.value.byteLength;){if(!a){let m=Math.min(l.byteLength-s,d.value.byteLength-o);if(l.set(d.value.subarray(o,o+m),s),s+=m,o+=m,s<l.byteLength)continue;let y=new DataView(l.buffer).getUint32(0,!1);if(y>le)throw new Error("[OpenRTC] incoming media frame exceeds the portable media limit.");s=0,a=new Uint8Array(y),n=0,y===0&&(yield a,a=null);continue}let c=Math.min(a.byteLength-n,d.value.byteLength-o);a.set(d.value.subarray(o,o+c),n),n+=c,o+=c,n===a.byteLength&&(yield a,a=null,n=0);}}if(s!==0||a!==null)throw new Error("[OpenRTC] incoming media stream ended with a truncated frame.")}finally{e?.removeEventListener("abort",r),t.releaseLock();}}function H(i){switch(i){case "h264":return "avc1.42e01f";case "av1":return "av01.0.04M.08";default:return i}}function Ge(i){let e=Number(i.numberOfFrames),t=Number(i.numberOfChannels);if(!Number.isSafeInteger(e)||e<1||!Number.isSafeInteger(t)||t<1||typeof i.copyTo!="function")throw new Error("[OpenRTC] PCM audio requires copyable AudioData frames.");let r=new Uint8Array(e*t*2),l=new DataView(r.buffer),s=new Float32Array(e);for(let a=0;a<t;a+=1){s.fill(0),i.copyTo(s,{planeIndex:a,format:"f32-planar"});for(let n=0;n<e;n+=1){let d=Math.max(-1,Math.min(1,s[n])),o=d<0?Math.round(d*32768):Math.round(d*32767);l.setInt16((a*e+n)*2,o,true);}}return r}var Z=class{constructor(e,t,r,l){this.options=t;this.streams=r;this.runtime=l;this.publicationId="";this.stopped=false;this.abort=null;this.run=null;this.encodeLatency=new B;this.protectedWriteLatency=new B;this.pendingWrites=new Map;this.nextPendingWriteId=0;this.currentTrack=e,this.stats={publicationId:"",mediaGeneration:0,accepted:0,queued:0,queuedBytes:0,queuedAgeMs:0,transmitted:0,dropped:0,bytes:0,maxQueued:0,maxQueuedBytes:0,maxQueuedAgeMs:0,lastError:void 0,encodeLatency:this.encodeLatency.snapshot(),protectedWriteLatency:this.protectedWriteLatency.snapshot()};}get id(){return this.publicationId}get track(){return this.currentTrack}async start(){if(!this.currentTrack)return;this.stats.lastError=void 0;let e=new AbortController;this.abort=e;let t,r,l=new Promise((s,a)=>{t=s,r=a;});this.run=this.encode(this.currentTrack,e.signal,t).catch(s=>{throw e.signal.aborted||(this.stats.lastError=s instanceof Error?s.message:String(s)),r(s),s}),this.run.catch(()=>{});try{await l;}catch(s){throw e.abort(),await this.run.catch(()=>{}),s}}async replaceTrack(e){if(this.stopped)throw new Error("[OpenRTC] media sender is stopped.");this.abort?.abort(),await this.run?.catch(()=>{}),this.publicationId&&await this.runtime.pauseOpenRtcMediaPublication(this.publicationId),this.currentTrack=e,e&&await this.start();}async setEnabled(e){if(this.stopped)throw new Error("[OpenRTC] media sender is stopped.");this.currentTrack&&(this.currentTrack.enabled=e);}async stop(){this.stopped||(this.stopped=true,this.abort?.abort(),await this.run?.catch(()=>{}),this.currentTrack=null,this.publicationId&&await this.runtime.retireOpenRtcMediaPublication(this.publicationId));}async restartForPhysicalGeneration(){this.stopped||!this.currentTrack||(this.abort?.abort(),await this.run?.catch(()=>{}),this.publicationId&&await this.runtime.pauseOpenRtcMediaPublication(this.publicationId),!this.stopped&&this.currentTrack&&await this.start());}async getStats(){return this.updatePendingWriteStats(),{...this.stats,encodeLatency:this.encodeLatency.snapshot(),protectedWriteLatency:this.protectedWriteLatency.snapshot()}}updatePendingWriteStats(e=C()){for(let[r,l]of this.pendingWrites)e-l.acceptedAtMs<=J||(this.pendingWrites.delete(r),this.stats.dropped+=1);this.stats.queued=this.pendingWrites.size,this.stats.queuedBytes=[...this.pendingWrites.values()].reduce((r,l)=>r+l.bytes,0);let t=[...this.pendingWrites.values()].reduce((r,l)=>r===null||l.acceptedAtMs<r?l.acceptedAtMs:r,null);this.stats.queuedAgeMs=t===null?0:Math.max(0,e-t),this.stats.maxQueued=Math.max(this.stats.maxQueued,this.stats.queued),this.stats.maxQueuedBytes=Math.max(this.stats.maxQueuedBytes,this.stats.queuedBytes),this.stats.maxQueuedAgeMs=Math.max(this.stats.maxQueuedAgeMs,this.stats.queuedAgeMs);}async encode(e,t,r){let l=globalThis;if(e.kind!=="audio"&&e.kind!=="video")throw new Error(`[OpenRTC] Unsupported media track kind '${e.kind}'.`);let s=await ae(e),a=s.readable.getReader(),n=async()=>{await s.close?.();},d=()=>{a.cancel("media-generation-replaced");},o,c=new Promise(h=>{o=h;}),m=()=>o();t.addEventListener("abort",d,{once:true}),t.addEventListener("abort",m,{once:true});let y=null,k;try{k=await Promise.race([a.read(),new Promise((h,E)=>{y=setTimeout(()=>{E(new Error("[OpenRTC] media encoder startup timed out."));},ue);})]);}catch(h){throw await a.cancel("media-encoder-startup-failed").catch(()=>{}),a.releaseLock(),await n().catch(()=>{}),t.removeEventListener("abort",d),t.removeEventListener("abort",m),h}finally{y&&clearTimeout(y);}if(k.done||!k.value||t.aborted)throw a.releaseLock(),await n().catch(()=>{}),t.removeEventListener("abort",d),t.removeEventListener("abort",m),new Error("[OpenRTC] media track ended before its encoder became ready.");let w=k.value,A=e.kind==="video"?"vp8":typeof l.AudioEncoder=="function"?"opus":"pcm",v=(this.options.codec??A).toLowerCase(),f=v.startsWith("avc1")?"h264":v.startsWith("av01")?"av1":v,u=e.kind==="audio"&&f==="pcm";if(f==="pcm"&&e.kind!=="audio")throw w.close?.(),a.releaseLock(),await n().catch(()=>{}),t.removeEventListener("abort",d),new Error("[OpenRTC] PCM is supported only for audio tracks.");let O=e.kind==="video"?l.VideoEncoder:l.AudioEncoder;if(!u&&typeof O!="function")throw w.close?.(),a.releaseLock(),await n().catch(()=>{}),t.removeEventListener("abort",d),new Error("[OpenRTC] WebCodecs encode support is required for compressed browser media.");let D={publicationId:this.publicationId,kind:e.kind,codec:f,clockRate:e.kind==="audio"?Number(w.sampleRate??48e3):1e6,codedWidth:e.kind==="video"?Number(w.displayWidth??w.codedWidth):void 0,codedHeight:e.kind==="video"?Number(w.displayHeight??w.codedHeight):void 0,channels:e.kind==="audio"?Number(w.numberOfChannels??2):void 0},G=Promise.resolve(),S=null,L=false,I=null,N=null,F=null,q=0,V=false,W=false,z=false,_=new Map,U=h=>N?(F??(F=N(h)),F):Promise.resolve(),Q=()=>{U("media-generation-replaced").catch(()=>{});},x=h=>{S===null&&(S=h),o(),a.cancel("media-sender-failed").catch(()=>{}),U("media-sender-failed").catch(()=>{});},K=()=>{L=true,o(),a.cancel("media-peer-receiver-stopped").catch(()=>{});},X=h=>{try{if(t.aborted||S){this.stats.dropped+=1;return}let E=Number(h.timestamp??0),T=_.get(E);T!==void 0&&(this.encodeLatency.observe(C()-T),_.delete(E));let b=e.kind==="video"?ke:Re,P=e.kind==="video"?Te:Se,M=new Uint8Array(h.byteLength);if(this.pendingWrites.size>=b||this.stats.queuedBytes+M.byteLength>P||!I){this.stats.dropped+=1;return}h.copyTo(M),this.stats.accepted+=1;let R=++this.nextPendingWriteId,te=C();this.pendingWrites.set(R,{bytes:M.byteLength,acceptedAtMs:te}),this.updatePendingWriteStats(te),G=G.then(async()=>{let $=this.pendingWrites.get(R);if(!$||t.aborted)return;if(C()-$.acceptedAtMs>J){this.pendingWrites.delete(R),this.stats.dropped+=1;return}if(this.updatePendingWriteStats(),!this.pendingWrites.has(R))return;let pe=await this.runtime.encodeOpenRtcMediaSample({publicationId:this.id,timestampUs:Number(h.timestamp??0),durationUs:Number(h.duration??0),keyframe:h.type==="key",discardable:e.kind==="video"&&h.type!=="key",payload:M});if(t.aborted||S)return;let Y=this.pendingWrites.get(R);if(!Y||C()-Y.acceptedAtMs>J){Y&&(this.pendingWrites.delete(R),this.stats.dropped+=1);return}this.pendingWrites.delete(R),this.updatePendingWriteStats();let me=C();await I.write(se(pe)),!(t.aborted||S)&&(this.protectedWriteLatency.observe(C()-me),this.stats.transmitted+=1,this.stats.bytes+=M.byteLength);}).catch($=>{We($)?K():x($);}).finally(()=>{this.pendingWrites.delete(R),this.updatePendingWriteStats();});}catch(E){x(E),this.stats.dropped+=1;}},g=u?null:new O({output:X,error:h=>{x(h);}}),j=e.kind==="video"?{codec:H(f),width:D.codedWidth,height:D.codedHeight,bitrate:this.options.bitrate??15e5,framerate:30,latencyMode:"realtime"}:{codec:H(f),sampleRate:D.clockRate,numberOfChannels:D.channels,bitrate:this.options.bitrate??96e3},p=h=>{try{if(t.aborted)return;if(u){let P=Number(h.timestamp??0);_.set(P,C());let M=Ge(h);X({timestamp:P,duration:Number(h.duration??0),type:"key",byteLength:M.byteLength,copyTo(R){R.set(M);}});return}let E=e.kind==="video"?4:8;if(g.encodeQueueSize>=E){this.stats.dropped+=1;return}let T=e.kind==="video"&&q%Pe===0;q+=1;let b=Number(h.timestamp??0);if(_.size>=64){let P=_.keys().next().value;P!==void 0&&_.delete(P);}_.set(b,C()),g.encode(h,e.kind==="video"?{keyFrame:T}:void 0);}finally{h.close?.();}};try{if(!u&&typeof O.isConfigSupported!="function")throw new Error("[OpenRTC] The browser cannot verify WebCodecs encoder support.");let h=u?null:await O.isConfigSupported(j);if(!u&&!h?.supported)throw new Error(`[OpenRTC] The browser cannot encode '${f}' for this track.`);let E=h?.config??j,T=await this.runtime.beginOpenRtcMediaPublication(D);V=!0,this.publicationId=T.publicationId,this.stats.publicationId=T.publicationId,this.stats.mediaGeneration=T.mediaGeneration;let b$1=await this.streams.createBidirectionalStream({protocol:ce});for(N=b(b$1.writable),I=b$1.writable.getWriter(),t.addEventListener("abort",Q,{once:!0}),t.aborted&&Q(),b$1.readable.cancel("media-v1-has-no-reverse-control").catch(()=>{}),await I.write(se(T.control)),g?.configure(E),r(),z=!0,p(w);!t.aborted&&!S&&!L;){let P=await a.read();if(P.done)break;P.value&&p(P.value);}if(!t.aborted&&!S&&!L&&(g&&await Promise.race([g.flush(),c]),!t.aborted&&!S&&!L&&await Promise.race([G,c])),S)throw S;if(L)await this.runtime.pauseOpenRtcMediaPublication(this.publicationId);else if(!t.aborted){let P=I.close();await Promise.race([P,c]),W=!t.aborted&&!S;}}catch(h){throw V&&!t.aborted&&await this.runtime.pauseOpenRtcMediaPublication(this.publicationId),h}finally{if(t.removeEventListener("abort",d),t.removeEventListener("abort",m),t.removeEventListener("abort",Q),z||w.close?.(),a.releaseLock(),await n().catch(()=>{}),g&&g.state!=="closed")try{g.close?.();}catch{}if(I&&!W){let h=t.aborted?"media-generation-replaced":L?"media-peer-receiver-stopped":"media-sender-failed";await U(h).catch(()=>{}),await I.abort(h).catch(()=>{});}await G.catch(()=>{});try{I?.releaseLock();}catch{}}}},ee=class{constructor(e,t,r,l,s){this.id=e;this.track=t;this.stats=r;this.receiveToDecodeLatency=l;this.renderWriteLatency=s;}async getStats(){return {...this.stats,receiveToDecodeLatency:this.receiveToDecodeLatency.snapshot(),renderWriteLatency:this.renderWriteLatency.snapshot()}}},de=class{constructor(e,t,r,l=()=>({registered:true,peers:1,boundConnections:0,observed:0,accepted:0,declined:0,lastResolution:"none"})){this.streams=e;this.runtime=t;this.incomingDemux=l;this.senderMap=new Map;this.receiverMap=new Map;this.listeners=new Set;this.incomingRuns=new Map;this.receiverRuns=new Map;this.incomingFailures=[];this.incomingProtocolStreams=0;this.stopped=false;this.physicalGeneration=null;this.recoveryTail=Promise.resolve();this.stopIncoming=r(ce,s=>{if(this.incomingProtocolStreams+=1,this.stopped||this.incomingRuns.size>=Ae){s.readable.cancel("incoming-media-publication-limit").catch(()=>{}),s.writable.abort("incoming-media-publication-limit").catch(()=>{});return}let a=new AbortController,n=this.receivePublication(s.readable,s.writable,a);this.incomingRuns.set(a,n),n.catch(d=>{let o=d instanceof Error?d.message:String(d);this.incomingFailures.length===Oe&&this.incomingFailures.shift(),this.incomingFailures.push(o),console.error("[OpenRTC][media] incoming publication failed",{message:o});}).finally(()=>this.incomingRuns.delete(a));});}async addTrack(e,t={}){if(this.stopped)throw new Error("[OpenRTC] media connection is closed.");if(e.kind!=="audio"&&e.kind!=="video")throw new Error(`[OpenRTC] Unsupported media track kind '${e.kind}'.`);let r=new Z(e,t,this.streams,this.runtime);try{return await r.start(),this.senderMap.set(r.id,r),r}catch(l){throw await r.stop().catch(()=>{}),l}}async removeTrack(e){let t=this.senderMap.get(e.id);!t||t!==e||(this.senderMap.delete(e.id),await t.stop());}onTrack(e){return this.listeners.add(e),()=>this.listeners.delete(e)}senders(){return [...this.senderMap.values()]}receivers(){return [...this.receiverMap.values()]}async getStats(){return {senders:await Promise.all([...this.senderMap.values()].map(e=>e.getStats())),receivers:await Promise.all([...this.receiverMap.values()].map(e=>e.getStats())),incomingFailures:[...this.incomingFailures],incomingProtocolStreams:this.incomingProtocolStreams,incomingDemux:this.incomingDemux()}}async observePhysicalGeneration(e){if(this.stopped)return;if(Ie(e),this.physicalGeneration===null){this.physicalGeneration={...e};return}let t=this.physicalGeneration;if(!(e.transportGeneration<t.transportGeneration)){if(e.transportGeneration===t.transportGeneration){if(e.transportStableId!==t.transportStableId)throw new Error("[OpenRTC] media rejected an inconsistent physical generation tuple.");e.routeGeneration>t.routeGeneration&&(this.physicalGeneration={...e});return}if(e.transportStableId===t.transportStableId)throw new Error("[OpenRTC] media rejected a reused physical transport identity.");this.physicalGeneration={...e},this.recoveryTail=this.recoveryTail.catch(()=>{}).then(async()=>{if(!this.stopped)for(let r of this.senderMap.values())await r.restartForPhysicalGeneration();}),await this.recoveryTail;}}async close(){if(this.stopped)return;this.stopped=true,this.stopIncoming(),await this.recoveryTail.catch(()=>{}),await Promise.all([...this.senderMap.values()].map(t=>t.stop())),this.senderMap.clear(),this.listeners.clear();let e=[...this.incomingRuns.entries()];for(let[t]of e)t.abort();await Promise.allSettled(e.map(([,t])=>t)),this.incomingRuns.clear(),this.receiverRuns.clear();for(let t of this.receiverMap.values())t.track.stop();this.receiverMap.clear(),this.incomingFailures.splice(0);}async receivePublication(e,t,r){if(this.stopped){await e.cancel("media-connection-closed").catch(()=>{}),await t.abort("media-connection-closed").catch(()=>{});return}let l=xe(e,r.signal),s=null,a;try{a=await Promise.race([l.next(),new Promise((p,h)=>{s=setTimeout(()=>{h(new Error("[OpenRTC] incoming media control timed out."));},ue);})]);}catch(p){throw r.abort(),await l.return(void 0).catch(()=>{}),await e.cancel("incoming-media-control-failed").catch(()=>{}),await t.abort("incoming-media-control-failed").catch(()=>{}),p}finally{s&&clearTimeout(s);}if(a.done){await t.close().catch(()=>{});return}let n;try{let p=await this.runtime.decodeOpenRtcMediaControl(a.value);if(p.type!=="publish")throw new Error("[OpenRTC] media stream did not begin with publish control.");n=p;}catch(p){throw r.abort(),await l.return(void 0).catch(()=>{}),await e.cancel("incoming-media-control-invalid").catch(()=>{}),await t.abort("incoming-media-control-invalid").catch(()=>{}),p}let d=n.publicationId,o=async(p,h)=>{throw r.abort(),await l.return(void 0).catch(()=>{}),await this.runtime.retireOpenRtcMediaReceiver(d,n.mediaGeneration),await t.abort(p).catch(()=>{}),h},c=globalThis,m=n.kind==="audio"&&n.codec==="pcm",y=n.kind==="video"?c.VideoDecoder:c.AudioDecoder,k=n.kind==="video"?c.EncodedVideoChunk:c.EncodedAudioChunk;if(!m&&(typeof y!="function"||typeof k!="function"))return o("media-decoder-api-unavailable",new Error("[OpenRTC] WebCodecs decode support is required for browser media."));if(m&&typeof c.AudioData!="function")return o("media-pcm-api-unavailable",new Error("[OpenRTC] AudioData is required for PCM browser media."));let w=n.kind==="video"?{codec:H(n.codec),codedWidth:n.codedWidth,codedHeight:n.codedHeight,optimizeForLatency:true}:{codec:H(n.codec),sampleRate:n.clockRate,numberOfChannels:n.channels??2};if(!m&&typeof y.isConfigSupported!="function")return o("media-decoder-support-unverifiable",new Error("[OpenRTC] The browser cannot verify WebCodecs decoder support."));let A=null;try{m||(A=await y.isConfigSupported(w));}catch(p){return o("media-decoder-support-check-failed",p)}if(!m&&!A?.supported)return o("media-decoder-unsupported",new Error(`[OpenRTC] The browser cannot decode '${n.codec}'.`));let v,f;try{let p=await oe({kind:n.kind,sampleRate:n.clockRate,channels:n.channels??2,signal:r.signal});v=p.track,f=p.writable.getWriter();}catch(p){return o("media-renderer-setup-failed",p)}let u={publicationId:d,mediaGeneration:n.mediaGeneration,received:0,decoded:0,rendered:0,dropped:0,integrityFailures:0,malformedFrames:0,replayDrops:0,videoRecoveries:0,awaitingKeyframe:n.kind==="video",maxVideoRecoveryMs:0,bytes:0,decoderQueued:0,maxDecoderQueued:0,renderQueued:0,maxRenderQueued:0,receiveToDecodeLatency:new B().snapshot(),renderWriteLatency:new B().snapshot()},O=new B,D=new B,G=new Map,S=[],L=n.kind==="video",I=L,N=null,F=null,q=()=>{L&&(I=true,u.awaitingKeyframe=true,N===null&&(N=C()));},V=Promise.resolve(),W=null,z,_=new Promise(p=>{z=p;}),U=()=>{z(),f.abort("media-receiver-cancelled").catch(()=>{});};r.signal.addEventListener("abort",U,{once:true}),r.signal.aborted&&U();let Q=p=>{W===null&&(W=p),r.abort();},x=0,K=n.kind==="video"?Ce:Ee,X=(p,h=0)=>{if(r.signal.aborted||W){p.close?.();return}u.decoderQueued=h;let E=Number(p.timestamp??0),T=L?G.get(E):S.shift();if(T!==void 0&&(O.observe(C()-T),L&&G.delete(E)),x>=K){u.dropped+=1,p.close?.();return}x+=1,u.renderQueued=x,u.maxRenderQueued=Math.max(u.maxRenderQueued,x),V=V.then(async()=>{if(r.signal.aborted)return;let b=C();await f.write(p),D.observe(C()-b),u.decoded+=1,u.rendered+=1;}).catch(b=>{r.signal.aborted||Q(b);}).finally(()=>{p.close?.(),x-=1,u.renderQueued=x;});},g=null;try{m||(g=new y({output:p=>{X(p,Number(g?.decodeQueueSize??0));},error:p=>{r.signal.aborted||Q(p);}})),g?.configure(A?.config??w);}catch(p){r.signal.removeEventListener("abort",U),f.abort("media-decoder-setup-failed").catch(()=>{});try{f.releaseLock();}catch{}return v.stop(),o("media-decoder-setup-failed",p)}let j=new ee(d,v,u,O,D);try{let p=this.receiverRuns.get(d);if(p&&p.abort!==r&&p.mediaGeneration>=n.mediaGeneration)throw new Error(`[OpenRTC] stale media generation ${n.mediaGeneration} cannot replace ${p.mediaGeneration} for '${d}'.`);if(this.receiverRuns.set(d,{mediaGeneration:n.mediaGeneration,abort:r}),p&&p.abort!==r&&(p.abort.abort(),await this.incomingRuns.get(p.abort)?.catch(()=>{})),this.stopped||r.signal.aborted)return;let h=this.receiverMap.get(d);h&&h.track.stop(),this.receiverMap.set(d,j);let E=new MediaStream([v]);for(let T of this.listeners)try{T({track:v,receiver:j,streams:[E]});}catch{}for await(let T of l){if(r.signal.aborted||W||this.stopped)break;let b;try{b=await this.runtime.decodeOpenRtcMediaChunk(T);}catch(M){let R=String(M);/integrity/i.test(R)?(u.integrityFailures+=1,q()):/replay|retired/i.test(R)?u.replayDrops+=1:/truncated|invalidmagic|unsupported|chunktoolarge|too large|lengthmismatch/i.test(R)?(u.malformedFrames+=1,q()):u.dropped+=1;continue}if(r.signal.aborted||this.stopped)break;if(b.publicationId!==d||b.mediaGeneration!==n.mediaGeneration){u.dropped+=1;continue}if(F!==null&&b.sequence>F+1&&q(),F=F===null?b.sequence:Math.max(F,b.sequence),u.received+=1,u.bytes+=b.payload.byteLength,L&&I){if(!b.keyframe){u.dropped+=1;continue}if(N!==null){let M=C()-N;u.videoRecoveries+=1,u.maxVideoRecoveryMs=Math.max(u.maxVideoRecoveryMs,M),g?.reset?.(),g?.configure(A?.config??w);}I=!1,N=null,u.awaitingKeyframe=!1;}if((g?.decodeQueueSize??x)>=K){u.dropped+=1;continue}let P=C();if(L){if(G.size>=64){let M=G.keys().next().value;M!==void 0&&G.delete(M);}G.set(b.timestampUs,P);}else S.length>=64&&S.shift(),S.push(P);if(m){let M=n.channels??2,R=M*2;if(b.payload.byteLength===0||b.payload.byteLength%R!==0){u.dropped+=1;continue}X(new c.AudioData({format:"s16-planar",sampleRate:n.clockRate,numberOfFrames:b.payload.byteLength/R,numberOfChannels:M,timestamp:b.timestampUs,data:b.payload}));}else try{g.decode(new k({type:b.keyframe?"key":"delta",timestamp:b.timestampUs,duration:b.durationUs||void 0,data:b.payload}));}catch(M){Q(M);break}u.decoderQueued=Number(g?.decodeQueueSize??x),u.maxDecoderQueued=Math.max(u.maxDecoderQueued,u.decoderQueued);}if(!r.signal.aborted&&!W&&g&&await Promise.race([g.flush(),_]),!r.signal.aborted&&!W&&await Promise.race([V,_]),W)throw W}finally{r.signal.removeEventListener("abort",U);try{g?.close?.();}catch{}r.signal.aborted||W?f.abort("media-receiver-finished").catch(()=>{}):f.close().catch(()=>{});try{f.releaseLock();}catch{}this.receiverRuns.get(d)?.abort===r&&this.receiverRuns.delete(d),this.receiverMap.get(d)===j&&this.receiverMap.delete(d),await this.runtime.retireOpenRtcMediaReceiver(d,u.mediaGeneration),v.stop(),r.signal.aborted||W?t.abort("media-receiver-finished").catch(()=>{}):t.close().catch(()=>{});}}};export{se as a,de as b};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {d as d$1,a as a$1}from'./chunk-3B4IDT2M.js';var s="openrtc-ticket-v1.",c=16*1024,d=/^[A-Za-z0-9_.:@-]{1,160}$/;function n(t){return d$1(a$1.TICKET_INVITE_INVALID,t,{retryable:false,plane:"admission"})}function a(t){if(!/^[A-Za-z0-9_-]+$/.test(t))throw n("[OpenRTC] Invalid ticket invitation encoding.");return atob(t.replace(/-/g,"+").replace(/_/g,"/"))}function g(t){if(typeof t.id!="string"||!d.test(t.id)||!Number.isSafeInteger(t.maxPeers)||t.maxPeers<2||t.maxPeers>8||typeof t.mesh!="boolean"||typeof t.ticket!="string"||!t.ticket||t.ticket.length>c)throw n("[OpenRTC] Invalid ticket invitation.");let i=t.ticket.lastIndexOf(".");if(i<1)throw n("[OpenRTC] Ticket invitation has no endpoint grant.");let e;try{e=JSON.parse(a(t.ticket.slice(i+1)));}catch{throw n("[OpenRTC] Ticket invitation has an invalid endpoint grant.")}if(!e||typeof e!="object"||Array.isArray(e)||e.s!==`ticket:${t.id}`||typeof e.t!="string"||!e.t||e.m!==0||typeof e.h!="string"||!e.h||typeof e.e!="number"||!Number.isSafeInteger(e.e)||e.e<=Date.now()||e.a!=="openrtc:endpoint-ticket:v1"||typeof e.n!="string"||!e.n)throw n("[OpenRTC] Ticket invitation grant does not match its avenue.");return t}function u(t){if(t.length>c||!t.startsWith(s))throw n("[OpenRTC] Invalid ticket invitation format.");let i;try{i=JSON.parse(a(t.slice(s.length)));}catch{throw n("[OpenRTC] Invalid ticket invitation body.")}if(!i||typeof i!="object"||Array.isArray(i)||Object.keys(i).some(e=>!["id","ticket","max_peers","mesh"].includes(e)))throw n("[OpenRTC] Invalid ticket invitation body.");return g({id:i.id,ticket:i.ticket,maxPeers:i.max_peers,mesh:i.mesh})}var l=class{constructor(i){this.transmit=i;this.pending=null;this.running=false;this.closedError=null;}send(i){return this.closedError?Promise.reject(this.closedError):new Promise((e,p)=>{this.pending&&this.pending.resolve(),this.pending={payload:i.slice(),resolve:e,reject:p},this.pump();})}close(i=new Error("Latest-state channel is closed.")){this.closedError=i;let e=this.pending;this.pending=null,e?.reject(i);}pump(){this.running||this.closedError||(this.running=true,(async()=>{for(;this.pending&&!this.closedError;){let i=this.pending;this.pending=null;try{await this.transmit(i.payload),i.resolve();}catch(e){i.reject(e);}}})().finally(()=>{this.running=false,this.pending&&!this.closedError&&this.pump();}));}};export{l as a,u as b};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {a as a$1}from'./chunk-AYHD4X2R.js';import {o,b,a,t,m,g,x,y,h,z,B,C,F,G,H,d as d$1,e as e$1}from'./chunk-WD47V4PK.js';import {c,e,d,f,b as b$1}from'./chunk-XMYBBLYK.js';import {a as a$2}from'./chunk-OT7IPLZE.js';import {a as a$3}from'./chunk-CNAW5BZ3.js';import {c as c$1}from'./chunk-CCCYE3XN.js';import {a as a$4}from'./chunk-JPBW67B3.js';function _(u){if(!u)return null;let e=2166136261;for(let t=0;t<u.length;t+=1)e^=u.charCodeAt(t),e=Math.imul(e,16777619);return `fp-${(e>>>0).toString(16).padStart(8,"0")}`}var R=class R{constructor(e){this.deps=e;this.startedAutoConnectKey=null;this.browserAutoConnectUnsubscribe=null;this.desiredPeerRevision=0;this.desiredPeerSignature=null;this.desiredPeerSubmission=null;this.desiredPeerSubmissionQueue=Promise.resolve();this.queuedDesiredPeers=null;this.desiredPeersByDeviceId=new Map;this.wakeSubmission=null;this.presenceState=null;this.presenceStartGeneration=0;this.localExcludedPeers=new Set;this.localDesiredPeerDeviceId=null;for(let t of e.initialExcludedPeers??[]){let i=t.trim().toLowerCase();i&&this.localExcludedPeers.add(i);}}stop(){this.stopAutoConnect(),this.stopPresenceLoop();}get autoConnectKey(){return this.startedAutoConnectKey}set autoConnectKey(e){this.startedAutoConnectKey=e;}get presenceLoopState(){return this.presenceState}set presenceLoopState(e){this.presenceState=e;}stopPresence(){this.stopPresenceLoop();}updatePresenceLoopState(e){this.presenceState=e;}startAutoConnect(e,t){if(this.deps.isTicketOnlyMode())return;let i=t.trim()||this.deps.resolveWebLogicalDeviceId(),n=`${e}::${i}`;this.startedAutoConnectKey===n&&this.browserAutoConnectUnsubscribe||(this.stopAutoConnect(),this.localDesiredPeerDeviceId=i,this.startedAutoConnectKey=n,this.browserAutoConnectUnsubscribe=this.deps.getCoordinationSignaling().onDevicesChange(o=>this.submitDesiredPeers(o),this.currentLocalNodeId()??void 0));}wakeRustAutoConnectOwner(){return this.deps.isTicketOnlyMode()||!this.startedAutoConnectKey||this.wakeSubmission?false:(this.wakeSubmission=this.deps.waitForWasmClient(500).then(async e=>{e&&typeof e.wake_browser_auto_connect=="function"&&await e.wake_browser_auto_connect();}).finally(()=>{this.wakeSubmission=null;}),true)}submitDesiredPeers(e){if(!this.startedAutoConnectKey)return;let i=this.normalizeDesiredPeers(e);this.rememberDesiredPeers(i)&&(this.queuedDesiredPeers=i,this.flushDesiredPeerSubmission());}observeDesiredPeerProjection(e){this.rememberDesiredPeers(this.normalizeDesiredPeers(e));}async submitDesiredPeerProjection(e,t){if(!Number.isSafeInteger(e)||e<=0)throw new Error("Desired-peer projection revision must be a positive safe integer.");let i=this.startedAutoConnectKey;if(!i)throw new Error("Cannot submit a desired-peer projection before managed auto-connect starts.");let n=this.normalizeDesiredPeers(t);this.rememberDesiredPeers(n),this.queuedDesiredPeers=null,this.desiredPeerRevision=Math.max(this.desiredPeerRevision,e),await this.enqueueDesiredPeerSubmission(i,e,n);}async handleRoomArchitectureChange(){let e=this.startedAutoConnectKey;if(this.deps.isTicketOnlyMode()||!e)return false;let t=Array.from(this.desiredPeersByDeviceId.values());this.queuedDesiredPeers=null;let i=++this.desiredPeerRevision;return await this.enqueueDesiredPeerSubmission(e,i,t),true}rememberDesiredPeers(e){this.desiredPeersByDeviceId=new Map(e.map(i=>[i.deviceId,i]));let t=JSON.stringify(e);return t===this.desiredPeerSignature?false:(this.desiredPeerSignature=t,this.deps.onDesiredPeersChanged?.(),true)}resolveDesiredPeer(e,t){let i=typeof e=="string"?e.trim():"",n=typeof t=="string"?t.trim():"";if(i){let o=this.desiredPeersByDeviceId.get(i);if(o&&(!n||!o.nodeId||o.nodeId===n))return o}return n?Array.from(this.desiredPeersByDeviceId.values()).find(o=>o.nodeId===n)??null:null}flushDesiredPeerSubmission(){if(this.desiredPeerSubmission||!this.queuedDesiredPeers||!this.startedAutoConnectKey)return;let e=this.startedAutoConnectKey,t=this.queuedDesiredPeers,i=++this.desiredPeerRevision;this.queuedDesiredPeers=null,this.desiredPeerSubmission=this.enqueueDesiredPeerSubmission(e,i,t).catch(()=>{}).finally(()=>{this.desiredPeerSubmission=null,this.flushDesiredPeerSubmission();});}normalizeDesiredPeers(e){return (Array.isArray(e)?e:[]).map(t=>({deviceId:String(t?.deviceId??"").trim(),nodeId:typeof t?.nodeId=="string"&&t.nodeId.trim()||null,ticket:typeof t?.ticket=="string"&&t.ticket.trim()||null,online:t?.online===true,sessionId:typeof t?.sessionId=="string"&&t.sessionId.trim()||null,excludedPeers:Array.isArray(t?.excludedPeers)?[...new Set(t.excludedPeers.map(i=>String(i??"").trim().toLowerCase()).filter(Boolean))].sort():[],devicePublicKeyJwk:t?.devicePublicKeyJwk,topologyRole:t?.topologyRole,topologyRevision:t?.topologyRevision})).filter(t=>t.deviceId.length>0).sort((t,i)=>t.deviceId.localeCompare(i.deviceId))}enqueueDesiredPeerSubmission(e,t,i,n=this.roomGossipFanoutEnabled()){let o=this.desiredPeerSubmissionQueue.then(async()=>{if(this.startedAutoConnectKey!==e)return;let r=await this.deps.waitForWasmClient();if(this.startedAutoConnectKey===e){if(!r||typeof r.submit_browser_desired_peers!="function"){this.deps.warnMissingWasmOnce("submitBrowserDesiredPeers");return}if(await Promise.all(i.map(async s=>{if(s.ticket)try{await this.deps.rememberRouteRepairTokenFromTicket(s.ticket);}catch(c){console.warn("[WasmSignaling] failed to retain desired-peer admission token",{deviceId:s.deviceId,nodeId:s.nodeId,error:c});}})),n){if(typeof r.submit_browser_desired_peers_with_sparse_fanout!="function"){await r.submit_browser_desired_peers(t,JSON.stringify([])),this.deps.warnMissingWasmOnce("submitBrowserDesiredPeersWithSparseFanout");return}if(!this.deps.capabilityKey)throw new Error("Sparse fanout requires an explicit capability avenue.");await r.submit_browser_desired_peers_with_sparse_fanout(t,JSON.stringify(i),this.deps.capabilityKey,this.localDesiredPeerDeviceId,this.deps.localDeviceKeyX,true);}else await r.submit_browser_desired_peers(t,JSON.stringify(i));}});return this.desiredPeerSubmissionQueue=o.catch(r=>{console.warn("[WasmSignaling] failed to submit browser desired peers to Rust",{revision:t,error:r});}),o}roomGossipFanoutEnabled(){return typeof this.deps.roomGossipFanout=="function"?this.deps.roomGossipFanout():this.deps.roomGossipFanout===true}async excludeAutoConnect(e,t){let i=await this.deps.waitForWasmClient();i&&typeof i.set_auto_connect_excluded=="function"&&await i.set_auto_connect_excluded(e,t),await this.recordAutoConnectExcludedForPresence(e,t);}async installInitialAutoConnectExclusions(e){if(typeof e?.set_auto_connect_excluded=="function")for(let t of this.currentExcludedPeersSnapshot())await e.set_auto_connect_excluded(t,true);}async recordAutoConnectExcludedForPresence(e,t){let i=e.trim().toLowerCase();if(!i)return;t?this.localExcludedPeers.add(i):this.localExcludedPeers.delete(i);let n=this.deps.resolveWebLogicalDeviceId();n&&await this.deps.updateExcludedPeers(n,this.currentExcludedPeersSnapshot());}async startPresenceLoop(e,t,i,n,o){if(this.deps.isTicketOnlyMode())return;this.stopPresenceLoop();let r=this.presenceStartGeneration;this.presenceState={userId:e,localNodeId:t,ticket:n,metadata:o,deviceName:i};let s=this.deps.resolveWebLogicalDeviceId(),c=await this.deps.withWebPresenceMetadata(o,s);r!==this.presenceStartGeneration||this.presenceState===null||await this.deps.updatePresence(t,n,true,R.PRESENCE_LEASE_MS,c,i);}stopAutoConnect(){this.browserAutoConnectUnsubscribe?.(),this.browserAutoConnectUnsubscribe=null,this.startedAutoConnectKey=null,this.localDesiredPeerDeviceId=null,this.desiredPeerSignature=null,this.queuedDesiredPeers=null,this.desiredPeersByDeviceId.clear(),this.wakeSubmission=null;}currentExcludedPeersSnapshot(){return Array.from(this.localExcludedPeers).sort()}currentLocalNodeId(){let e=this.presenceState?.localNodeId;return typeof e=="string"&&e.trim()||null}stopPresenceLoop(){this.presenceStartGeneration+=1,this.presenceState=null;}};R.PRESENCE_LEASE_MS=15*6e4;var M=R;function ne(){if(!(typeof window>"u"))try{if(new URL(import.meta.url).pathname.includes("/node_modules/.vite/deps/"))return new URL("/node_modules/openrtc/dist/openrtc_bg.wasm",window.location.origin)}catch{}}async function oe(){let u=await import('./openrtc-H2DETG65.js');return {initWasm:e=>u.default(e??ne()),WasmClient:u.WasmClient,start:u.start}}function re(u){try{let e=u.replace(/-/g,"+").replace(/_/g,"/"),t=(4-e.length%4)%4,i=e+"=".repeat(t);if(typeof atob=="function")return JSON.parse(atob(i));let n=globalThis.Buffer;if(n)return JSON.parse(n.from(i,"base64").toString("utf8"))}catch{return null}return null}function se(u){let e=typeof u=="string"?u.trim():"";if(!e)return {present:false};let t=e.lastIndexOf("."),i=t>=0?e.slice(0,t):e,n=t>=0?e.slice(t+1):null,o=n?re(n):null,r=o&&typeof o.t=="string"&&o.t.trim().length>0?o.t.trim():null,s=o&&typeof o.s=="string"&&o.s.trim().length>0?o.s.trim():null,c=o&&typeof o.m=="number"&&Number.isFinite(o.m)?o.m:null;return {present:true,irohFingerprint:_(i),tokenFingerprint:_(r),tokenSuffixFingerprint:_(n),scope:s,maxConnections:c}}function E(u,e,t={}){let i=typeof u.finishSend=="function"?u.finishSend.bind(u):typeof u.finish_send=="function"?u.finish_send.bind(u):null,n=typeof u.cancelSend=="function"?u.cancelSend.bind(u):typeof u.cancel_send=="function"?u.cancel_send.bind(u):null;if(!i){if(t.requireFinish===true)throw new Error("WASM peer stream is missing finishSend(); rebuild the current OpenRTC WASM before sending application data");return e}let o=e.getWriter(),r=new WritableStream({write:s=>o.write(s),async close(){await o.close(),await i();},async abort(s){await n?.(),await o.abort(s);}});return a$4(r,n)}var p=class p{constructor(e$1){this.spaceNamespaceIdPromise=null;this.cachedSpaceNamespaceId=null;this.authListeners=[];this.wasmClient=null;this.createdAtMs=Date.now();this.missingWasmWarnings=new Set;this.wasmReadyWarningDelayMs=15e3;this.browserCoordinationSignaling=null;this.effectiveRoomArchitecture="mesh";this.lastObservedFirebaseUserId=null;this.sessionReaders=new Set;this.authContext=null;this.injectedBrowserAuthSessionActive=false;this.hasSyncedAuthToWasmClient=false;this.lastWasmAuthUserId=null;this.lastWasmAuthToken=null;this.lastDeliveredConnectionStates=new Map;this.authScopedRuntimeGeneration=0;this.coreClient=null;this.applicationRouteEscalations=new Map;this.applicationRouteEscalationAttemptKeys=new Map;this.applicationRouteEscalationUnsubscribe=null;this.routeSubscriptionGeneration=-1;this.applicationRouteEscalationSubscriptionEpoch=0;this.appTag=c(e$1),this.options={...e$1,appTag:this.appTag,authMode:d(e$1),projectId:e(e$1)},this.effectiveRoomArchitecture=e$1.coordinationRoomArchitecture==="sparse"||e$1.coordinationRoomGossipFanout===true?"sparse":"mesh",this.coordinationHost=new b({appTag:this.appTag,projectId:this.options.projectId,discoveryMode:this.options.discoveryMode,signalingMode:this.options.signalingMode,gateway:this.options.coordinationGateway,avenueOverride:this.options.coordinationAvenueOverride,roomArchitecture:this.options.coordinationRoomArchitecture,initialExcludedPeers:this.options.initialAutoConnectExcludedDeviceIds,resolveSpaceNamespaceId:()=>this.ensureSpaceNamespaceIdPromise(),getCurrentUserId:()=>this.getCurrentUserId(),getAuthToken:async(r=false)=>this.currentUser?.getToken?.(r)??null,getAppCheckToken:async(r=false)=>{let s=this.authContext?.appCheckTokenProvider??this.options.attestationTokenProvider;return s?s(r):a().getAppCheckToken(r)},getLocalDeviceId:()=>this.resolveWebLogicalDeviceId(),getDefaultDeviceName:()=>this.getDefaultBrowserDeviceName(),getPlatformType:()=>this.options.coordinationPlatformType??"web",normalizeDevice:(r,s)=>this.normalizeDevice(r,s)});let n=this.options.coordinationRoomGossipFanout===true||this.options.coordinationRoomArchitecture==="auto"||this.options.coordinationRoomArchitecture==="sparse"?c$1(this.options.coordinationAvenueOverride).key:void 0;if(this.presenceManager=new M({isTicketOnlyMode:()=>this.isTicketOnlyMode(),waitForWasmClient:(r,s)=>this.waitForWasmClient(r,s),warnMissingWasmOnce:r=>this.warnMissingWasmOnce(r),resolveWebLogicalDeviceId:()=>this.resolveWebLogicalDeviceId(),withWebPresenceMetadata:(r,s)=>this.withWebPresenceMetadata(r,s),updatePresence:(r,s,c,a,d,h)=>this.updatePresence(r,s,c,a,d,h),updateExcludedPeers:(r,s)=>this.getCoordinationSignaling().updateDevice(r,{excludedPeers:s}),getCoordinationSignaling:()=>this.getCoordinationSignaling(),rememberRouteRepairTokenFromTicket:r=>this.coreClient?.rememberRouteRepairTokenFromTicket?.(r)??Promise.resolve(false),onDesiredPeersChanged:()=>this.retryManagedApplicationRouteEscalations(),roomGossipFanout:()=>this.effectiveRoomArchitecture==="sparse",capabilityKey:n,localDeviceKeyX:this.options.coordinationDevicePublicKeyX,initialExcludedPeers:this.options.initialAutoConnectExcludedDeviceIds}),this.persistenceReady=Promise.resolve(),this.isTicketOnlyMode()||this.usesProviderNeutralGrant()){this.app=null,this.auth=null;return}let o=a();this.app=o.getApp(),this.auth=o.getAuth(),o.onAuthStateChanged(r=>{if(this.authContext)return;if(this.isSpaceMode()){this.authListeners.forEach(a=>a(this.toRuntimeIdentity(r)));return}let s=r?.uid??null,c=this.lastObservedFirebaseUserId;this.lastObservedFirebaseUserId=s,c&&c!==s&&this.stopAuthActivity({userId:c}),this.browserCoordinationSignaling?.handleScopeChange()??this.coordinationHost.handleScopeChange(),this.authListeners.forEach(a=>a(this.toRuntimeIdentity(r)));});}async loadBrowserWasmRuntime(){return oe()}get tag(){return this.appTag}capabilities(){return t()}getDeviceIdentityStorageKey(){let e=f(this.options);return `${p.WEB_DEVICE_ID_STORAGE_PREFIX}_${e}`}getDeviceIdPersistenceMode(){return this.options.deviceIdPersistence??this.options.nodeIdPersistence??"persistent"}isTicketOnlyMode(){return this.options.signalingMode==="ticket-only"}usesProviderNeutralGrant(){return typeof this.options.coordinationGateway?.grantProvider=="function"}createRandomDeviceId(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`web-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}resolveWebLogicalDeviceId(){let e=this.options.localDeviceId?.trim();if(e)return e;let t=this.getDeviceIdPersistenceMode();if(typeof localStorage>"u")return this.createRandomDeviceId();let i=this.getDeviceIdentityStorageKey(),n=Date.now(),o=null;try{let d=localStorage.getItem(i);o=d?JSON.parse(d):null;}catch{o=null;}let r=typeof o?.deviceId=="string"?o.deviceId.trim():"",s=typeof o?.expiresAt=="number"?o.expiresAt:void 0;if(t==="persistent"){let d=r||this.createRandomDeviceId();return localStorage.setItem(i,JSON.stringify({deviceId:d})),d}if(r&&typeof s=="number"&&s>n){let d=n+p.EPHEMERAL_DEVICE_ID_TTL_MS;return localStorage.setItem(i,JSON.stringify({deviceId:r,expiresAt:d})),r}let c=this.createRandomDeviceId(),a=n+p.EPHEMERAL_DEVICE_ID_TTL_MS;return localStorage.setItem(i,JSON.stringify({deviceId:c,expiresAt:a})),c}getDefaultBrowserDeviceName(){return this.options.deviceName?.trim()||(this.options.storagePrefix?`Web (${this.options.storagePrefix.replace(/_$/,"")})`:"Web Browser")}async getLocalDeviceInfo(){return {deviceId:this.resolveWebLogicalDeviceId(),deviceName:this.getDefaultBrowserDeviceName(),platformType:this.options.coordinationPlatformType??"web"}}getCoordinationSignaling(){return this.browserCoordinationSignaling??this.coordinationHost.getSignaling()}usesCoordinationGateway(){return this.coordinationHost.usesGateway()}setCoordinationHostAvailability(e){this.coordinationHost.setHostAvailability(e),this.browserCoordinationSignaling?.setHostAvailability?.(e);}async reconnectCoordinationAfterHostResume(){let e=this.browserCoordinationSignaling;if(e?.reconnectAfterHostResume){await e.reconnectAfterHostResume();return}await this.coordinationHost?.reconnectAfterHostResume();}async getCoordinationNativeTrustToken(e=false){return this.coordinationHost.getNativeTrustToken(e)}invalidateCoordinationNativeTrustToken(){this.coordinationHost.invalidateNativeTrustToken();}subscribeCoordinationNativeTrustToken(e,t){return this.coordinationHost.subscribeNativeTrustToken(e,t)}setCoordinationLocalDeviceId(e){if(!this.options.coordinationGateway)return;let t=e.trim();t&&(this.options.localDeviceId=t);}setCoordinationPlatformType(e){this.options.coordinationGateway&&(this.options.coordinationPlatformType=e);}async setCoordinationExcludedPeers(e){let t=this.resolveWebLogicalDeviceId();if(!t)throw new Error("The local device must be known before publishing peer exclusions.");await this.getCoordinationSignaling().updateDevice(t,{excludedPeers:e});}async joinCoordinationRoom(e,t,i){let n=this.getCoordinationSignaling();if(!n.joinCoordinationRoom)throw new Error("The active coordination provider does not support rooms.");await n.joinCoordinationRoom(e,t,i);}async leaveCoordinationRoom(e){await this.getCoordinationSignaling().leaveCoordinationRoom?.(e);}async getCoordinationRoomMembers(e){let t=this.getCoordinationSignaling();if(!t.getCoordinationRoomMembers)throw new Error("The active coordination provider does not support rooms.");return t.getCoordinationRoomMembers(e)}watchCoordinationRoomMembers(e,t){let i=this.getCoordinationSignaling();if(!i.watchCoordinationRoomMembers)throw new Error("The active coordination provider does not support rooms.");return i.watchCoordinationRoomMembers(e,t)}async withWebPresenceMetadata(e,t){let i;if(!e||!e.trim())i=JSON.stringify({deviceId:t});else {try{let n=JSON.parse(e);if(n&&typeof n=="object"&&!Array.isArray(n))return i=JSON.stringify({...n,deviceId:t}),await m(i)??i}catch{}i=JSON.stringify({deviceId:t,metadata:e});}return await m(i)??i}async setAuthContext(e){let t=this.injectedBrowserAuthSessionActive,i=this.authContext?.userId??null,n=e?.userId??null;if(this.authContext=e,!this.isTicketOnlyMode()&&!this.usesProviderNeutralGrant()&&e?.customToken?.trim()&&!(g()&&this.options.authMode==="external"&&typeof e.tokenProvider=="function"))try{await this.ensureBrowserPlatformAuth(e.userId,e.customToken.trim());}catch(o){console.warn("[WasmBridge] ensureBrowserPlatformAuth failed (non-fatal):",o);}else if(!this.isTicketOnlyMode()&&!this.usesProviderNeutralGrant()&&!e&&t)try{await this.auth?.signOut();}catch(o){console.warn("[WasmBridge] Failed to clear injected browser auth session:",o);}finally{this.injectedBrowserAuthSessionActive=false;}this.syncWasmAuthToken(),!this.isTicketOnlyMode()&&i!==n&&await(this.browserCoordinationSignaling?.handleScopeChange()??this.coordinationHost.handleScopeChange()),this.authListeners.forEach(o=>o(this.currentUser));}async ensureBrowserPlatformAuth(e,t){if((this.auth?.currentUser?.uid??null)===e){this.injectedBrowserAuthSessionActive=true;return}await a().signInWithCustomTokenValue(t),this.injectedBrowserAuthSessionActive=true;}syncWasmAuthToken(){let e=this.wasmClient?.setIdentityCredential??this.wasmClient?.set_auth_token;if(!this.wasmClient||typeof e!="function"||!this.authContext&&this.isSpaceMode())return;let t=this.authContext?.userId??null,i=this.authContext?.token,n=typeof i=="string"&&i.trim().length>0?i:null;if(!(this.hasSyncedAuthToWasmClient&&this.lastWasmAuthUserId===t&&this.lastWasmAuthToken===n)){if(this.lastWasmAuthUserId=t,this.lastWasmAuthToken=n,this.hasSyncedAuthToWasmClient=true,n===null&&typeof this.wasmClient.clearIdentityCredential=="function"){this.wasmClient.clearIdentityCredential();return}e.call(this.wasmClient,n);}}toRuntimeIdentity(e){return e?{id:e.uid,email:e.email,displayName:e.displayName,isAnonymous:e.isAnonymous,getToken:async(t=false)=>{try{return await e.getIdToken(t)}catch{return null}}}:null}getCurrentUserId(){return this.authContext?.userId?this.authContext.userId:this.isTicketOnlyMode()?null:this.auth?.currentUser?.uid??null}getCurrentUserIdForScope(){return this.getCurrentUserId()}getAuthContext(){return this.authContext}isSpaceMode(){return x(this.options)}getResolvedOptions(){return this.options}getDiscoveryScopeId(){if(this.isTicketOnlyMode())return null;let e=this.getCurrentUserId();return e||(this.isSpaceMode()?this.resolveWebLogicalDeviceId():null)}matchesTag(e){return y(e,this.appTag,this.isSpaceMode())}matchesLegacyOrCurrentTag(e){return this.matchesTag(e)}async stopSessionSubscriptions(){let e=Array.from(this.sessionReaders);this.sessionReaders.clear(),await Promise.allSettled(e.map(async t=>{try{await t.cancel();}catch{}}));}async stopRuntimeAuthScopedLoops(){let e=await this.waitForWasmClient(250);if(e)try{typeof e.stop_auth_scoped_activity=="function"?await e.stop_auth_scoped_activity():(typeof e.stop_presence_loop=="function"&&await e.stop_presence_loop(),typeof e.stop_auto_connect=="function"&&await e.stop_auto_connect());}catch(t){console.warn("[WasmSignaling] Failed to stop auth-scoped runtime loops:",t);}}async stopAuthActivity(e){h("WasmBridge.stopAuthActivity",{userId:e?.userId??null}),this.authScopedRuntimeGeneration+=1,this.stopApplicationRouteEscalationSubscription();let t=await this.waitForWasmClient(500);if(t&&typeof t.revoke_tokens_by_scope=="function")try{await t.revoke_tokens_by_scope("user-device");}catch(i){console.warn("[WasmBridge] user-device revoke during auth-scoped shutdown failed:",i);}this.presenceManager.stop(),this.browserCoordinationSignaling?.stopAuthActivity(),this.coordinationHost?.stopAuthActivity(),await this.stopSessionSubscriptions(),this.lastDeliveredConnectionStates.clear(),this.applicationRouteEscalations?.clear(),this.applicationRouteEscalationAttemptKeys?.clear(),await this.stopRuntimeAuthScopedLoops();}setWasmClient(e){this.wasmClient=e,this.coordinationHost.setWasmClient(e),this.lastWasmAuthUserId=null,this.lastWasmAuthToken=null,this.hasSyncedAuthToWasmClient=this.authContext===null,this.lastDeliveredConnectionStates.clear(),this.applicationRouteEscalations?.clear(),this.applicationRouteEscalationAttemptKeys?.clear(),this.syncWasmAuthToken();}async createBroadcastPublisher(){let e=await this.waitForWasmClient();if(!e)throw new Error("WASM broadcast publisher runtime is unavailable");return a$1.create(e)}async initializePersistentIrohProtocols(e){let t=await this.waitForWasmClient(),i=t?.__initPersistentIrohProtocols;if(typeof i!="function")throw new Error("This OpenRTC WASM host was built without persistent Iroh protocols");await i.call(t,e);}async createPersistentIrohNamespace(e,t){return (await this.requirePersistentProtocolHost()).__createPersistentIrohNamespace(BigInt(e),BigInt(t))}async importPersistentIrohTicket(e,t,i){return (await this.requirePersistentProtocolHost()).__importPersistentIrohTicket(e,BigInt(t),BigInt(i))}async sharePersistentIrohNamespace(e,t){return (await this.requirePersistentProtocolHost()).__sharePersistentIrohNamespace(e,t)}async removePersistentIrohNamespace(e,t,i){await(await this.requirePersistentProtocolHost()).__removePersistentIrohNamespace(e,BigInt(t),BigInt(i));}async putPersistentIrohBytes(e,t,i){return (await this.requirePersistentProtocolHost()).__putPersistentIrohBytes(e,t,i)}async setPersistentIrohHash(e,t,i,n){return (await this.requirePersistentProtocolHost()).__setPersistentIrohHash(e,t,i,BigInt(n))}async deletePersistentIrohPrefix(e,t){return (await this.requirePersistentProtocolHost()).__deletePersistentIrohPrefix(e,t)}async queryPersistentIrohNamespace(e,t){return (await this.requirePersistentProtocolHost()).__queryPersistentIrohNamespace(e,t)}async hydratePersistentIrohBlob(e){await(await this.requirePersistentProtocolHost()).__hydratePersistentIrohBlob(e);}async acknowledgePersistentIrohOutbox(e){await(await this.requirePersistentProtocolHost()).__acknowledgePersistentIrohOutbox(e);}async flushPersistentIrohProtocols(){await(await this.waitForWasmClient(500))?.__flushPersistentIrohProtocols?.();}async shutdownPersistentIrohProtocols(){await(await this.waitForWasmClient(500))?.__shutdownPersistentIrohProtocols?.();}async requirePersistentProtocolHost(){let e=await this.waitForWasmClient();if(!e||typeof e.__queryPersistentIrohNamespace!="function")throw new Error("This OpenRTC WASM host was built without persistent Iroh protocols");return e}warnMissingWasmOnce(e){!this.wasmClient&&Date.now()-this.createdAtMs<this.wasmReadyWarningDelayMs||this.missingWasmWarnings.has(e)||(this.missingWasmWarnings.add(e),console.warn(`[WasmSignaling] ${e} skipped: wasm client is not ready.`));}async waitForWasmClient(e=4e3,t=50){if(this.wasmClient)return this.wasmClient;let i=Date.now();for(;!this.wasmClient&&Date.now()-i<e;)await a$2(t);return this.wasmClient??null}normalizeDevice(e,t){return z(e,t)}normalizeDeviceRecord(e,t){return this.normalizeDevice(e,t)}getResolvedWebLogicalDeviceId(){return this.resolveWebLogicalDeviceId()}async encodeSparseFanoutMessage(e,t){let i=await this.waitForWasmClient(),n=this.options.coordinationDeviceSign;if(!i?.prepareSparseFanoutMessage||!i?.finalizeSparseFanoutMessage||!n)throw new Error("[OpenRTC] Browser sparse fanout signer is unavailable.");let o=await i.prepareSparseFanoutMessage(e,t),r=new Uint8Array(o.signingInput??o.signing_input??[]),s=await n(r);return new Uint8Array(await i.finalizeSparseFanoutMessage(String(o.requestId??o.request_id??""),s))}async acceptSparseFanoutMessage(e,t,i){let n=await this.waitForWasmClient();if(!n?.acceptSparseFanoutMessage)throw new Error("[OpenRTC] Browser sparse fanout verifier is unavailable.");let o=await n.acceptSparseFanoutMessage(e,t,i);return {payload:new Uint8Array(o.payload??[]),authorDeviceId:String(o.authorDeviceId??o.author_device_id??""),authorPeerId:String(o.authorPeerId??o.author_peer_id??""),topologyRevision:Number(o.topologyRevision??o.topology_revision),hop:Number(o.hop),forwardPeerIds:Array.isArray(o.forwardPeerIds??o.forward_peer_ids)?(o.forwardPeerIds??o.forward_peer_ids).map(String):[],forwardPeerLimit:Number(o.forwardPeerLimit??o.forward_peer_limit),forwardQueueCapacity:Number(o.forwardQueueCapacity??o.forward_queue_capacity),...o.forward==null?{}:{forward:new Uint8Array(o.forward)}}}async recordSparseFanoutForwardQueueDrop(e,t){let i=await this.waitForWasmClient();i?.recordSparseFanoutForwardQueueDrop&&await i.recordSparseFanoutForwardQueueDrop(e,t);}normalizeDeviceStatusSnapshot(e){return B(e)}normalizePeerSessionSnapshot(e){return C(e)}toBackendConnectionStateFromPeerSession(e){return F(e)}normalizeStateSnapshot(e){return G(e)}stabilizeConnectionState(e){let t=this.lastDeliveredConnectionStates.get(e.connectionId);return {...e,deviceId:e.deviceId??t?.deviceId??null,deviceIdHint:e.deviceIdHint??t?.deviceIdHint??null,remoteNodeId:e.remoteNodeId??t?.remoteNodeId??null,createdAt:e.createdAt??t?.createdAt,updatedAt:e.updatedAt??t?.updatedAt}}sameConnectionState(e,t){return H(e,t)}deliverConnectionState(e,t,i,n){let o=this.stabilizeConnectionState(e);this.lastDeliveredConnectionStates.set(o.connectionId,o);let s=(n??this.lastDeliveredConnectionStates).get(o.connectionId);this.sameConnectionState(s,o)||(n&&n.set(o.connectionId,o),t(o));}get browserPresenceLoopState(){return this.presenceManager.presenceLoopState}set browserPresenceLoopState(e){this.presenceManager.presenceLoopState=e;}get currentUser(){if(this.authContext?.userId){let e=this.authContext.token??null,t=this.authContext.tokenProvider;return {id:this.authContext.userId,getToken:async(i=false)=>{if(e&&(!i||!t))return e;if(t)try{let o=await t(i);if(o)return o}catch{}let n=this.isTicketOnlyMode()?null:this.auth?.currentUser??null;if(n&&n.uid===this.authContext?.userId)try{return await n.getIdToken(i)}catch{return null}return null}}}return this.isTicketOnlyMode()?null:this.toRuntimeIdentity(this.auth?.currentUser??null)}onAuthChange(e){return this.authListeners.push(e),e(this.currentUser),()=>{this.authListeners=this.authListeners.filter(t=>t!==e);}}async checkForSSOToken(){this.isTicketOnlyMode()||this.usesProviderNeutralGrant()||await a().checkForSSOToken();}async waitForAuth(){this.isTicketOnlyMode()||this.usesProviderNeutralGrant()||this.isSpaceMode()||this.authContext?.userId||this.auth?.currentUser||await a().waitForAuth();}async signInAnonymously(){if(!this.isTicketOnlyMode()){if(this.options.authMode!=="anonymous")throw new Error(`[pluto-rtc] Anonymous sign-in is disabled when authMode=${this.options.authMode}.`);await a().signInAnonymously();}}async signInWithPluto(){if(this.isTicketOnlyMode())throw new Error('[openrtc] Pluto sign-in is unavailable when signalingMode="ticket-only".');await a().signInWithPluto();}async signOut(){let e=this.getCurrentUserId();await this.stopAuthActivity({userId:e}),this.authContext=null,this.syncWasmAuthToken(),this.isTicketOnlyMode()||await this.auth?.signOut(),this.authListeners.forEach(t=>t(this.currentUser));}async getTurnCredentials(){return this.isTicketOnlyMode()||!this.auth?.currentUser?null:typeof this.options.turnCredentialsProvider=="function"?await this.options.turnCredentialsProvider()??null:null}async updatePresence(e,t,i=true,n=3e5,o,r){if(this.isTicketOnlyMode())return;let s=this.resolveWebLogicalDeviceId(),c=this.getDeviceIdPersistenceMode()==="ephemeral"?p.EPHEMERAL_DEVICE_ID_TTL_MS:n,a=await this.withWebPresenceMetadata(o,s);this.presenceManager.updatePresenceLoopState({userId:this.getCurrentUserId()??"",localNodeId:e,ticket:t,metadata:a,deviceName:r?.trim()||this.getDefaultBrowserDeviceName()}),await this.getCoordinationSignaling().updatePresence(e,t,i,c,a,r);}async refreshLivePresence(e,t,i,n){if(this.isTicketOnlyMode())return;let o=this.resolveWebLogicalDeviceId(),r=await this.withWebPresenceMetadata(i,o);this.presenceManager.updatePresenceLoopState({userId:this.getCurrentUserId()??"",localNodeId:e,ticket:t,metadata:r,deviceName:n?.trim()||this.getDefaultBrowserDeviceName()}),await this.getCoordinationSignaling().updatePresence(e,t,true,15*6e4,r,n);}async setOffline(e){this.presenceManager.stopPresence(),!this.isTicketOnlyMode()&&await this.getCoordinationSignaling().setOffline(e);}async updateDevice(e,t){if(!e?.trim())throw new Error("updateDevice requires a deviceId");this.isTicketOnlyMode()||await this.getCoordinationSignaling().updateDevice(e,t);}async deleteDevice(e){if(!e?.trim())throw new Error("deleteDevice requires a deviceId");this.isTicketOnlyMode()||await this.getCoordinationSignaling().deleteDevice(e);}async cleanupStaleDevices(){this.isTicketOnlyMode()||await this.getCoordinationSignaling().cleanupStaleDevices();}async sendMessage(e,t,i,n){if(this.isTicketOnlyMode())throw new Error('[openrtc] sendMessage() is unavailable when signalingMode="ticket-only".');return this.getCoordinationSignaling().sendMessage(e,t,i,n)}async pollMessages(e){return this.isTicketOnlyMode()?[]:this.getCoordinationSignaling().pollMessages(e)}async searchDevices(e){return this.isTicketOnlyMode()?[]:this.getCoordinationSignaling().searchDevices(e)}async listDeviceStatus(){if(this.isTicketOnlyMode())return [];if(!this.getDiscoveryScopeId())return [];let t=await this.getCoordinationSignaling().listDevices(),i=this.wasmClient;return Promise.all(t.map(async n=>{let o=this.normalizeDeviceStatusSnapshot({...n,connectionStatus:n.online?"online":"disconnected"}),r=typeof n.nodeId=="string"?n.nodeId.trim():"";if(!r||typeof i?.iroh_path_kind!="function"||typeof i?.iroh_transport_rtt_ms!="function")return o;try{let[s,c]=await Promise.all([i.iroh_path_kind(r),i.iroh_transport_rtt_ms(r)]);if(typeof c!="number"||!Number.isFinite(c))return o;let a=Math.max(0,Math.round(c)),d={};if(s==="direct-lan")d.irohLan=a;else if(s==="direct-quic")d.iroh=a;else if(s==="ble")d.ble=a;else if(s==="relay")d.irohRelay=a;else if(s==="webrtc")d.webrtc=a;else if(s==="moq")d.moq=a;else return o;return {...o,latencyMs:a,latencyByTransport:d}}catch(s){return d$1("[WasmBridge] iroh transport latency unavailable",{deviceId:n.deviceId,error:s instanceof Error?s.message:String(s)}),o}}))}async getPeerSession(e){let t=await this.waitForWasmClient(500);if(t&&typeof t.peer_session=="function"){let i=await t.peer_session(e);return !i||typeof i!="object"?null:this.normalizePeerSessionSnapshot(i)}return this.warnMissingWasmOnce("getPeerSession"),null}async listPeerSessions(){let e=await this.waitForWasmClient(500);if(e&&typeof e.peer_sessions=="function"){let t=await e.peer_sessions();return (Array.isArray(t)?t:[]).map(n=>this.normalizePeerSessionSnapshot(n)).filter(n=>!!(n.peerId||n.deviceId||n.deviceIdHint||n.nodeId||n.activeConnectionId))}return this.warnMissingWasmOnce("listPeerSessions"),[]}async waitForSettledPeer(e,t){let i=await this.waitForWasmClient(500);if(i&&typeof i.wait_for_peer=="function"){let n=await i.wait_for_peer(e,t);return !n||typeof n!="object"?null:this.normalizePeerSessionSnapshot(n)}return this.warnMissingWasmOnce("waitForSettledPeer"),null}async waitForSettledScope(e,t){let i=await this.waitForWasmClient(500);if(i&&typeof i.wait_for_settled_scope=="function"){let n=await i.wait_for_settled_scope(e,t);return !n||typeof n!="object"?null:this.normalizePeerSessionSnapshot(n)}return this.warnMissingWasmOnce("waitForSettledScope"),null}async openPeerBi(e,t){let i=await this.waitForWasmClient(500);if(i&&typeof i.open_peer_bi=="function"){let n=await i.open_peer_bi(e,t);if(!n?.recv||!n?.send)throw new Error("WASM open_peer_bi returned an invalid bidirectional stream");return {readable:n.recv,writable:E(n,n.send)}}throw this.warnMissingWasmOnce("openPeerBi"),new Error("WASM runtime does not support open_peer_bi()")}async openPeerBiRaw(e,t){if(this.options.applicationCrypto?.requireEncrypted)throw new Error("[WasmBridge] openPeerBiRaw is debug-only and cannot be used when application crypto is required");let i=await this.waitForWasmClient(500),n=i&&typeof i.open_peer_bi_transport_only=="function";if(console.debug("[WasmBridge] openPeerBiRaw",{peerId:e,hasWasmClient:!!i,hasTransportOnly:n,timeoutMs:t}),n){let o=await i.open_peer_bi_transport_only(e,t);if(!o?.recv||!o?.send)throw new Error("WASM open_peer_bi_transport_only returned an invalid bidirectional stream");return {readable:o.recv,writable:E(o,o.send)}}throw new Error("WASM runtime does not support the restricted transport-only diagnostic stream")}async openPeerUni(e,t){let i=await this.waitForWasmClient(500);if(i&&typeof i.open_peer_uni=="function"){let n=await i.open_peer_uni(e,t),o=n?.writable??n;if(!o)throw new Error("WASM open_peer_uni returned an invalid writable stream");return {writable:E(n,o)}}throw this.warnMissingWasmOnce("openPeerUni"),new Error("WASM runtime does not support open_peer_uni()")}beginOpenRtcMediaPublication(e){let t=this.wasmClient?.__beginOpenRtcMediaPublication;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include Rust-owned media sessions.");let i=t.call(this.wasmClient,e.publicationId||void 0,e.kind,e.codec,e.clockRate,e.codedWidth,e.codedHeight,e.channels);return {...i,control:new Uint8Array(i.control)}}encodeOpenRtcMediaSample(e){let t=this.wasmClient?.__encodeOpenRtcMediaSample;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include Rust-owned media sessions.");return new Uint8Array(t.call(this.wasmClient,e.publicationId,e.timestampUs,e.durationUs,e.keyframe,e.discardable,e.payload))}pauseOpenRtcMediaPublication(e){let t=this.wasmClient?.__pauseOpenRtcMediaPublication;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include Rust-owned media sessions.");t.call(this.wasmClient,e);}retireOpenRtcMediaPublication(e){let t=this.wasmClient?.__retireOpenRtcMediaPublication;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include Rust-owned media sessions.");t.call(this.wasmClient,e);}retireOpenRtcMediaReceiver(e,t){let i=this.wasmClient?.__retireOpenRtcMediaReceiver;if(typeof i!="function")throw new Error("[OpenRTC] This WASM build does not include Rust-owned media sessions.");i.call(this.wasmClient,e,t);}decodeOpenRtcMediaChunk(e){let t=this.wasmClient?.__decodeOpenRtcMediaChunk;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include the shared media protocol.");let i=t.call(this.wasmClient,e);return {...i,payload:new Uint8Array(i.payload)}}decodeOpenRtcMediaControl(e){let t=this.wasmClient?.__decodeOpenRtcMediaControl;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include the shared media protocol.");return t.call(this.wasmClient,e)}async sendPeerDatagram(e,t,i){let n=await this.waitForWasmClient(500),o=n?.sendPeerDatagram;if(typeof o!="function")throw new Error("[OpenRTC] This WASM build does not include protected peer datagrams.");return await o.call(n,e,t,i)!==false}async receivePeerDatagram(e){let t=await this.waitForWasmClient(500),i=t?.receivePeerDatagram;if(typeof i!="function")throw new Error("[OpenRTC] This WASM build does not include protected peer datagrams.");return new Uint8Array(await i.call(t,e))}peerDatagramMaxSize(){let e=this.wasmClient?.peerDatagramMaxSize?.();return Number.isSafeInteger(e)&&e>0?e:1024}createPeerDatagramPolicy(){let e=this.wasmClient?.createPeerDatagramPolicy;if(typeof e!="function")throw new Error("[OpenRTC] This WASM build does not include shared datagram policy.");return e.call(this.wasmClient)}async resolvePeerRecords(e){let t=await this.waitForWasmClient(500);if(t&&typeof t.resolve_peer_connection_records=="function"){let i=await t.resolve_peer_connection_records(e);return (Array.isArray(i)?i:[]).map(n=>({connectionId:typeof n.connectionId=="string"?n.connectionId:"",nodeId:typeof n.nodeId=="string"?n.nodeId:null,deviceId:typeof n.deviceId=="string"?n.deviceId:null,deviceIdHint:typeof n.deviceIdHint=="string"?n.deviceIdHint:null,endpointId:typeof n.endpointId=="string"?n.endpointId:null,transportGeneration:typeof n.transportGeneration=="number"?n.transportGeneration:0,routeGeneration:typeof n.routeGeneration=="number"?n.routeGeneration:void 0,transportStableId:typeof n.transportStableId=="number"?n.transportStableId:null,transportSource:typeof n.transportSource=="string"?n.transportSource:null,lastTransportChangeAtMs:typeof n.lastTransportChangeAtMs=="number"?n.lastTransportChangeAtMs:0,lastRouteChangeAtMs:typeof n.lastRouteChangeAtMs=="number"?n.lastRouteChangeAtMs:void 0,state:typeof n.state=="string"?n.state:"pending",statusReason:typeof n.statusReason=="string"?n.statusReason:null,createdAtMs:typeof n.createdAtMs=="number"?n.createdAtMs:0,updatedAtMs:typeof n.updatedAtMs=="number"?n.updatedAtMs:0}))}return this.warnMissingWasmOnce("resolvePeerRecords"),[]}async resolvePeerIdentity(e){let t=await this.waitForWasmClient(500);if(t){let i=n=>{if(!n||typeof n!="object")return {peerId:null,deviceId:null,deviceIdHint:null,nodeId:null};let o=n;return {peerId:typeof o.peerId=="string"?o.peerId:null,deviceId:typeof o.deviceId=="string"?o.deviceId:null,deviceIdHint:typeof o.deviceIdHint=="string"?o.deviceIdHint:null,nodeId:typeof o.nodeId=="string"?o.nodeId:null}};if(typeof t.peer_session=="function")try{let n=await t.peer_session(e),o=i(n);if(o.peerId||o.deviceId||o.deviceIdHint||o.nodeId)return o}catch{}if(typeof t.peer_snapshot=="function")try{return i(await t.peer_snapshot(e))}catch{}}return this.warnMissingWasmOnce("resolvePeerIdentity"),{peerId:null,deviceId:null,deviceIdHint:null,nodeId:null}}onDevicesChange(e,t){return this.isTicketOnlyMode()?(e([]),()=>{}):this.getCoordinationSignaling().onDevicesChange(e,t)}onRoomArchitectureChange(e){return this.getCoordinationSignaling().onRoomArchitectureChange?.(t=>{let i=this.effectiveRoomArchitecture!==t.effective;this.effectiveRoomArchitecture=t.effective,i&&this.presenceManager.handleRoomArchitectureChange().catch(n=>{console.warn("[WasmSignaling] failed to replay desired peers after room architecture change",{effectiveArchitecture:t.effective,epoch:t.epoch,error:n});}),e(t);})??(()=>{})}onRoomAuthorityAssignmentChange(e){return this.getCoordinationSignaling().onRoomAuthorityAssignmentChange?.(e)??(()=>{})}async publishAuthorityAssignment(e){let t=this.getCoordinationSignaling();if(!t.publishAuthorityAssignment)throw new Error("[OpenRTC] Authority assignment publication is unavailable.");await t.publishAuthorityAssignment(e);}async publishManagedRoomMessage(e){let t=this.getCoordinationSignaling().publishManagedRoomMessage;if(!t)throw new Error("[OpenRTC] Managed room fanout is unavailable.");await t.call(this.getCoordinationSignaling(),e);}onManagedRoomMessage(e){return this.getCoordinationSignaling().onManagedRoomMessage?.(e)??(()=>{})}async subscribeDevices(e){return this.isTicketOnlyMode()?new ReadableStream({start(t){t.close();}}):this.getCoordinationSignaling().subscribeDevices()}async startAutoConnect(e,t){if(this.isTicketOnlyMode())return;this.startApplicationRouteEscalationSubscription();let i=this.authScopedRuntimeGeneration;try{let n=await this.waitForWasmClient();if(i!==this.authScopedRuntimeGeneration||!n||typeof n.start_auto_connect!="function")return;await this.presenceManager.installInitialAutoConnectExclusions(n),await n.start_auto_connect(e,t),i===this.authScopedRuntimeGeneration&&this.presenceManager.startAutoConnect(e,t);}catch(n){console.warn("[WasmBridge] failed to initialize WASM auto-connect context",{userId:e,localDeviceId:t,error:n});}}async startAutoConnectOnce(e,t){await this.startAutoConnect(e,t),this.forceReconnect();}notifyDisconnectRequested(e){this.presenceManager.wakeRustAutoConnectOwner();}async excludeAutoConnect(e,t){await this.presenceManager.excludeAutoConnect(e,t);}async disconnectDevice(e){let t=await this.waitForWasmClient();if(!t||typeof t.disconnect_device!="function"){this.warnMissingWasmOnce("disconnectDevice"),await this.presenceManager.excludeAutoConnect(e,true).catch(()=>{});return}try{await t.disconnect_device(e,null),await this.presenceManager.recordAutoConnectExcludedForPresence(e,!0).catch(()=>{});}catch(i){throw console.warn("[WasmBridge] disconnect_device failed",{deviceId:e,error:i?.message??String(i)}),i}}async submitDesiredPeerProjection(e,t){return this.presenceManager.submitDesiredPeerProjection(e,t)}observeManagedDesiredPeers(e){this.presenceManager.observeDesiredPeerProjection(e),e$1("[OpenRTC][route-escalation] observed managed desired peers",{peerCount:e.length,peersWithTickets:e.filter(t=>typeof t.ticket=="string"&&t.ticket.trim()).length,deviceIds:e.map(t=>t.deviceId)});}setCoreClient(e){e&&typeof e.ensureManagedApplicationRoute=="function"?(this.coreClient=e,e$1("[OpenRTC][route-escalation] attached shared core client"),this.startApplicationRouteEscalationSubscription(),this.retryManagedApplicationRouteEscalations()):(this.coreClient=null,e$1("[OpenRTC][route-escalation] detached shared core client"),this.stopApplicationRouteEscalationSubscription());}startApplicationRouteEscalationSubscription(){if(this.applicationRouteEscalationUnsubscribe&&this.routeSubscriptionGeneration===this.authScopedRuntimeGeneration)return;this.stopApplicationRouteEscalationSubscription();let e=this.authScopedRuntimeGeneration,t=this.applicationRouteEscalationSubscriptionEpoch,i=this.onStateChange(n=>{let o=this.stabilizeConnectionState(n);this.lastDeliveredConnectionStates.set(o.connectionId,o),e$1("[OpenRTC][route-escalation] observed Rust connection state",{connectionId:o.connectionId,deviceId:o.deviceId??o.deviceIdHint??null,remoteNodeId:o.remoteNodeId??null,state:o.state,transportGeneration:o.transportGeneration??null,routeGeneration:o.routeGeneration??null}),this.escalateManagedApplicationRoute(o);});this.applicationRouteEscalationUnsubscribe=()=>{},this.routeSubscriptionGeneration=e,Promise.resolve(i).then(n=>{if(!this.coreClient||e!==this.authScopedRuntimeGeneration||t!==this.applicationRouteEscalationSubscriptionEpoch){n();return}this.applicationRouteEscalationUnsubscribe=n,this.routeSubscriptionGeneration=e;});}stopApplicationRouteEscalationSubscription(){this.applicationRouteEscalationSubscriptionEpoch+=1,this.applicationRouteEscalationUnsubscribe?.(),this.applicationRouteEscalationUnsubscribe=null,this.routeSubscriptionGeneration=-1;}retryManagedApplicationRouteEscalations(){for(let e of this.lastDeliveredConnectionStates.values())this.escalateManagedApplicationRoute(e);}escalateManagedApplicationRoute(e){if(!this.coreClient||!["connected","connecting"].includes(e.state))return;let t=[e.transportGeneration??0,e.routeGeneration??0].join(":"),i=this.applicationRouteEscalationAttemptKeys??(this.applicationRouteEscalationAttemptKeys=new Map);if(i.get(e.connectionId)===t||this.applicationRouteEscalations.has(e.connectionId))return;let n=this.presenceManager.resolveDesiredPeer(e.deviceId??e.deviceIdHint,e.remoteNodeId);if(!n?.ticket){e$1("[OpenRTC][route-escalation] awaiting matching desired-peer ticket",{connectionId:e.connectionId,deviceId:e.deviceId??e.deviceIdHint??null,remoteNodeId:e.remoteNodeId??null});return}let o=this.authScopedRuntimeGeneration,r=this.coreClient;i.set(e.connectionId,t),e$1("[OpenRTC][route-escalation] adopting Rust-managed generation",{connectionId:e.connectionId,deviceId:n.deviceId,remoteNodeId:e.remoteNodeId??n.nodeId??null,transportGeneration:e.transportGeneration??null,routeGeneration:e.routeGeneration??null});let s;s=(async()=>{let c=await r.ensureManagedApplicationRoute({ticket:n.ticket,connectionId:e.connectionId,remoteNodeId:e.remoteNodeId??n.nodeId,expectedDeviceId:n.deviceId,timeoutMs:2e4});if(o!==this.authScopedRuntimeGeneration)return;let a=c,d=a.id?.trim()||e.connectionId,h=a.remoteNodeId?.trim()||e.remoteNodeId?.trim()||a.deviceId?.trim()||n.deviceId;if(r.hasApplicationRouteForPeer?.(d,h)!==true&&r.hasApplicationRouteForPeer?.(d,h)!==true)throw new Error(`application crypto was not ready for ${h}`)})().catch(c=>{o===this.authScopedRuntimeGeneration&&console.warn("[OpenRTC][route-escalation] Rust-managed route remains pending",{connectionId:e.connectionId,deviceId:n.deviceId,remoteNodeId:e.remoteNodeId??n.nodeId,error:c?.message??String(c)});}).finally(()=>{if(this.applicationRouteEscalations.get(e.connectionId)===s){this.applicationRouteEscalations.delete(e.connectionId);let c=this.lastDeliveredConnectionStates?.get(e.connectionId),a=c?[c.transportGeneration??0,c.routeGeneration??0].join(":"):null;c&&a!==t&&o===this.authScopedRuntimeGeneration&&queueMicrotask(()=>this.escalateManagedApplicationRoute(c));}}),this.applicationRouteEscalations.set(e.connectionId,s);}async issueTicketMesh(e,t,i){let n=await this.waitForWasmClient();if(typeof n?.issue_ticket_mesh!="function")throw new Error("WASM runtime does not support Rust-owned ticket meshes.");return n.issue_ticket_mesh(e,t,i)}async joinTicketMesh(e,t){let i=await this.waitForWasmClient();if(typeof i?.join_ticket_mesh!="function")throw new Error("WASM runtime does not support Rust-owned ticket meshes.");return i.join_ticket_mesh(e,t)}async receiveTicketMeshFrame(e,t,i){let n=await this.waitForWasmClient();if(typeof n?.receive_ticket_mesh_frame!="function")throw new Error("WASM runtime does not support Rust-owned ticket meshes.");n.receive_ticket_mesh_frame(e,t,i);}async ticketMeshIssuerNode(e){let t=await this.waitForWasmClient();if(typeof t?.ticket_mesh_issuer_node!="function")throw new Error("WASM ticket mesh issuer projection is unavailable.");return t.ticket_mesh_issuer_node(e)}async closeTicketMesh(e){let t=await this.waitForWasmClient();if(typeof t?.close_ticket_mesh!="function")throw new Error("WASM runtime does not support closing Rust-owned ticket meshes.");await t.close_ticket_mesh(e);}async connectToDevice(e){let t=await this.waitForWasmClient();if(!t||typeof t.connect_device!="function")throw this.warnMissingWasmOnce("connectToDevice"),new Error("WASM runtime does not support connect_device()");let i=e.endpointTicket?.trim()??"",n=e.admissionToken?.trim()??"",o=e.admissionScope?.trim()??"",r=!i,s=i;if(r&&(!e.deviceId||!n||!o||typeof t.connect_known_device_with_token!="function"))throw new Error("WASM connectToDevice requires an endpoint ticket or supported known-device admission intent.");let c=Date.now();e$1("[WasmBridge][ROUTE-ESCALATION] starting managed transport dial",{deviceId:e.deviceId??null,ticket:se(i),knownDeviceAdmission:r,hasCoreClient:!!this.coreClient});let a=r?await(async()=>{let h=Date.now(),l=Math.max(1,e.timeoutMs??3e4),m=()=>Math.max(1,l-(Date.now()-h)),y=e.admissionPeerUserId?.trim()??"";if(y){let v=(await this.getCoordinationSignaling().waitForFriendDevice(y,e.deviceId,Math.min(1e4,m()))).ticket?.trim()??"";if(!v)throw new Error(`[pluto-rtc] authorized device ${e.deviceId} did not publish an endpoint ticket.`);if(typeof t.observe_known_device_endpoint!="function")throw new Error("WASM runtime does not support provider-authorized endpoint observations.");await t.observe_known_device_endpoint(e.deviceId,v),s=a$3(v).irohTicket;}return t.connect_known_device_with_token(e.deviceId,n,o,e.admissionMaxConnections??0,e.admissionExpiresAtMs==null?null:BigInt(Math.floor(e.admissionExpiresAtMs)),Math.min(1e4,m()))})():await t.connect_device(e.deviceId??null,i,e.timeoutMs??null);e$1("[WasmBridge][ROUTE-ESCALATION] managed transport dial completed",{deviceId:e.deviceId??null,remoteNodeId:a?.remoteNodeId??null,connectionId:a?.connectionId??null,elapsedMs:Date.now()-c});let d=s;if(d&&this.coreClient){let h=this.coreClient;try{e$1("[WasmBridge][ROUTE-ESCALATION] starting typed application connection",{deviceId:e.deviceId??null,remoteNodeId:a?.remoteNodeId??null,connectionId:a?.connectionId??null});let l=await h.ensureManagedApplicationRoute({ticket:d,connectionId:a?.connectionId??null,remoteNodeId:a?.remoteNodeId??null,expectedDeviceId:e.deviceId??null,approvedScope:a?.approvedScope??null,timeoutMs:2e4}),m=typeof l?.remoteNodeId=="string"?l.remoteNodeId.trim():"",y=typeof l?.deviceId=="string"?l.deviceId.trim():"",g=m||a?.remoteNodeId?.trim?.()||y||e.deviceId?.trim?.()||"",v=typeof h.hasApplicationRouteForPeer=="function"?h.hasApplicationRouteForPeer.bind(h):null;if(!(!!g&&v?.(l?.id??void 0,g)===!0)&&g&&typeof h.waitForApplicationCryptoForPeer=="function"&&!(!!await h.waitForApplicationCryptoForPeer(g,2e4)&&(!v||v(l?.id??void 0,g)===!0)))throw console.warn("[WasmBridge][ROUTE-ESCALATION] application route still pending after managed dial",{deviceId:e.deviceId??null,remoteNodeId:m||(a?.remoteNodeId??null),connectionId:a?.connectionId??null,peerForCrypto:g,elapsedMs:Date.now()-c}),Object.assign(new Error(`application crypto was not ready for ${g}`),{applicationCryptoNotReady:!0});e$1("[WasmBridge][ROUTE-ESCALATION] application route ready",{deviceId:e.deviceId??null,remoteNodeId:m||(a?.remoteNodeId??null),connectionId:a?.connectionId??null,elapsedMs:Date.now()-c});}catch(l){if(l?.applicationCryptoNotReady)throw l;return console.warn("[WasmBridge] Managed transport connected; TS application route escalation is still pending",{deviceId:e.deviceId??null,remoteNodeId:a?.remoteNodeId??null,connectionId:a?.connectionId??null,error:l?.message??String(l)}),a}}return a}forceReconnect(){this.isTicketOnlyMode()||!this.app||!this.auth||this.presenceManager.wakeRustAutoConnectOwner();}startPresenceLoop(e,t,i,n,o){return this.presenceManager.startPresenceLoop(e,t,i,n,o)}ensureSpaceNamespaceIdPromise(){if(this.cachedSpaceNamespaceId)return Promise.resolve(this.cachedSpaceNamespaceId);if(!this.spaceNamespaceIdPromise){let e=this.options.apiKey?.trim()??"",t=this.options.spaceKey?.trim()??"";if(!e||!t)return Promise.resolve(null);this.spaceNamespaceIdPromise=b$1(e,t).then(i=>(this.cachedSpaceNamespaceId=i,i)).catch(()=>null);}return this.spaceNamespaceIdPromise}async createSession(e){if(this.isTicketOnlyMode())throw new Error('[openrtc] createSession() is unavailable when signalingMode="ticket-only".');let t=this.getCurrentUserId();if(!t&&!e.initiator&&!e.target&&!this.isSpaceMode())throw new Error("createSession requires user scope");let i={...e,appTag:e.appTag??this.appTag,initiator:e.initiator??t??void 0,target:e.target??t??void 0};await this.getCoordinationSignaling().createSession(i);}async updateSession(e,t){if(this.isTicketOnlyMode())throw new Error('[openrtc] updateSession() is unavailable when signalingMode="ticket-only".');await this.getCoordinationSignaling().updateSession(e,t);}async subscribeSessions(e){return this.isTicketOnlyMode()?new ReadableStream({start(t){t.close();}}):this.getCoordinationSignaling().subscribeSessions(e)}async getLocalDeviceId(){return this.resolveWebLogicalDeviceId()}async isConnected(e){let t=await this.waitForWasmClient();return t&&typeof t.is_connected=="function"?t.is_connected(e):false}async getConnectionStates(){let e=await this.waitForWasmClient(500);if(e&&typeof e.connection_states=="function"){let n=await e.connection_states(),o=(Array.isArray(n)?n:[]).map(r=>this.normalizeStateSnapshot(r)).filter(r=>!!r);return o.length>0&&d$1("[WasmBridge] replaying current wasm connection states",o.map(r=>({connectionId:r.connectionId,deviceId:r.deviceId??null,deviceIdHint:r.deviceIdHint??null,remoteNodeId:r.remoteNodeId??null,state:r.state,transportState:r.transportState??null,protocolState:r.protocolState??null,routable:r.routable??null}))),o}let i=(await this.listPeerSessions().catch(()=>[])).map(n=>this.toBackendConnectionStateFromPeerSession(n)).filter(n=>!!n);return i.length>0&&d$1("[WasmBridge] replaying current wasm connection states",i.map(n=>({connectionId:n.connectionId,deviceId:n.deviceId??null,deviceIdHint:n.deviceIdHint??null,remoteNodeId:n.remoteNodeId??null,state:n.state,transportState:n.transportState??null,protocolState:n.protocolState??null,routable:n.routable??null}))),i}onStateChange(e){let t=new Map,i=new Map,n=this.authScopedRuntimeGeneration,o=false,r=a=>{let d=a.detail,h=this.normalizeStateSnapshot(d),l=typeof d?.connectionId=="string"?d.connectionId.trim():"";if(!l||o)return;if(h&&(h.state==="closed"||h.state==="failed"||h.state==="disconnected")){this.deliverConnectionState(h,e,"rust-event-detail",t);return}let m=(i.get(l)??0)+1;i.set(l,m);let y=this.authScopedRuntimeGeneration;(async()=>{let g=await this.waitForWasmClient(500);if(!(o||y!==this.authScopedRuntimeGeneration||i.get(l)!==m)){if(g&&typeof g.connection_state=="function"){let v=await g.connection_state(l),w=this.normalizeStateSnapshot(v);if(!o&&y===this.authScopedRuntimeGeneration&&i.get(l)===m&&w){this.deliverConnectionState(w,e,"rust-event",t);return}}!o&&y===this.authScopedRuntimeGeneration&&i.get(l)===m&&h&&this.deliverConnectionState(h,e,"rust-event-detail",t);}})().catch(g=>{o||console.warn("[WasmBridge] Failed to read Rust connection state after lifecycle event",{connectionId:l,error:g});});},s=typeof window<"u"?window:null,c=typeof s?.addEventListener=="function"&&typeof s?.removeEventListener=="function";return c&&s.addEventListener("connection-state-changed",r),this.getConnectionStates().then(a=>{!o&&n===this.authScopedRuntimeGeneration&&a.forEach(d=>{i.has(d.connectionId)||this.deliverConnectionState(d,e,"replay",t);});}).catch(a=>{console.warn("[WasmBridge] Failed to replay wasm connection states after subscription:",a);}),()=>{o=true,i.clear(),c&&s.removeEventListener("connection-state-changed",r);}}async sendExplicitFilePath(e,t,i=""){throw new Error("sendExplicitFilePath is native-only. Use sendExplicitFileData in web/wasm runtime.")}sanitizeExplicitFileName(e){let i=(typeof e=="string"?e.replace(/\\/g,"/"):"").split("/").reverse().find(r=>r.trim().length>0)?.trim()??"";if(!i||i==="."||i==="..")return p.FALLBACK_EXPLICIT_FILE_NAME;let n="";for(let r of i){if([...n].length>=p.MAX_EXPLICIT_FILE_NAME_CHARS)break;let s=r.charCodeAt(0);r==="/"||r==="\\"||r==="\0"||s<32||s===127?n+="_":n+=r;}let o=n.trim();return !o||o==="."||o===".."?p.FALLBACK_EXPLICIT_FILE_NAME:o}sanitizeExplicitMimeType(e){let t=typeof e=="string"?e.trim():"";if(!t)return p.FALLBACK_EXPLICIT_MIME_TYPE;let i="";for(let n of t){if(i.length>=p.MAX_EXPLICIT_MIME_TYPE_CHARS)break;let o=n.charCodeAt(0);o<33||o>126||n==='"'||n==="\\"?i+="_":i+=n;}return i.length>0?i:p.FALLBACK_EXPLICIT_MIME_TYPE}assertExplicitTransferHeaderSize(e){if(e.byteLength===0||e.byteLength>p.MAX_EXPLICIT_TRANSFER_HEADER_BYTES)throw new Error(`Explicit transfer header is too large: ${e.byteLength} bytes`)}createWebRTCExplicitTransferId(){let e=new Uint8Array(16),t=globalThis.crypto;if(t&&typeof t.getRandomValues=="function")return t.getRandomValues(e),e;for(let i=0;i<e.byteLength;i+=1)e[i]=Math.floor(Math.random()*256);return e}createWebRTCExplicitTransferFrame(e,t,i,n,o){let r=o?.headerFrame===true?4:0,s=new Uint8Array(25+r+n.byteLength);s[0]=p.EXPLICIT_FILE_PROTOCOL_TYPE,s.set(e,1);let c=new DataView(s.buffer);c.setUint32(17,t,false),c.setUint32(21,i,false);let a=o?.headerFrame===true?29:25;return o?.headerFrame===true&&c.setUint32(25,n.byteLength,false),s.set(n,a),s}async sendExplicitFileData(e){let t=e.connection,i=e.file,n=e.applicationCrypto??this.options.applicationCrypto;if((e.requireApplicationCrypto===true||t?.requireApplicationCrypto===true)&&!n)throw new Error("[WasmBridge] Explicit transfer requires application crypto but none is available for this connection");let r=e.transferId&&e.transferId.trim().length>0?e.transferId:`transfer-${Date.now()}`;typeof e.receiverPlatformType=="string"?e.receiverPlatformType.trim().toLowerCase():null;let c=e.remoteNodeId?.trim()||t?.remoteNodeId?.trim()||t?.deviceId?.trim();if(e$1("[WasmBridge] sendExplicitFileData start",{connectionId:e.connectionId??null,connectionRemoteNodeId:t?.remoteNodeId??null,remoteNodeId:c??null,fileName:i.name,fileSize:i.size,transferId:r}),!c)throw new Error("Web explicit transfer requires an active connection with a resolved remote node ID");let a=await this.waitForWasmClient();if(!a)throw new Error("WASM explicit transfer requires an initialized WASM client");let d=new TextEncoder,h={transfer_id:r,filename:this.sanitizeExplicitFileName(i.name),size:i.size,mime_type:this.sanitizeExplicitMimeType(i.type)},l=d.encode(JSON.stringify(h));this.assertExplicitTransferHeaderSize(l);let m=new Uint8Array(4);new DataView(m.buffer).setUint32(0,l.byteLength,false);let y=new Uint8Array(m.byteLength+l.byteLength);y.set(m,0),y.set(l,m.byteLength);let g=async()=>{let v=a.open_peer_bi_explicit_file_sender;if(typeof v!="function")return false;let w=await v.call(a,c,5e3),S=w?.writable??w?.send;if(!S||typeof S.getWriter!="function")throw new Error("WASM explicit peer stream returned an invalid writable stream");e$1("[WasmBridge] sendExplicitFileData open_peer_bi_explicit_file_sender resolved",{remoteNodeId:c,transferId:e.transferId??null,applicationCryptoWrapped:w.applicationCryptoWrapped===true});let P=E(w,S,{requireFinish:true}).getWriter(),D=false;try{await P.write(y);let C=new Uint8Array(await i.arrayBuffer());for(let b=0;b<C.byteLength;b+=p.EXPLICIT_FILE_CHUNK_SIZE_BYTES){let ie=C.slice(b,Math.min(b+p.EXPLICIT_FILE_CHUNK_SIZE_BYTES,C.byteLength));await P.write(ie);}}catch(C){throw D=true,C}finally{try{await P.close();}catch(C){if(!D)throw C}finally{P.releaseLock();}}return true};try{if(await g())return;throw new Error("[WasmBridge] Explicit transfer requires the generation-fenced open_peer_bi_explicit_file_sender path, but it is unavailable on this WASM build. Rebuild the current OpenRTC WASM; raw open_bi fallback is intentionally unsupported for application data.")}finally{e$1("[WasmBridge] sendExplicitFileData completed",{remoteNodeId:c,transferId:r,fileName:i.name,fileSize:i.size});}}async getTransferHistory(e=50){return []}async deleteTransferJob(e){}watchFriendDevices(e,t){return this.isTicketOnlyMode()?()=>{}:this.getCoordinationSignaling().watchFriendDevices(e,t)}async updateFriendTicket(e){this.isTicketOnlyMode()||await this.getCoordinationSignaling().updateFriendTicket(e);}};p.EXPLICIT_FILE_PROTOCOL_TYPE=2,p.EXPLICIT_FILE_CHUNK_SIZE_BYTES=64*1024,p.MAX_EXPLICIT_TRANSFER_HEADER_BYTES=64*1024,p.FALLBACK_EXPLICIT_FILE_NAME="openrtc-transfer.bin",p.MAX_EXPLICIT_FILE_NAME_CHARS=180,p.FALLBACK_EXPLICIT_MIME_TYPE="application/octet-stream",p.MAX_EXPLICIT_MIME_TYPE_CHARS=255,p.WEB_DEVICE_ID_STORAGE_PREFIX="pluto_rtc_web_device_identity",p.EPHEMERAL_DEVICE_ID_TTL_MS=o.browserIdentity.ephemeralDeviceIdTtlMs;var te=p;export{oe as a,te as b};
|
|
1
|
+
import {a as a$1}from'./chunk-AYHD4X2R.js';import {o,b,a,t,m,g,x,y,h,z,B,C,F,G,H,d as d$1,e as e$1}from'./chunk-XK2JESZY.js';import {c,e,d,f,b as b$1}from'./chunk-XMYBBLYK.js';import {a as a$2}from'./chunk-OT7IPLZE.js';import {a as a$3}from'./chunk-CNAW5BZ3.js';import {c as c$1}from'./chunk-CCCYE3XN.js';import {a as a$4}from'./chunk-JPBW67B3.js';function _(u){if(!u)return null;let e=2166136261;for(let t=0;t<u.length;t+=1)e^=u.charCodeAt(t),e=Math.imul(e,16777619);return `fp-${(e>>>0).toString(16).padStart(8,"0")}`}var R=class R{constructor(e){this.deps=e;this.startedAutoConnectKey=null;this.browserAutoConnectUnsubscribe=null;this.desiredPeerRevision=0;this.desiredPeerSignature=null;this.desiredPeerSubmission=null;this.desiredPeerSubmissionQueue=Promise.resolve();this.queuedDesiredPeers=null;this.desiredPeersByDeviceId=new Map;this.wakeSubmission=null;this.presenceState=null;this.presenceStartGeneration=0;this.localExcludedPeers=new Set;this.localDesiredPeerDeviceId=null;for(let t of e.initialExcludedPeers??[]){let i=t.trim().toLowerCase();i&&this.localExcludedPeers.add(i);}}stop(){this.stopAutoConnect(),this.stopPresenceLoop();}get autoConnectKey(){return this.startedAutoConnectKey}set autoConnectKey(e){this.startedAutoConnectKey=e;}get presenceLoopState(){return this.presenceState}set presenceLoopState(e){this.presenceState=e;}stopPresence(){this.stopPresenceLoop();}updatePresenceLoopState(e){this.presenceState=e;}startAutoConnect(e,t){if(this.deps.isTicketOnlyMode())return;let i=t.trim()||this.deps.resolveWebLogicalDeviceId(),n=`${e}::${i}`;this.startedAutoConnectKey===n&&this.browserAutoConnectUnsubscribe||(this.stopAutoConnect(),this.localDesiredPeerDeviceId=i,this.startedAutoConnectKey=n,this.browserAutoConnectUnsubscribe=this.deps.getCoordinationSignaling().onDevicesChange(o=>this.submitDesiredPeers(o),this.currentLocalNodeId()??void 0));}wakeRustAutoConnectOwner(){return this.deps.isTicketOnlyMode()||!this.startedAutoConnectKey||this.wakeSubmission?false:(this.wakeSubmission=this.deps.waitForWasmClient(500).then(async e=>{e&&typeof e.wake_browser_auto_connect=="function"&&await e.wake_browser_auto_connect();}).finally(()=>{this.wakeSubmission=null;}),true)}submitDesiredPeers(e){if(!this.startedAutoConnectKey)return;let i=this.normalizeDesiredPeers(e);this.rememberDesiredPeers(i)&&(this.queuedDesiredPeers=i,this.flushDesiredPeerSubmission());}observeDesiredPeerProjection(e){this.rememberDesiredPeers(this.normalizeDesiredPeers(e));}async submitDesiredPeerProjection(e,t){if(!Number.isSafeInteger(e)||e<=0)throw new Error("Desired-peer projection revision must be a positive safe integer.");let i=this.startedAutoConnectKey;if(!i)throw new Error("Cannot submit a desired-peer projection before managed auto-connect starts.");let n=this.normalizeDesiredPeers(t);this.rememberDesiredPeers(n),this.queuedDesiredPeers=null,this.desiredPeerRevision=Math.max(this.desiredPeerRevision,e),await this.enqueueDesiredPeerSubmission(i,e,n);}async handleRoomArchitectureChange(){let e=this.startedAutoConnectKey;if(this.deps.isTicketOnlyMode()||!e)return false;let t=Array.from(this.desiredPeersByDeviceId.values());this.queuedDesiredPeers=null;let i=++this.desiredPeerRevision;return await this.enqueueDesiredPeerSubmission(e,i,t),true}rememberDesiredPeers(e){this.desiredPeersByDeviceId=new Map(e.map(i=>[i.deviceId,i]));let t=JSON.stringify(e);return t===this.desiredPeerSignature?false:(this.desiredPeerSignature=t,this.deps.onDesiredPeersChanged?.(),true)}resolveDesiredPeer(e,t){let i=typeof e=="string"?e.trim():"",n=typeof t=="string"?t.trim():"";if(i){let o=this.desiredPeersByDeviceId.get(i);if(o&&(!n||!o.nodeId||o.nodeId===n))return o}return n?Array.from(this.desiredPeersByDeviceId.values()).find(o=>o.nodeId===n)??null:null}flushDesiredPeerSubmission(){if(this.desiredPeerSubmission||!this.queuedDesiredPeers||!this.startedAutoConnectKey)return;let e=this.startedAutoConnectKey,t=this.queuedDesiredPeers,i=++this.desiredPeerRevision;this.queuedDesiredPeers=null,this.desiredPeerSubmission=this.enqueueDesiredPeerSubmission(e,i,t).catch(()=>{}).finally(()=>{this.desiredPeerSubmission=null,this.flushDesiredPeerSubmission();});}normalizeDesiredPeers(e){return (Array.isArray(e)?e:[]).map(t=>({deviceId:String(t?.deviceId??"").trim(),nodeId:typeof t?.nodeId=="string"&&t.nodeId.trim()||null,ticket:typeof t?.ticket=="string"&&t.ticket.trim()||null,online:t?.online===true,sessionId:typeof t?.sessionId=="string"&&t.sessionId.trim()||null,excludedPeers:Array.isArray(t?.excludedPeers)?[...new Set(t.excludedPeers.map(i=>String(i??"").trim().toLowerCase()).filter(Boolean))].sort():[],devicePublicKeyJwk:t?.devicePublicKeyJwk,topologyRole:t?.topologyRole,topologyRevision:t?.topologyRevision})).filter(t=>t.deviceId.length>0).sort((t,i)=>t.deviceId.localeCompare(i.deviceId))}enqueueDesiredPeerSubmission(e,t,i,n=this.roomGossipFanoutEnabled()){let o=this.desiredPeerSubmissionQueue.then(async()=>{if(this.startedAutoConnectKey!==e)return;let r=await this.deps.waitForWasmClient();if(this.startedAutoConnectKey===e){if(!r||typeof r.submit_browser_desired_peers!="function"){this.deps.warnMissingWasmOnce("submitBrowserDesiredPeers");return}if(await Promise.all(i.map(async s=>{if(s.ticket)try{await this.deps.rememberRouteRepairTokenFromTicket(s.ticket);}catch(c){console.warn("[WasmSignaling] failed to retain desired-peer admission token",{deviceId:s.deviceId,nodeId:s.nodeId,error:c});}})),n){if(typeof r.submit_browser_desired_peers_with_sparse_fanout!="function"){await r.submit_browser_desired_peers(t,JSON.stringify([])),this.deps.warnMissingWasmOnce("submitBrowserDesiredPeersWithSparseFanout");return}if(!this.deps.capabilityKey)throw new Error("Sparse fanout requires an explicit capability avenue.");await r.submit_browser_desired_peers_with_sparse_fanout(t,JSON.stringify(i),this.deps.capabilityKey,this.localDesiredPeerDeviceId,this.deps.localDeviceKeyX,true);}else await r.submit_browser_desired_peers(t,JSON.stringify(i));}});return this.desiredPeerSubmissionQueue=o.catch(r=>{console.warn("[WasmSignaling] failed to submit browser desired peers to Rust",{revision:t,error:r});}),o}roomGossipFanoutEnabled(){return typeof this.deps.roomGossipFanout=="function"?this.deps.roomGossipFanout():this.deps.roomGossipFanout===true}async excludeAutoConnect(e,t){let i=await this.deps.waitForWasmClient();i&&typeof i.set_auto_connect_excluded=="function"&&await i.set_auto_connect_excluded(e,t),await this.recordAutoConnectExcludedForPresence(e,t);}async installInitialAutoConnectExclusions(e){if(typeof e?.set_auto_connect_excluded=="function")for(let t of this.currentExcludedPeersSnapshot())await e.set_auto_connect_excluded(t,true);}async recordAutoConnectExcludedForPresence(e,t){let i=e.trim().toLowerCase();if(!i)return;t?this.localExcludedPeers.add(i):this.localExcludedPeers.delete(i);let n=this.deps.resolveWebLogicalDeviceId();n&&await this.deps.updateExcludedPeers(n,this.currentExcludedPeersSnapshot());}async startPresenceLoop(e,t,i,n,o){if(this.deps.isTicketOnlyMode())return;this.stopPresenceLoop();let r=this.presenceStartGeneration;this.presenceState={userId:e,localNodeId:t,ticket:n,metadata:o,deviceName:i};let s=this.deps.resolveWebLogicalDeviceId(),c=await this.deps.withWebPresenceMetadata(o,s);r!==this.presenceStartGeneration||this.presenceState===null||await this.deps.updatePresence(t,n,true,R.PRESENCE_LEASE_MS,c,i);}stopAutoConnect(){this.browserAutoConnectUnsubscribe?.(),this.browserAutoConnectUnsubscribe=null,this.startedAutoConnectKey=null,this.localDesiredPeerDeviceId=null,this.desiredPeerSignature=null,this.queuedDesiredPeers=null,this.desiredPeersByDeviceId.clear(),this.wakeSubmission=null;}currentExcludedPeersSnapshot(){return Array.from(this.localExcludedPeers).sort()}currentLocalNodeId(){let e=this.presenceState?.localNodeId;return typeof e=="string"&&e.trim()||null}stopPresenceLoop(){this.presenceStartGeneration+=1,this.presenceState=null;}};R.PRESENCE_LEASE_MS=15*6e4;var M=R;function ne(){if(!(typeof window>"u"))try{if(new URL(import.meta.url).pathname.includes("/node_modules/.vite/deps/"))return new URL("/node_modules/openrtc/dist/openrtc_bg.wasm",window.location.origin)}catch{}}async function oe(){let u=await import('./openrtc-K6B3ZZIG.js');return {initWasm:e=>u.default(e??ne()),WasmClient:u.WasmClient,start:u.start}}function re(u){try{let e=u.replace(/-/g,"+").replace(/_/g,"/"),t=(4-e.length%4)%4,i=e+"=".repeat(t);if(typeof atob=="function")return JSON.parse(atob(i));let n=globalThis.Buffer;if(n)return JSON.parse(n.from(i,"base64").toString("utf8"))}catch{return null}return null}function se(u){let e=typeof u=="string"?u.trim():"";if(!e)return {present:false};let t=e.lastIndexOf("."),i=t>=0?e.slice(0,t):e,n=t>=0?e.slice(t+1):null,o=n?re(n):null,r=o&&typeof o.t=="string"&&o.t.trim().length>0?o.t.trim():null,s=o&&typeof o.s=="string"&&o.s.trim().length>0?o.s.trim():null,c=o&&typeof o.m=="number"&&Number.isFinite(o.m)?o.m:null;return {present:true,irohFingerprint:_(i),tokenFingerprint:_(r),tokenSuffixFingerprint:_(n),scope:s,maxConnections:c}}function E(u,e,t={}){let i=typeof u.finishSend=="function"?u.finishSend.bind(u):typeof u.finish_send=="function"?u.finish_send.bind(u):null,n=typeof u.cancelSend=="function"?u.cancelSend.bind(u):typeof u.cancel_send=="function"?u.cancel_send.bind(u):null;if(!i){if(t.requireFinish===true)throw new Error("WASM peer stream is missing finishSend(); rebuild the current OpenRTC WASM before sending application data");return e}let o=e.getWriter(),r=new WritableStream({write:s=>o.write(s),async close(){await o.close(),await i();},async abort(s){await n?.(),await o.abort(s);}});return a$4(r,n)}var p=class p{constructor(e$1){this.spaceNamespaceIdPromise=null;this.cachedSpaceNamespaceId=null;this.authListeners=[];this.wasmClient=null;this.createdAtMs=Date.now();this.missingWasmWarnings=new Set;this.wasmReadyWarningDelayMs=15e3;this.browserCoordinationSignaling=null;this.effectiveRoomArchitecture="mesh";this.lastObservedFirebaseUserId=null;this.sessionReaders=new Set;this.authContext=null;this.injectedBrowserAuthSessionActive=false;this.hasSyncedAuthToWasmClient=false;this.lastWasmAuthUserId=null;this.lastWasmAuthToken=null;this.lastDeliveredConnectionStates=new Map;this.authScopedRuntimeGeneration=0;this.coreClient=null;this.applicationRouteEscalations=new Map;this.applicationRouteEscalationAttemptKeys=new Map;this.applicationRouteEscalationUnsubscribe=null;this.routeSubscriptionGeneration=-1;this.applicationRouteEscalationSubscriptionEpoch=0;this.appTag=c(e$1),this.options={...e$1,appTag:this.appTag,authMode:d(e$1),projectId:e(e$1)},this.effectiveRoomArchitecture=e$1.coordinationRoomArchitecture==="sparse"||e$1.coordinationRoomGossipFanout===true?"sparse":"mesh",this.coordinationHost=new b({appTag:this.appTag,projectId:this.options.projectId,discoveryMode:this.options.discoveryMode,signalingMode:this.options.signalingMode,gateway:this.options.coordinationGateway,avenueOverride:this.options.coordinationAvenueOverride,roomArchitecture:this.options.coordinationRoomArchitecture,initialExcludedPeers:this.options.initialAutoConnectExcludedDeviceIds,resolveSpaceNamespaceId:()=>this.ensureSpaceNamespaceIdPromise(),getCurrentUserId:()=>this.getCurrentUserId(),getAuthToken:async(r=false)=>this.currentUser?.getToken?.(r)??null,getAppCheckToken:async(r=false)=>{let s=this.authContext?.appCheckTokenProvider??this.options.attestationTokenProvider;return s?s(r):a().getAppCheckToken(r)},getLocalDeviceId:()=>this.resolveWebLogicalDeviceId(),getDefaultDeviceName:()=>this.getDefaultBrowserDeviceName(),getPlatformType:()=>this.options.coordinationPlatformType??"web",normalizeDevice:(r,s)=>this.normalizeDevice(r,s)});let n=this.options.coordinationRoomGossipFanout===true||this.options.coordinationRoomArchitecture==="auto"||this.options.coordinationRoomArchitecture==="sparse"?c$1(this.options.coordinationAvenueOverride).key:void 0;if(this.presenceManager=new M({isTicketOnlyMode:()=>this.isTicketOnlyMode(),waitForWasmClient:(r,s)=>this.waitForWasmClient(r,s),warnMissingWasmOnce:r=>this.warnMissingWasmOnce(r),resolveWebLogicalDeviceId:()=>this.resolveWebLogicalDeviceId(),withWebPresenceMetadata:(r,s)=>this.withWebPresenceMetadata(r,s),updatePresence:(r,s,c,a,d,h)=>this.updatePresence(r,s,c,a,d,h),updateExcludedPeers:(r,s)=>this.getCoordinationSignaling().updateDevice(r,{excludedPeers:s}),getCoordinationSignaling:()=>this.getCoordinationSignaling(),rememberRouteRepairTokenFromTicket:r=>this.coreClient?.rememberRouteRepairTokenFromTicket?.(r)??Promise.resolve(false),onDesiredPeersChanged:()=>this.retryManagedApplicationRouteEscalations(),roomGossipFanout:()=>this.effectiveRoomArchitecture==="sparse",capabilityKey:n,localDeviceKeyX:this.options.coordinationDevicePublicKeyX,initialExcludedPeers:this.options.initialAutoConnectExcludedDeviceIds}),this.persistenceReady=Promise.resolve(),this.isTicketOnlyMode()||this.usesProviderNeutralGrant()){this.app=null,this.auth=null;return}let o=a();this.app=o.getApp(),this.auth=o.getAuth(),o.onAuthStateChanged(r=>{if(this.authContext)return;if(this.isSpaceMode()){this.authListeners.forEach(a=>a(this.toRuntimeIdentity(r)));return}let s=r?.uid??null,c=this.lastObservedFirebaseUserId;this.lastObservedFirebaseUserId=s,c&&c!==s&&this.stopAuthActivity({userId:c}),this.browserCoordinationSignaling?.handleScopeChange()??this.coordinationHost.handleScopeChange(),this.authListeners.forEach(a=>a(this.toRuntimeIdentity(r)));});}async loadBrowserWasmRuntime(){return oe()}get tag(){return this.appTag}capabilities(){return t()}getDeviceIdentityStorageKey(){let e=f(this.options);return `${p.WEB_DEVICE_ID_STORAGE_PREFIX}_${e}`}getDeviceIdPersistenceMode(){return this.options.deviceIdPersistence??this.options.nodeIdPersistence??"persistent"}isTicketOnlyMode(){return this.options.signalingMode==="ticket-only"}usesProviderNeutralGrant(){return typeof this.options.coordinationGateway?.grantProvider=="function"}createRandomDeviceId(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`web-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}resolveWebLogicalDeviceId(){let e=this.options.localDeviceId?.trim();if(e)return e;let t=this.getDeviceIdPersistenceMode();if(typeof localStorage>"u")return this.createRandomDeviceId();let i=this.getDeviceIdentityStorageKey(),n=Date.now(),o=null;try{let d=localStorage.getItem(i);o=d?JSON.parse(d):null;}catch{o=null;}let r=typeof o?.deviceId=="string"?o.deviceId.trim():"",s=typeof o?.expiresAt=="number"?o.expiresAt:void 0;if(t==="persistent"){let d=r||this.createRandomDeviceId();return localStorage.setItem(i,JSON.stringify({deviceId:d})),d}if(r&&typeof s=="number"&&s>n){let d=n+p.EPHEMERAL_DEVICE_ID_TTL_MS;return localStorage.setItem(i,JSON.stringify({deviceId:r,expiresAt:d})),r}let c=this.createRandomDeviceId(),a=n+p.EPHEMERAL_DEVICE_ID_TTL_MS;return localStorage.setItem(i,JSON.stringify({deviceId:c,expiresAt:a})),c}getDefaultBrowserDeviceName(){return this.options.deviceName?.trim()||(this.options.storagePrefix?`Web (${this.options.storagePrefix.replace(/_$/,"")})`:"Web Browser")}async getLocalDeviceInfo(){return {deviceId:this.resolveWebLogicalDeviceId(),deviceName:this.getDefaultBrowserDeviceName(),platformType:this.options.coordinationPlatformType??"web"}}getCoordinationSignaling(){return this.browserCoordinationSignaling??this.coordinationHost.getSignaling()}usesCoordinationGateway(){return this.coordinationHost.usesGateway()}setCoordinationHostAvailability(e){this.coordinationHost.setHostAvailability(e),this.browserCoordinationSignaling?.setHostAvailability?.(e);}async reconnectCoordinationAfterHostResume(){let e=this.browserCoordinationSignaling;if(e?.reconnectAfterHostResume){await e.reconnectAfterHostResume();return}await this.coordinationHost?.reconnectAfterHostResume();}async getCoordinationNativeTrustToken(e=false){return this.coordinationHost.getNativeTrustToken(e)}invalidateCoordinationNativeTrustToken(){this.coordinationHost.invalidateNativeTrustToken();}subscribeCoordinationNativeTrustToken(e,t){return this.coordinationHost.subscribeNativeTrustToken(e,t)}setCoordinationLocalDeviceId(e){if(!this.options.coordinationGateway)return;let t=e.trim();t&&(this.options.localDeviceId=t);}setCoordinationPlatformType(e){this.options.coordinationGateway&&(this.options.coordinationPlatformType=e);}async setCoordinationExcludedPeers(e){let t=this.resolveWebLogicalDeviceId();if(!t)throw new Error("The local device must be known before publishing peer exclusions.");await this.getCoordinationSignaling().updateDevice(t,{excludedPeers:e});}async joinCoordinationRoom(e,t,i){let n=this.getCoordinationSignaling();if(!n.joinCoordinationRoom)throw new Error("The active coordination provider does not support rooms.");await n.joinCoordinationRoom(e,t,i);}async leaveCoordinationRoom(e){await this.getCoordinationSignaling().leaveCoordinationRoom?.(e);}async getCoordinationRoomMembers(e){let t=this.getCoordinationSignaling();if(!t.getCoordinationRoomMembers)throw new Error("The active coordination provider does not support rooms.");return t.getCoordinationRoomMembers(e)}watchCoordinationRoomMembers(e,t){let i=this.getCoordinationSignaling();if(!i.watchCoordinationRoomMembers)throw new Error("The active coordination provider does not support rooms.");return i.watchCoordinationRoomMembers(e,t)}async withWebPresenceMetadata(e,t){let i;if(!e||!e.trim())i=JSON.stringify({deviceId:t});else {try{let n=JSON.parse(e);if(n&&typeof n=="object"&&!Array.isArray(n))return i=JSON.stringify({...n,deviceId:t}),await m(i)??i}catch{}i=JSON.stringify({deviceId:t,metadata:e});}return await m(i)??i}async setAuthContext(e){let t=this.injectedBrowserAuthSessionActive,i=this.authContext?.userId??null,n=e?.userId??null;if(this.authContext=e,!this.isTicketOnlyMode()&&!this.usesProviderNeutralGrant()&&e?.customToken?.trim()&&!(g()&&this.options.authMode==="external"&&typeof e.tokenProvider=="function"))try{await this.ensureBrowserPlatformAuth(e.userId,e.customToken.trim());}catch(o){console.warn("[WasmBridge] ensureBrowserPlatformAuth failed (non-fatal):",o);}else if(!this.isTicketOnlyMode()&&!this.usesProviderNeutralGrant()&&!e&&t)try{await this.auth?.signOut();}catch(o){console.warn("[WasmBridge] Failed to clear injected browser auth session:",o);}finally{this.injectedBrowserAuthSessionActive=false;}this.syncWasmAuthToken(),!this.isTicketOnlyMode()&&i!==n&&await(this.browserCoordinationSignaling?.handleScopeChange()??this.coordinationHost.handleScopeChange()),this.authListeners.forEach(o=>o(this.currentUser));}async ensureBrowserPlatformAuth(e,t){if((this.auth?.currentUser?.uid??null)===e){this.injectedBrowserAuthSessionActive=true;return}await a().signInWithCustomTokenValue(t),this.injectedBrowserAuthSessionActive=true;}syncWasmAuthToken(){let e=this.wasmClient?.setIdentityCredential??this.wasmClient?.set_auth_token;if(!this.wasmClient||typeof e!="function"||!this.authContext&&this.isSpaceMode())return;let t=this.authContext?.userId??null,i=this.authContext?.token,n=typeof i=="string"&&i.trim().length>0?i:null;if(!(this.hasSyncedAuthToWasmClient&&this.lastWasmAuthUserId===t&&this.lastWasmAuthToken===n)){if(this.lastWasmAuthUserId=t,this.lastWasmAuthToken=n,this.hasSyncedAuthToWasmClient=true,n===null&&typeof this.wasmClient.clearIdentityCredential=="function"){this.wasmClient.clearIdentityCredential();return}e.call(this.wasmClient,n);}}toRuntimeIdentity(e){return e?{id:e.uid,email:e.email,displayName:e.displayName,isAnonymous:e.isAnonymous,getToken:async(t=false)=>{try{return await e.getIdToken(t)}catch{return null}}}:null}getCurrentUserId(){return this.authContext?.userId?this.authContext.userId:this.isTicketOnlyMode()?null:this.auth?.currentUser?.uid??null}getCurrentUserIdForScope(){return this.getCurrentUserId()}getAuthContext(){return this.authContext}isSpaceMode(){return x(this.options)}getResolvedOptions(){return this.options}getDiscoveryScopeId(){if(this.isTicketOnlyMode())return null;let e=this.getCurrentUserId();return e||(this.isSpaceMode()?this.resolveWebLogicalDeviceId():null)}matchesTag(e){return y(e,this.appTag,this.isSpaceMode())}matchesLegacyOrCurrentTag(e){return this.matchesTag(e)}async stopSessionSubscriptions(){let e=Array.from(this.sessionReaders);this.sessionReaders.clear(),await Promise.allSettled(e.map(async t=>{try{await t.cancel();}catch{}}));}async stopRuntimeAuthScopedLoops(){let e=await this.waitForWasmClient(250);if(e)try{typeof e.stop_auth_scoped_activity=="function"?await e.stop_auth_scoped_activity():(typeof e.stop_presence_loop=="function"&&await e.stop_presence_loop(),typeof e.stop_auto_connect=="function"&&await e.stop_auto_connect());}catch(t){console.warn("[WasmSignaling] Failed to stop auth-scoped runtime loops:",t);}}async stopAuthActivity(e){h("WasmBridge.stopAuthActivity",{userId:e?.userId??null}),this.authScopedRuntimeGeneration+=1,this.stopApplicationRouteEscalationSubscription();let t=await this.waitForWasmClient(500);if(t&&typeof t.revoke_tokens_by_scope=="function")try{await t.revoke_tokens_by_scope("user-device");}catch(i){console.warn("[WasmBridge] user-device revoke during auth-scoped shutdown failed:",i);}this.presenceManager.stop(),this.browserCoordinationSignaling?.stopAuthActivity(),this.coordinationHost?.stopAuthActivity(),await this.stopSessionSubscriptions(),this.lastDeliveredConnectionStates.clear(),this.applicationRouteEscalations?.clear(),this.applicationRouteEscalationAttemptKeys?.clear(),await this.stopRuntimeAuthScopedLoops();}setWasmClient(e){this.wasmClient=e,this.coordinationHost.setWasmClient(e),this.lastWasmAuthUserId=null,this.lastWasmAuthToken=null,this.hasSyncedAuthToWasmClient=this.authContext===null,this.lastDeliveredConnectionStates.clear(),this.applicationRouteEscalations?.clear(),this.applicationRouteEscalationAttemptKeys?.clear(),this.syncWasmAuthToken();}async createBroadcastPublisher(){let e=await this.waitForWasmClient();if(!e)throw new Error("WASM broadcast publisher runtime is unavailable");return a$1.create(e)}async initializePersistentIrohProtocols(e){let t=await this.waitForWasmClient(),i=t?.__initPersistentIrohProtocols;if(typeof i!="function")throw new Error("This OpenRTC WASM host was built without persistent Iroh protocols");await i.call(t,e);}async createPersistentIrohNamespace(e,t){return (await this.requirePersistentProtocolHost()).__createPersistentIrohNamespace(BigInt(e),BigInt(t))}async importPersistentIrohTicket(e,t,i){return (await this.requirePersistentProtocolHost()).__importPersistentIrohTicket(e,BigInt(t),BigInt(i))}async sharePersistentIrohNamespace(e,t){return (await this.requirePersistentProtocolHost()).__sharePersistentIrohNamespace(e,t)}async removePersistentIrohNamespace(e,t,i){await(await this.requirePersistentProtocolHost()).__removePersistentIrohNamespace(e,BigInt(t),BigInt(i));}async putPersistentIrohBytes(e,t,i){return (await this.requirePersistentProtocolHost()).__putPersistentIrohBytes(e,t,i)}async setPersistentIrohHash(e,t,i,n){return (await this.requirePersistentProtocolHost()).__setPersistentIrohHash(e,t,i,BigInt(n))}async deletePersistentIrohPrefix(e,t){return (await this.requirePersistentProtocolHost()).__deletePersistentIrohPrefix(e,t)}async queryPersistentIrohNamespace(e,t){return (await this.requirePersistentProtocolHost()).__queryPersistentIrohNamespace(e,t)}async hydratePersistentIrohBlob(e){await(await this.requirePersistentProtocolHost()).__hydratePersistentIrohBlob(e);}async acknowledgePersistentIrohOutbox(e){await(await this.requirePersistentProtocolHost()).__acknowledgePersistentIrohOutbox(e);}async flushPersistentIrohProtocols(){await(await this.waitForWasmClient(500))?.__flushPersistentIrohProtocols?.();}async shutdownPersistentIrohProtocols(){await(await this.waitForWasmClient(500))?.__shutdownPersistentIrohProtocols?.();}async requirePersistentProtocolHost(){let e=await this.waitForWasmClient();if(!e||typeof e.__queryPersistentIrohNamespace!="function")throw new Error("This OpenRTC WASM host was built without persistent Iroh protocols");return e}warnMissingWasmOnce(e){!this.wasmClient&&Date.now()-this.createdAtMs<this.wasmReadyWarningDelayMs||this.missingWasmWarnings.has(e)||(this.missingWasmWarnings.add(e),console.warn(`[WasmSignaling] ${e} skipped: wasm client is not ready.`));}async waitForWasmClient(e=4e3,t=50){if(this.wasmClient)return this.wasmClient;let i=Date.now();for(;!this.wasmClient&&Date.now()-i<e;)await a$2(t);return this.wasmClient??null}normalizeDevice(e,t){return z(e,t)}normalizeDeviceRecord(e,t){return this.normalizeDevice(e,t)}getResolvedWebLogicalDeviceId(){return this.resolveWebLogicalDeviceId()}async encodeSparseFanoutMessage(e,t){let i=await this.waitForWasmClient(),n=this.options.coordinationDeviceSign;if(!i?.prepareSparseFanoutMessage||!i?.finalizeSparseFanoutMessage||!n)throw new Error("[OpenRTC] Browser sparse fanout signer is unavailable.");let o=await i.prepareSparseFanoutMessage(e,t),r=new Uint8Array(o.signingInput??o.signing_input??[]),s=await n(r);return new Uint8Array(await i.finalizeSparseFanoutMessage(String(o.requestId??o.request_id??""),s))}async acceptSparseFanoutMessage(e,t,i){let n=await this.waitForWasmClient();if(!n?.acceptSparseFanoutMessage)throw new Error("[OpenRTC] Browser sparse fanout verifier is unavailable.");let o=await n.acceptSparseFanoutMessage(e,t,i);return {payload:new Uint8Array(o.payload??[]),authorDeviceId:String(o.authorDeviceId??o.author_device_id??""),authorPeerId:String(o.authorPeerId??o.author_peer_id??""),topologyRevision:Number(o.topologyRevision??o.topology_revision),hop:Number(o.hop),forwardPeerIds:Array.isArray(o.forwardPeerIds??o.forward_peer_ids)?(o.forwardPeerIds??o.forward_peer_ids).map(String):[],forwardPeerLimit:Number(o.forwardPeerLimit??o.forward_peer_limit),forwardQueueCapacity:Number(o.forwardQueueCapacity??o.forward_queue_capacity),...o.forward==null?{}:{forward:new Uint8Array(o.forward)}}}async recordSparseFanoutForwardQueueDrop(e,t){let i=await this.waitForWasmClient();i?.recordSparseFanoutForwardQueueDrop&&await i.recordSparseFanoutForwardQueueDrop(e,t);}normalizeDeviceStatusSnapshot(e){return B(e)}normalizePeerSessionSnapshot(e){return C(e)}toBackendConnectionStateFromPeerSession(e){return F(e)}normalizeStateSnapshot(e){return G(e)}stabilizeConnectionState(e){let t=this.lastDeliveredConnectionStates.get(e.connectionId);return {...e,deviceId:e.deviceId??t?.deviceId??null,deviceIdHint:e.deviceIdHint??t?.deviceIdHint??null,remoteNodeId:e.remoteNodeId??t?.remoteNodeId??null,createdAt:e.createdAt??t?.createdAt,updatedAt:e.updatedAt??t?.updatedAt}}sameConnectionState(e,t){return H(e,t)}deliverConnectionState(e,t,i,n){let o=this.stabilizeConnectionState(e);this.lastDeliveredConnectionStates.set(o.connectionId,o);let s=(n??this.lastDeliveredConnectionStates).get(o.connectionId);this.sameConnectionState(s,o)||(n&&n.set(o.connectionId,o),t(o));}get browserPresenceLoopState(){return this.presenceManager.presenceLoopState}set browserPresenceLoopState(e){this.presenceManager.presenceLoopState=e;}get currentUser(){if(this.authContext?.userId){let e=this.authContext.token??null,t=this.authContext.tokenProvider;return {id:this.authContext.userId,getToken:async(i=false)=>{if(e&&(!i||!t))return e;if(t)try{let o=await t(i);if(o)return o}catch{}let n=this.isTicketOnlyMode()?null:this.auth?.currentUser??null;if(n&&n.uid===this.authContext?.userId)try{return await n.getIdToken(i)}catch{return null}return null}}}return this.isTicketOnlyMode()?null:this.toRuntimeIdentity(this.auth?.currentUser??null)}onAuthChange(e){return this.authListeners.push(e),e(this.currentUser),()=>{this.authListeners=this.authListeners.filter(t=>t!==e);}}async checkForSSOToken(){this.isTicketOnlyMode()||this.usesProviderNeutralGrant()||await a().checkForSSOToken();}async waitForAuth(){this.isTicketOnlyMode()||this.usesProviderNeutralGrant()||this.isSpaceMode()||this.authContext?.userId||this.auth?.currentUser||await a().waitForAuth();}async signInAnonymously(){if(!this.isTicketOnlyMode()){if(this.options.authMode!=="anonymous")throw new Error(`[pluto-rtc] Anonymous sign-in is disabled when authMode=${this.options.authMode}.`);await a().signInAnonymously();}}async signInWithPluto(){if(this.isTicketOnlyMode())throw new Error('[openrtc] Pluto sign-in is unavailable when signalingMode="ticket-only".');await a().signInWithPluto();}async signOut(){let e=this.getCurrentUserId();await this.stopAuthActivity({userId:e}),this.authContext=null,this.syncWasmAuthToken(),this.isTicketOnlyMode()||await this.auth?.signOut(),this.authListeners.forEach(t=>t(this.currentUser));}async getTurnCredentials(){return this.isTicketOnlyMode()||!this.auth?.currentUser?null:typeof this.options.turnCredentialsProvider=="function"?await this.options.turnCredentialsProvider()??null:null}async updatePresence(e,t,i=true,n=3e5,o,r){if(this.isTicketOnlyMode())return;let s=this.resolveWebLogicalDeviceId(),c=this.getDeviceIdPersistenceMode()==="ephemeral"?p.EPHEMERAL_DEVICE_ID_TTL_MS:n,a=await this.withWebPresenceMetadata(o,s);this.presenceManager.updatePresenceLoopState({userId:this.getCurrentUserId()??"",localNodeId:e,ticket:t,metadata:a,deviceName:r?.trim()||this.getDefaultBrowserDeviceName()}),await this.getCoordinationSignaling().updatePresence(e,t,i,c,a,r);}async refreshLivePresence(e,t,i,n){if(this.isTicketOnlyMode())return;let o=this.resolveWebLogicalDeviceId(),r=await this.withWebPresenceMetadata(i,o);this.presenceManager.updatePresenceLoopState({userId:this.getCurrentUserId()??"",localNodeId:e,ticket:t,metadata:r,deviceName:n?.trim()||this.getDefaultBrowserDeviceName()}),await this.getCoordinationSignaling().updatePresence(e,t,true,15*6e4,r,n);}async setOffline(e){this.presenceManager.stopPresence(),!this.isTicketOnlyMode()&&await this.getCoordinationSignaling().setOffline(e);}async updateDevice(e,t){if(!e?.trim())throw new Error("updateDevice requires a deviceId");this.isTicketOnlyMode()||await this.getCoordinationSignaling().updateDevice(e,t);}async deleteDevice(e){if(!e?.trim())throw new Error("deleteDevice requires a deviceId");this.isTicketOnlyMode()||await this.getCoordinationSignaling().deleteDevice(e);}async cleanupStaleDevices(){this.isTicketOnlyMode()||await this.getCoordinationSignaling().cleanupStaleDevices();}async sendMessage(e,t,i,n){if(this.isTicketOnlyMode())throw new Error('[openrtc] sendMessage() is unavailable when signalingMode="ticket-only".');return this.getCoordinationSignaling().sendMessage(e,t,i,n)}async pollMessages(e){return this.isTicketOnlyMode()?[]:this.getCoordinationSignaling().pollMessages(e)}async searchDevices(e){return this.isTicketOnlyMode()?[]:this.getCoordinationSignaling().searchDevices(e)}async listDeviceStatus(){if(this.isTicketOnlyMode())return [];if(!this.getDiscoveryScopeId())return [];let t=await this.getCoordinationSignaling().listDevices(),i=this.wasmClient;return Promise.all(t.map(async n=>{let o=this.normalizeDeviceStatusSnapshot({...n,connectionStatus:n.online?"online":"disconnected"}),r=typeof n.nodeId=="string"?n.nodeId.trim():"";if(!r||typeof i?.iroh_path_kind!="function"||typeof i?.iroh_transport_rtt_ms!="function")return o;try{let[s,c]=await Promise.all([i.iroh_path_kind(r),i.iroh_transport_rtt_ms(r)]);if(typeof c!="number"||!Number.isFinite(c))return o;let a=Math.max(0,Math.round(c)),d={};if(s==="direct-lan")d.irohLan=a;else if(s==="direct-quic")d.iroh=a;else if(s==="ble")d.ble=a;else if(s==="relay")d.irohRelay=a;else if(s==="webrtc")d.webrtc=a;else if(s==="moq")d.moq=a;else return o;return {...o,latencyMs:a,latencyByTransport:d}}catch(s){return d$1("[WasmBridge] iroh transport latency unavailable",{deviceId:n.deviceId,error:s instanceof Error?s.message:String(s)}),o}}))}async getPeerSession(e){let t=await this.waitForWasmClient(500);if(t&&typeof t.peer_session=="function"){let i=await t.peer_session(e);return !i||typeof i!="object"?null:this.normalizePeerSessionSnapshot(i)}return this.warnMissingWasmOnce("getPeerSession"),null}async listPeerSessions(){let e=await this.waitForWasmClient(500);if(e&&typeof e.peer_sessions=="function"){let t=await e.peer_sessions();return (Array.isArray(t)?t:[]).map(n=>this.normalizePeerSessionSnapshot(n)).filter(n=>!!(n.peerId||n.deviceId||n.deviceIdHint||n.nodeId||n.activeConnectionId))}return this.warnMissingWasmOnce("listPeerSessions"),[]}async waitForSettledPeer(e,t){let i=await this.waitForWasmClient(500);if(i&&typeof i.wait_for_peer=="function"){let n=await i.wait_for_peer(e,t);return !n||typeof n!="object"?null:this.normalizePeerSessionSnapshot(n)}return this.warnMissingWasmOnce("waitForSettledPeer"),null}async waitForSettledScope(e,t){let i=await this.waitForWasmClient(500);if(i&&typeof i.wait_for_settled_scope=="function"){let n=await i.wait_for_settled_scope(e,t);return !n||typeof n!="object"?null:this.normalizePeerSessionSnapshot(n)}return this.warnMissingWasmOnce("waitForSettledScope"),null}async openPeerBi(e,t){let i=await this.waitForWasmClient(500);if(i&&typeof i.open_peer_bi=="function"){let n=await i.open_peer_bi(e,t);if(!n?.recv||!n?.send)throw new Error("WASM open_peer_bi returned an invalid bidirectional stream");return {readable:n.recv,writable:E(n,n.send)}}throw this.warnMissingWasmOnce("openPeerBi"),new Error("WASM runtime does not support open_peer_bi()")}async openPeerBiRaw(e,t){if(this.options.applicationCrypto?.requireEncrypted)throw new Error("[WasmBridge] openPeerBiRaw is debug-only and cannot be used when application crypto is required");let i=await this.waitForWasmClient(500),n=i&&typeof i.open_peer_bi_transport_only=="function";if(console.debug("[WasmBridge] openPeerBiRaw",{peerId:e,hasWasmClient:!!i,hasTransportOnly:n,timeoutMs:t}),n){let o=await i.open_peer_bi_transport_only(e,t);if(!o?.recv||!o?.send)throw new Error("WASM open_peer_bi_transport_only returned an invalid bidirectional stream");return {readable:o.recv,writable:E(o,o.send)}}throw new Error("WASM runtime does not support the restricted transport-only diagnostic stream")}async openPeerUni(e,t){let i=await this.waitForWasmClient(500);if(i&&typeof i.open_peer_uni=="function"){let n=await i.open_peer_uni(e,t),o=n?.writable??n;if(!o)throw new Error("WASM open_peer_uni returned an invalid writable stream");return {writable:E(n,o)}}throw this.warnMissingWasmOnce("openPeerUni"),new Error("WASM runtime does not support open_peer_uni()")}beginOpenRtcMediaPublication(e){let t=this.wasmClient?.__beginOpenRtcMediaPublication;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include Rust-owned media sessions.");let i=t.call(this.wasmClient,e.publicationId||void 0,e.kind,e.codec,e.clockRate,e.codedWidth,e.codedHeight,e.channels);return {...i,control:new Uint8Array(i.control)}}encodeOpenRtcMediaSample(e){let t=this.wasmClient?.__encodeOpenRtcMediaSample;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include Rust-owned media sessions.");return new Uint8Array(t.call(this.wasmClient,e.publicationId,e.timestampUs,e.durationUs,e.keyframe,e.discardable,e.payload))}pauseOpenRtcMediaPublication(e){let t=this.wasmClient?.__pauseOpenRtcMediaPublication;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include Rust-owned media sessions.");t.call(this.wasmClient,e);}retireOpenRtcMediaPublication(e){let t=this.wasmClient?.__retireOpenRtcMediaPublication;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include Rust-owned media sessions.");t.call(this.wasmClient,e);}retireOpenRtcMediaReceiver(e,t){let i=this.wasmClient?.__retireOpenRtcMediaReceiver;if(typeof i!="function")throw new Error("[OpenRTC] This WASM build does not include Rust-owned media sessions.");i.call(this.wasmClient,e,t);}decodeOpenRtcMediaChunk(e){let t=this.wasmClient?.__decodeOpenRtcMediaChunk;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include the shared media protocol.");let i=t.call(this.wasmClient,e);return {...i,payload:new Uint8Array(i.payload)}}decodeOpenRtcMediaControl(e){let t=this.wasmClient?.__decodeOpenRtcMediaControl;if(typeof t!="function")throw new Error("[OpenRTC] This WASM build does not include the shared media protocol.");return t.call(this.wasmClient,e)}async sendPeerDatagram(e,t,i){let n=await this.waitForWasmClient(500),o=n?.sendPeerDatagram;if(typeof o!="function")throw new Error("[OpenRTC] This WASM build does not include protected peer datagrams.");return await o.call(n,e,t,i)!==false}async receivePeerDatagram(e){let t=await this.waitForWasmClient(500),i=t?.receivePeerDatagram;if(typeof i!="function")throw new Error("[OpenRTC] This WASM build does not include protected peer datagrams.");return new Uint8Array(await i.call(t,e))}peerDatagramMaxSize(){let e=this.wasmClient?.peerDatagramMaxSize?.();return Number.isSafeInteger(e)&&e>0?e:1024}createPeerDatagramPolicy(){let e=this.wasmClient?.createPeerDatagramPolicy;if(typeof e!="function")throw new Error("[OpenRTC] This WASM build does not include shared datagram policy.");return e.call(this.wasmClient)}async resolvePeerRecords(e){let t=await this.waitForWasmClient(500);if(t&&typeof t.resolve_peer_connection_records=="function"){let i=await t.resolve_peer_connection_records(e);return (Array.isArray(i)?i:[]).map(n=>({connectionId:typeof n.connectionId=="string"?n.connectionId:"",nodeId:typeof n.nodeId=="string"?n.nodeId:null,deviceId:typeof n.deviceId=="string"?n.deviceId:null,deviceIdHint:typeof n.deviceIdHint=="string"?n.deviceIdHint:null,endpointId:typeof n.endpointId=="string"?n.endpointId:null,transportGeneration:typeof n.transportGeneration=="number"?n.transportGeneration:0,routeGeneration:typeof n.routeGeneration=="number"?n.routeGeneration:void 0,transportStableId:typeof n.transportStableId=="number"?n.transportStableId:null,transportSource:typeof n.transportSource=="string"?n.transportSource:null,lastTransportChangeAtMs:typeof n.lastTransportChangeAtMs=="number"?n.lastTransportChangeAtMs:0,lastRouteChangeAtMs:typeof n.lastRouteChangeAtMs=="number"?n.lastRouteChangeAtMs:void 0,state:typeof n.state=="string"?n.state:"pending",statusReason:typeof n.statusReason=="string"?n.statusReason:null,createdAtMs:typeof n.createdAtMs=="number"?n.createdAtMs:0,updatedAtMs:typeof n.updatedAtMs=="number"?n.updatedAtMs:0}))}return this.warnMissingWasmOnce("resolvePeerRecords"),[]}async resolvePeerIdentity(e){let t=await this.waitForWasmClient(500);if(t){let i=n=>{if(!n||typeof n!="object")return {peerId:null,deviceId:null,deviceIdHint:null,nodeId:null};let o=n;return {peerId:typeof o.peerId=="string"?o.peerId:null,deviceId:typeof o.deviceId=="string"?o.deviceId:null,deviceIdHint:typeof o.deviceIdHint=="string"?o.deviceIdHint:null,nodeId:typeof o.nodeId=="string"?o.nodeId:null}};if(typeof t.peer_session=="function")try{let n=await t.peer_session(e),o=i(n);if(o.peerId||o.deviceId||o.deviceIdHint||o.nodeId)return o}catch{}if(typeof t.peer_snapshot=="function")try{return i(await t.peer_snapshot(e))}catch{}}return this.warnMissingWasmOnce("resolvePeerIdentity"),{peerId:null,deviceId:null,deviceIdHint:null,nodeId:null}}onDevicesChange(e,t){return this.isTicketOnlyMode()?(e([]),()=>{}):this.getCoordinationSignaling().onDevicesChange(e,t)}onRoomArchitectureChange(e){return this.getCoordinationSignaling().onRoomArchitectureChange?.(t=>{let i=this.effectiveRoomArchitecture!==t.effective;this.effectiveRoomArchitecture=t.effective,i&&this.presenceManager.handleRoomArchitectureChange().catch(n=>{console.warn("[WasmSignaling] failed to replay desired peers after room architecture change",{effectiveArchitecture:t.effective,epoch:t.epoch,error:n});}),e(t);})??(()=>{})}onRoomAuthorityAssignmentChange(e){return this.getCoordinationSignaling().onRoomAuthorityAssignmentChange?.(e)??(()=>{})}async publishAuthorityAssignment(e){let t=this.getCoordinationSignaling();if(!t.publishAuthorityAssignment)throw new Error("[OpenRTC] Authority assignment publication is unavailable.");await t.publishAuthorityAssignment(e);}async publishManagedRoomMessage(e){let t=this.getCoordinationSignaling().publishManagedRoomMessage;if(!t)throw new Error("[OpenRTC] Managed room fanout is unavailable.");await t.call(this.getCoordinationSignaling(),e);}onManagedRoomMessage(e){return this.getCoordinationSignaling().onManagedRoomMessage?.(e)??(()=>{})}async subscribeDevices(e){return this.isTicketOnlyMode()?new ReadableStream({start(t){t.close();}}):this.getCoordinationSignaling().subscribeDevices()}async startAutoConnect(e,t){if(this.isTicketOnlyMode())return;this.startApplicationRouteEscalationSubscription();let i=this.authScopedRuntimeGeneration;try{let n=await this.waitForWasmClient();if(i!==this.authScopedRuntimeGeneration||!n||typeof n.start_auto_connect!="function")return;await this.presenceManager.installInitialAutoConnectExclusions(n),await n.start_auto_connect(e,t),i===this.authScopedRuntimeGeneration&&this.presenceManager.startAutoConnect(e,t);}catch(n){console.warn("[WasmBridge] failed to initialize WASM auto-connect context",{userId:e,localDeviceId:t,error:n});}}async startAutoConnectOnce(e,t){await this.startAutoConnect(e,t),this.forceReconnect();}notifyDisconnectRequested(e){this.presenceManager.wakeRustAutoConnectOwner();}async excludeAutoConnect(e,t){await this.presenceManager.excludeAutoConnect(e,t);}async disconnectDevice(e){let t=await this.waitForWasmClient();if(!t||typeof t.disconnect_device!="function"){this.warnMissingWasmOnce("disconnectDevice"),await this.presenceManager.excludeAutoConnect(e,true).catch(()=>{});return}try{await t.disconnect_device(e,null),await this.presenceManager.recordAutoConnectExcludedForPresence(e,!0).catch(()=>{});}catch(i){throw console.warn("[WasmBridge] disconnect_device failed",{deviceId:e,error:i?.message??String(i)}),i}}async submitDesiredPeerProjection(e,t){return this.presenceManager.submitDesiredPeerProjection(e,t)}observeManagedDesiredPeers(e){this.presenceManager.observeDesiredPeerProjection(e),e$1("[OpenRTC][route-escalation] observed managed desired peers",{peerCount:e.length,peersWithTickets:e.filter(t=>typeof t.ticket=="string"&&t.ticket.trim()).length,deviceIds:e.map(t=>t.deviceId)});}setCoreClient(e){e&&typeof e.ensureManagedApplicationRoute=="function"?(this.coreClient=e,e$1("[OpenRTC][route-escalation] attached shared core client"),this.startApplicationRouteEscalationSubscription(),this.retryManagedApplicationRouteEscalations()):(this.coreClient=null,e$1("[OpenRTC][route-escalation] detached shared core client"),this.stopApplicationRouteEscalationSubscription());}startApplicationRouteEscalationSubscription(){if(this.applicationRouteEscalationUnsubscribe&&this.routeSubscriptionGeneration===this.authScopedRuntimeGeneration)return;this.stopApplicationRouteEscalationSubscription();let e=this.authScopedRuntimeGeneration,t=this.applicationRouteEscalationSubscriptionEpoch,i=this.onStateChange(n=>{let o=this.stabilizeConnectionState(n);this.lastDeliveredConnectionStates.set(o.connectionId,o),e$1("[OpenRTC][route-escalation] observed Rust connection state",{connectionId:o.connectionId,deviceId:o.deviceId??o.deviceIdHint??null,remoteNodeId:o.remoteNodeId??null,state:o.state,transportGeneration:o.transportGeneration??null,routeGeneration:o.routeGeneration??null}),this.escalateManagedApplicationRoute(o);});this.applicationRouteEscalationUnsubscribe=()=>{},this.routeSubscriptionGeneration=e,Promise.resolve(i).then(n=>{if(!this.coreClient||e!==this.authScopedRuntimeGeneration||t!==this.applicationRouteEscalationSubscriptionEpoch){n();return}this.applicationRouteEscalationUnsubscribe=n,this.routeSubscriptionGeneration=e;});}stopApplicationRouteEscalationSubscription(){this.applicationRouteEscalationSubscriptionEpoch+=1,this.applicationRouteEscalationUnsubscribe?.(),this.applicationRouteEscalationUnsubscribe=null,this.routeSubscriptionGeneration=-1;}retryManagedApplicationRouteEscalations(){for(let e of this.lastDeliveredConnectionStates.values())this.escalateManagedApplicationRoute(e);}escalateManagedApplicationRoute(e){if(!this.coreClient||!["connected","connecting"].includes(e.state))return;let t=[e.transportGeneration??0,e.routeGeneration??0].join(":"),i=this.applicationRouteEscalationAttemptKeys??(this.applicationRouteEscalationAttemptKeys=new Map);if(i.get(e.connectionId)===t||this.applicationRouteEscalations.has(e.connectionId))return;let n=this.presenceManager.resolveDesiredPeer(e.deviceId??e.deviceIdHint,e.remoteNodeId);if(!n?.ticket){e$1("[OpenRTC][route-escalation] awaiting matching desired-peer ticket",{connectionId:e.connectionId,deviceId:e.deviceId??e.deviceIdHint??null,remoteNodeId:e.remoteNodeId??null});return}let o=this.authScopedRuntimeGeneration,r=this.coreClient;i.set(e.connectionId,t),e$1("[OpenRTC][route-escalation] adopting Rust-managed generation",{connectionId:e.connectionId,deviceId:n.deviceId,remoteNodeId:e.remoteNodeId??n.nodeId??null,transportGeneration:e.transportGeneration??null,routeGeneration:e.routeGeneration??null});let s;s=(async()=>{let c=await r.ensureManagedApplicationRoute({ticket:n.ticket,connectionId:e.connectionId,remoteNodeId:e.remoteNodeId??n.nodeId,expectedDeviceId:n.deviceId,timeoutMs:2e4});if(o!==this.authScopedRuntimeGeneration)return;let a=c,d=a.id?.trim()||e.connectionId,h=a.remoteNodeId?.trim()||e.remoteNodeId?.trim()||a.deviceId?.trim()||n.deviceId;if(r.hasApplicationRouteForPeer?.(d,h)!==true&&r.hasApplicationRouteForPeer?.(d,h)!==true)throw new Error(`application crypto was not ready for ${h}`)})().catch(c=>{o===this.authScopedRuntimeGeneration&&console.warn("[OpenRTC][route-escalation] Rust-managed route remains pending",{connectionId:e.connectionId,deviceId:n.deviceId,remoteNodeId:e.remoteNodeId??n.nodeId,error:c?.message??String(c)});}).finally(()=>{if(this.applicationRouteEscalations.get(e.connectionId)===s){this.applicationRouteEscalations.delete(e.connectionId);let c=this.lastDeliveredConnectionStates?.get(e.connectionId),a=c?[c.transportGeneration??0,c.routeGeneration??0].join(":"):null;c&&a!==t&&o===this.authScopedRuntimeGeneration&&queueMicrotask(()=>this.escalateManagedApplicationRoute(c));}}),this.applicationRouteEscalations.set(e.connectionId,s);}async issueTicketMesh(e,t,i){let n=await this.waitForWasmClient();if(typeof n?.issue_ticket_mesh!="function")throw new Error("WASM runtime does not support Rust-owned ticket meshes.");return n.issue_ticket_mesh(e,t,i)}async joinTicketMesh(e,t){let i=await this.waitForWasmClient();if(typeof i?.join_ticket_mesh!="function")throw new Error("WASM runtime does not support Rust-owned ticket meshes.");return i.join_ticket_mesh(e,t)}async receiveTicketMeshFrame(e,t,i){let n=await this.waitForWasmClient();if(typeof n?.receive_ticket_mesh_frame!="function")throw new Error("WASM runtime does not support Rust-owned ticket meshes.");n.receive_ticket_mesh_frame(e,t,i);}async ticketMeshIssuerNode(e){let t=await this.waitForWasmClient();if(typeof t?.ticket_mesh_issuer_node!="function")throw new Error("WASM ticket mesh issuer projection is unavailable.");return t.ticket_mesh_issuer_node(e)}async closeTicketMesh(e){let t=await this.waitForWasmClient();if(typeof t?.close_ticket_mesh!="function")throw new Error("WASM runtime does not support closing Rust-owned ticket meshes.");await t.close_ticket_mesh(e);}async connectToDevice(e){let t=await this.waitForWasmClient();if(!t||typeof t.connect_device!="function")throw this.warnMissingWasmOnce("connectToDevice"),new Error("WASM runtime does not support connect_device()");let i=e.endpointTicket?.trim()??"",n=e.admissionToken?.trim()??"",o=e.admissionScope?.trim()??"",r=!i,s=i;if(r&&(!e.deviceId||!n||!o||typeof t.connect_known_device_with_token!="function"))throw new Error("WASM connectToDevice requires an endpoint ticket or supported known-device admission intent.");let c=Date.now();e$1("[WasmBridge][ROUTE-ESCALATION] starting managed transport dial",{deviceId:e.deviceId??null,ticket:se(i),knownDeviceAdmission:r,hasCoreClient:!!this.coreClient});let a=r?await(async()=>{let h=Date.now(),l=Math.max(1,e.timeoutMs??3e4),m=()=>Math.max(1,l-(Date.now()-h)),y=e.admissionPeerUserId?.trim()??"";if(y){let v=(await this.getCoordinationSignaling().waitForFriendDevice(y,e.deviceId,Math.min(1e4,m()))).ticket?.trim()??"";if(!v)throw new Error(`[pluto-rtc] authorized device ${e.deviceId} did not publish an endpoint ticket.`);if(typeof t.observe_known_device_endpoint!="function")throw new Error("WASM runtime does not support provider-authorized endpoint observations.");await t.observe_known_device_endpoint(e.deviceId,v),s=a$3(v).irohTicket;}return t.connect_known_device_with_token(e.deviceId,n,o,e.admissionMaxConnections??0,e.admissionExpiresAtMs==null?null:BigInt(Math.floor(e.admissionExpiresAtMs)),Math.min(1e4,m()))})():await t.connect_device(e.deviceId??null,i,e.timeoutMs??null);e$1("[WasmBridge][ROUTE-ESCALATION] managed transport dial completed",{deviceId:e.deviceId??null,remoteNodeId:a?.remoteNodeId??null,connectionId:a?.connectionId??null,elapsedMs:Date.now()-c});let d=s;if(d&&this.coreClient){let h=this.coreClient;try{e$1("[WasmBridge][ROUTE-ESCALATION] starting typed application connection",{deviceId:e.deviceId??null,remoteNodeId:a?.remoteNodeId??null,connectionId:a?.connectionId??null});let l=await h.ensureManagedApplicationRoute({ticket:d,connectionId:a?.connectionId??null,remoteNodeId:a?.remoteNodeId??null,expectedDeviceId:e.deviceId??null,approvedScope:a?.approvedScope??null,timeoutMs:2e4}),m=typeof l?.remoteNodeId=="string"?l.remoteNodeId.trim():"",y=typeof l?.deviceId=="string"?l.deviceId.trim():"",g=m||a?.remoteNodeId?.trim?.()||y||e.deviceId?.trim?.()||"",v=typeof h.hasApplicationRouteForPeer=="function"?h.hasApplicationRouteForPeer.bind(h):null;if(!(!!g&&v?.(l?.id??void 0,g)===!0)&&g&&typeof h.waitForApplicationCryptoForPeer=="function"&&!(!!await h.waitForApplicationCryptoForPeer(g,2e4)&&(!v||v(l?.id??void 0,g)===!0)))throw console.warn("[WasmBridge][ROUTE-ESCALATION] application route still pending after managed dial",{deviceId:e.deviceId??null,remoteNodeId:m||(a?.remoteNodeId??null),connectionId:a?.connectionId??null,peerForCrypto:g,elapsedMs:Date.now()-c}),Object.assign(new Error(`application crypto was not ready for ${g}`),{applicationCryptoNotReady:!0});e$1("[WasmBridge][ROUTE-ESCALATION] application route ready",{deviceId:e.deviceId??null,remoteNodeId:m||(a?.remoteNodeId??null),connectionId:a?.connectionId??null,elapsedMs:Date.now()-c});}catch(l){if(l?.applicationCryptoNotReady)throw l;return console.warn("[WasmBridge] Managed transport connected; TS application route escalation is still pending",{deviceId:e.deviceId??null,remoteNodeId:a?.remoteNodeId??null,connectionId:a?.connectionId??null,error:l?.message??String(l)}),a}}return a}forceReconnect(){this.isTicketOnlyMode()||!this.app||!this.auth||this.presenceManager.wakeRustAutoConnectOwner();}startPresenceLoop(e,t,i,n,o){return this.presenceManager.startPresenceLoop(e,t,i,n,o)}ensureSpaceNamespaceIdPromise(){if(this.cachedSpaceNamespaceId)return Promise.resolve(this.cachedSpaceNamespaceId);if(!this.spaceNamespaceIdPromise){let e=this.options.apiKey?.trim()??"",t=this.options.spaceKey?.trim()??"";if(!e||!t)return Promise.resolve(null);this.spaceNamespaceIdPromise=b$1(e,t).then(i=>(this.cachedSpaceNamespaceId=i,i)).catch(()=>null);}return this.spaceNamespaceIdPromise}async createSession(e){if(this.isTicketOnlyMode())throw new Error('[openrtc] createSession() is unavailable when signalingMode="ticket-only".');let t=this.getCurrentUserId();if(!t&&!e.initiator&&!e.target&&!this.isSpaceMode())throw new Error("createSession requires user scope");let i={...e,appTag:e.appTag??this.appTag,initiator:e.initiator??t??void 0,target:e.target??t??void 0};await this.getCoordinationSignaling().createSession(i);}async updateSession(e,t){if(this.isTicketOnlyMode())throw new Error('[openrtc] updateSession() is unavailable when signalingMode="ticket-only".');await this.getCoordinationSignaling().updateSession(e,t);}async subscribeSessions(e){return this.isTicketOnlyMode()?new ReadableStream({start(t){t.close();}}):this.getCoordinationSignaling().subscribeSessions(e)}async getLocalDeviceId(){return this.resolveWebLogicalDeviceId()}async isConnected(e){let t=await this.waitForWasmClient();return t&&typeof t.is_connected=="function"?t.is_connected(e):false}async getConnectionStates(){let e=await this.waitForWasmClient(500);if(e&&typeof e.connection_states=="function"){let n=await e.connection_states(),o=(Array.isArray(n)?n:[]).map(r=>this.normalizeStateSnapshot(r)).filter(r=>!!r);return o.length>0&&d$1("[WasmBridge] replaying current wasm connection states",o.map(r=>({connectionId:r.connectionId,deviceId:r.deviceId??null,deviceIdHint:r.deviceIdHint??null,remoteNodeId:r.remoteNodeId??null,state:r.state,transportState:r.transportState??null,protocolState:r.protocolState??null,routable:r.routable??null}))),o}let i=(await this.listPeerSessions().catch(()=>[])).map(n=>this.toBackendConnectionStateFromPeerSession(n)).filter(n=>!!n);return i.length>0&&d$1("[WasmBridge] replaying current wasm connection states",i.map(n=>({connectionId:n.connectionId,deviceId:n.deviceId??null,deviceIdHint:n.deviceIdHint??null,remoteNodeId:n.remoteNodeId??null,state:n.state,transportState:n.transportState??null,protocolState:n.protocolState??null,routable:n.routable??null}))),i}onStateChange(e){let t=new Map,i=new Map,n=this.authScopedRuntimeGeneration,o=false,r=a=>{let d=a.detail,h=this.normalizeStateSnapshot(d),l=typeof d?.connectionId=="string"?d.connectionId.trim():"";if(!l||o)return;if(h&&(h.state==="closed"||h.state==="failed"||h.state==="disconnected")){this.deliverConnectionState(h,e,"rust-event-detail",t);return}let m=(i.get(l)??0)+1;i.set(l,m);let y=this.authScopedRuntimeGeneration;(async()=>{let g=await this.waitForWasmClient(500);if(!(o||y!==this.authScopedRuntimeGeneration||i.get(l)!==m)){if(g&&typeof g.connection_state=="function"){let v=await g.connection_state(l),w=this.normalizeStateSnapshot(v);if(!o&&y===this.authScopedRuntimeGeneration&&i.get(l)===m&&w){this.deliverConnectionState(w,e,"rust-event",t);return}}!o&&y===this.authScopedRuntimeGeneration&&i.get(l)===m&&h&&this.deliverConnectionState(h,e,"rust-event-detail",t);}})().catch(g=>{o||console.warn("[WasmBridge] Failed to read Rust connection state after lifecycle event",{connectionId:l,error:g});});},s=typeof window<"u"?window:null,c=typeof s?.addEventListener=="function"&&typeof s?.removeEventListener=="function";return c&&s.addEventListener("connection-state-changed",r),this.getConnectionStates().then(a=>{!o&&n===this.authScopedRuntimeGeneration&&a.forEach(d=>{i.has(d.connectionId)||this.deliverConnectionState(d,e,"replay",t);});}).catch(a=>{console.warn("[WasmBridge] Failed to replay wasm connection states after subscription:",a);}),()=>{o=true,i.clear(),c&&s.removeEventListener("connection-state-changed",r);}}async sendExplicitFilePath(e,t,i=""){throw new Error("sendExplicitFilePath is native-only. Use sendExplicitFileData in web/wasm runtime.")}sanitizeExplicitFileName(e){let i=(typeof e=="string"?e.replace(/\\/g,"/"):"").split("/").reverse().find(r=>r.trim().length>0)?.trim()??"";if(!i||i==="."||i==="..")return p.FALLBACK_EXPLICIT_FILE_NAME;let n="";for(let r of i){if([...n].length>=p.MAX_EXPLICIT_FILE_NAME_CHARS)break;let s=r.charCodeAt(0);r==="/"||r==="\\"||r==="\0"||s<32||s===127?n+="_":n+=r;}let o=n.trim();return !o||o==="."||o===".."?p.FALLBACK_EXPLICIT_FILE_NAME:o}sanitizeExplicitMimeType(e){let t=typeof e=="string"?e.trim():"";if(!t)return p.FALLBACK_EXPLICIT_MIME_TYPE;let i="";for(let n of t){if(i.length>=p.MAX_EXPLICIT_MIME_TYPE_CHARS)break;let o=n.charCodeAt(0);o<33||o>126||n==='"'||n==="\\"?i+="_":i+=n;}return i.length>0?i:p.FALLBACK_EXPLICIT_MIME_TYPE}assertExplicitTransferHeaderSize(e){if(e.byteLength===0||e.byteLength>p.MAX_EXPLICIT_TRANSFER_HEADER_BYTES)throw new Error(`Explicit transfer header is too large: ${e.byteLength} bytes`)}createWebRTCExplicitTransferId(){let e=new Uint8Array(16),t=globalThis.crypto;if(t&&typeof t.getRandomValues=="function")return t.getRandomValues(e),e;for(let i=0;i<e.byteLength;i+=1)e[i]=Math.floor(Math.random()*256);return e}createWebRTCExplicitTransferFrame(e,t,i,n,o){let r=o?.headerFrame===true?4:0,s=new Uint8Array(25+r+n.byteLength);s[0]=p.EXPLICIT_FILE_PROTOCOL_TYPE,s.set(e,1);let c=new DataView(s.buffer);c.setUint32(17,t,false),c.setUint32(21,i,false);let a=o?.headerFrame===true?29:25;return o?.headerFrame===true&&c.setUint32(25,n.byteLength,false),s.set(n,a),s}async sendExplicitFileData(e){let t=e.connection,i=e.file,n=e.applicationCrypto??this.options.applicationCrypto;if((e.requireApplicationCrypto===true||t?.requireApplicationCrypto===true)&&!n)throw new Error("[WasmBridge] Explicit transfer requires application crypto but none is available for this connection");let r=e.transferId&&e.transferId.trim().length>0?e.transferId:`transfer-${Date.now()}`;typeof e.receiverPlatformType=="string"?e.receiverPlatformType.trim().toLowerCase():null;let c=e.remoteNodeId?.trim()||t?.remoteNodeId?.trim()||t?.deviceId?.trim();if(e$1("[WasmBridge] sendExplicitFileData start",{connectionId:e.connectionId??null,connectionRemoteNodeId:t?.remoteNodeId??null,remoteNodeId:c??null,fileName:i.name,fileSize:i.size,transferId:r}),!c)throw new Error("Web explicit transfer requires an active connection with a resolved remote node ID");let a=await this.waitForWasmClient();if(!a)throw new Error("WASM explicit transfer requires an initialized WASM client");let d=new TextEncoder,h={transfer_id:r,filename:this.sanitizeExplicitFileName(i.name),size:i.size,mime_type:this.sanitizeExplicitMimeType(i.type)},l=d.encode(JSON.stringify(h));this.assertExplicitTransferHeaderSize(l);let m=new Uint8Array(4);new DataView(m.buffer).setUint32(0,l.byteLength,false);let y=new Uint8Array(m.byteLength+l.byteLength);y.set(m,0),y.set(l,m.byteLength);let g=async()=>{let v=a.open_peer_bi_explicit_file_sender;if(typeof v!="function")return false;let w=await v.call(a,c,5e3),S=w?.writable??w?.send;if(!S||typeof S.getWriter!="function")throw new Error("WASM explicit peer stream returned an invalid writable stream");e$1("[WasmBridge] sendExplicitFileData open_peer_bi_explicit_file_sender resolved",{remoteNodeId:c,transferId:e.transferId??null,applicationCryptoWrapped:w.applicationCryptoWrapped===true});let P=E(w,S,{requireFinish:true}).getWriter(),D=false;try{await P.write(y);let C=new Uint8Array(await i.arrayBuffer());for(let b=0;b<C.byteLength;b+=p.EXPLICIT_FILE_CHUNK_SIZE_BYTES){let ie=C.slice(b,Math.min(b+p.EXPLICIT_FILE_CHUNK_SIZE_BYTES,C.byteLength));await P.write(ie);}}catch(C){throw D=true,C}finally{try{await P.close();}catch(C){if(!D)throw C}finally{P.releaseLock();}}return true};try{if(await g())return;throw new Error("[WasmBridge] Explicit transfer requires the generation-fenced open_peer_bi_explicit_file_sender path, but it is unavailable on this WASM build. Rebuild the current OpenRTC WASM; raw open_bi fallback is intentionally unsupported for application data.")}finally{e$1("[WasmBridge] sendExplicitFileData completed",{remoteNodeId:c,transferId:r,fileName:i.name,fileSize:i.size});}}async getTransferHistory(e=50){return []}async deleteTransferJob(e){}watchFriendDevices(e,t){return this.isTicketOnlyMode()?()=>{}:this.getCoordinationSignaling().watchFriendDevices(e,t)}async updateFriendTicket(e){this.isTicketOnlyMode()||await this.getCoordinationSignaling().updateFriendTicket(e);}};p.EXPLICIT_FILE_PROTOCOL_TYPE=2,p.EXPLICIT_FILE_CHUNK_SIZE_BYTES=64*1024,p.MAX_EXPLICIT_TRANSFER_HEADER_BYTES=64*1024,p.FALLBACK_EXPLICIT_FILE_NAME="openrtc-transfer.bin",p.MAX_EXPLICIT_FILE_NAME_CHARS=180,p.FALLBACK_EXPLICIT_MIME_TYPE="application/octet-stream",p.MAX_EXPLICIT_MIME_TYPE_CHARS=255,p.WEB_DEVICE_ID_STORAGE_PREFIX="pluto_rtc_web_device_identity",p.EPHEMERAL_DEVICE_ID_TTL_MS=o.browserIdentity.ephemeralDeviceIdTtlMs;var te=p;export{oe as a,te as b};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {a}from'./chunk-COXQYBTI.js';function m(l){return [...new Set(l.capabilityKeys.filter(s=>typeof s=="string").map(s=>s.trim()).filter(Boolean))]}async function p(l,s){if(!l||typeof l!="object")return;let t=l.stream,e=[];t?.recv&&e.push(t.recv.cancel(s)),t?.send&&e.push(t.send.abort(s)),await Promise.allSettled(e);}var v=class{constructor(){this.host=null;this.consumers=new Map;this.hostReader=null;this.hostPump=null;this.consecutiveEstablishedFaults=0;this.closed=false;this.failedHostRelease=null;this.closeAttempt=null;}register(s,t){if(this.closed)throw new Error("[OpenRTC] Native projection broker is closed.");if(this.failedHostRelease)throw new Error("[OpenRTC] Native projection retirement is unconfirmed.");let e=s.trim();if(!e)throw new Error("[OpenRTC] Native capability projection key is required.");if(this.consumers.has(e))throw new Error(`[OpenRTC] Native capability '${e}' is already registered.`);return this.consumers.size===0?this.host=t:this.host??(this.host=t),this.consumers.set(e,{controller:null,stream:null,stateListeners:new Set,messageListeners:new Set,deviceListeners:new Set,serviceErrorListeners:new Set,latestDevices:null}),{__openrtcNativeCapabilityProjection:true,capabilityKey:e,incoming_streams:()=>this.incomingStreams(e),onStateChange:r=>this.subscribeState(e,r),onPeerMessage:r=>this.subscribePeerData(e,r),onDevices:r=>this.subscribeDevices(e,r),onServiceError:r=>this.subscribeServiceError(e,r),isCurrentTransport:(r,i)=>this.currentHost().isCurrentTransport(r,i)}}unregister(s){let t=s.trim(),e=this.consumers.get(t);if(e){this.consumers.delete(t);try{e.controller?.close();}catch{}e.controller=null,e.stream=null,e.stateListeners.clear(),e.messageListeners.clear(),e.deviceListeners.clear(),e.serviceErrorListeners.clear(),e.latestDevices=null,this.consumers.size===0&&this.cancelHostReader("no active native capabilities");}}subscribeState(s,t){let e=this.requireConsumer(s);return e.stateListeners.add(t),this.ensureHostPump(),()=>{e.stateListeners.delete(t),this.cancelHostReaderIfIdle();}}subscribePeerData(s,t){let e=this.requireConsumer(s);return e.messageListeners.add(t),this.ensureHostPump(),()=>{e.messageListeners.delete(t),this.cancelHostReaderIfIdle();}}subscribeDevices(s,t){let e=this.requireConsumer(s);return e.deviceListeners.add(t),this.ensureHostPump(),e.latestDevices&&t(e.latestDevices),()=>{e.deviceListeners.delete(t),this.cancelHostReaderIfIdle();}}subscribeServiceError(s,t){let e=this.requireConsumer(s);return e.serviceErrorListeners.add(t),this.ensureHostPump(),()=>{e.serviceErrorListeners.delete(t),this.cancelHostReaderIfIdle();}}requireConsumer(s){if(this.closed)throw new Error("[OpenRTC] Native projection broker is closed.");if(this.failedHostRelease)throw new Error("[OpenRTC] Native projection retirement is unconfirmed.");let t=this.consumers.get(s);if(!t)throw new Error(`[OpenRTC] Native capability '${s}' is not registered.`);return t}currentHost(){if(this.closed)throw new Error("[OpenRTC] Native projection broker is closed.");if(!this.host)throw new Error("[OpenRTC] Native projection broker has no IPC host.");return this.host}async incomingStreams(s){if(this.closed)throw new Error("[OpenRTC] Native projection broker is closed.");let t=this.requireConsumer(s);if(t.stream)return t.stream;let e;return e=new ReadableStream({start:r=>{t.controller=r,this.ensureHostPump();},cancel:()=>{t.stream===e&&(t.controller=null,t.stream=null),this.cancelHostReaderIfIdle();}},{highWaterMark:32}),t.stream=e,e}ensureHostPump(){if(this.hostPump||this.closed||this.failedHostRelease)return;let s=false;this.hostPump=this.pumpHost().then(t=>{s=t;}).catch(t=>{s=false;for(let e of this.consumers.values()){try{e.controller?.error(t);}catch{}e.controller=null,e.stream=null,e.stateListeners.clear(),e.messageListeners.clear(),e.deviceListeners.clear(),e.serviceErrorListeners.clear(),e.latestDevices=null;}}).finally(()=>{this.hostPump=null,this.hostReader=null,s&&!this.closed&&this.hasActiveConsumers()&&this.ensureHostPump();});}async pumpHost(){let s=this.currentHost(),t=null,e=false;try{let r=await s.incoming_projected_streams();if(this.closed)return await r.cancel("OpenRTC native root client closed").catch(()=>{}),!1;for(t=r.getReader(),this.hostReader=t;!this.closed&&this.hasActiveConsumers();){let{done:i,value:n}=await t.read();if(i){if(!this.closed&&this.host!==s&&this.hasActiveConsumers())return !0;for(let o of this.consumers.values()){try{o.controller?.close();}catch{}o.controller=null,o.stream=null,o.stateListeners.clear(),o.messageListeners.clear(),o.deviceListeners.clear(),o.serviceErrorListeners.clear(),o.latestDevices=null;}return this.consecutiveEstablishedFaults=0,!1}this.consecutiveEstablishedFaults=0;let u=m(n);if(n.kind==="stream"){let o=u.length===1?u[0]:null,a=o?this.consumers.get(o):void 0;if(!a?.controller||(a.controller.desiredSize??0)<=0){await p(n.payload,o?`inactive native capability ${o}`:"ambiguous unscoped native projection");continue}a.controller.enqueue(n.payload);continue}for(let o of u){let a$1=this.consumers.get(o);if(a$1)if(n.kind==="connection-state")for(let c of a$1.stateListeners)c(n.payload);else if(n.kind==="devices"){a$1.latestDevices=n.payload.devices;for(let c of a$1.deviceListeners)c(n.payload.devices);}else if(n.kind==="service-error"){let c=a(n.payload.serviceError,n.payload.avenue);if(c)for(let h of a$1.serviceErrorListeners)try{Promise.resolve(h(c)).catch(()=>{});}catch{}}else for(let c of a$1.messageListeners)c(n.payload);}}return !this.closed&&this.host!==s&&this.hasActiveConsumers()}catch(r){if(!this.closed){e=t!==null&&this.consecutiveEstablishedFaults===0,e?this.consecutiveEstablishedFaults=1:this.consecutiveEstablishedFaults=0;for(let i of this.consumers.values()){try{i.controller?.error(r);}catch{}i.controller=null,i.stream=null,e||(i.stateListeners.clear(),i.messageListeners.clear(),i.deviceListeners.clear(),i.serviceErrorListeners.clear(),i.latestDevices=null);}}return e}finally{let r=t;if(this.hostReader===r&&(this.hostReader=null),r)try{r.releaseLock();}catch{}if(typeof s.releaseNativeProjectionSubscription=="function")try{await s.releaseNativeProjectionSubscription();}catch(i){throw this.failedHostRelease={host:s,error:i},i}}}hasActiveConsumers(){return [...this.consumers.values()].some(s=>s.controller!==null||s.stateListeners.size>0||s.messageListeners.size>0||s.deviceListeners.size>0||s.serviceErrorListeners.size>0)}cancelHostReaderIfIdle(){this.hasActiveConsumers()||this.cancelHostReader("no active native projection consumers");}async cancelHostReader(s){let t=this.hostReader;this.hostReader=null,await t?.cancel(s).catch(()=>{});}close(){if(this.closeAttempt)return this.closeAttempt;let s=this.failedHostRelease;this.closed=true;for(let r of this.consumers.values())try{r.controller?.close();}catch{}this.consumers.clear(),this.host=null;let t=(async()=>{if(await this.cancelHostReader("OpenRTC native root client closed"),await this.hostPump,s&&(await s.host.releaseNativeProjectionSubscription(),this.failedHostRelease===s&&(this.failedHostRelease=null)),this.failedHostRelease)throw this.failedHostRelease.error})();this.closeAttempt=t;let e=()=>{this.closeAttempt===t&&(this.closeAttempt=null);};return t.then(e,e),t}};export{v as a};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var i={CREDIT_EXHAUSTED:"credit-exhausted",APP_BUDGET_EXHAUSTED:"app-budget-exhausted",APP_RATE_LIMITED:"app-rate-limited",PRINCIPAL_RATE_LIMITED:"principal-rate-limited",EDGE_RATE_LIMITED:"edge-rate-limited",PROVIDER_SAFETY_PAUSED:"provider-safety-paused",USAGE_PRICE_STALE:"usage-price-stale",RELAY_BUDGET_EXHAUSTED:"relay-budget-exhausted",ROOM_CAPACITY_EXCEEDED:"room-capacity-exceeded"},a={"edge-rate-exceeded":{code:i.EDGE_RATE_LIMITED,scope:"ip"},"route-rate-exceeded":{code:i.EDGE_RATE_LIMITED,scope:"avenue"}};function n(t){if(typeof t!="string")return;let e=t.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(a,e)?a[e]:void 0}function p(t){return c(t)?{code:t}:n(t)}var s=new Set(Object.values(i));function c(t){return typeof t=="string"&&s.has(t)}var d="https://openrtc-docs.web.app/openrtc/api/errors";function E(t){let e=t,r={documentationUrl:d};typeof e.scope=="string"&&["account","app","principal","ip","avenue","platform"].includes(e.scope)&&(r.scope=e.scope),typeof e.operation=="string"&&/^[a-z0-9.-]{1,100}$/.test(e.operation)&&(r.operation=e.operation),typeof e.requestId=="string"&&/^[A-Za-z0-9_.:-]{1,160}$/.test(e.requestId)&&(r.requestId=e.requestId);for(let o of ["retryAfterMs","resetAt"])Number.isSafeInteger(e[o])&&Number(e[o])>=0&&(r[o]=Number(e[o]));return r}
|
|
2
|
+
export{i as a,n as b,p as c,c as d,E as e};
|