openrtc 1.0.27 → 2.0.0-rc.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.
Files changed (64) hide show
  1. package/README.md +143 -205
  2. package/dist/DelegatingRuntimeAdapter-DqfHkjLy.d.ts +373 -0
  3. package/dist/ITransport-BsPcaov7.d.ts +16 -0
  4. package/dist/OpenRTCShared-TKAQLONA.js +1 -0
  5. package/dist/WasmBridge-2A22U7RU.js +1 -0
  6. package/dist/auth/index.js +1 -1
  7. package/dist/auth/internal.js +1 -1
  8. package/dist/{capabilities-CaqXOIUU.d.ts → capabilities-YSskrE8H.d.ts} +1 -1
  9. package/dist/chunk-2QHDEGVX.js +1 -0
  10. package/dist/chunk-4K2QPYGT.js +2 -0
  11. package/dist/chunk-7Z6N46RB.js +2 -0
  12. package/dist/chunk-A3IAG6EL.js +1 -0
  13. package/dist/chunk-BXFXPIXO.js +1 -0
  14. package/dist/chunk-CEMN2JKR.js +3 -0
  15. package/dist/chunk-DTWEQS3J.js +1 -0
  16. package/dist/chunk-GW7P3D54.js +1 -0
  17. package/dist/chunk-K37WVIZL.js +1 -0
  18. package/dist/chunk-N26S7V4N.js +1 -0
  19. package/dist/chunk-N4SX7C3W.js +2 -0
  20. package/dist/chunk-NB4H5TP3.js +1 -0
  21. package/dist/chunk-NT5YHZQH.js +1 -0
  22. package/dist/chunk-PODAMIL6.js +2 -0
  23. package/dist/chunk-RD3JEGGF.js +2 -0
  24. package/dist/chunk-UEYM6WTT.js +2 -0
  25. package/dist/chunk-VK6KX433.js +1 -0
  26. package/dist/chunk-WMRCP3YX.js +1 -0
  27. package/dist/chunk-XE43HAXV.js +2 -0
  28. package/dist/chunk-YBXGNKM7.js +2 -0
  29. package/dist/chunk-YGJ6OAPR.js +1 -0
  30. package/dist/factories-O5575ECL.js +1 -0
  31. package/dist/index.d.ts +11 -65
  32. package/dist/index.js +1 -1
  33. package/dist/ipcFactory-FBNUVH7V.js +1 -0
  34. package/dist/native.d.ts +9 -15
  35. package/dist/native.js +1 -1
  36. package/dist/openrtc_bg.wasm +0 -0
  37. package/dist/runtime/WasmRuntimeAdapter.d.ts +3 -3
  38. package/dist/runtime/WasmRuntimeAdapter.js +1 -1
  39. package/dist/runtime/device-status.d.ts +3 -2
  40. package/dist/runtime/index.d.ts +110 -17
  41. package/dist/runtime/index.js +2 -1
  42. package/dist/runtime/tauri.d.ts +4 -4
  43. package/dist/runtime/tauri.js +1 -1
  44. package/dist/{tauri-BpsecNrp.d.ts → tauri-Cz9n17g8.d.ts} +2 -2
  45. package/dist/testing.d.ts +29 -0
  46. package/dist/testing.js +1 -0
  47. package/dist/transport/index.d.ts +47 -7
  48. package/dist/transport/index.js +1 -1
  49. package/dist/{assembly-CscFVHYK.d.ts → types-BDc7AZYI.d.ts} +446 -28
  50. package/dist/{types-BJU2GoVb.d.ts → types-BUXwspL0.d.ts} +11 -17
  51. package/dist/{types-zT2QwuCv.d.ts → types-BVJr065k.d.ts} +43 -3
  52. package/package.json +15 -4
  53. package/dist/DelegatingRuntimeAdapter-Cg3jFk1b.d.ts +0 -133
  54. package/dist/chunk-4IK5EKHY.js +0 -2
  55. package/dist/chunk-BW6OKBHV.js +0 -2
  56. package/dist/chunk-EVJYUIBK.js +0 -1
  57. package/dist/chunk-H5VWKP4Q.js +0 -2
  58. package/dist/chunk-HYHVKPQN.js +0 -3
  59. package/dist/chunk-LAUABWCB.js +0 -2
  60. package/dist/chunk-OCSZA6PK.js +0 -2
  61. package/dist/chunk-OMDHDMDJ.js +0 -1
  62. package/dist/chunk-QT2ASNI3.js +0 -1
  63. package/dist/framing-zRvEKOld.d.ts +0 -29
  64. package/dist/spaceTokens-CiwcKKr2.d.ts +0 -297
@@ -1,2 +0,0 @@
1
- import {h,b as b$2}from'./chunk-QT2ASNI3.js';import {v,b as b$1,d,c,G as G$1,e,t,u as u$1,a,w as w$1,x as x$1}from'./chunk-OCSZA6PK.js';import {xchacha20poly1305}from'@noble/ciphers/chacha.js';import*as $ from'tweetnacl';function ht(){if(typeof globalThis<"u"&&globalThis.__OPENRTC_DEBUG__===true)return true;if(typeof localStorage<"u")try{return localStorage.getItem("openrtc:debug")==="1"}catch{return false}return false}function pe(n,e,t){if(ht()){if(typeof t>"u"){console[n](e);return}console[n](e,t);}}function te(n,e){pe("debug",n,e);}function A(n,e){pe("info",n,e);}function mn(n,e){pe("log",n,e);}var W=new Uint8Array([79,82,84,67,69,49]),ne=2,H=8,q=24,Ne=32,ft=3,mt=16*1024*1024,gt=4096;function yt(n,e){if(n.byteLength<e.byteLength)return false;let t=0;for(let i=0;i<e.byteLength;i+=1)t|=n[i]^e[i];return t===0}function vt(n){let e=new Uint8Array(n),t=globalThis.crypto;if(!t||typeof t.getRandomValues!="function")throw new Error("[OpenRTC] application payload crypto requires crypto.getRandomValues");return t.getRandomValues(e),e}function bt(n,e){let t="";for(let i of e)t+=i.toString(16).padStart(2,"0");return `${n}:${t}`}function xe(n){if(!yt(n,W))return null;let e=n[W.byteLength];return e===ne?e:null}function St(n){return xe(n)===ne&&n.byteLength>W.byteLength+1+H+q}function bn(n,e={}){if(!(n instanceof Uint8Array)||n.byteLength!==Ne)throw new Error(`[OpenRTC] application payload crypto key must be ${Ne} bytes`);let t=new Uint8Array(n),i=e.requireEncrypted??true,r=e.randomBytes??vt,o=e.replayProtection??true,s=0,a=new Set,d=[];return {requireEncrypted:i,protectPayload(l,c){let p=r(q);if(!(p instanceof Uint8Array)||p.byteLength!==q)throw new Error(`[OpenRTC] application payload crypto nonce must be ${q} bytes`);let h=new Uint8Array(1+c.byteLength);h[0]=l,h.set(c,1);let y=xchacha20poly1305(t,p).encrypt(h);if(!o)throw new Error("[OpenRTC] ORTCE1 v1 envelopes are not supported; replay protection is required");let v=new Uint8Array(W.byteLength+1+H+p.byteLength+y.byteLength),S=0;v.set(W,S),S+=W.byteLength,v[S]=ne,S+=1;let O=s;return s+=1,new DataView(v.buffer,v.byteOffset+S,H).setBigUint64(0,BigInt(O),false),S+=H,v.set(p,S),S+=p.byteLength,v.set(y,S),v},openPayload(l,c){if(!St(c))return i?null:c;if(xe(c)!==ne)return null;let h=W.byteLength+1,y=Number(new DataView(c.buffer,c.byteOffset+h,H).getBigUint64(0,false));if(!Number.isFinite(y))return null;let v=h+H,S=v+q,O=c.slice(v,S),I=o?bt(y,O):null;if(I&&a.has(I))return null;let _=c.slice(S),R;try{R=xchacha20poly1305(t,O).decrypt(_);}catch{return null}if(R.byteLength<1||R[0]!==l)return null;if(I)for(a.add(I),d.push(I);d.length>gt;){let E=d.shift();E&&a.delete(E);}return R.slice(1)}}}function wt(n){let e=new Uint8Array(4+n.byteLength);return new DataView(e.buffer,e.byteOffset,e.byteLength).setUint32(0,n.byteLength,false),e.set(n,4),e}function Le(n,e={}){let t=e.typeId??ft,i=e.maxFrameBytes??mt;if(!Number.isInteger(t)||t<0||t>255)throw new Error("[OpenRTC] raw application crypto stream typeId must be an integer from 0 to 255");if(!Number.isInteger(i)||i<=0)throw new Error("[OpenRTC] raw application crypto maxFrameBytes must be a positive integer");let r=c=>n.protectPayload(t,c),o=c=>n.openPayload(t,c),s=()=>new TransformStream({transform(c,p){p.enqueue(wt(r(new Uint8Array(c))));}}),a=()=>{let c=new Uint8Array(0);return new TransformStream({transform(p,h){for(c=w$1([c,new Uint8Array(p)]);c.byteLength>=4;){let y=new DataView(c.buffer,c.byteOffset,c.byteLength).getUint32(0,false);if(y===0||y>i)throw new Error("[OpenRTC] invalid encrypted raw stream frame length");if(c.byteLength<4+y)return;let v=c.slice(4,4+y);c=c.slice(4+y);let S=o(v);if(!S)throw new Error("[OpenRTC] encrypted raw stream frame failed authentication");h.enqueue(S);}},flush(){if(c.byteLength!==0)throw new Error("[OpenRTC] encrypted raw stream ended mid-frame")}})},d=c=>c.pipeThrough(a()),l=c=>{let p=s();return p.readable.pipeTo(c).catch(()=>{}),p.writable};return {typeId:t,protectFrame:r,openFrame:o,createOutboundTransform:s,createInboundTransform:a,wrapReadable:d,wrapWritable:l,wrapBiStream(c){return {...c,send:l(c.send),recv:d(c.recv)}}}}var It="[OpenRTC][teardown-trace]";function Tt(){try{let n=globalThis;if(n.OPENRTC_TEARDOWN_TRACE===!0||n.localStorage?.getItem("OPENRTC_TEARDOWN_TRACE")==="1")return !0}catch{}return false}function Be(n,e={}){console.info(It,{kind:n,ts:new Date().toISOString(),...e}),Tt()&&console.info("[OpenRTC][teardown-trace:stack]",{kind:n,stack:new Error(`teardown: ${n}`).stack});}var f={AUTH_NOT_READY:"auth/not-ready",AUTH_DENIED:"auth/denied",AUTH_EXPIRED:"auth/expired",ADMISSION_DENIED:"admission/denied",ADMISSION_SCOPE_MISMATCH:"admission/scope-mismatch",BUDGET_EXCEEDED:"budget/exceeded",BUDGET_STALE:"budget/stale",BUDGET_RENEWAL_REQUIRED:"budget/renewal-required",COORDINATION_DISCONNECTED:"coordination/disconnected",COORDINATION_PROTOCOL:"coordination/protocol",COORDINATION_RATE_LIMITED:"coordination/rate-limited",TRANSPORT_DIAL_EXHAUSTED:"transport/dial-exhausted",TRANSPORT_UNAVAILABLE:"transport/unavailable",TRANSPORT_TICKET_MISSING:"transport/ticket-missing",DELIVERY_NOT_READY:"delivery/not-ready",INTERNAL:"internal/error"},D=class n extends Error{constructor(t){super(t.message);this.name="OpenRtcError";t.cause!==void 0&&(this.cause=t.cause),this.code=t.code,this.retryable=t.retryable,this.plane=t.plane,this.generation=t.generation,this.transportGeneration=t.transportGeneration,this.routeGeneration=t.routeGeneration,this.revision=t.revision;}static isOpenRtcError(t){return t instanceof n||typeof t=="object"&&t!==null&&t.name==="OpenRtcError"&&typeof t.code=="string"&&typeof t.retryable=="boolean"&&typeof t.plane=="string"}static shouldAppRetry(t){let i=ie(t);return i.retryable?i.plane==="coordination"||i.plane==="transport"||i.plane==="auth":false}toJSON(){return {name:this.name,code:this.code,message:this.message,retryable:this.retryable,plane:this.plane,generation:this.generation??null,transportGeneration:this.transportGeneration??null,routeGeneration:this.routeGeneration??null,revision:this.revision??null}}};function Fe(n){let e=ie(n);return {errorCode:e.code,retryable:e.retryable,errorPlane:e.plane}}function w(n,e,t){let i=Rt(n);return new D({code:n,message:e,retryable:t.retryable??i.retryable,plane:t.plane??i.plane,cause:t.cause,generation:t.generation,transportGeneration:t.transportGeneration,routeGeneration:t.routeGeneration,revision:t.revision})}function Rt(n){switch(n){case f.AUTH_NOT_READY:case f.AUTH_EXPIRED:return {retryable:true,plane:"auth"};case f.AUTH_DENIED:return {retryable:false,plane:"auth"};case f.ADMISSION_DENIED:case f.ADMISSION_SCOPE_MISMATCH:return {retryable:false,plane:"admission"};case f.BUDGET_EXCEEDED:return {retryable:false,plane:"budget"};case f.BUDGET_STALE:case f.BUDGET_RENEWAL_REQUIRED:return {retryable:true,plane:"budget"};case f.COORDINATION_DISCONNECTED:case f.COORDINATION_RATE_LIMITED:return {retryable:true,plane:"coordination"};case f.COORDINATION_PROTOCOL:return {retryable:false,plane:"coordination"};case f.TRANSPORT_DIAL_EXHAUSTED:case f.TRANSPORT_UNAVAILABLE:case f.TRANSPORT_TICKET_MISSING:return {retryable:true,plane:"transport"};case f.DELIVERY_NOT_READY:return {retryable:true,plane:"delivery"};case f.INTERNAL:default:return {retryable:false,plane:"internal"}}}function ie(n){if(D.isOpenRtcError(n))return n instanceof D?n:new D({code:n.code,message:n.message||String(n),retryable:n.retryable,plane:n.plane,cause:n,generation:n.generation,transportGeneration:n.transportGeneration,routeGeneration:n.routeGeneration,revision:n.revision});if(typeof n=="object"&&n!==null){let t=n,i=typeof t.code=="string"?t.code:"",r=typeof t.message=="string"?t.message:n instanceof Error?n.message:String(n),o=typeof t.retryable=="boolean"?t.retryable:void 0;if(i){let s=Ct(i,r,o);if(s)return s}if(typeof t.name=="string"&&t.name==="CoordinationConnectError")return w(f.COORDINATION_DISCONNECTED,r,{retryable:o??true,plane:"coordination",cause:n});if(typeof t.name=="string"&&t.name==="CoordinationGatewayProtocolError")return w(i||f.COORDINATION_PROTOCOL,r,{retryable:o??false,plane:Ue(i),cause:n})}let e=n instanceof Error?n.message:String(n??"unknown error");return Pt(e,n)}function Ct(n,e,t){let i=n.trim().toLowerCase();return i==="unauthenticated"||i==="functions/unauthenticated"||i==="auth/unauthorized"||i.includes("permission-denied")?w(f.AUTH_DENIED,e,{retryable:false,plane:"auth"}):i==="budget-renewal-required"||i==="budget/renewal-required"?w(f.BUDGET_RENEWAL_REQUIRED,e,{retryable:t??true,plane:"budget"}):i.includes("resource-exhausted")||i.includes("budget")||i==="budget-exceeded"||i==="insufficient-budget"?i.includes("stale")||/stale-budget/i.test(e)?w(f.BUDGET_STALE,e,{retryable:t??true,plane:"budget"}):w(f.BUDGET_EXCEEDED,e,{retryable:false,plane:"budget"}):i.includes("rate-limit")||i==="rate_limited"||i==="too-many-requests"?w(f.COORDINATION_RATE_LIMITED,e,{retryable:t??true,plane:"coordination"}):i.includes("admission")||i==="permission-denied"||i==="session-token-denied"?w(f.ADMISSION_DENIED,e,{retryable:false,plane:"admission"}):i.includes("scope")?w(f.ADMISSION_SCOPE_MISMATCH,e,{retryable:false,plane:"admission"}):i.includes("disconnect")||i.includes("unavailable")||i==="aborted"?w(f.COORDINATION_DISCONNECTED,e,{retryable:t??true,plane:"coordination"}):i.startsWith("coordination/")||i.includes("protocol")?w(n,e,{retryable:t??false,plane:Ue(n)}):null}function Ue(n){let e=n.trim().toLowerCase();return e.includes("budget")?"budget":e.includes("auth")?"auth":e.includes("admission")||e.includes("scope")?"admission":(e.includes("rate"),"coordination")}function Pt(n,e){return /auth(?:entication)?\s*(?:not ready|pending|missing)/i.test(n)||/token\s*(?:not ready|pending|missing)/i.test(n)||/awaiting[- ]auth/i.test(n)?w(f.AUTH_NOT_READY,n,{retryable:true,plane:"auth",cause:e}):/missing endpoint ticket|ticket missing/i.test(n)?w(f.TRANSPORT_TICKET_MISSING,n,{retryable:true,plane:"transport",cause:e}):/dial.*(exhaust|budget)|retry budget|connection.*did not become application-routable/i.test(n)?w(f.TRANSPORT_DIAL_EXHAUSTED,n,{retryable:true,plane:"transport",cause:e}):/stale[- ]budget/i.test(n)?w(f.BUDGET_STALE,n,{retryable:true,plane:"budget",cause:e}):/budget|credit|quota|limit\s*exceeded/i.test(n)?w(f.BUDGET_EXCEEDED,n,{retryable:false,plane:"budget",cause:e}):/admission|session[- ]token.*(deny|reject)|permission[- ]denied/i.test(n)?w(f.ADMISSION_DENIED,n,{retryable:false,plane:"admission",cause:e}):/not\s+application-routable|not[- ]ready|settledReady/i.test(n)?w(f.DELIVERY_NOT_READY,n,{retryable:true,plane:"delivery",cause:e}):/gateway|coordination|websocket|signaling/i.test(n)?w(f.COORDINATION_DISCONNECTED,n,{retryable:true,plane:"coordination",cause:e}):w(f.INTERNAL,n,{retryable:false,plane:"internal",cause:e})}var he={managedSession:{nativeStartRetryWindowMs:12e4,nativeStartRetryMinDelayMs:400,nativeStartRetryMaxDelayMs:5e3,reconciliationIntervalMs:5e3,deviceStatusRefreshDebounceMs:50},browserAutoConnect:{scanDebounceMs:150,retryCooldownMs:2e3,settleGuardMs:1e4,retryMaxMs:8e3,nonInitiatorBaseGraceMs:2e3,nonInitiatorMaxGraceMs:16e3},nativeIpc:{authRequiredWaitMs:15e3,defaultBoundedCommandTimeoutMs:15e3,connectionEventSubscribeWindowMs:15e3,connectionEventRetryMinDelayMs:250,connectionEventRetryMaxDelayMs:1e3,tauriIpcNegativeCacheMs:2e3},browserIdentity:{ephemeralDeviceIdTtlMs:6e4}};function Tn(){return he}var Et={adapter:"browser-wasm",signaling:{coordinationGateway:true,nativeIpc:false,managedPresence:true},transport:{irohQuic:true,irohLan:false,webRtcUpgrade:true,webRtcLan:true,nativeWebRtc:false,moq:true,ble:false,wasm:true},nativeProtocols:{productAlpn:false,irohDocs:false,irohBlobs:false,irohGossip:false},lifecycle:{managedSession:true,autoConnect:true,manualDisconnect:true,connectionStateEvents:true,peerSessions:true},transfers:{explicitFilePath:false,explicitFileData:true,history:false},fallback:{wasm:false}},At={adapter:"native-ipc",signaling:{coordinationGateway:true,nativeIpc:true,managedPresence:true},transport:{irohQuic:true,irohLan:false,webRtcUpgrade:false,webRtcLan:false,nativeWebRtc:false,moq:false,ble:false,wasm:false},nativeProtocols:{productAlpn:true,irohDocs:true,irohBlobs:true,irohGossip:true},lifecycle:{managedSession:true,autoConnect:true,manualDisconnect:true,connectionStateEvents:true,peerSessions:true},transfers:{explicitFilePath:true,explicitFileData:true,history:true},fallback:{wasm:false}};function We(n){return {adapter:n.adapter,signaling:{...n.signaling},transport:{...n.transport},nativeProtocols:{...n.nativeProtocols},lifecycle:{...n.lifecycle},transfers:{...n.transfers},fallback:{...n.fallback}}}function re(n=globalThis){let e=We(Et),t=typeof n?.RTCPeerConnection=="function";return e.transport.webRtcUpgrade=t,e.transport.webRtcLan=t,e}function G(n){return n?.compiled===true&&n.enabled===true}function Cn(n,e=false){let t=We(At),i=n?.transport;return i&&(t.transport.irohQuic=G(i.irohQuic),t.transport.irohLan=G(i.irohLan),t.transport.webRtcUpgrade=G(i.webRtc),t.transport.nativeWebRtc=G(i.webRtc),t.transport.webRtcLan=G(i.webRtcLan),t.transport.moq=G(i.moq),t.transport.ble=G(i.ble)),t.transport.wasm=false,t.fallback.wasm=e,t}function Pn(n){return {environment:n.adapter==="native-ipc"||n.adapter==="tauri-ipc"?"native":n.adapter==="browser-wasm"?"web":"unknown",transports:{quic:n.transport.irohQuic,irohRelay:n.transport.irohQuic,irohLan:n.transport.irohLan,webRtc:n.transport.webRtcUpgrade||n.transport.nativeWebRtc,webRtcLan:n.transport.webRtcLan,moq:n.transport.moq,ble:n.transport.ble},lifecycle:{...n.lifecycle},storage:{localFileSystem:n.transfers.explicitFilePath,transferHistory:n.transfers.history},nativeProtocols:{...n.nativeProtocols}}}var Ge=3e4,kt=3e4,Dt=12,fe=15e3,Mt=15e3,Ot=1e3,He=250,Nt="openrtc.v1",xt="openrtc.auth.",b=class extends D{constructor(t,i){super({code:f.COORDINATION_DISCONNECTED,message:t,retryable:i,plane:"coordination"});this.name="CoordinationConnectError";}},oe=class extends D{constructor(t,i,r){let o=ie({code:t,message:i,retryable:r});super({code:o.code||t||f.COORDINATION_PROTOCOL,message:`Coordination gateway ${t}: ${i}`,retryable:r,plane:o.plane});this.name="CoordinationGatewayProtocolError";}};function Ke(n){return n instanceof b&&/\bstale-budget\b/i.test(n.message)}function je(n){let e=typeof n=="object"&&n!==null&&"code"in n?String(n.code??""):"";return ["functions/unauthenticated","functions/permission-denied","functions/invalid-argument","functions/failed-precondition","functions/resource-exhausted","unauthenticated","permission-denied","invalid-argument","failed-precondition","resource-exhausted"].includes(e)}function Lt(n){let e=new Uint32Array(1);return crypto.getRandomValues(e),Math.max(1,Math.round(n*(.75+e[0]/4294967295*.5)))}function k(n){if(typeof crypto.randomUUID=="function")return `${n}:${crypto.randomUUID()}`;let e=new Uint8Array(16);crypto.getRandomValues(e);let t=Array.from(e,i=>i.toString(16).padStart(2,"0")).join("");return `${n}:${t}`}async function Bt(n){let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n)),t="";for(let i of new Uint8Array(e))t+=String.fromCharCode(i);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function Ft(n,e){let t=new URL(n);if(t.search||t.hash||t.username||t.password)throw new Error("[OpenRTC] Coordination gateway endpoint must not contain credentials, query, or fragment.");if(t.protocol==="https:")t.protocol="wss:";else if(t.protocol==="http:")t.protocol="ws:";else if(t.protocol!=="wss:"&&t.protocol!=="ws:")throw new Error("[OpenRTC] Coordination gateway endpoint must use HTTPS/WSS.");return t.pathname=`${t.pathname.replace(/\/+$/,"")}/v1/connect/${e}`,t.toString()}function ze(n){let e=new URL(n);return e.protocol==="wss:"&&(e.protocol="https:"),e.protocol==="ws:"&&(e.protocol="http:"),e.origin}function Ut(n,e){let t=n.trim();if(!t)throw new Error("[OpenRTC] Firebase project ID is required for the native gateway credential.");let i=typeof globalThis>"u"?"":String(globalThis.__OPENRTC_FUNCTIONS_EMULATOR_HOST__??"").trim();if(i)return `http://${i}/${encodeURIComponent(t)}/us-central1`;let r=e.controlPlaneEndpoint?.trim()||(e.environment==="production"?"https://api.openrtc.app":"");if(!r)throw new Error("[OpenRTC] Internal staging coordination requires coordinationGateway.controlPlaneEndpoint.");let o=typeof globalThis.location?.origin=="string"?globalThis.location.origin:void 0,s=new URL(r,o);if(s.protocol!=="https:"&&s.protocol!=="http:"||s.username||s.password||s.search||s.hash)throw new Error("[OpenRTC] Coordination control-plane endpoint is invalid.");return s.toString().replace(/\/+$/,"")}function qe(n,e,t){return `${Ut(n,e)}/${encodeURIComponent(t)}`}async function Ye(n){let e=`request failed with status ${n.status}`;try{let t=await n.json(),i=typeof t.error?.message=="string"?t.error.message.trim():"";return i?i.slice(0,256):e}catch{return e}}var se=class n{constructor(e){this.options=e;this.runtimeInstanceId=k("runtime");this.socket=null;this.socketReady=false;this.connectPromise=null;this.desiredPresence=null;this.desiredExcludedPeers=[];this.devices=new Map;this.deviceListeners=new Set;this.deviceStreams=new Set;this.sessionStreams=new Set;this.pendingAcks=new Map;this.pendingMessages=[];this.roomConnections=new Map;this.friendConnections=new Map;this.reconnectTimer=null;this.authRefreshTimer=null;this.pendingAuthRefresh=null;this.budgetRenewalPromise=null;this.budgetRenewalEpoch=0;this.reconnectAttempt=0;this.reconnectCircuitOpen=false;this.hostResumeReconnectPromise=null;this.lastHostResumeReconnectAtMs=0;this.desiredPresenceRevision=0;this.appliedPresenceRevision=0;this.stopped=false;if(e.gateway.environment!=="staging"&&e.gateway.environment!=="production")throw new Error("[OpenRTC] Coordination gateway environment is invalid.");let t=new URL(e.gateway.endpoint),i=t.hostname==="127.0.0.1"||t.hostname==="localhost"||t.hostname==="[::1]",r=t.protocol==="https:"||t.protocol==="wss:",s=!!(typeof globalThis>"u"?"":String(globalThis.__OPENRTC_FUNCTIONS_EMULATOR_HOST__??"").trim())&&i&&(t.protocol==="http:"||t.protocol==="ws:");if(!r&&!s)throw new Error("[OpenRTC] Coordination gateway requires HTTPS/WSS.");if(t.username||t.password||t.search||t.hash)throw new Error("[OpenRTC] Coordination gateway credentials and parameters cannot be supplied in its URL.")}async updatePresence(e,t,i,r,o,s){let a=this.desiredPresence;this.desiredPresence={localNodeId:e,ticket:t,online:i,ttlMs:r,metadata:o,deviceName:s?.trim()||this.options.getDefaultDeviceName()},(!a||a.localNodeId!==e||a.ticket!==t||a.online!==i||a.ttlMs!==r||a.metadata!==o||a.deviceName!==this.desiredPresence.deviceName)&&(this.desiredPresenceRevision+=1,this.reconnectCircuitOpen=false,this.reconnectAttempt=0);let l=this.desiredPresenceRevision;await this.ensureConnected(),!(this.appliedPresenceRevision>=l)&&(a&&a.ticket!==t&&await this.refreshAuthentication(),await this.sendOperation({v:1,type:"presence.upsert",idempotencyKey:k("presence"),ttlMs:r,device:this.gatewayDevice(this.desiredPresence)}),this.appliedPresenceRevision=Math.max(this.appliedPresenceRevision,l));}async setOffline(e){this.desiredPresence&&(this.desiredPresence.online=false,this.socket?.readyState===WebSocket.OPEN&&await this.sendOperation({v:1,type:"presence.offline",idempotencyKey:k("offline")}));}async reconnectAfterHostResume(){if(this.desiredPresence){if(this.hostResumeReconnectPromise)return this.hostResumeReconnectPromise;if(!(Date.now()-this.lastHostResumeReconnectAtMs<Mt)){this.lastHostResumeReconnectAtMs=Date.now(),this.hostResumeReconnectPromise=(async()=>{(this.socket?.readyState===WebSocket.OPEN||this.socketReady)&&this.stopSocket(),await this.ensureConnected();})();try{await this.hostResumeReconnectPromise;}finally{this.hostResumeReconnectPromise=null;}}}}async updateDevice(e,t){if(e!==this.options.getLocalDeviceId())throw new Error("A coordination socket can update only its local device.");let i=t;if(t.excludedPeers!==void 0){let r=[...new Set(t.excludedPeers.map(o=>String(o??"").trim().toLowerCase()).filter(Boolean))].sort();if(r.length>He)throw new Error(`Coordination excluded-peer set exceeds ${He} devices.`);this.desiredExcludedPeers=r,i={...t,excludedPeers:r};}await this.ensureConnected(),await this.sendOperation({v:1,type:"device.patch",idempotencyKey:k("device-patch"),patch:i});}async deleteDevice(e){if(this.options.credentialPurpose!=="device-control"&&(!this.socketReady||this.socket?.readyState!==WebSocket.OPEN)){let t=new n({...this.options,credentialPurpose:"device-control"});try{await t.deleteDevice(e);}finally{t.stopAuthScopedActivity();}return}await this.ensureConnected();try{await this.sendOperation({v:1,type:"device.delete",idempotencyKey:k("device-delete"),targetDeviceId:e});}finally{this.options.credentialPurpose==="device-control"&&this.stopSocket();}}async cleanupStaleDevices(){}async searchDevices(e){return this.snapshot(e)}async listDevices(e){return this.snapshot(e)}onDevicesChange(e,t){let i=r=>e(t?r.filter(o=>o.nodeId!==t):r);return this.deviceListeners.add(i),i(this.snapshot()),this.desiredPresence&&this.ensureConnected(),()=>this.deviceListeners.delete(i)}async subscribeDevices(){let e=null;return new ReadableStream({start:t=>{e=t,this.deviceStreams.add(t);let i=this.snapshot().map(r=>({type:"added",device:r}));i.length>0&&t.enqueue(i);},cancel:()=>{e&&this.deviceStreams.delete(e),e=null;}})}async createSession(e){await this.ensureConnected(),await this.sendOperation({v:1,type:"session.put",idempotencyKey:k("session-put"),sessionId:e.connectionId,session:e,expiresAtMs:e.expiresAt??Date.now()+15*6e4});}async updateSession(e,t){await this.ensureConnected(),await this.sendOperation({v:1,type:"session.put",idempotencyKey:k("session-update"),sessionId:this.unscopedId(e),session:t,expiresAtMs:typeof t.expiresAt=="number"?t.expiresAt:Date.now()+15*6e4});}async subscribeSessions(e){let t=null;return new ReadableStream({start:i=>{t=i,this.sessionStreams.add(i);},cancel:()=>{t&&this.sessionStreams.delete(t),t=null;}})}async sendMessage(e,t,i,r){await this.ensureConnected();let o=k("signal");return await this.sendOperation({v:1,type:"signal.send",idempotencyKey:o,targetDeviceId:this.unscopedId(e),payload:t,state:i,replyPayload:r}),o}async pollMessages(e){return this.pendingMessages.splice(0,this.pendingMessages.length)}watchFriendDevices(e,t){let i=[...new Set(e.map(a=>a.trim()).filter(Boolean))];if(i.length>25)throw new RangeError(`watchFriendDevices accepts at most ${25} unique friend IDs per runtime.`);for(let a of i)if(a.length>128||a.includes("/"))throw new TypeError('Friend user IDs must be 1-128 characters and cannot contain "/".');let r={value:false},o=new Map,s=[];t(new Map);for(let a of i)!a||a===this.options.getCurrentUserId()||this.openFriendConnection(a).then(d=>{if(r.value){d.stopAuthScopedActivity();return}s.push(d.onDevicesChange(l=>{o.set(a,l.filter(c=>c.online)),t(new Map(o));}));}).catch(()=>{r.value||(o.set(a,[]),t(new Map(o)));});return ()=>{r.value=true;for(let a of s)a();for(let a of i)this.friendConnections.get(a)?.stopAuthScopedActivity(),this.friendConnections.delete(a);}}async updateFriendTicket(e){await this.ensureConnected(),await this.sendOperation({v:1,type:"device.patch",idempotencyKey:k("friend-ticket"),patch:{friendTicket:e??""}});}async handleScopeChange(){this.stopSocket(),this.reconnectCircuitOpen=false,this.reconnectAttempt=0,this.appliedPresenceRevision=0,this.devices.clear(),this.emitDevices();}stopAuthScopedActivity(){this.stopped=true,this.stopSocket(),this.desiredExcludedPeers=[];for(let e of this.pendingAcks.values())clearTimeout(e.timer),e.reject(new Error("Coordination session stopped."));this.pendingAcks.clear(),this.devices.clear(),this.pendingMessages.splice(0,this.pendingMessages.length),this.emitDevices();for(let e of this.roomConnections.values())e.stopAuthScopedActivity();this.roomConnections.clear();for(let e of this.friendConnections.values())e.stopAuthScopedActivity();this.friendConnections.clear();}usesCoordinationGateway(){return true}async joinCoordinationRoom(e,t,i){let r=e.trim().toUpperCase(),o=this.roomConnections.get(r);o||(o=new n({...this.options,avenueOverride:{kind:"room",id:r}}),this.roomConnections.set(r,o)),await o.updatePresence(t,i,true,5*6e4,void 0,this.options.getDefaultDeviceName());}async leaveCoordinationRoom(e){let t=e.trim().toUpperCase(),i=this.roomConnections.get(t);i&&(await i.setOffline(this.options.getLocalDeviceId()).catch(()=>{}),i.stopAuthScopedActivity(),this.roomConnections.delete(t));}async getCoordinationRoomMembers(e){return this.requireRoomConnection(e).snapshot().map(i=>this.roomMember(i))}watchCoordinationRoomMembers(e,t){return this.requireRoomConnection(e).onDevicesChange(r=>t(r.map(o=>this.roomMember(o))))}async ensureConnected(){if(this.connectPromise)return this.connectPromise;if(!(this.socket?.readyState===WebSocket.OPEN&&this.socketReady)){if(!this.desiredPresence&&this.options.credentialPurpose!=="device-control")throw new Error("Coordination presence must be initialized before the gateway can connect.");if(this.reconnectCircuitOpen)throw new b("Coordination reconnect circuit is open until presence or scope changes.",false);if(this.reconnectTimer)throw new b("Coordination reconnect is already scheduled.",true);this.stopped=false,this.connectPromise=this.connect();try{await this.connectPromise;}catch(e){throw this.scheduleReconnect(e),e}finally{this.connectPromise=null;}}}async connect(){let e=this.desiredPresence??this.controlPresence(),t=this.desiredPresenceRevision,i=async()=>{let r=await this.mintGatewayCredential(e);await new Promise((o,s)=>{let a=new WebSocket(Ft(r.gatewayUrl,r.routeKey),[Nt,`${xt}${r.token}`]);this.socket=a;let d=false,l=null,c=setTimeout(()=>{a.close(4408,"authentication timeout"),l=new b("Coordination gateway authentication timed out.",true),s(l);},fe);a.onopen=()=>{a.send(JSON.stringify({v:1,type:"auth",token:r.token,device:this.gatewayDevice(e)}));},a.onmessage=p=>{let h;try{h=JSON.parse(String(p.data));}catch{a.close(4400,"invalid gateway frame"),d||(clearTimeout(c),s(new Error("Coordination gateway returned an invalid frame.")));return}if(h.type==="ready"&&!d&&(d=true,this.socketReady=true,this.appliedPresenceRevision=Math.max(this.appliedPresenceRevision,this.desiredPresence?t:0),clearTimeout(c),this.reconnectAttempt=0,this.scheduleAuthRefresh(r.expiresAtMs),o()),h.type==="error"&&!d){l=new b(`Coordination gateway ${h.code}: ${h.message}`,h.retryable),clearTimeout(c),s(l),a.close(4403,h.code);return}this.handleFrame(h);},a.onerror=()=>{d||(clearTimeout(c),l??(l=new b("Coordination gateway connection failed.",true)),s(l));},a.onclose=p=>{clearTimeout(c),this.socket===a&&(this.socket=null,this.socketReady=false),this.rejectPendingAcks("Coordination gateway connection closed."),this.rejectPendingAuthRefresh(new b("Coordination gateway closed during credential refresh.",p.code!==4401&&p.code!==4403)),!this.stopped&&this.desiredPresence&&p.code!==1e3&&!Ke(l)&&this.scheduleReconnect(l??new b(`Coordination gateway closed (${p.code}).`,p.code!==4401));};});};try{await i();}catch(r){if(!Ke(r))throw r;await i();}}async mintGatewayCredential(e){let i={avenue:await this.resolveAvenue(),deviceId:this.options.getLocalDeviceId(),runtimeInstanceId:this.runtimeInstanceId,ticketFingerprint:await Bt(e.ticket),purpose:this.options.credentialPurpose??"presence",idempotencyKey:k("credential")},r;try{r=this.options.getPlatformType()==="web"?await this.mintBrowserCredential(i):await this.mintNativeCredential(i);}catch(s){throw s instanceof b?s:new b(s instanceof Error?s.message:"Coordination credential mint failed.",!je(s))}if(r.protocolVersion!==1)throw new b("Unsupported coordination gateway protocol.",false);let o=ze(this.options.gateway.endpoint);if(ze(r.gatewayUrl)!==o)throw new b("Coordination credential returned an unexpected gateway origin.",false);return r}async mintBrowserCredential(e){let t=async s=>{let a=await this.options.getAuthToken(s);if(!a)throw new b("[OpenRTC] Browser coordination requires an authenticated runtime.",false);let d=await this.options.getAppCheckToken(s);if(!d)throw new b("[OpenRTC] Browser coordination requires platform attestation.",false);return fetch(qe(this.options.projectId,this.options.gateway,"mintCoordinationCredential"),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`,"X-Firebase-AppCheck":d},body:JSON.stringify({data:e}),signal:AbortSignal.timeout(15e3)})},i=await t(false);if((i.status===401||i.status===403)&&(i=await t(true)),!i.ok)throw new b(`[OpenRTC] Browser coordination credential denied: ${await Ye(i)}`,i.status===408||i.status===425||i.status===429||i.status>=500);let r=await i.json(),o=r.result??r.data;if(!o)throw new b("[OpenRTC] Browser coordination credential returned an invalid callable response.",false);return o}async getNativeTrustToken(e=false){return (await this.options.nativeTrustTokens.get(e)).token}async mintNativeCredential(e){let t=await this.options.getAuthToken(false);if(!t)throw new Error("[OpenRTC] Native coordination requires an authenticated runtime.");let i=async a=>{let[d,l]=await Promise.all([a?this.options.getAuthToken(true):Promise.resolve(t),this.getNativeTrustToken(a)]);if(!d)throw new Error("[OpenRTC] Native coordination requires an authenticated runtime.");return fetch(qe(this.options.projectId,this.options.gateway,"mintNativeCoordinationCredential"),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${d}`,"X-Firebase-AppCheck":l},body:JSON.stringify({data:e}),signal:AbortSignal.timeout(15e3)})},r=await i(false);if((r.status===401||r.status===403)&&(this.options.nativeTrustTokens.invalidate(),r=await i(true)),!r.ok)throw new b(`[OpenRTC] Native coordination credential denied: ${await Ye(r)}`,r.status===408||r.status===425||r.status===429||r.status>=500);let o=await r.json(),s=o.result??o.data;if(!s)throw new Error("[OpenRTC] Native coordination credential returned an invalid callable response.");return s}handleFrame(e){if(e.type==="auth.refreshed"){let t=this.pendingAuthRefresh;t&&(clearTimeout(t.timer),this.pendingAuthRefresh=null,this.scheduleAuthRefresh(e.expiresAtMs),t.resolve());}else if(e.type==="roster.snapshot"){this.devices.clear();for(let t of e.devices)this.devices.set(t.deviceId,this.toDevice(t));this.emitDevices();}else if(e.type==="presence.changed"){if(e.operation==="delete")this.devices.delete(e.device.deviceId),this.emitDeviceEvents([{type:"removed",deviceId:e.device.deviceId}]);else {let t=this.devices.has(e.device.deviceId),i=this.toDevice(e.device);this.devices.set(i.deviceId,i),this.emitDeviceEvents([{type:t?"modified":"added",device:i}]);}this.emitDevices();}else if(e.type==="signal.received")this.pendingMessages.length>=Ot&&this.pendingMessages.shift(),this.pendingMessages.push({senderId:e.senderDeviceId,targetId:this.options.getLocalDeviceId(),payload:e.payload,state:e.state,replyPayload:e.replyPayload,timestamp:e.createdAtMs,appTag:this.options.appTag});else if(e.type==="session.changed"){let t=e.operation==="delete"?[{type:"removed",sessionId:e.sessionId}]:[{type:"modified",session:{...e.session??{},connectionId:e.sessionId}}];for(let i of this.sessionStreams)i.enqueue(t);}else if(e.type==="ack"){let t=this.pendingAcks.get(e.idempotencyKey);t&&(clearTimeout(t.timer),this.pendingAcks.delete(e.idempotencyKey),t.resolve());}else if(e.type==="error"){if(!e.idempotencyKey&&this.pendingAuthRefresh){let i=this.pendingAuthRefresh;clearTimeout(i.timer),this.pendingAuthRefresh=null,i.reject(new b(`Coordination gateway ${e.code}: ${e.message}`,e.retryable));return}let t=e.idempotencyKey?this.pendingAcks.get(e.idempotencyKey):null;t&&(clearTimeout(t.timer),this.pendingAcks.delete(e.idempotencyKey),t.reject(new oe(e.code,e.message,e.retryable)));}}async sendOperation(e){this.budgetRenewalPromise&&await this.budgetRenewalPromise;let t=this.budgetRenewalEpoch;try{await this.sendOperationOnce(e);}catch(i){if(!(i instanceof oe)||i.code!=="budget-renewal-required"&&i.code!==f.BUDGET_RENEWAL_REQUIRED||!i.retryable)throw i;this.budgetRenewalEpoch===t&&await this.renewBudget(),await this.sendOperationOnce(e);}}async sendOperationOnce(e){let t=this.socket;if(!t||t.readyState!==WebSocket.OPEN||!this.socketReady)throw new Error("Coordination gateway is not connected.");await new Promise((i,r)=>{let o=setTimeout(()=>{this.pendingAcks.delete(e.idempotencyKey),r(new Error("Coordination gateway acknowledgement timed out."));},fe);this.pendingAcks.set(e.idempotencyKey,{resolve:i,reject:r,timer:o}),t.send(JSON.stringify(e));});}async renewBudget(){if(this.budgetRenewalPromise)return this.budgetRenewalPromise;let e=this.refreshAuthentication().then(()=>{this.budgetRenewalEpoch+=1;});this.budgetRenewalPromise=e;try{await e;}finally{this.budgetRenewalPromise===e&&(this.budgetRenewalPromise=null);}}async resolveAvenue(){if(this.options.avenueOverride)return this.options.avenueOverride;if((this.options.discoveryMode??"space")==="space"){let t=await this.options.resolveSpaceNamespaceId();if(!t)throw new Error("Space namespace is not available for coordination.");return {kind:"space",id:t}}let e=this.options.getCurrentUserId();if(!e)throw new Error("Authenticated user is required for coordination.");return {kind:"user",id:e}}gatewayDevice(e){return {deviceId:this.options.getLocalDeviceId(),runtimeInstanceId:this.runtimeInstanceId,nodeId:e.localNodeId,deviceName:e.deviceName,platformType:this.options.getPlatformType(),ticket:e.ticket,metadata:e.metadata,excludedPeers:this.desiredExcludedPeers,online:e.online}}controlPresence(){if(this.options.credentialPurpose!=="device-control")throw new Error("Coordination presence must be initialized before the gateway can connect.");return {localNodeId:this.options.getLocalDeviceId(),ticket:`openrtc-device-control:${this.runtimeInstanceId}`,online:false,ttlMs:0,deviceName:this.options.getDefaultDeviceName()}}toDevice(e){return this.options.normalizeDevice({...e,appTag:this.options.appTag,lastSeenAt:e.updatedAtMs,expiresAt:e.expiresAtMs},e.deviceId)}snapshot(e){return [...this.devices.values()].filter(t=>!e||t.nodeId!==e).sort((t,i)=>t.deviceId.localeCompare(i.deviceId))}emitDevices(){let e=this.snapshot();for(let t of this.deviceListeners)t(e);}emitDeviceEvents(e){for(let t of this.deviceStreams)t.enqueue(e);}scheduleAuthRefresh(e){this.authRefreshTimer&&clearTimeout(this.authRefreshTimer);let t=e-Date.now(),i=t>Ge+1e3;this.authRefreshTimer=setTimeout(()=>{if(this.authRefreshTimer=null,!this.stopped){if(!i){this.stopSocket(false),this.scheduleReconnect(new b("Coordination credential crossed a billing boundary.",true));return}this.refreshAuthentication().catch(r=>{this.stopSocket(false),this.scheduleReconnect(r);});}},i?t-Ge:Math.max(1e3,t+1e3));}async refreshAuthentication(){let e=this.socket,t=this.desiredPresence;if(!e||e.readyState!==WebSocket.OPEN||!this.socketReady||!t)throw new b("Coordination socket is unavailable for credential refresh.",true);if(this.pendingAuthRefresh)return this.pendingAuthRefresh.promise;let i=await this.mintGatewayCredential(t),r,o,s=new Promise((d,l)=>{r=d,o=l;}),a=setTimeout(()=>{this.pendingAuthRefresh?.timer===a&&(this.pendingAuthRefresh=null),o(new b("Coordination credential refresh timed out.",true));},fe);this.pendingAuthRefresh={promise:s,resolve:r,reject:o,timer:a},e.send(JSON.stringify({v:1,type:"auth.refresh",token:i.token})),await s;}scheduleReconnect(e){if(this.reconnectTimer||this.reconnectCircuitOpen||this.stopped)return;if(!(e instanceof b?e.retryable:!je(e))||this.reconnectAttempt>=Dt){this.reconnectCircuitOpen=true;return}let i=Lt(x$1(this.reconnectAttempt++,250,kt));this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.ensureConnected().catch(r=>this.scheduleReconnect(r));},i);}stopSocket(e=true){e&&this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.authRefreshTimer&&clearTimeout(this.authRefreshTimer),this.reconnectTimer=null,this.authRefreshTimer=null,this.rejectPendingAuthRefresh(new b("Coordination credential refresh was canceled.",true));let t=this.socket;this.socket=null,this.socketReady=false,t?.close(1e3,"coordination session stopped");}rejectPendingAuthRefresh(e){let t=this.pendingAuthRefresh;t&&(clearTimeout(t.timer),this.pendingAuthRefresh=null,t.reject(e));}rejectPendingAcks(e){for(let t of this.pendingAcks.values())clearTimeout(t.timer),t.reject(new Error(e));this.pendingAcks.clear();}unscopedId(e){let t=e.split("::");return t.length===2?t[1]:e}requireRoomConnection(e){let t=e.trim().toUpperCase(),i=this.roomConnections.get(t);if(!i)throw new Error(`Room ${t} is not joined through the coordination gateway.`);return i}async openFriendConnection(e){let t=this.friendConnections.get(e);if(t||(t=new n({...this.options,avenueOverride:{kind:"user",id:e}}),this.friendConnections.set(e,t)),!t.desiredPresence){if(!this.desiredPresence)throw new Error("Local coordination presence must start before friend discovery.");t.desiredPresence={...this.desiredPresence};}return await t.ensureConnected(),t}roomMember(e){return {nodeId:e.nodeId??e.deviceId,userId:e.userId??"",ticket:e.ticket,joinedAt:Number(e.createdAt??e.lastSeenAt??Date.now()),lastSeenAt:Number(e.lastSeenAt??Date.now()),expiresAt:typeof e.expiresAt=="number"?e.expiresAt:void 0}}};var ae=class{constructor(e){this.provider=e;this.cached=null;this.inFlight=null;this.refreshTimer=null;this.refreshRetryUsed=false;this.listeners=new Set;}async get(e=false){if(!this.provider)throw new Error("[OpenRTC] Native coordination requires coordinationGateway.nativeTrustTokenProvider; obtain tokens through a trusted backend without shipping the developer secret.");let t=Date.now();if(!e&&this.cached&&this.cached.expiresAtMs>t+3e4)return this.cached;if(this.inFlight)return this.inFlight;let i=(async()=>{let r=await this.provider(e),o=r?.token?.trim()??"",s=Number(r?.expiresAtMs),a=Date.now();if(!o||!Number.isFinite(s)||s<=a+3e4)throw new Error("[OpenRTC] Native trust token provider returned no usable short-lived token.");let d={token:o,expiresAtMs:s};return this.cached=d,this.refreshRetryUsed=false,this.notify(d),this.scheduleRefresh(d),d})();this.inFlight=i;try{return await i}finally{this.inFlight===i&&(this.inFlight=null);}}invalidate(){this.cached=null,this.clearRefreshTimer(),this.notify(null);}clear(){this.invalidate(),this.listeners.clear();}subscribe(e,t){return this.listeners.add(e),this.cached&&this.cached.expiresAtMs>Date.now()&&(t?.emitCurrent!==false&&e(this.cached),this.scheduleRefresh(this.cached)),()=>{this.listeners.delete(e),this.listeners.size===0&&this.clearRefreshTimer();}}notify(e){for(let t of this.listeners)t(e);}scheduleRefresh(e){if(this.clearRefreshTimer(),this.listeners.size===0)return;let t=Math.max(0,e.expiresAtMs-Date.now()-3e4);this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,this.get(true).catch(()=>{if(this.listeners.size===0||this.refreshRetryUsed){this.invalidate();return}this.refreshRetryUsed=true,this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,this.get(true).catch(()=>this.invalidate());},15e3);});},t);}clearRefreshTimer(){this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=null);}};function ce(n){if(!n)return null;let e=2166136261;for(let t=0;t<n.length;t+=1)e^=n.charCodeAt(t),e=Math.imul(e,16777619);return `fp-${(e>>>0).toString(16).padStart(8,"0")}`}var T=class T{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.durablePresenceRetryTimer=null;this.durablePresenceRetryAttempt=0;this.localExcludedPeers=new Set;}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(),r=`${e}::${i}`;this.startedAutoConnectKey===r&&this.browserAutoConnectUnsubscribe||(this.stopAutoConnect(),this.startedAutoConnectKey=r,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 t=this.normalizeDesiredPeers(e);this.desiredPeersByDeviceId=new Map(t.map(r=>[r.deviceId,r]));let i=JSON.stringify(t);i!==this.desiredPeerSignature&&(this.desiredPeerSignature=i,this.deps.onDesiredPeersChanged?.(),this.queuedDesiredPeers=t,this.flushDesiredPeerSubmission());}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 r=this.normalizeDesiredPeers(t),o=JSON.stringify(r),s=o!==this.desiredPeerSignature;this.desiredPeerSignature=o,this.desiredPeersByDeviceId=new Map(r.map(a=>[a.deviceId,a])),this.queuedDesiredPeers=null,this.desiredPeerRevision=Math.max(this.desiredPeerRevision,e),s&&this.deps.onDesiredPeersChanged?.(),await this.enqueueDesiredPeerSubmission(i,e,r);}resolveDesiredPeer(e,t){let i=typeof e=="string"?e.trim():"",r=typeof t=="string"?t.trim():"";if(i){let o=this.desiredPeersByDeviceId.get(i);if(o&&(!r||!o.nodeId||o.nodeId===r))return o}return r?Array.from(this.desiredPeersByDeviceId.values()).find(o=>o.nodeId===r)??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():[]})).filter(t=>t.deviceId.length>0).sort((t,i)=>t.deviceId.localeCompare(i.deviceId))}enqueueDesiredPeerSubmission(e,t,i){let r=this.desiredPeerSubmissionQueue.then(async()=>{if(this.startedAutoConnectKey!==e)return;let o=await this.deps.waitForWasmClient();if(this.startedAutoConnectKey===e){if(!o||typeof o.submit_browser_desired_peers!="function"){this.deps.warnMissingWasmOnce("submitBrowserDesiredPeers");return}await Promise.all(i.map(async s=>{if(s.ticket)try{await this.deps.rememberRouteRepairTokenFromTicket(s.ticket);}catch(a){console.warn("[WasmSignaling] failed to retain desired-peer admission token",{deviceId:s.deviceId,nodeId:s.nodeId,error:a});}})),await o.submit_browser_desired_peers(t,JSON.stringify(i));}});return this.desiredPeerSubmissionQueue=r.catch(o=>{console.warn("[WasmSignaling] failed to submit browser desired peers to Rust",{revision:t,error:o});}),r}async setAutoConnectExcluded(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 recordAutoConnectExcludedForPresence(e,t){let i=e.trim().toLowerCase();if(!i)return;t?this.localExcludedPeers.add(i):this.localExcludedPeers.delete(i);let r=this.deps.resolveWebLogicalDeviceId();r&&await this.deps.updateExcludedPeers(r,this.currentExcludedPeersSnapshot());}startPresenceLoop(e,t,i,r,o){if(this.deps.isTicketOnlyMode())return;this.stopPresenceLoop();let s=++this.presenceStartGeneration;this.presenceState={userId:e,localNodeId:t,ticket:r,metadata:o,deviceName:i};let a=this.deps.resolveWebLogicalDeviceId();(async()=>{let l=await this.deps.withWebPresenceMetadata(o,a);if(!(s===this.presenceStartGeneration&&this.presenceState!==null))return;let p=false,h=null,y=(v,S)=>{this.scheduleDurableRosterRetry(a,s,T.PRESENCE_LEASE_MS,v,S);};h=setTimeout(()=>{p||y("initial coordination presence write timed out");},T.INITIAL_PRESENCE_WRITE_TIMEOUT_MS),this.deps.updatePresence(t,r,true,T.PRESENCE_LEASE_MS,l,i).then(()=>{p=true,h&&(clearTimeout(h),h=null),this.clearDurablePresenceRetryTimer(),this.durablePresenceRetryAttempt=0;}).catch(v=>{h&&(clearTimeout(h),h=null),y("initial coordination presence write failed",v);});})();}clearDurablePresenceRetryTimer(){this.durablePresenceRetryTimer&&(clearTimeout(this.durablePresenceRetryTimer),this.durablePresenceRetryTimer=null);}scheduleDurableRosterRetry(e,t,i,r,o){if(t!==this.presenceStartGeneration||this.presenceState===null||this.durablePresenceRetryTimer||this.isPermanentProviderError(o))return;let s=this.durablePresenceRetryAttempt+1;if(s>T.PRESENCE_RETRY_LIMIT){console.warn(`[WasmBridge] ${r}; durable roster retry circuit opened after ${T.PRESENCE_RETRY_LIMIT} attempts`,o);return}this.durablePresenceRetryAttempt=s;let a=Math.min(T.PRESENCE_RETRY_MIN_DELAY_MS*2**Math.min(8,s-1),T.PRESENCE_RETRY_MAX_DELAY_MS),d=(s*17%21-10)/100,l=Math.max(T.PRESENCE_RETRY_MIN_DELAY_MS,Math.trunc(a+a*d));console.warn(`[WasmBridge] ${r}; retrying coordination presence in ${l}ms`,o),this.durablePresenceRetryTimer=setTimeout(()=>{this.durablePresenceRetryTimer=null,!(t!==this.presenceStartGeneration||this.presenceState===null)&&(async()=>{if(this.presenceState===null)return;let c=await this.deps.withWebPresenceMetadata(this.presenceState.metadata,e);t!==this.presenceStartGeneration||this.presenceState===null||await this.deps.updatePresence(this.presenceState.localNodeId,this.presenceState.ticket,true,i,c,this.presenceState.deviceName);})().then(()=>{this.durablePresenceRetryAttempt=0,this.clearDurablePresenceRetryTimer();}).catch(c=>{this.scheduleDurableRosterRetry(e,t,i,"durable roster registration retry failed",c);});},l);}isPermanentProviderError(e){let i=(e&&typeof e=="object"&&"code"in e?String(e.code??""):"").toLowerCase().replace(/^functions\//,"");return ["auth/invalid-user-token","auth/user-token-expired","auth/user-disabled","permission-denied","unauthenticated","invalid-argument","failed-precondition"].some(r=>i===r||i.endsWith(`/${r}`))}stopAutoConnect(){this.browserAutoConnectUnsubscribe?.(),this.browserAutoConnectUnsubscribe=null,this.startedAutoConnectKey=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.clearDurablePresenceRetryTimer(),this.durablePresenceRetryAttempt=0,this.presenceState=null;}};T.INITIAL_PRESENCE_WRITE_TIMEOUT_MS=5e3,T.PRESENCE_RETRY_MIN_DELAY_MS=2e3,T.PRESENCE_RETRY_MAX_DELAY_MS=6e4,T.PRESENCE_RETRY_LIMIT=8,T.PRESENCE_LEASE_MS=15*6e4;var de=T;var ue="trustedDevice",Wt="plutonium:e2ee:identity:v1",Gt="plutonium:e2ee:identity:session:v1",Ht="openrtc-trust",K="identity",$e="transport-trust:v1",Kt=1,P=null,Y=null;function M(n){let e=atob(n),t=new Uint8Array(e.length);for(let i=0;i<e.length;i+=1)t[i]=e.charCodeAt(i);return t}function X(n){let e="";for(let t=0;t<n.length;t+=1)e+=String.fromCharCode(n[t]);return btoa(e)}async function me(n){let e=await crypto.subtle.digest("SHA-256",n),t=new Uint8Array(e);return Array.from(t).map(i=>i.toString(16).padStart(2,"0")).join("")}function jt(){return typeof sessionStorage>"u"?null:sessionStorage}function zt(){if(!(typeof localStorage>"u"))try{localStorage.removeItem(Wt);}catch{}}var le=null;async function Xe(){return le||(le=(async()=>{let n=globalThis.crypto?.subtle;if(!n||typeof n.generateKey!="function")return false;try{let e=await n.generateKey({name:"Ed25519"},!1,["sign","verify"]);return !!(e&&e.privateKey&&e.publicKey)}catch{return false}})(),le)}async function qt(n){let e=await crypto.subtle.exportKey("raw",n);return new Uint8Array(e)}function Yt(){try{return typeof indexedDB<"u"?indexedDB:null}catch{return null}}function Ve(){let n=Yt();return n?new Promise(e=>{let t;try{t=n.open(Ht,1);}catch{e(null);return}t.onupgradeneeded=()=>{let i=t.result;i.objectStoreNames.contains(K)||i.createObjectStore(K);},t.onsuccess=()=>e(t.result),t.onerror=()=>e(null),t.onblocked=()=>e(null);}):Promise.resolve(null)}async function $t(){let n=await Ve();if(!n)return null;try{return await new Promise(e=>{let r=n.transaction(K,"readonly").objectStore(K).get($e);r.onsuccess=()=>{let o=r.result;e(o&&o.privateKey&&o.publicKey?o:null);},r.onerror=()=>e(null);})}catch{return null}finally{n.close();}}async function Xt(n){let e=await Ve();if(!e)return false;try{return await new Promise(t=>{let i=e.transaction(K,"readwrite");i.objectStore(K).put(n,$e),i.oncomplete=()=>t(!0),i.onerror=()=>t(!1),i.onabort=()=>t(!1);})}catch{return false}finally{e.close();}}async function Je(n,e){let t=await qt(n.publicKey),i=await me(t),r=n.privateKey;return {publicKey:t,fingerprint:i,backend:"webcrypto-nonextractable",durable:e,privateKey:r,async signChallenge(o){let s=await crypto.subtle.sign({name:"Ed25519"},r,M(o));return X(new Uint8Array(s))}}}function Vt(n,e,t){let i=n.secretKey;return {publicKey:n.publicKey,secretKey:i,fingerprint:e,backend:"tweetnacl",durable:t,async signChallenge(r){return Jt(r,i)}}}function Ln(n=32){let e=crypto.getRandomValues(new Uint8Array(n));return X(e)}function Jt(n,e){let t=$.sign.detached(M(n),e);return X(t)}function Qt(n,e,t){try{return $.sign.detached.verify(M(n),M(e),M(t))}catch{return false}}async function Bn(n,e,t){let i=globalThis.crypto?.subtle;if(i&&typeof i.importKey=="function"&&typeof i.verify=="function")try{let r=await i.importKey("raw",M(t),{name:"Ed25519"},!1,["verify"]);return await i.verify({name:"Ed25519"},r,M(e),M(n))}catch{}return Qt(n,e,t)}function Fn(n){return X(n)}function Un(n){if(!n||!n.trim())return null;try{let e=JSON.parse(n),t=e&&typeof e=="object"&&!Array.isArray(e)?e[ue]:null;if(!t||typeof t!="object"||Array.isArray(t))return null;let i=t,r=typeof i.version=="number"?i.version:null,o=typeof i.identityPublicKey=="string"?i.identityPublicKey:null,s=typeof i.identityFingerprint=="string"?i.identityFingerprint:null;return !r||!o||!s?null:{version:r,identityPublicKey:o,identityFingerprint:s}}catch{return null}}async function Zt(){let n=await on().catch(()=>null);return n?{version:Kt,identityPublicKey:X(n.publicKey),identityFingerprint:n.fingerprint}:null}async function ge(n){let e=await Zt();if(!e)return n??void 0;let t=typeof n=="string"?n.trim():"";if(!t)return JSON.stringify({[ue]:e});try{let i=JSON.parse(t);if(i&&typeof i=="object"&&!Array.isArray(i))return JSON.stringify({...i,[ue]:e})}catch{}return JSON.stringify({metadata:n,[ue]:e})}function en(){if(typeof window>"u")return null;let n=window.__TAURI_INTERNALS__;return !n||typeof n.invoke!="function"?null:n.invoke.bind(n)}async function tn(){if(typeof window>"u")return null;let n=en();if(!t()&&!n)return null;if(!n)throw new Error("[OpenRTC] Tauri transport trust requires the native signing provider, but Tauri invoke is unavailable.");try{let e=await n("openrtc_get_transport_trust_identity"),t=M(e.publicKeyBase64);if(t.byteLength!==$.sign.publicKeyLength)throw new Error("native transport trust public key has an invalid length");let i=await me(t);if(e.fingerprint!==i)throw new Error("native transport trust fingerprint does not match its public key");return {publicKey:t,fingerprint:i,backend:"native-provider",durable:!0,async signChallenge(r){return n("openrtc_sign_transport_trust_challenge",{challenge:r})}}}catch(e){let t=new Error("[OpenRTC] native transport trust provider failed; refusing WebCrypto fallback in Tauri.");throw t.cause=e,t}}function nn(){let n=jt();n&&n.removeItem(Gt);}async function rn(){if(zt(),nn(),P)return P;let n=await tn();if(n)return P=n,P;if(await Xe()){let e=await $t();if(e)return P=await Je(e,true),P}return null}async function on(n={}){let e=await rn();if(e)return e;if(Y)return Y;let t=sn(n);Y=t;try{return await t}finally{Y===t&&(Y=null);}}async function sn(n){if(P)return P;let e=n.ephemeral===true;if(await Xe())try{let t=await crypto.subtle.generateKey({name:"Ed25519"},!1,["sign","verify"]),i=!1;return e||(i=await Xt(t)),P=await Je(t,i),P}catch{}if(!e)return console.warn("[OpenRTC][TRUST] Managed transport trust requires WebCrypto Ed25519 or native keychain; refusing extractable fallback storage"),null;try{let t=$.sign.keyPair(),i=await me(v(t.publicKey));return P=Vt(t,i,!1),P}catch{return null}}function Qe(n){if(n.errorCode)return n;let e=n.error||n.readinessReason;if(!e)return n;let t=Fe(e);return {...n,errorCode:t.errorCode,retryable:t.retryable,errorPlane:t.errorPlane}}function j(n){return !n||typeof n!="object"?{}:n instanceof Map?Object.fromEntries(n):n}function ye(n){let e=j(n),t=j(e.device);if(!Object.keys(t).length)return e;let i={...t,...e};return delete i.device,i}function u(n,...e){for(let t of e){let i=n[t];if(typeof i=="string"&&i.trim().length>0)return i}}function x(n,...e){for(let t of e){let i=n[t];if(typeof i=="boolean")return i}}function m(n,...e){for(let t of e){let i=n[t];if(typeof i=="number"&&Number.isFinite(i))return i}}function L(n){if(typeof n=="number"&&Number.isFinite(n))return n;if(n instanceof Date){let e=n.getTime();return Number.isFinite(e)?e:void 0}if(typeof n=="string"){let e=Date.parse(n);return Number.isFinite(e)?e:void 0}if(n&&typeof n=="object"){let e=n;if(typeof e.toMillis=="function"){let i=e.toMillis();return Number.isFinite(i)?i:void 0}let t=typeof e.seconds=="number"?e.seconds:typeof e._seconds=="number"?e._seconds:void 0;if(t!==void 0&&Number.isFinite(t)){let i=typeof e.nanoseconds=="number"?e.nanoseconds:typeof e._nanoseconds=="number"?e._nanoseconds:0;return t*1e3+Math.floor((Number.isFinite(i)?i:0)/1e6)}}}function ve(...n){let e=n.map(L).filter(t=>typeof t=="number"&&Number.isFinite(t));return e.length?Math.max(...e):void 0}function be(n){if(typeof n!="string")return;let e=n.trim().toLowerCase();return e==="online"||e==="idle"||e==="offline"?e:void 0}function Ze(n){let e=be("presenceStatus"in n?n.presenceStatus:void 0),t="presenceUpdatedAt"in n?L(n.presenceUpdatedAt):void 0,i="presenceExpiresAt"in n?L(n.presenceExpiresAt):void 0,r=t??ve(n.lastSeenAt,n.updatedAt,n.createdAt),o=i??L(n.expiresAt),s=e;s||(n.online?r!==void 0&&r+3e5<=Date.now()?s="idle":s="online":s="offline");let a=typeof n.ticket=="string"?n.ticket.trim():"",d="connectable"in n&&typeof n.connectable=="boolean"?n.connectable:s==="online"&&a.length>0;return {presenceStatus:s,presenceUpdatedAt:r,presenceExpiresAt:o,connectable:d}}function et(n){return b$2(n)}function z(n,...e){return et(u(n,...e))}function J(n){if(!Array.isArray(n))return;let e=Array.from(new Set(n.map(et).filter(t=>!!t)));return e.length?e:void 0}function tt(n){let e=j(n),t={webrtc:m(e,"webrtc"),webrtcLan:m(e,"webrtcLan","webrtc_lan"),webrtcTurn:m(e,"webrtcTurn","webrtc_turn"),iroh:m(e,"iroh"),irohLan:m(e,"irohLan","iroh_lan"),irohRelay:m(e,"irohRelay","iroh_relay"),ble:m(e,"ble"),moq:m(e,"moq")};return Object.values(t).some(i=>i!==void 0)?t:void 0}function nt(n){return (n.discoveryMode??"space")==="space"&&typeof n.apiKey=="string"&&n.apiKey.trim().length>0&&typeof n.spaceKey=="string"&&n.spaceKey.trim().length>0}function it(n,e,t){return t?true:(typeof n.appTag=="string"?n.appTag:typeof n.tag=="string"?n.tag:void 0)===e}function Se(n,e){let t=ye(n),i=u(t,"deviceId","device_id")||e||"",r=u(t,"nodeId","node_id")||"",o=u(t,"ticket")||"";return {deviceId:i,deviceName:u(t,"deviceName","device_name")||"Unknown Device",online:!!t.online,ticket:o,friendTicket:u(t,"friendTicket","friend_ticket"),presenceStatus:be(u(t,"presenceStatus","presence_status","livenessStatus","liveness_status")),presenceUpdatedAt:m(t,"presenceUpdatedAt","presence_updated_at")??ve(t.presenceUpdatedAt,t.presence_updated_at,t.lastSeenAt,t.last_seen_at,t.updatedAt,t.updated_at,t.createdAt,t.created_at),presenceExpiresAt:m(t,"presenceExpiresAt","presence_expires_at")??L(t.presenceExpiresAt??t.presence_expires_at)??L(t.expiresAt??t.expires_at),connectable:x(t,"connectable"),kind:u(t,"kind"),nodeId:r||void 0,platformType:u(t,"platformType","platform_type"),capabilities:t.capabilities||void 0,sessionId:u(t,"sessionId","session_id"),userId:u(t,"userId","user_id"),lastSeenAt:t.lastSeenAt??t.last_seen_at,expiresAt:t.expiresAt??t.expires_at,createdAt:t.createdAt??t.created_at,updatedAt:t.updatedAt??t.updated_at,metadata:u(t,"metadata"),excludedPeers:we(t.excludedPeers??t.excluded_peers),availableTransports:J(t.availableTransports??t.available_transports),transports:J(t.transports)}}function we(n){return Array.isArray(n)?n.filter(e=>typeof e=="string"):[]}function an(n){let e=Ze(n);return {...n,...e,connectionStatus:"connectionStatus"in n&&typeof n.connectionStatus=="string"?n.connectionStatus:n.online?"online":"disconnected",settledReady:"settledReady"in n&&typeof n.settledReady=="boolean"?n.settledReady:false,readinessState:"readinessState"in n&&typeof n.readinessState=="string"?n.readinessState:void 0,readinessReason:"readinessReason"in n&&typeof n.readinessReason=="string"?n.readinessReason:void 0,peerHealth:"peerHealth"in n&&typeof n.peerHealth=="string"?n.peerHealth:"unknown",peerId:"peerId"in n&&typeof n.peerId=="string"?n.peerId:void 0,promotionEligible:"promotionEligible"in n&&typeof n.promotionEligible=="boolean"?n.promotionEligible:true,scopes:"scopes"in n?we(n.scopes):[],connectionId:"connectionId"in n&&typeof n.connectionId=="string"?n.connectionId:void 0,deviceIdHint:"deviceIdHint"in n&&typeof n.deviceIdHint=="string"?n.deviceIdHint:void 0,activeTransportStableId:"activeTransportStableId"in n&&typeof n.activeTransportStableId=="number"?n.activeTransportStableId:"activeTransportStableId"in n?n.activeTransportStableId??null:void 0,transportGeneration:"transportGeneration"in n&&typeof n.transportGeneration=="number"?n.transportGeneration:void 0,routeGeneration:"routeGeneration"in n&&typeof n.routeGeneration=="number"?n.routeGeneration:void 0,activeTransport:"activeTransport"in n?n.activeTransport:void 0,parallelTransport:"parallelTransport"in n?n.parallelTransport:void 0,availableTransports:"availableTransports"in n?J(n.availableTransports):"transports"in n?J(n.transports):void 0,latencyMs:"latencyMs"in n&&typeof n.latencyMs=="number"?n.latencyMs:void 0,latencyByTransport:"latencyByTransport"in n?tt(n.latencyByTransport):void 0}}function V(n,e){return e===void 0?true:e===null?n==null:n==null||n===e}function rt(n,e){let t=V(n.connectionId,e.connectionId)&&V(n.nodeId,e.nodeId)&&V(n.activeTransportStableId,e.activeTransportStableId)&&V(n.transportGeneration,e.transportGeneration)&&V(n.routeGeneration,e.routeGeneration),i=(r,o)=>r!==void 0?r:t?o:void 0;return {inheritsSnapshot:t,fields:{connectionId:i(e.connectionId??void 0,n.connectionId),activeTransportStableId:i(e.activeTransportStableId,n.activeTransportStableId),transportGeneration:i(e.transportGeneration,n.transportGeneration),routeGeneration:i(e.routeGeneration,n.routeGeneration),activeTransport:i(e.activeTransport,n.activeTransport),parallelTransport:i(e.parallelTransport,n.parallelTransport),latencyMs:t?n.latencyMs:void 0,latencyByTransport:t?n.latencyByTransport:void 0}}}var cn={connectionId:void 0,activeTransportStableId:null,transportGeneration:void 0,routeGeneration:void 0,activeTransport:void 0,parallelTransport:void 0,latencyMs:void 0,latencyByTransport:void 0};function dn(n,e,t){let i=rt(n,{connectionId:e.activeConnectionId,nodeId:e.nodeId,activeTransportStableId:e.activeTransportStableId,transportGeneration:e.transportGeneration,routeGeneration:e.routeGeneration,activeTransport:e.activeTransport,parallelTransport:e.parallelTransport}),r=t?t({connectionId:e.activeConnectionId??void 0,deviceId:e.deviceId??void 0,deviceIdHint:e.deviceIdHint??void 0,nodeId:e.nodeId??void 0}):n.promotionEligible??true;if(!r)return {...n,peerHealth:e.health??n.peerHealth,peerId:e.peerId??n.peerId,promotionEligible:r,scopes:e.scopes?.length?[...e.scopes]:n.scopes,nodeId:e.nodeId===void 0?n.nodeId:e.nodeId??void 0,deviceIdHint:e.deviceIdHint??n.deviceIdHint,...i.fields,readinessReason:e.readinessReason??n.readinessReason};let o=e.status??n.connectionStatus,s=typeof o=="string"?o.trim().toLowerCase():"",a=s==="failed"||s==="closed"||s==="disconnected",l=typeof e.readinessState=="string"&&e.readinessState.trim().length>0?e.readinessState==="routable":e.settledReady===true,c=n.settledReady===true||n.readinessState==="routable";if(i.inheritsSnapshot&&c&&!a&&!l)return {...n,peerHealth:e.health??n.peerHealth,peerId:e.peerId??n.peerId,promotionEligible:r,scopes:e.scopes?.length?[...e.scopes]:n.scopes,nodeId:e.nodeId===void 0?n.nodeId:e.nodeId??void 0,deviceIdHint:e.deviceIdHint??n.deviceIdHint,...i.fields,readinessReason:e.readinessReason??n.readinessReason};let p=a?false:l,h=l&&!a&&(s==="connecting"||s==="connected")?"connected":o,y=l?"routable":e.readinessState??(i.inheritsSnapshot?n.readinessState:void 0),v=p?e.readinessReason??"peer-session-settled":e.readinessReason??(i.inheritsSnapshot?n.readinessReason:void 0);return {...n,connectionStatus:h,settledReady:p,readinessState:y,readinessReason:v,peerHealth:e.health??n.peerHealth,peerId:e.peerId??n.peerId,promotionEligible:r,scopes:e.scopes?.length?[...e.scopes]:n.scopes,nodeId:e.nodeId===void 0?n.nodeId:e.nodeId??void 0,deviceIdHint:e.deviceIdHint??n.deviceIdHint,...i.fields}}function ln(n,e){let t=rt(n,{connectionId:e.connectionId,nodeId:e.nodeId,activeTransportStableId:e.activeTransportStableId,transportGeneration:e.transportGeneration,routeGeneration:e.routeGeneration,activeTransport:e.activeTransport,parallelTransport:e.parallelTransport});if(e.promotionEligible===false)return {...n,peerHealth:e.health??n.peerHealth,peerId:e.peerId??n.peerId,promotionEligible:false,nodeId:e.nodeId??n.nodeId,deviceIdHint:e.deviceIdHint??n.deviceIdHint,...t.fields,scopes:e.scopes?.length?[...e.scopes]:n.scopes};let i=e.status??n.connectionStatus,r=typeof i=="string"?i.trim().toLowerCase():"",o=r==="failed"||r==="closed"||r==="disconnected",s=n.settledReady===true||n.readinessState==="routable",a=e.routable===false;if(t.inheritsSnapshot&&s&&o&&!a)return {...n,peerHealth:n.peerHealth??e.health,peerId:n.peerId??e.peerId,promotionEligible:e.promotionEligible??n.promotionEligible??true,connectionId:n.connectionId??e.connectionId,deviceIdHint:n.deviceIdHint??e.deviceIdHint,scopes:n.scopes?.length?n.scopes:e.scopes??n.scopes};if(s&&o)return {...n,connectionStatus:i,settledReady:false,readinessState:void 0,readinessReason:e.error??n.readinessReason,peerHealth:e.health??n.peerHealth,peerId:e.peerId??n.peerId,promotionEligible:e.promotionEligible??n.promotionEligible??true,deviceIdHint:e.deviceIdHint??n.deviceIdHint,...cn,scopes:e.scopes?.length?[...e.scopes]:n.scopes};let d=e.routable===true||e.protocolState==="routable";if(t.inheritsSnapshot&&s&&!o&&!d)return {...n,peerHealth:n.peerHealth??e.health,peerId:n.peerId??e.peerId,promotionEligible:e.promotionEligible??n.promotionEligible??true,connectionId:n.connectionId??e.connectionId,deviceIdHint:n.deviceIdHint??e.deviceIdHint,activeTransportStableId:n.activeTransportStableId??e.activeTransportStableId,transportGeneration:n.transportGeneration??e.transportGeneration,routeGeneration:n.routeGeneration??e.routeGeneration,activeTransport:n.activeTransport??e.activeTransport,parallelTransport:n.parallelTransport===void 0?e.parallelTransport:n.parallelTransport,scopes:n.scopes?.length?n.scopes:e.scopes??n.scopes};let l=e.transportState==="connected"&&e.health==="healthy",c=o?false:d,p=!o&&(d||l)&&(r==="connecting"||r==="connected"||e.transportState==="connected")?"connected":i,h=c?"routable":(e.routable===false&&e.protocolState?e.protocolState:void 0)??(t.inheritsSnapshot?n.readinessState:void 0)??(e.status==="connecting"?e.transportState==="connected"?"transport-only":"connecting":void 0),y=c?(t.inheritsSnapshot?n.readinessReason:void 0)??(e.routable===true?"peer-projection-routable":void 0):(e.routable===false&&e.error?e.error:void 0)??(t.inheritsSnapshot?n.readinessReason:void 0)??(e.status==="connecting"?e.transportState==="connected"?"peer-projection-transport-ready":"peer-projection-connecting":void 0);return {...n,connectionStatus:p,settledReady:c,readinessState:h,readinessReason:y,peerHealth:e.health??n.peerHealth,peerId:e.peerId??n.peerId,promotionEligible:e.promotionEligible??n.promotionEligible??true,nodeId:e.nodeId??n.nodeId,deviceIdHint:e.deviceIdHint??n.deviceIdHint,...t.fields,scopes:e.scopes?.length?[...e.scopes]:n.scopes}}function un(n){let{device:e,session:t=null,peer:i=null,isPromotionEligible:r}=n,o=an(e);return t&&(o=dn(o,t,r)),i&&(o=ln(o,i)),Qe(o)}function ot(n){let e=ye(n),t=Se(e),i=be(u(e,"presenceStatus","presence_status","livenessStatus","liveness_status")),r=Ze({...t,...i?{presenceStatus:i}:{},presenceUpdatedAt:m(e,"presenceUpdatedAt","presence_updated_at")??ve(e.presenceUpdatedAt,e.presence_updated_at,e.lastSeenAt,e.last_seen_at,e.updatedAt,e.updated_at,e.createdAt,e.created_at),presenceExpiresAt:m(e,"presenceExpiresAt","presence_expires_at")??L(e.presenceExpiresAt??e.presence_expires_at)??L(e.expiresAt??e.expires_at),connectable:x(e,"connectable")}),o={...t,...r,connectionStatus:u(e,"connectionStatus","connection_status")||"disconnected",settledReady:x(e,"settledReady","settled_ready")??false,readinessState:u(e,"readinessState","readiness_state")??void 0,readinessReason:u(e,"readinessReason","readiness_reason")??void 0,peerHealth:u(e,"peerHealth","peer_health")||"unknown",peerId:u(e,"peerId","peer_id"),scopes:we(e.scopes),connectionId:u(e,"connectionId","connection_id"),deviceIdHint:u(e,"deviceIdHint","device_id_hint"),activeTransportStableId:m(e,"activeTransportStableId","active_transport_stable_id")??void 0,transportGeneration:m(e,"transportGeneration","transport_generation")??void 0,routeGeneration:m(e,"routeGeneration","route_generation")??void 0,activeTransport:z(e,"activeTransport","active_transport"),parallelTransport:z(e,"parallelTransport","parallel_transport")??null,availableTransports:J(e.availableTransports??e.available_transports),latencyMs:m(e,"latencyMs","latency_ms"),latencyByTransport:tt(e.latencyByTransport??e.latency_by_transport)};return un({device:o})}function st(n){let e=ye(n);return Qe({peerId:u(e,"peerId","peer_id")||"",deviceId:u(e,"deviceId","device_id"),deviceIdHint:u(e,"deviceIdHint","device_id_hint"),nodeId:u(e,"nodeId","node_id"),activeConnectionId:u(e,"activeConnectionId","active_connection_id"),candidateConnectionIds:Array.isArray(e.candidateConnectionIds)?e.candidateConnectionIds.filter(t=>typeof t=="string"):Array.isArray(e.candidate_connection_ids)?e.candidate_connection_ids.filter(t=>typeof t=="string"):[],status:u(e,"status")||"disconnected",health:u(e,"health")||"unknown",settledReady:x(e,"settledReady","settled_ready")??false,readinessState:u(e,"readinessState","readiness_state")??void 0,activeTransportStableId:m(e,"activeTransportStableId","active_transport_stable_id")??void 0,transportGeneration:m(e,"transportGeneration","transport_generation")??void 0,routeGeneration:m(e,"routeGeneration","route_generation")??void 0,activeTransport:z(e,"activeTransport","active_transport"),parallelTransport:z(e,"parallelTransport","parallel_transport")??null,replacementPending:x(e,"replacementPending","replacement_pending")??void 0,lastLifecycleTransitionAtMs:m(e,"lastLifecycleTransitionAtMs","last_lifecycle_transition_at_ms")??void 0,readinessReason:u(e,"readinessReason","readiness_reason")??void 0,transitionCount:m(e,"transitionCount","transition_count")??void 0,connectingTransitionCount:m(e,"connectingTransitionCount","connecting_transition_count")??void 0,replacementCount:m(e,"replacementCount","replacement_count")??void 0,retireCount:m(e,"retireCount","retire_count")??void 0,lastDisconnectReason:u(e,"lastDisconnectReason","last_disconnect_reason")??void 0,lastReconnectReason:u(e,"lastReconnectReason","last_reconnect_reason")??void 0,scopes:Array.isArray(e.scopes)?e.scopes.filter(t=>typeof t=="string"):[],lastSeenAtMs:typeof e.lastSeenAtMs=="number"?e.lastSeenAtMs:typeof e.last_seen_at_ms=="number"?e.last_seen_at_ms:0,error:u(e,"error"),errorCode:u(e,"errorCode","error_code")??void 0,retryable:x(e,"retryable")??void 0,errorPlane:u(e,"errorPlane","error_plane")??void 0})}function jn(n){let e=j(n);return {connectionId:typeof e.connectionId=="string"?e.connectionId:"",nodeId:typeof e.nodeId=="string"?e.nodeId:null,deviceId:typeof e.deviceId=="string"?e.deviceId:null,deviceIdHint:typeof e.deviceIdHint=="string"?e.deviceIdHint:null,endpointId:typeof e.endpointId=="string"?e.endpointId:null,transportGeneration:typeof e.transportGeneration=="number"?e.transportGeneration:0,routeGeneration:typeof e.routeGeneration=="number"?e.routeGeneration:void 0,transportStableId:typeof e.transportStableId=="number"?e.transportStableId:null,transportSource:typeof e.transportSource=="string"?e.transportSource:null,lastTransportChangeAtMs:typeof e.lastTransportChangeAtMs=="number"?e.lastTransportChangeAtMs:0,lastRouteChangeAtMs:typeof e.lastRouteChangeAtMs=="number"?e.lastRouteChangeAtMs:void 0,state:typeof e.state=="string"?e.state:"pending",statusReason:typeof e.statusReason=="string"?e.statusReason:null,transitionCount:typeof e.transitionCount=="number"?e.transitionCount:void 0,connectingTransitionCount:typeof e.connectingTransitionCount=="number"?e.connectingTransitionCount:void 0,replacementCount:typeof e.replacementCount=="number"?e.replacementCount:void 0,retireCount:typeof e.retireCount=="number"?e.retireCount:void 0,lastDisconnectReason:typeof e.lastDisconnectReason=="string"?e.lastDisconnectReason:void 0,lastReconnectReason:typeof e.lastReconnectReason=="string"?e.lastReconnectReason:void 0,createdAtMs:typeof e.createdAtMs=="number"?e.createdAtMs:0,updatedAtMs:typeof e.updatedAtMs=="number"?e.updatedAtMs:0}}function zn(n){let e=j(n);return {peerId:typeof e.peerId=="string"?e.peerId:null,deviceId:typeof e.deviceId=="string"?e.deviceId:null,deviceIdHint:typeof e.deviceIdHint=="string"?e.deviceIdHint:null,nodeId:typeof e.nodeId=="string"?e.nodeId:null}}function pn(n){switch(n){case "connected":return "connected";case "connecting":return "connecting";case "failed":return "failed";default:return "closed"}}function at(n){let e=n.activeConnectionId||n.candidateConnectionIds[0]||null;if(!e)return null;let t=pn(n.status),i=t==="connected"?"connected":t==="connecting"?"connecting":"closed",r=t==="connected"?n.settledReady?"routable":"transport-only":t==="connecting"?"connecting":"closed";return {connectionId:e,deviceId:n.deviceId??null,deviceIdHint:n.deviceIdHint??null,remoteNodeId:n.nodeId??null,state:t,transportState:i,protocolState:r,routable:!!n.settledReady,readinessState:n.readinessState,readinessReason:n.readinessReason,transportGeneration:n.transportGeneration,routeGeneration:n.routeGeneration,activeTransportStableId:n.activeTransportStableId,activeTransport:n.activeTransport,parallelTransport:n.parallelTransport??null,replacementInProgress:n.replacementPending,lastLifecycleTransitionAtMs:n.lastLifecycleTransitionAtMs,transitionCount:n.transitionCount,connectingTransitionCount:n.connectingTransitionCount,replacementCount:n.replacementCount,retireCount:n.retireCount,lastDisconnectReason:n.lastDisconnectReason??void 0,lastReconnectReason:n.lastReconnectReason??void 0,updatedAt:n.lastSeenAtMs,error:n.error??void 0}}function ct(n){let e=j(n),t=u(e,"connectionId","connection_id");if(!t)return null;let i=u(e,"state")||"connecting",r=m(e,"createdAt","created_at")??m(e,"updatedAt","updated_at")??Date.now(),o=m(e,"updatedAt","updated_at")??r;return {connectionId:t,deviceId:u(e,"deviceId","device_id"),deviceIdHint:u(e,"deviceIdHint","device_id_hint"),remoteNodeId:u(e,"remoteNodeId","remote_node_id"),state:i,transportState:u(e,"transportState","transport_state")??(i==="connected"?"connected":i==="connecting"?"connecting":"closed"),protocolState:u(e,"protocolState","protocol_state")??(i==="connected"?"routable":i==="connecting"?"connecting":"closed"),routable:x(e,"routable")??false,readinessState:u(e,"readinessState","readiness_state")??void 0,readinessReason:u(e,"readinessReason","readiness_reason")??void 0,transportGeneration:m(e,"transportGeneration","transport_generation")??void 0,routeGeneration:m(e,"routeGeneration","route_generation")??void 0,activeTransportStableId:m(e,"activeTransportStableId","active_transport_stable_id")??void 0,activeTransport:z(e,"activeTransport","active_transport"),parallelTransport:z(e,"parallelTransport","parallel_transport")??null,replacementInProgress:x(e,"replacementInProgress","replacement_in_progress")??void 0,lastLifecycleTransitionAtMs:m(e,"lastLifecycleTransitionAtMs","last_lifecycle_transition_at_ms")??void 0,transitionCount:m(e,"transitionCount","transition_count")??void 0,connectingTransitionCount:m(e,"connectingTransitionCount","connecting_transition_count")??void 0,replacementCount:m(e,"replacementCount","replacement_count")??void 0,retireCount:m(e,"retireCount","retire_count")??void 0,lastDisconnectReason:u(e,"lastDisconnectReason","last_disconnect_reason")??void 0,lastReconnectReason:u(e,"lastReconnectReason","last_reconnect_reason")??void 0,error:u(e,"error")??void 0,createdAt:r,updatedAt:o}}function dt(n,e){return n?n.connectionId===e.connectionId&&(n.deviceId??null)===(e.deviceId??null)&&(n.deviceIdHint??null)===(e.deviceIdHint??null)&&(n.remoteNodeId??null)===(e.remoteNodeId??null)&&n.state===e.state&&(n.transportState??null)===(e.transportState??null)&&(n.protocolState??null)===(e.protocolState??null)&&!!n.routable==!!e.routable&&(n.activeTransport??null)===(e.activeTransport??null)&&(n.parallelTransport??null)===(e.parallelTransport??null)&&(n.activeTransportStableId??null)===(e.activeTransportStableId??null)&&(n.transportGeneration??null)===(e.transportGeneration??null)&&(n.routeGeneration??null)===(e.routeGeneration??null)&&!!n.replacementInProgress==!!e.replacementInProgress&&(n.transitionCount??null)===(e.transitionCount??null)&&(n.connectingTransitionCount??null)===(e.connectingTransitionCount??null)&&(n.replacementCount??null)===(e.replacementCount??null)&&(n.retireCount??null)===(e.retireCount??null)&&(n.lastDisconnectReason??null)===(e.lastDisconnectReason??null)&&(n.lastReconnectReason??null)===(e.lastReconnectReason??null)&&(n.error??null)===(e.error??null):false}function hn(n){try{let e=n.replace(/-/g,"+").replace(/_/g,"/"),t=(4-e.length%4)%4,i=e+"=".repeat(t);if(typeof atob=="function")return JSON.parse(atob(i));let r=globalThis.Buffer;if(r)return JSON.parse(r.from(i,"base64").toString("utf8"))}catch{return null}return null}function fn(n){let e=typeof n=="string"?n.trim():"";if(!e)return {present:false};let t=e.lastIndexOf("."),i=t>=0?e.slice(0,t):e,r=t>=0?e.slice(t+1):null,o=r?hn(r):null,s=o&&typeof o.t=="string"&&o.t.trim().length>0?o.t.trim():null,a=o&&typeof o.s=="string"&&o.s.trim().length>0?o.s.trim():null,d=o&&typeof o.m=="number"&&Number.isFinite(o.m)?o.m:null;return {present:true,irohFingerprint:ce(i),tokenFingerprint:ce(s),tokenSuffixFingerprint:ce(r),scope:a,maxConnections:d}}function Q(n,e,t={}){let i=typeof n.finishSend=="function"?n.finishSend.bind(n):typeof n.finish_send=="function"?n.finish_send.bind(n):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 r=e.getWriter();return new WritableStream({write:o=>r.write(o),async close(){await r.close(),await i();},abort:o=>r.abort(o)})}var g=class g{constructor(e){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.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.applicationRouteEscalationUnsubscribe=null;this.applicationRouteEscalationSubscriptionGeneration=-1;this.applicationRouteEscalationSubscriptionEpoch=0;if(this.appTag=b$1(e),this.options={...e,appTag:this.appTag,authMode:c(e),projectId:d(e)},this.nativeTrustTokens=this.options.coordinationGateway?new ae(this.options.coordinationGateway.nativeTrustTokenProvider):null,this.presenceManager=new de({isTicketOnlyMode:()=>this.isTicketOnlyMode(),waitForWasmClient:(i,r)=>this.waitForWasmClient(i,r),warnMissingWasmOnce:i=>this.warnMissingWasmOnce(i),resolveWebLogicalDeviceId:()=>this.resolveWebLogicalDeviceId(),withWebPresenceMetadata:(i,r)=>this.withWebPresenceMetadata(i,r),updatePresence:(i,r,o,s,a,d)=>this.updatePresence(i,r,o,s,a,d),updateExcludedPeers:(i,r)=>this.getCoordinationSignaling().updateDevice(i,{excludedPeers:r}),getCoordinationSignaling:()=>this.getCoordinationSignaling(),rememberRouteRepairTokenFromTicket:i=>this.coreClient?.rememberRouteRepairTokenFromTicket?.(i)??Promise.resolve(false),onDesiredPeersChanged:()=>this.retryManagedApplicationRouteEscalations()}),this.persistenceReady=Promise.resolve(),this.isTicketOnlyMode()){this.app=null,this.auth=null;return}let t=G$1();this.app=t.getApp(),this.auth=t.getAuth(),t.onAuthStateChanged(i=>{if(this.authContext)return;if(this.isSpaceMode()){this.authListeners.forEach(s=>s(this.toRuntimeIdentity(i)));return}let r=i?.uid??null,o=this.lastObservedFirebaseUserId;this.lastObservedFirebaseUserId=r,o&&o!==r&&this.stopAuthScopedActivity({userId:o}),this.browserCoordinationSignaling?.handleScopeChange(),this.authListeners.forEach(s=>s(this.toRuntimeIdentity(i)));});}get tag(){return this.appTag}getRuntimeCapabilities(){return re()}getDeviceIdentityStorageKey(){let e$1=e(this.options);return `${g.WEB_DEVICE_ID_STORAGE_PREFIX}_${e$1}`}getDeviceIdPersistenceMode(){return this.options.deviceIdPersistence??this.options.nodeIdPersistence??"persistent"}isTicketOnlyMode(){return this.options.signalingMode==="ticket-only"}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(),r=Date.now(),o=null;try{let c=localStorage.getItem(i);o=c?JSON.parse(c):null;}catch{o=null;}let s=typeof o?.deviceId=="string"?o.deviceId.trim():"",a=typeof o?.expiresAt=="number"?o.expiresAt:void 0;if(t==="persistent"){let c=s||this.createRandomDeviceId();return localStorage.setItem(i,JSON.stringify({deviceId:c})),c}if(s&&typeof a=="number"&&a>r){let c=r+g.EPHEMERAL_DEVICE_ID_TTL_MS;return localStorage.setItem(i,JSON.stringify({deviceId:s,expiresAt:c})),s}let d=this.createRandomDeviceId(),l=r+g.EPHEMERAL_DEVICE_ID_TTL_MS;return localStorage.setItem(i,JSON.stringify({deviceId:d,expiresAt:l})),d}getDefaultBrowserDeviceName(){return this.options.deviceName?.trim()||(this.options.storagePrefix?`Web (${this.options.storagePrefix.replace(/_$/,"")})`:"Web Browser")}getCoordinationSignaling(){if(this.isTicketOnlyMode())throw new Error('[openrtc] Browser signaling is disabled when signalingMode="ticket-only".');if(!this.options.coordinationGateway)throw new Error("[OpenRTC] Managed coordination requires coordinationGateway; the legacy direct Firebase data plane has been removed.");return this.browserCoordinationSignaling||(this.browserCoordinationSignaling=new se({projectId:this.options.projectId,gateway:this.options.coordinationGateway,appTag:this.appTag,discoveryMode:this.options.discoveryMode,resolveSpaceNamespaceId:()=>this.ensureSpaceNamespaceIdPromise(),getCurrentUserId:()=>this.getCurrentUserId(),getAuthToken:async(e=false)=>{let t=this.currentUser;return t?.getToken?t.getToken(e):null},getAppCheckToken:async(e=false)=>{let t=this.authContext?.appCheckTokenProvider??this.options.platformAttestationTokenProvider;return t?t(e):G$1().getAppCheckToken(e)},getLocalDeviceId:()=>this.resolveWebLogicalDeviceId(),getDefaultDeviceName:()=>this.getDefaultBrowserDeviceName(),getPlatformType:()=>this.options.coordinationPlatformType??"web",normalizeDevice:(e,t)=>this.normalizeDevice(e,t),nativeTrustTokens:this.nativeTrustTokens})),this.browserCoordinationSignaling}usesCoordinationGateway(){return !!this.options.coordinationGateway}async reconnectCoordinationAfterHostResume(){await this.browserCoordinationSignaling?.reconnectAfterHostResume?.();}async getCoordinationNativeTrustToken(e=false){if(!this.nativeTrustTokens)throw new Error("[OpenRTC] Native trust tokens require a coordination gateway.");return this.nativeTrustTokens.get(e)}invalidateCoordinationNativeTrustToken(){this.nativeTrustTokens?.invalidate();}subscribeCoordinationNativeTrustToken(e,t){return this.nativeTrustTokens?this.nativeTrustTokens.subscribe(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 r=this.getCoordinationSignaling();if(!r.joinCoordinationRoom)throw new Error("The active coordination provider does not support rooms.");await r.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 r=JSON.parse(e);if(r&&typeof r=="object"&&!Array.isArray(r))return i=JSON.stringify({...r,deviceId:t}),await ge(i)??i}catch{}i=JSON.stringify({deviceId:t,metadata:e});}return await ge(i)??i}async setAuthContext(e){let t$1=this.injectedBrowserAuthSessionActive;if(this.authContext=e,!this.isTicketOnlyMode()&&e?.customToken?.trim()&&!(t()&&this.options.authMode==="external"&&typeof e.tokenProvider=="function"))try{await this.ensureBrowserPlatformAuth(e.userId,e.customToken.trim());}catch(i){console.warn("[WasmBridge] ensureBrowserPlatformAuth failed (non-fatal):",i);}else if(!this.isTicketOnlyMode()&&!e&&t$1)try{await this.auth?.signOut();}catch(i){console.warn("[WasmBridge] Failed to clear injected browser auth session:",i);}finally{this.injectedBrowserAuthSessionActive=false;}this.syncWasmAuthToken(),this.isTicketOnlyMode()||await this.browserCoordinationSignaling?.handleScopeChange(),this.authListeners.forEach(i=>i(this.currentUser));}async ensureBrowserPlatformAuth(e,t){if((this.auth?.currentUser?.uid??null)===e){this.injectedBrowserAuthSessionActive=true;return}await G$1().signInWithCustomTokenValue(t),this.injectedBrowserAuthSessionActive=true;}syncWasmAuthToken(){if(!this.wasmClient||typeof this.wasmClient.set_auth_token!="function"||!this.authContext&&this.isSpaceMode())return;let e=this.authContext?.userId??null,t=this.authContext?.token??null;this.hasSyncedAuthToWasmClient&&this.lastWasmAuthUserId===e&&this.lastWasmAuthToken===t||(this.lastWasmAuthUserId=e,this.lastWasmAuthToken=t,this.hasSyncedAuthToWasmClient=true,this.wasmClient.set_auth_token(t));}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 nt(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 it(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 stopAuthScopedActivity(e){Be("WasmBridge.stopAuthScopedActivity",{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?.stopAuthScopedActivity(),await this.stopSessionSubscriptions(),this.lastDeliveredConnectionStates.clear(),this.applicationRouteEscalations?.clear(),await this.stopRuntimeAuthScopedLoops();}setWasmClient(e){this.wasmClient=e,this.hasSyncedAuthToWasmClient=false,this.lastDeliveredConnectionStates.clear(),this.applicationRouteEscalations?.clear(),this.syncWasmAuthToken();}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 u$1(t);return this.wasmClient??null}normalizeDevice(e,t){return Se(e,t)}normalizeDeviceRecord(e,t){return this.normalizeDevice(e,t)}getResolvedWebLogicalDeviceId(){return this.resolveWebLogicalDeviceId()}normalizeDeviceStatusSnapshot(e){return ot(e)}normalizePeerSessionSnapshot(e){return st(e)}toBackendConnectionStateFromPeerSession(e){return at(e)}normalizeConnectionStateSnapshot(e){return ct(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 dt(e,t)}deliverConnectionState(e,t,i,r){let o=this.stabilizeConnectionState(e);this.escalateManagedApplicationRoute(o),this.lastDeliveredConnectionStates.set(o.connectionId,o);let a=(r??this.lastDeliveredConnectionStates).get(o.connectionId);this.sameConnectionState(a,o)||(r&&r.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 r=this.isTicketOnlyMode()?null:this.auth?.currentUser??null;if(r&&r.uid===this.authContext?.userId)try{return await r.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()||await G$1().checkForSSOToken();}async waitForAuth(){this.isTicketOnlyMode()||this.isSpaceMode()||this.authContext?.userId||this.auth?.currentUser||await G$1().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 G$1().signInAnonymously();}}async signInWithPluto(){if(this.isTicketOnlyMode())throw new Error('[openrtc] Pluto sign-in is unavailable when signalingMode="ticket-only".');await G$1().signInWithPluto();}async signOut(){let e=this.getCurrentUserId();await this.stopAuthScopedActivity({userId:e}),this.authContext=null,this.hasSyncedAuthToWasmClient=false,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,r=3e5,o,s){if(this.isTicketOnlyMode())return;let a=this.resolveWebLogicalDeviceId(),d=this.getDeviceIdPersistenceMode()==="ephemeral"?g.EPHEMERAL_DEVICE_ID_TTL_MS:r,l=await this.withWebPresenceMetadata(o,a);this.presenceManager.updatePresenceLoopState({userId:this.getCurrentUserId()??"",localNodeId:e,ticket:t,metadata:l,deviceName:s?.trim()||this.getDefaultBrowserDeviceName()}),await this.getCoordinationSignaling().updatePresence(e,t,i,d,l,s);}async refreshLivePresence(e,t,i,r){if(this.isTicketOnlyMode())return;let o=this.resolveWebLogicalDeviceId(),s=await this.withWebPresenceMetadata(i,o);this.presenceManager.updatePresenceLoopState({userId:this.getCurrentUserId()??"",localNodeId:e,ticket:t,metadata:s,deviceName:r?.trim()||this.getDefaultBrowserDeviceName()}),await this.getCoordinationSignaling().updatePresence(e,t,true,15*6e4,s,r);}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,r){if(this.isTicketOnlyMode())throw new Error('[openrtc] sendMessage() is unavailable when signalingMode="ticket-only".');return this.getCoordinationSignaling().sendMessage(e,t,i,r)}async pollMessages(e){return this.isTicketOnlyMode()?[]:this.getCoordinationSignaling().pollMessages(e)}async searchDevices(e){return this.isTicketOnlyMode()?[]:this.getCoordinationSignaling().searchDevices(e)}async listDevicesWithStatus(){if(this.isTicketOnlyMode())return [];if(!this.getDiscoveryScopeId())return [];let t=await this.getCoordinationSignaling().listDevices(),i=this.wasmClient;return Promise.all(t.map(async r=>{let o=this.normalizeDeviceStatusSnapshot({...r,connectionStatus:r.online?"online":"disconnected"}),s=typeof r.nodeId=="string"?r.nodeId.trim():"";if(!s||typeof i?.iroh_path_kind!="function"||typeof i?.iroh_transport_rtt_ms!="function")return o;try{let[a,d]=await Promise.all([i.iroh_path_kind(s),i.iroh_transport_rtt_ms(s)]);if(typeof d!="number"||!Number.isFinite(d))return o;let l=Math.max(0,Math.round(d)),c={};if(a==="direct-lan")c.irohLan=l;else if(a==="direct-quic")c.iroh=l;else if(a==="ble")c.ble=l;else if(a==="relay")c.irohRelay=l;else return o;return {...o,latencyMs:l,latencyByTransport:c}}catch(a){return te("[WasmBridge] iroh transport latency unavailable",{deviceId:r.deviceId,error:a instanceof Error?a.message:String(a)}),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(r=>this.normalizePeerSessionSnapshot(r)).filter(r=>!!(r.peerId||r.deviceId||r.deviceIdHint||r.nodeId||r.activeConnectionId))}return this.warnMissingWasmOnce("listPeerSessions"),[]}async waitForSettledPeer(e,t){let i=await this.waitForWasmClient(500);if(i&&typeof i.wait_for_settled_peer=="function"){let r=await i.wait_for_settled_peer(e,t);return !r||typeof r!="object"?null:this.normalizePeerSessionSnapshot(r)}return this.warnMissingWasmOnce("waitForSettledPeer"),null}async openPeerBi(e,t){let i=await this.waitForWasmClient(500);if(i&&typeof i.open_peer_bi=="function"){let r=await i.open_peer_bi(e,t);if(!r?.recv||!r?.send)throw new Error("WASM open_peer_bi returned an invalid bidirectional stream");return {readable:r.recv,writable:Q(r,r.send)}}throw this.warnMissingWasmOnce("openPeerBi"),new Error("WASM runtime does not support open_peer_bi()")}async openPeerNativeBi(e,t,i){let r=await this.waitForWasmClient(500),o=r&&r.open_peer_native_bi;if(typeof o=="function"){let s=await o.call(r,e,t,i);if(!s?.recv||!s?.send)throw new Error("WASM open_peer_native_bi returned an invalid bidirectional stream");return {readable:s.recv,writable:Q(s,s.send)}}throw this.warnMissingWasmOnce("openPeerNativeBi"),new Error("WASM runtime does not support open_peer_native_bi()")}async openPeerBiTransportOnly(e,t){if(this.options.applicationCrypto?.requireEncrypted)throw new Error("[WasmBridge] openPeerBiTransportOnly is debug-only and cannot be used when application crypto is required");let i=await this.waitForWasmClient(500),r=i&&typeof i.open_peer_bi_transport_only=="function";if(console.debug("[WasmBridge] openPeerBiTransportOnly",{peerId:e,hasWasmClient:!!i,hasTransportOnly:r,timeoutMs:t}),r){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:Q(o,o.send)}}return console.debug("[WasmBridge] openPeerBiTransportOnly falling back to openPeerBi",{peerId:e}),this.openPeerBi(e,t)}async openPeerUni(e,t){let i=await this.waitForWasmClient(500);if(i&&typeof i.open_peer_uni=="function"){let r=await i.open_peer_uni(e,t),o=r?.writable??r;if(!o)throw new Error("WASM open_peer_uni returned an invalid writable stream");return {writable:Q(r,o)}}throw this.warnMissingWasmOnce("openPeerUni"),new Error("WASM runtime does not support open_peer_uni()")}async resolvePeerConnectionRecords(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(r=>({connectionId:typeof r.connectionId=="string"?r.connectionId:"",nodeId:typeof r.nodeId=="string"?r.nodeId:null,deviceId:typeof r.deviceId=="string"?r.deviceId:null,deviceIdHint:typeof r.deviceIdHint=="string"?r.deviceIdHint:null,endpointId:typeof r.endpointId=="string"?r.endpointId:null,transportGeneration:typeof r.transportGeneration=="number"?r.transportGeneration:0,routeGeneration:typeof r.routeGeneration=="number"?r.routeGeneration:void 0,transportStableId:typeof r.transportStableId=="number"?r.transportStableId:null,transportSource:typeof r.transportSource=="string"?r.transportSource:null,lastTransportChangeAtMs:typeof r.lastTransportChangeAtMs=="number"?r.lastTransportChangeAtMs:0,lastRouteChangeAtMs:typeof r.lastRouteChangeAtMs=="number"?r.lastRouteChangeAtMs:void 0,state:typeof r.state=="string"?r.state:"pending",statusReason:typeof r.statusReason=="string"?r.statusReason:null,createdAtMs:typeof r.createdAtMs=="number"?r.createdAtMs:0,updatedAtMs:typeof r.updatedAtMs=="number"?r.updatedAtMs:0}))}return this.warnMissingWasmOnce("resolvePeerConnectionRecords"),[]}async resolvePeerIdentity(e){let t=await this.waitForWasmClient(500);if(t){let i=r=>{if(!r||typeof r!="object")return {peerId:null,deviceId:null,deviceIdHint:null,nodeId:null};let o=r;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 r=await t.peer_session(e),o=i(r);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)}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 r=await this.waitForWasmClient();if(i!==this.authScopedRuntimeGeneration||!r||typeof r.start_auto_connect!="function")return;await r.start_auto_connect(e,t),i===this.authScopedRuntimeGeneration&&this.presenceManager.startAutoConnect(e,t);}catch(r){console.warn("[WasmBridge] failed to initialize WASM auto-connect context",{userId:e,localDeviceId:t,error:r});}}async startAutoConnectOnce(e,t){await this.startAutoConnect(e,t),this.forceReconnectSnapshot();}notifyDisconnectRequested(e){this.presenceManager.wakeRustAutoConnectOwner();}async setAutoConnectExcluded(e,t){await this.presenceManager.setAutoConnectExcluded(e,t);}async disconnectDevice(e){let t=await this.waitForWasmClient();if(!t||typeof t.disconnect_device!="function"){this.warnMissingWasmOnce("disconnectDevice"),await this.presenceManager.setAutoConnectExcluded(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)}setCoreClient(e){e&&typeof e.connect=="function"?(this.coreClient=e,this.startApplicationRouteEscalationSubscription(),this.retryManagedApplicationRouteEscalations()):(this.coreClient=null,this.stopApplicationRouteEscalationSubscription());}startApplicationRouteEscalationSubscription(){if(this.applicationRouteEscalationUnsubscribe&&this.applicationRouteEscalationSubscriptionGeneration===this.authScopedRuntimeGeneration)return;this.stopApplicationRouteEscalationSubscription();let e=this.authScopedRuntimeGeneration,t=this.applicationRouteEscalationSubscriptionEpoch,i=this.onConnectionStateChange(()=>{});this.applicationRouteEscalationUnsubscribe=()=>{},this.applicationRouteEscalationSubscriptionGeneration=e,Promise.resolve(i).then(r=>{if(!this.coreClient||e!==this.authScopedRuntimeGeneration||t!==this.applicationRouteEscalationSubscriptionEpoch){r();return}this.applicationRouteEscalationUnsubscribe=r,this.applicationRouteEscalationSubscriptionGeneration=e;});}stopApplicationRouteEscalationSubscription(){this.applicationRouteEscalationSubscriptionEpoch+=1,this.applicationRouteEscalationUnsubscribe?.(),this.applicationRouteEscalationUnsubscribe=null,this.applicationRouteEscalationSubscriptionGeneration=-1;}retryManagedApplicationRouteEscalations(){for(let e of this.lastDeliveredConnectionStates.values())this.escalateManagedApplicationRoute(e);}escalateManagedApplicationRoute(e){if(!this.coreClient||!["connected","connecting"].includes(e.state)||this.applicationRouteEscalations.has(e.connectionId)||e.remoteNodeId&&this.coreClient.hasApplicationRouteForPeer?.(e.connectionId,e.remoteNodeId)===true)return;let t=this.presenceManager.resolveDesiredPeer(e.deviceId??e.deviceIdHint,e.remoteNodeId);if(!t?.ticket)return;let i=this.authScopedRuntimeGeneration,r=this.coreClient,o;o=(async()=>{let s=typeof r.ensureManagedApplicationRoute=="function"?await r.ensureManagedApplicationRoute({ticket:t.ticket,connectionId:e.connectionId,remoteNodeId:e.remoteNodeId??t.nodeId,expectedDeviceId:t.deviceId,timeoutMs:2e4}):await r.connect(t.ticket,2e4,t.deviceId,void 0,{admissionAlreadyPresented:true});if(i!==this.authScopedRuntimeGeneration)return;let a=s,d=a.id?.trim()||e.connectionId,l=a.remoteNodeId?.trim()||e.remoteNodeId?.trim()||a.deviceId?.trim()||t.deviceId;if(r.hasApplicationRouteForPeer?.(d,l)!==true&&r.hasApplicationRouteForPeer?.(d,l)!==true)throw new Error(`application crypto was not ready for ${l}`)})().catch(s=>{i===this.authScopedRuntimeGeneration&&console.warn("[WasmBridge][ROUTE-ESCALATION] Rust-managed route remains pending",{connectionId:e.connectionId,deviceId:t.deviceId,remoteNodeId:e.remoteNodeId??t.nodeId,error:s?.message??String(s)});}).finally(()=>{this.applicationRouteEscalations.get(e.connectionId)===o&&this.applicationRouteEscalations.delete(e.connectionId);}),this.applicationRouteEscalations.set(e.connectionId,o);}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=Date.now();A("[WasmBridge][ROUTE-ESCALATION] starting managed transport dial",{deviceId:e.deviceId??null,ticket:fn(e.endpointTicket),hasCoreClient:!!this.coreClient});let r=await t.connect_device(e.deviceId??null,e.endpointTicket);A("[WasmBridge][ROUTE-ESCALATION] managed transport dial completed",{deviceId:e.deviceId??null,remoteNodeId:r?.remoteNodeId??null,connectionId:r?.connectionId??null,elapsedMs:Date.now()-i});let o=e.endpointTicket;if(o&&this.coreClient){let s=this.coreClient;try{A("[WasmBridge][ROUTE-ESCALATION] starting typed application connection",{deviceId:e.deviceId??null,remoteNodeId:r?.remoteNodeId??null,connectionId:r?.connectionId??null});let a=typeof s.ensureManagedApplicationRoute=="function"?await s.ensureManagedApplicationRoute({ticket:o,connectionId:r?.connectionId??null,remoteNodeId:r?.remoteNodeId??null,expectedDeviceId:e.deviceId??null,approvedScope:r?.approvedScope??null,timeoutMs:2e4}):await s.connect(o,2e4,e.deviceId??null,void 0,{admissionAlreadyPresented:!0,approvedScope:r?.approvedScope??null}),d=typeof a?.remoteNodeId=="string"?a.remoteNodeId.trim():"",l=typeof a?.deviceId=="string"?a.deviceId.trim():"",c=d||r?.remoteNodeId?.trim?.()||l||e.deviceId?.trim?.()||"",p=typeof s.hasApplicationRouteForPeer=="function"?s.hasApplicationRouteForPeer.bind(s):null;if(!(!!c&&p?.(a?.id??void 0,c)===!0)&&c&&typeof s.waitForApplicationCryptoForPeer=="function"&&!(!!await s.waitForApplicationCryptoForPeer(c,2e4)&&(!p||p(a?.id??void 0,c)===!0)))throw console.warn("[WasmBridge][ROUTE-ESCALATION] application route still pending after managed dial",{deviceId:e.deviceId??null,remoteNodeId:d||(r?.remoteNodeId??null),connectionId:r?.connectionId??null,peerForCrypto:c,elapsedMs:Date.now()-i}),Object.assign(new Error(`application crypto was not ready for ${c}`),{applicationCryptoNotReady:!0});A("[WasmBridge][ROUTE-ESCALATION] application route ready",{deviceId:e.deviceId??null,remoteNodeId:d||(r?.remoteNodeId??null),connectionId:r?.connectionId??null,elapsedMs:Date.now()-i});}catch(a){if(a?.applicationCryptoNotReady)throw a;return console.warn("[WasmBridge] Managed transport connected; TS application route escalation is still pending",{deviceId:e.deviceId??null,remoteNodeId:r?.remoteNodeId??null,connectionId:r?.connectionId??null,error:a?.message??String(a)}),r}}return r}forceReconnectSnapshot(){this.isTicketOnlyMode()||!this.app||!this.auth||this.presenceManager.wakeRustAutoConnectOwner();}startPresenceLoop(e,t,i,r,o){this.presenceManager.startPresenceLoop(e,t,i,r,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=a(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"&&await t.is_connected(e)?true:this.hasConnectedIndependentPeerRoute(t,e)}async hasConnectedIndependentPeerRoute(e,t){if(!e||typeof t!="string"||t.trim().length===0)return false;let i=t.trim(),r=[];if(typeof e.peer_session=="function")try{let o=await e.peer_session(i);o&&typeof o=="object"&&r.push(this.normalizePeerSessionSnapshot(o));}catch{}if(typeof e.peer_sessions=="function")try{let o=await e.peer_sessions();Array.isArray(o)&&r.push(...o.filter(s=>!!s&&typeof s=="object").map(s=>this.normalizePeerSessionSnapshot(s)));}catch{}return r.some(o=>{let s=typeof o.peerId=="string"?o.peerId.trim():"",a=typeof o.deviceId=="string"?o.deviceId.trim():"",d=typeof o.deviceIdHint=="string"?o.deviceIdHint.trim():"",l=typeof o.nodeId=="string"?o.nodeId.trim():"";return (i===s||i===a||i===d||i===l)&&o.status==="connected"&&o.settledReady===true&&o.replacementPending!==true&&h(o.activeTransport)})}async getConnectionStates(){let e=await this.waitForWasmClient(500);if(e&&typeof e.connection_states=="function"){let r=await e.connection_states(),o=(Array.isArray(r)?r:[]).map(s=>this.normalizeConnectionStateSnapshot(s)).filter(s=>!!s);return o.length>0&&te("[WasmBridge] replaying current wasm connection states",o.map(s=>({connectionId:s.connectionId,deviceId:s.deviceId??null,deviceIdHint:s.deviceIdHint??null,remoteNodeId:s.remoteNodeId??null,state:s.state,transportState:s.transportState??null,protocolState:s.protocolState??null,routable:s.routable??null}))),o}let i=(await this.listPeerSessions().catch(()=>[])).map(r=>this.toBackendConnectionStateFromPeerSession(r)).filter(r=>!!r);return i.length>0&&te("[WasmBridge] replaying current wasm connection states",i.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}))),i}onConnectionStateChange(e){let t=new Map,i=new Map,r=this.authScopedRuntimeGeneration,o=false,s=l=>{let c=l.detail,p=typeof c?.connectionId=="string"?c.connectionId.trim():"";if(!p||o)return;let h=(i.get(p)??0)+1;i.set(p,h);let y=this.authScopedRuntimeGeneration;(async()=>{let v=this.normalizeConnectionStateSnapshot(c),S=await this.waitForWasmClient(500);if(!(o||y!==this.authScopedRuntimeGeneration||i.get(p)!==h)){if(S&&typeof S.connection_state=="function"){let O=await S.connection_state(p),I=this.normalizeConnectionStateSnapshot(O);if(!o&&y===this.authScopedRuntimeGeneration&&i.get(p)===h&&I){this.deliverConnectionState(I,e,"rust-event",t);return}}!o&&y===this.authScopedRuntimeGeneration&&i.get(p)===h&&v&&this.deliverConnectionState(v,e,"rust-event-detail",t);}})().catch(v=>{o||console.warn("[WasmBridge] Failed to read Rust connection state after lifecycle event",{connectionId:p,error:v});});},a=typeof window<"u"?window:null,d=typeof a?.addEventListener=="function"&&typeof a?.removeEventListener=="function";return d&&a.addEventListener("connection-state-changed",s),this.getConnectionStates().then(l=>{!o&&r===this.authScopedRuntimeGeneration&&l.forEach(c=>{i.has(c.connectionId)||this.deliverConnectionState(c,e,"replay",t);});}).catch(l=>{console.warn("[WasmBridge] Failed to replay wasm connection states after subscription:",l);}),()=>{o=true,i.clear(),d&&a.removeEventListener("connection-state-changed",s);}}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(s=>s.trim().length>0)?.trim()??"";if(!i||i==="."||i==="..")return g.FALLBACK_EXPLICIT_FILE_NAME;let r="";for(let s of i){if([...r].length>=g.MAX_EXPLICIT_FILE_NAME_CHARS)break;let a=s.charCodeAt(0);s==="/"||s==="\\"||s==="\0"||a<32||a===127?r+="_":r+=s;}let o=r.trim();return !o||o==="."||o===".."?g.FALLBACK_EXPLICIT_FILE_NAME:o}sanitizeExplicitMimeType(e){let t=typeof e=="string"?e.trim():"";if(!t)return g.FALLBACK_EXPLICIT_MIME_TYPE;let i="";for(let r of t){if(i.length>=g.MAX_EXPLICIT_MIME_TYPE_CHARS)break;let o=r.charCodeAt(0);o<33||o>126||r==='"'||r==="\\"?i+="_":i+=r;}return i.length>0?i:g.FALLBACK_EXPLICIT_MIME_TYPE}assertExplicitTransferHeaderSize(e){if(e.byteLength===0||e.byteLength>g.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,r,o){let s=o?.headerFrame===true?4:0,a=new Uint8Array(25+s+r.byteLength);a[0]=g.EXPLICIT_FILE_PROTOCOL_TYPE,a.set(e,1);let d=new DataView(a.buffer);d.setUint32(17,t,false),d.setUint32(21,i,false);let l=o?.headerFrame===true?29:25;return o?.headerFrame===true&&d.setUint32(25,r.byteLength,false),a.set(r,l),a}async sendExplicitFileData(e){let t=e.connection,i=e.file,r=e.applicationCrypto??this.options.applicationCrypto;if((e.requireApplicationCrypto===true||t?.requireApplicationCrypto===true)&&!r)throw new Error("[WasmBridge] Explicit transfer requires application crypto but none is available for this connection");let s=e.transferId&&e.transferId.trim().length>0?e.transferId:`transfer-${Date.now()}`,a=typeof e.receiverPlatformType=="string"?e.receiverPlatformType.trim().toLowerCase():null,d=e.remoteNodeId?.trim()||t?.remoteNodeId?.trim()||t?.deviceId?.trim();if(A("[WasmBridge] sendExplicitFileData start",{connectionId:e.connectionId??null,connectionRemoteNodeId:t?.remoteNodeId??null,remoteNodeId:d??null,fileName:i.name,fileSize:i.size,transferId:s}),!d)throw new Error("Web explicit transfer requires an active connection with a resolved remote node ID");let l=await this.waitForWasmClient();if(!l)throw new Error("WASM explicit transfer requires an initialized WASM client");let c=new TextEncoder,p={transfer_id:s,filename:this.sanitizeExplicitFileName(i.name),size:i.size,mime_type:this.sanitizeExplicitMimeType(i.type)},h=c.encode(JSON.stringify(p));this.assertExplicitTransferHeaderSize(h);let y=new Uint8Array(4);new DataView(y.buffer).setUint32(0,h.byteLength,false);let v=new Uint8Array(y.byteLength+h.byteLength);v.set(y,0),v.set(h,y.byteLength);let S=async()=>{if(a!=="web"||!t||typeof t.sendOnWebRTC!="function"||typeof t.isWebRtcApplicationRouteReady!="function"||t.isWebRtcApplicationRouteReady()!==true)return a&&a!=="web"&&typeof t?.isWebRtcApplicationRouteReady=="function"&&t.isWebRtcApplicationRouteReady()===true&&A("[WasmBridge] sendExplicitFileData kept on Iroh for non-browser receiver",{remoteNodeId:d,transferId:s,receiverPlatformType:a}),false;let I=r?Le(r):null,_=U=>I?I.protectFrame(U):U,R=new Uint8Array(await i.arrayBuffer()),E=this.createWebRTCExplicitTransferId(),B=Math.max(1,Math.ceil(R.byteLength/g.EXPLICIT_FILE_CHUNK_SIZE_BYTES)),C=typeof t.getWebRTCTransport=="function"?t.getWebRTCTransport():null,F=async()=>{C&&typeof C.getBufferedAmount=="function"&&typeof C.waitForDrain=="function"&&C.getBufferedAmount()>g.EXPLICIT_FILE_CHUNK_SIZE_BYTES*4&&await C.waitForDrain(g.EXPLICIT_FILE_CHUNK_SIZE_BYTES*2);};if(await t.sendOnWebRTC(this.createWebRTCExplicitTransferFrame(E,4294967295,B,_(h),{headerFrame:true})),await F(),R.byteLength===0)return await t.sendOnWebRTC(this.createWebRTCExplicitTransferFrame(E,0,B,_(new Uint8Array(0)))),true;let Z=0;for(let U=0;U<R.byteLength;U+=g.EXPLICIT_FILE_CHUNK_SIZE_BYTES){let pt=R.slice(U,Math.min(U+g.EXPLICIT_FILE_CHUNK_SIZE_BYTES,R.byteLength));await t.sendOnWebRTC(this.createWebRTCExplicitTransferFrame(E,Z,B,_(pt))),Z+=1,await F();}return A("[WasmBridge] sendExplicitFileData sent over WebRTC explicit route",{connectionId:e.connectionId??null,remoteNodeId:d,transferId:s,chunks:B,encrypted:!!I}),true},O=async()=>{let I=l.open_peer_bi_explicit_file_sender;if(typeof I!="function")return false;let _=await I.call(l,d,5e3),R=_?.writable??_?.send;if(!R||typeof R.getWriter!="function")throw new Error("WASM explicit peer stream returned an invalid writable stream");A("[WasmBridge] sendExplicitFileData open_peer_bi_explicit_file_sender resolved",{remoteNodeId:d,transferId:e.transferId??null,applicationCryptoWrapped:_.applicationCryptoWrapped===true});let E=Q(_,R,{requireFinish:true}).getWriter(),B=false;try{await E.write(v);let C=new Uint8Array(await i.arrayBuffer());for(let F=0;F<C.byteLength;F+=g.EXPLICIT_FILE_CHUNK_SIZE_BYTES){let Z=C.slice(F,Math.min(F+g.EXPLICIT_FILE_CHUNK_SIZE_BYTES,C.byteLength));await E.write(Z);}}catch(C){throw B=true,C}finally{try{await E.close();}catch(C){if(!B)throw C}finally{E.releaseLock();}}return true};try{try{if(await S())return}catch(I){A("[WasmBridge] sendExplicitFileData WebRTC explicit route failed; falling back",{remoteNodeId:d,transferId:s,error:I instanceof Error?I.message:String(I)});}if(await O())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{A("[WasmBridge] sendExplicitFileData completed",{remoteNodeId:d,transferId:s,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);}};g.EXPLICIT_FILE_PROTOCOL_TYPE=2,g.EXPLICIT_FILE_CHUNK_SIZE_BYTES=64*1024,g.MAX_EXPLICIT_TRANSFER_HEADER_BYTES=64*1024,g.FALLBACK_EXPLICIT_FILE_NAME="openrtc-transfer.bin",g.MAX_EXPLICIT_FILE_NAME_CHARS=180,g.FALLBACK_EXPLICIT_MIME_TYPE="application/octet-stream",g.MAX_EXPLICIT_MIME_TYPE_CHARS=255,g.WEB_DEVICE_ID_STORAGE_PREFIX="pluto_rtc_web_device_identity",g.EPHEMERAL_DEVICE_ID_TTL_MS=he.browserIdentity.ephemeralDeviceIdTtlMs;var lt=g;var ut=class{constructor(e){this.backend=e;}get currentUser(){return this.backend.currentUser}setAuthContext(e){return this.backend.setAuthContext?.(e)}async signInAnonymously(){return this.backend.signInAnonymously()}async signInWithPluto(){if(typeof this.backend.signInWithPluto!="function")throw new Error("Selected runtime adapter does not support Pluto SSO.");return this.backend.signInWithPluto()}async signOut(){return this.backend.signOut()}async stopAuthScopedActivity(){typeof this.backend.stopAuthScopedActivity=="function"&&await this.backend.stopAuthScopedActivity();}usesCoordinationGateway(){return this.backend.usesCoordinationGateway?.()===true}async joinCoordinationRoom(e,t,i){if(!this.backend.joinCoordinationRoom)throw new Error("Selected runtime adapter does not support coordination rooms.");await this.backend.joinCoordinationRoom(e,t,i);}async leaveCoordinationRoom(e){if(!this.backend.leaveCoordinationRoom)throw new Error("Selected runtime adapter does not support coordination rooms.");await this.backend.leaveCoordinationRoom(e);}async getCoordinationRoomMembers(e){if(!this.backend.getCoordinationRoomMembers)throw new Error("Selected runtime adapter does not support coordination rooms.");return this.backend.getCoordinationRoomMembers(e)}watchCoordinationRoomMembers(e,t){if(!this.backend.watchCoordinationRoomMembers)throw new Error("Selected runtime adapter does not support coordination rooms.");return this.backend.watchCoordinationRoomMembers(e,t)}async getTurnCredentials(){return this.backend.getTurnCredentials()}async updatePresence(e,t,i,r,o){return this.backend.updatePresence(e,t,i,r,o)}async refreshLivePresence(e,t,i){if(typeof this.backend.refreshLivePresence!="function")throw new Error("Selected runtime adapter does not support refreshLivePresence().");return this.backend.refreshLivePresence(e,t,i)}async setOffline(e){return this.backend.setOffline(e)}async cleanupStaleDevices(){return this.backend.cleanupStaleDevices()}async searchDevices(e){return this.backend.searchDevices(e)}async listDevicesWithStatus(){if(typeof this.backend.listDevicesWithStatus!="function")throw new Error("Selected runtime adapter does not support listDevicesWithStatus().");return this.backend.listDevicesWithStatus()}async getPeerSession(e){return typeof this.backend.getPeerSession!="function"?null:this.backend.getPeerSession(e)}async listPeerSessions(){return typeof this.backend.listPeerSessions!="function"?[]:this.backend.listPeerSessions()}async waitForSettledPeer(e,t){return typeof this.backend.waitForSettledPeer!="function"?null:this.backend.waitForSettledPeer(e,t)}async resolvePeerIdentity(e){return typeof this.backend.resolvePeerIdentity!="function"?{peerId:null,deviceId:null,deviceIdHint:null,nodeId:null}:this.backend.resolvePeerIdentity(e)}async resolvePeerConnectionRecords(e){return typeof this.backend.resolvePeerConnectionRecords!="function"?[]:this.backend.resolvePeerConnectionRecords(e)}async updateDevice(e,t){return this.backend.updateDevice(e,t)}async deleteDevice(e){return this.backend.deleteDevice(e)}onDevicesChange(e,t){return this.backend.onDevicesChange(e,t)}onAuthChange(e){return this.backend.onAuthChange(e)}async checkForSSOToken(){return this.backend.checkForSSOToken()}async waitForAuth(){return this.backend.waitForAuth()}async sendMessage(e,t,i,r){return this.backend.sendMessage(e,t,i,r)}async pollMessages(e){return this.backend.pollMessages(e)}watchFriendDevices(e,t){let i=this.backend;return i.watchFriendDevices?i.watchFriendDevices(e,t):()=>{}}async updateFriendTicket(e){let t=this.backend;t.updateFriendTicket&&await t.updateFriendTicket(e);}async subscribeDevices(e){return this.backend.subscribeDevices(e)}startAutoConnect(e,t){this.backend.startAutoConnect(e,t);}async submitDesiredPeerProjection(e,t){if(typeof this.backend.submitDesiredPeerProjection!="function")throw new Error("Selected runtime adapter does not support desired-peer projections.");await this.backend.submitDesiredPeerProjection(e,t);}startPresenceLoop(e,t,i,r,o){this.backend.startPresenceLoop(e,t,i,r,o);}async createSession(e){return this.backend.createSession(e)}async updateSession(e,t){return this.backend.updateSession(e,t)}async subscribeSessions(e){return this.backend.subscribeSessions(e)}forceReconnectSnapshot(){this.backend.forceReconnectSnapshot();}async getLocalDeviceId(){return typeof this.backend.getLocalDeviceId!="function"?null:this.backend.getLocalDeviceId()}async getLocalDeviceInfo(){return typeof this.backend.getLocalDeviceInfo!="function"?null:this.backend.getLocalDeviceInfo()}async updateLocalDeviceName(e){return typeof this.backend.updateLocalDeviceName!="function"?null:this.backend.updateLocalDeviceName(e)}async startManagedSessionNative(e){let t=this.backend;if(typeof t.startManagedSessionNative!="function")throw new Error("Selected runtime adapter does not support startManagedSessionNative().");return t.startManagedSessionNative(e)}async notifyNetworkChange(e){return typeof this.backend.notifyNetworkChange!="function"?null:this.backend.notifyNetworkChange(e)}async getManagedNodeId(e){if(console.info("[DelegatingRuntimeAdapter][getManagedNodeId] enter",{hasMethod:typeof this.backend.getManagedNodeId=="function",backendCtor:this.backend.constructor?.name??null}),typeof this.backend.getManagedNodeId!="function")return null;let t=await this.backend.getManagedNodeId(e);return console.info("[DelegatingRuntimeAdapter][getManagedNodeId] resolved",{result:t}),t}async startPresenceLoopOnce(e,t,i,r,o){let s=this.backend;if(typeof s.startPresenceLoopOnce!="function")throw new Error("Selected runtime adapter does not support startPresenceLoopOnce().");return s.startPresenceLoopOnce(e,t,i,r,o)}async startAutoConnectOnce(e,t){let i=this.backend;if(typeof i.startAutoConnectOnce!="function")throw new Error("Selected runtime adapter does not support startAutoConnectOnce().");return i.startAutoConnectOnce(e,t)}async getEndpointTicket(){if(typeof this.backend.getEndpointTicket!="function")throw new Error("Selected runtime adapter does not support getEndpointTicket().");return this.backend.getEndpointTicket()}async getEndpointTicketWithToken(e,t){let i=this.backend;return typeof i.getEndpointTicketWithToken!="function"?null:i.getEndpointTicketWithToken(e,t)}async registerSessionToken(e,t,i){let r=this.backend;typeof r.registerSessionToken=="function"&&await r.registerSessionToken(e,t,i);}async revokeSessionTokensByScope(e){let t=this.backend;return typeof t.revokeSessionTokensByScope!="function"?[]:t.revokeSessionTokensByScope(e)}async openPeerBi(e,t){if(typeof this.backend.openPeerBi!="function")throw new Error("Selected runtime adapter does not support openPeerBi().");return this.backend.openPeerBi(e,t)}async incoming_streams(){let e=this.backend;if(typeof e.incoming_streams!="function")throw new Error("Selected runtime adapter does not support incoming_streams().");return e.incoming_streams()}async is_current_transport_stable_id(e,t){let i=this.backend;return typeof i.is_current_transport_stable_id!="function"?false:i.is_current_transport_stable_id(e,t)}async openPeerNativeBi(e,t,i){let r=this.backend;if(typeof r.openPeerNativeBi!="function")throw new Error("Selected runtime adapter does not support openPeerNativeBi().");return r.openPeerNativeBi(e,t,i)}async openPeerBiTransportOnly(e,t){let i=this.backend;return typeof i.openPeerBiTransportOnly=="function"?i.openPeerBiTransportOnly(e,t):this.openPeerBi(e,t)}async openPeerUni(e,t){if(typeof this.backend.openPeerUni!="function")throw new Error("Selected runtime adapter does not support openPeerUni().");return this.backend.openPeerUni(e,t)}async connectToDevice(e){if(typeof this.backend.connectToDevice!="function")throw new Error("Selected runtime adapter does not support connectToDevice().");return this.backend.connectToDevice(e)}async disconnectDevice(e){if(typeof this.backend.disconnectDevice!="function")throw new Error("Selected runtime adapter does not support disconnectDevice().");return this.backend.disconnectDevice(e)}async setAutoConnectExcluded(e,t){if(typeof this.backend.setAutoConnectExcluded!="function")throw new Error("Selected runtime adapter does not support setAutoConnectExcluded().");return this.backend.setAutoConnectExcluded(e,t)}async isConnected(e){return this.backend.isConnected(e)}async getConnectionStates(){return typeof this.backend.getConnectionStates!="function"?[]:this.backend.getConnectionStates()}onConnectionStateChange(e){return typeof this.backend.onConnectionStateChange!="function"?()=>{}:this.backend.onConnectionStateChange(e)}async sendExplicitFilePath(e,t,i){if(typeof this.backend.sendExplicitFilePath!="function")throw new Error("Selected runtime adapter does not support sendExplicitFilePath().");return this.backend.sendExplicitFilePath(e,t,i)}async sendExplicitFileData(e){if(typeof this.backend.sendExplicitFileData!="function")throw new Error("Selected runtime adapter does not support sendExplicitFileData().");return this.backend.sendExplicitFileData(e)}async getTransferHistory(e){return typeof this.backend.getTransferHistory!="function"?[]:this.backend.getTransferHistory(e)}async deleteTransferJob(e){if(typeof this.backend.deleteTransferJob=="function")return this.backend.deleteTransferJob(e)}getRuntimeCapabilities(){let e=this.backend;return typeof e.getRuntimeCapabilities=="function"?e.getRuntimeCapabilities():re()}async onIncomingNativeMessage(e){let t=this.backend;return typeof t.onIncomingNativeMessage!="function"?()=>{}:t.onIncomingNativeMessage(e)}unwrap(){return this.backend}setCoreClient(e){let t=this.backend;typeof t.setCoreClient=="function"&&t.setCoreClient(e);}};
2
- export{he as A,Tn as B,Et as C,At as D,We as E,re as F,Cn as G,Pn as H,lt as I,ut as J,ht as a,te as b,A as c,mn as d,Ln as e,Bn as f,Fn as g,Un as h,ge as i,on as j,St as k,bn as l,Le as m,Be as n,f as o,D as p,Fe as q,w as r,ie as s,ye as t,un as u,ot as v,st as w,jn as x,zn as y,ct as z};
@@ -1,2 +0,0 @@
1
- import {c}from'./chunk-C7YN5MSV.js';import {getApps,initializeApp}from'firebase/app';import {getToken,initializeAppCheck,ReCaptchaEnterpriseProvider}from'firebase/app-check';import {getFunctions,connectFunctionsEmulator,httpsCallable}from'firebase/functions';import {browserLocalPersistence,inMemoryPersistence,browserPopupRedirectResolver,initializeAuth,getAuth,connectAuthEmulator,setPersistence,onIdTokenChanged,getIdToken,signInWithCustomToken,onAuthStateChanged,signInAnonymously,signInWithEmailAndPassword,createUserWithEmailAndPassword,signOut,deleteUser,updateProfile,GoogleAuthProvider,OAuthProvider,signInWithCredential,signInWithPopup,signInWithRedirect,getRedirectResult}from'firebase/auth';function S(){return typeof window>"u"?false:!!(window.__TAURI_IPC__||window.__TAURI_INTERNALS__||window.__TAURI__||window.location.protocol==="tauri:"||window.location.hostname==="tauri.localhost")}var H=new Set;function I(t,e){H.has(t)||(H.add(t),console.warn(e));}function ie(t){return /^pk_(live|test)_[0-9a-f]{40}$/.test(t)}async function Qe(t,e){let n=`${t}:${e}`,o=new TextEncoder().encode(n),i=await crypto.subtle.digest("SHA-256",o);return Array.from(new Uint8Array(i)).map(d=>d.toString(16).padStart(2,"0")).join("")}function R(t){let e=typeof t.apiKey=="string"?t.apiKey.trim():"";if(e)return ie(e)||I(`invalid-api-key:${e.slice(0,10)}`,"[pluto-rtc] The provided `apiKey` does not match the expected format (pk_live_... or pk_test_...). Create an app at https://api.openrtc.app/developer."),`app_${e.slice(-16)}`;throw new Error("[openrtc] `apiKey` is required. Create an app at https://api.openrtc.app/developer.")}function T(t){return t.authMode?t.authMode:("apiKey"in t&&typeof t.apiKey=="string"&&t.apiKey.trim().length>0&&typeof(t.spaceKey??t.space)=="string"&&(t.spaceKey??t.space).trim().length>0||I("default-auth-mode","[pluto-rtc] `authMode` is not set; defaulting to `anonymous` for compatibility."),"anonymous")}function Ye(t){let e=typeof t.projectId=="string"?t.projectId.trim():"";return e||(I("default-project-id","[pluto-rtc] `projectId` is not set; defaulting to the built-in PlutoRTC Firebase project."),y)}function B(t){return t.trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function $e(t){let e="storagePrefix"in t&&typeof t.storagePrefix=="string"?B(t.storagePrefix):"";return e||B(R(t))||"default"}var ae={devicesPerUser:100,maxRooms:1e4,maxMembersPerRoom:250,maxPersonalDevices:25e3},Je=ae;var se=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun.cloudflare.com:3478"}],F={iceServers:se},Xe={};var q=["iroh-relay","iroh","moq"];function le(t){return (Array.isArray(t.urls)?t.urls:[t.urls]).some(n=>typeof n=="string"&&(n.startsWith("turn:")||n.startsWith("turns:")))}function ce(t){let n=(Array.isArray(t.urls)?t.urls:[t.urls]).filter(r=>typeof r=="string"&&!r.startsWith("stun:"));return n.length===0?null:{...t,urls:Array.isArray(t.urls)?n:n[0]}}function C(t){if(t)return t.map(e=>ce(e)).filter(e=>e!==null)}function K(t,e){let n=new Set(["iroh-relay","iroh","moq"]);e&&n.add("webrtc");let r=(t??q).filter(o=>n.has(o));return r.length>0?r:[...q]}function et(t){return !!t?.transports?.webrtc}function tt(t,e){let n=t?.transports?.webrtc||void 0;if(n)return t?.strictMode||n.privacyMode?{...n,iceServers:C(n.iceServers),iceTransportPolicy:"relay"}:n.iceTransportPolicy==="relay"&&!(Array.isArray(n.iceServers)&&n.iceServers.some(o=>le(o)))?(e?.("[Client] Overriding relay-only ICE policy to all because no TURN servers are configured"),{...n,iceTransportPolicy:"all"}):n}var de=/^[A-Za-z0-9._-]+$/,ue="[redacted]";function W(t){let e;try{e=new URL(t);}catch{throw new Error("[OpenRTC] transports.moq.relayUrl must be a valid HTTPS URL.")}if(e.protocol!=="https:")throw new Error("[OpenRTC] transports.moq.relayUrl must use HTTPS/WebTransport.");if(e.hash)throw new Error("[OpenRTC] transports.moq.relayUrl must not contain a fragment.");if(e.searchParams.has("jwt"))throw new Error("[OpenRTC] transports.moq.relayUrl must not contain a jwt query parameter; use transports.moq.accessToken.");return e}function A(t){return W(t.trim()).toString()}function rt(t,e){let n=W(t.trim());if(e!==void 0){let r=e.trim();if(!r)throw new Error("[OpenRTC] transports.moq.accessToken must not be empty when provided.");if(new TextEncoder().encode(r).byteLength>16384)throw new Error("[OpenRTC] transports.moq.accessToken exceeds the maximum supported size.");if(!de.test(r))throw new Error("[OpenRTC] transports.moq.accessToken must be a URL-safe JWT.");n.searchParams.append("jwt",r);}return n.toString()}function ot(t){try{let e=new URL(t);return e.search="",e.hash="",e.toString()}catch{return "invalid-moq-relay-url"}}function it(t,e){let n=t instanceof Error?`${t.name}: ${t.message}`:String(t),r=e?.trim();return r?n.split(r).join(ue):n}var pe=[...c];function k(t){let e=t.spaceKey??t.space;return {...t,...e!==void 0?{spaceKey:e}:{}}}function j(t){return {...t,iceServers:t.iceServers?t.iceServers.map(e=>({...e})):t.iceServers}}function me(t){return {...t}}function ge(t){return {...t}}function fe(t){if(t)return {iroh:typeof t.iroh=="object"?ge(t.iroh):t.iroh,webrtc:typeof t.webrtc=="object"?j(t.webrtc):t.webrtc,ble:typeof t.ble=="object"?{...t.ble}:t.ble,moq:typeof t.moq=="object"?me(t.moq):t.moq}}function ye(t){if(t.strictMode&&!t.transports&&(t.transports={iroh:{relayOnly:true}}),!!t.transports){if(t.transports.webrtc===true?t.transports.webrtc=j(F):t.transports.webrtc===false&&(t.transports.webrtc=void 0),t.transports.moq===true)throw new Error("[OpenRTC] transports.moq=true is ambiguous because no anonymous MoQ relay is available; provide transports.moq.relayUrl explicitly.");if(t.transports.moq===false)t.transports.moq=void 0;else if(t.transports.moq&&typeof t.transports.moq=="object"){let e=t.transports.moq,n=e.relayUrl?.trim(),r=e.accessToken;if(r!==void 0&&!r.trim())throw new Error("[OpenRTC] transports.moq.accessToken must not be empty when provided.");t.transports.moq={...e,...n?{relayUrl:A(n)}:{},...r!==void 0?{accessToken:r.trim()}:{}};}t.transports.iroh===true?t.transports.iroh={}:t.transports.iroh===false&&(t.transports.iroh=void 0);}}function he(t){if(!t.strictMode||!t.transports)return;let e=t.transports.iroh&&typeof t.transports.iroh=="object"?t.transports.iroh:{};t.transports.iroh={...e,relayOnly:true,relayTransportPolicy:e.relayTransportPolicy??"websocketRequired",localDiscovery:false,localDiscoveryMode:void 0},t.transports.ble=void 0;let n=t.transports.webrtc;n&&typeof n=="object"&&(t.transports.webrtc={...n,privacyMode:true,lanMode:false,iceServers:C(n.iceServers)??[],iceTransportPolicy:"relay"});let r=t.transports.moq;if(r&&typeof r=="object"){let o=r.relayUrl?.trim();if(!o)throw new Error("[OpenRTC] strictMode requires an explicit transports.moq.relayUrl.");t.transports.moq={...r,relayUrl:A(o)};}}function pt(t){let e=k(t),n=R(e),r=T(e),o={strictMode:false,disableIrohFallback:false,transportPriority:[...pe],...e,authMode:r,transports:fe(e.transports)};ye(o),he(o),o.strictMode&&(o.transportPriority=K(e.transportPriority,!!o.transports?.webrtc));let i=G(o),a=(o.discoveryMode??"space")==="space"?"client-open":"client-auth";return {appTag:n,authMode:r,configuredPersistenceMode:i,options:o,roomCreationMode:a}}function G(t){let e=t.transports?.iroh;return t.endpointIdPersistence??t.nodeIdPersistence??(typeof e=="object"?e.persistenceMode:void 0)??"ephemeral"}function mt(t){return "options"in t&&"configuredPersistenceMode"in t?{apiKey:t.options.apiKey,authMode:T(t.options),projectId:t.options.projectId,storagePrefix:t.options.storagePrefix,nodeIdPersistence:t.configuredPersistenceMode}:{apiKey:t.apiKey,authMode:T(t),projectId:t.projectId,storagePrefix:t.storagePrefix,nodeIdPersistence:G(t)}}function gt(t,e){e&&(t.transports={...t.transports||{},...e});}var y="pluto-rtc-prod",w="https://api.openrtc.app",be="https://gateway.openrtc.app",U={apiKey:"AIzaSyA62Krj-7ZYFT5xjrTUq7mXana41Ahj_mM",authDomain:"api.openrtc.app",projectId:y,storageBucket:"pluto-rtc-prod.firebasestorage.app",messagingSenderId:"607066575224",appId:"1:607066575224:web:ed3f51825ba228db92b88d",recaptchaSiteKey:"6LfGv2gtAAAAALFAuE_kpLYpNBpk2IsKiLIGdOGl"};function ht(t){let e=k(t),r=(typeof e.projectId=="string"&&e.projectId.trim()?e.projectId.trim():void 0)??y,o=r===y;return {...e,projectId:r,coordinationGateway:e.coordinationGateway??(o?{endpoint:be,controlPlaneEndpoint:w,environment:"production"}:void 0)}}function z(t){return new Promise(e=>setTimeout(e,t))}function Pt(t){let e=new Uint8Array(t.byteLength);return e.set(t),e}function Tt(t){let e=t.reduce((o,i)=>o+i.byteLength,0),n=new Uint8Array(e),r=0;for(let o of t)n.set(o,r),r+=o.byteLength;return n}function vt(t,e,n){let r=e*Math.pow(2,Math.max(0,t-1));return Math.min(n,r)}function St(t){try{let e=t;return !!e&&!!e.send&&typeof e.send.getWriter=="function"&&!!e.recv&&typeof e.recv.getReader=="function"}catch{return false}}function It(t,e,n){let r=t;if(!r)return null;try{let o=r.send,i=r.recv;if(!o||typeof o.getWriter!="function"||!i||typeof i.getReader!="function")return null;let a=typeof r.endpoint_id=="string"&&r.endpoint_id.trim().length>0?r.endpoint_id:e,c=Number.isSafeInteger(r.transport_stable_id)&&Number(r.transport_stable_id)>0?Number(r.transport_stable_id):void 0,d=Number.isSafeInteger(n)&&Number(n)>0?Number(n):void 0;if(c!==void 0&&d!==void 0&&c!==d)return null;let s=c??d;return {send:o,recv:i,endpoint_id:a,...s?{transport_stable_id:s}:{}}}catch{return null}}function Rt(t,e){let n={send:t.send,recv:e,endpoint_id:typeof t.endpoint_id=="string"?t.endpoint_id:"",...Number.isSafeInteger(t.transport_stable_id)&&Number(t.transport_stable_id)>0?{transport_stable_id:Number(t.transport_stable_id)}:{}};return t?.applicationCryptoWrapped===true&&(n.applicationCryptoWrapped=true),n}async function Ct(t,e){if(!t)return false;try{let n=t.send?.getWriter?.();if(n)try{await n.close();}catch{}finally{try{n.releaseLock();}catch{}}}catch{}try{let n=t.recv?.getReader?.();if(n)try{await n.cancel(e);}catch{}finally{try{n.releaseLock();}catch{}}}catch{}return true}function At(t,e,n={}){let r=n.context??"prependBytesToReader",o=n.traceId,i=e.byteLength===0,a=n.pendingRead??null,c=s=>n.release?.(s),d=(s,p)=>n.log?.(s,p);return new ReadableStream({async pull(s){if(!i){i=true,s.enqueue(e);return}if(a){let u=a;a=null;let m;try{m=await u;}catch(f){s.error(f),c("pending-read-error"),d("prepend-bytes:pending-read-error",{context:r,traceId:o||null,error:f?.message||String(f)});return}if(m.done){s.close(),c("pending-done");return}m.value&&s.enqueue(m.value);return}let p;try{p=await t.read();}catch(u){s.error(u),c("read-error"),d("prepend-bytes:read-error",{context:r,traceId:o||null,error:u?.message||String(u)});return}let{done:v,value:P}=p;if(v){s.close(),c("done");return}P&&s.enqueue(P);},async cancel(s){c("cancel");}})}async function kt(t,e){let n=t.read(),r=e-Date.now();if(r<=0)return {status:"timeout",pendingRead:n};let o=Symbol("probe-timeout"),i,a=new Promise(c=>{i=setTimeout(()=>c(o),r);});try{let c=await Promise.race([n,a]);if(c===o)return {status:"timeout",pendingRead:n};let{done:d,value:s}=c;return d?{status:"done"}:{status:"data",value:s&&s.byteLength>0?new Uint8Array(s):new Uint8Array(0)}}finally{i&&clearTimeout(i);}}function Q(t,e,n){let r;return new Promise((o,i)=>{r=setTimeout(()=>{if(r=void 0,typeof n=="function"){i(n());return}let a=n?`${n} timed out`:"timeout";i(new Error(`${a} after ${e}ms`));},e),t.then(a=>{r!==void 0&&clearTimeout(r),o(a);},a=>{r!==void 0&&clearTimeout(r),i(a);});})}var Z="pluto-rtc-auth";function Be(t){return t?.DEV===true||String(t?.VITE_E2E??"").trim().toLowerCase()==="true"}function Fe(t=S){return t()}function qe(t){if(Fe())return null;let e=typeof import.meta<"u"?import.meta.env:null,n=String(e?.VITE_OPENRTC_APP_CHECK_SITE_KEY??globalThis.__OPENRTC_APP_CHECK_SITE_KEY__??U.recaptchaSiteKey??"").trim(),r=String(e?.VITE_OPENRTC_APP_CHECK_MODE??globalThis.__OPENRTC_APP_CHECK_MODE__??"monitor").trim().toLowerCase();if(!n)return r==="enforce"&&console.error("[PLUTO-RTC][APP-CHECK] Enforcement requested without VITE_OPENRTC_APP_CHECK_SITE_KEY"),null;let o=String(e?.VITE_OPENRTC_APP_CHECK_DEBUG_TOKEN??"").trim();o&&!Be(e)?console.error("[PLUTO-RTC][APP-CHECK] Debug tokens are allowed only in development or explicit E2E builds"):o&&typeof self<"u"&&(self.FIREBASE_APPCHECK_DEBUG_TOKEN=o==="true"?true:o);try{return initializeAppCheck(t,{provider:new ReCaptchaEnterpriseProvider(n),isTokenAutoRefreshEnabled:!0})}catch(i){let a=i instanceof Error?i.message:String(i);return a.toLowerCase().includes("already exists")||console.warn("[PLUTO-RTC][APP-CHECK] Initialization failed",{message:a}),null}}var D=null;function Ke(){if(typeof globalThis<"u"&&globalThis.__OPENRTC_DEBUG__===true)return true;if(typeof localStorage<"u")try{return localStorage.getItem("openrtc:debug")==="1"}catch{return false}return false}function l(t,e){if(Ke()){if(typeof e>"u"){console.log(t);return}console.log(t,e);}}function jt(t){D=t;}function We(){return S()}function re(){return typeof navigator>"u"?false:/iPhone|iPad|iPod|Android/i.test(navigator.userAgent||"")}function ee(){return We()&&re()}function g(t,e,n){return Q(t,e,()=>new Error(`${n} timeout after ${e}ms`))}function te(t){let e="0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz-._",n=new Uint8Array(t);window.crypto.getRandomValues(n);let r="";for(let o=0;o<t;o+=1)r+=e[n[o]%e.length];return r}async function ne(t){let n=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(r)).map(i=>i.toString(16).padStart(2,"0")).join("")}var N=class{constructor(){this.redirectResultPromise=null;this.redirectResultConsumed=false;this.lastRelayedToken=null;this.lastRelayedRefreshToken=null;let e=getApps().find(o=>o.name===Z);this.app=e||initializeApp(U,Z),this.appCheck=qe(this.app);let n=re(),r=ee();if(n)try{let o=r?{persistence:[browserLocalPersistence,inMemoryPersistence]}:{persistence:[browserLocalPersistence,inMemoryPersistence],popupRedirectResolver:browserPopupRedirectResolver};this.auth=initializeAuth(this.app,o),l("[PLUTO-RTC][AUTH-HOST] Using mobile-safe Firebase auth initialization",{appName:this.app.name,persistence:"browserLocalPersistence->inMemoryPersistence",redirectResolver:r?"disabled-for-tauri-mobile":"browserPopupRedirectResolver",tauriMobile:r});}catch{this.auth=getAuth(this.app),console.warn("[PLUTO-RTC][AUTH-HOST] Mobile-safe auth initialization unavailable; falling back to default getAuth");}else this.auth=getAuth(this.app);this.functions=getFunctions(this.app,w);try{let o=typeof globalThis<"u"?String(globalThis.__OPENRTC_AUTH_EMULATOR_HOST__??"").trim():"",i=typeof globalThis<"u"?String(globalThis.__OPENRTC_FUNCTIONS_EMULATOR_HOST__??"").trim():"",a=typeof import.meta<"u"?import.meta.env:null;if(!!o||!!i||!!a&&String(a.VITE_USE_EMULATORS)==="true"&&(a.DEV||String(a.VITE_E2E)==="true")){let d=String(a?.VITE_OPENRTC_EMULATOR_HOST??"127.0.0.1").trim()||"127.0.0.1",[s,p]=o.split(":"),[v,P]=i.split(":"),u=(s??"").trim()||d,m=(v??"").trim()||d,f=Number(p??a?.VITE_OPENRTC_AUTH_EMULATOR_PORT??9100),oe=Number(P??a?.VITE_OPENRTC_FUNCTIONS_EMULATOR_PORT??5002);try{connectAuthEmulator(this.auth,`http://${u}:${f}`,{disableWarnings:!0});}catch{}try{connectFunctionsEmulator(this.functions,m,oe);}catch{}}}catch{}n?this.persistenceReady=Promise.resolve():this.persistenceReady=setPersistence(this.auth,browserLocalPersistence).catch(o=>{console.warn("[PLUTO-RTC][AUTH-HOST] Failed to set auth persistence",{message:o?.message});}),l("[PLUTO-RTC][AUTH-HOST] Initialized auth host",{appName:this.app.name,mobileSafeAuth:n}),onIdTokenChanged(this.auth,o=>{l("[PLUTO-RTC][AUTH-HOST] Firebase ID token changed",{hasUser:!!o,uid:o?.uid,providerDataCount:o?.providerData?.length||0}),this.syncDesktopAuthToken(o);});}async syncDesktopAuthToken(e,n=false){if(!D)return;let r=e?await getIdToken(e,n).catch(()=>null):null,o=e?e.refreshToken??null:null;if(r===this.lastRelayedToken&&o===this.lastRelayedRefreshToken)return;this.lastRelayedToken=r,this.lastRelayedRefreshToken=o;let i=await Promise.allSettled([Promise.resolve(D({authToken:r,refreshToken:o}))]);i[0]?.status==="rejected"&&console.warn("[PLUTO-RTC][AUTH-HOST] Failed to relay auth token to desktop backend",{message:i[0].reason?.message});}getApp(){return this.app}getFunctions(){return this.functions}async getAppCheckToken(e=false){if(!this.appCheck)return null;try{return (await getToken(this.appCheck,e)).token?.trim()||null}catch(n){let r=n instanceof Error?n.message:String(n);return console.warn("[PLUTO-RTC][APP-CHECK] Token acquisition failed",{message:r}),null}}getCurrentUser(){return this.auth.currentUser}getAuth(){return this.auth}onAuthStateChanged(e){return l("[PLUTO-RTC][AUTH-HOST] onAuthStateChanged listener registered (via onIdTokenChanged)"),onIdTokenChanged(this.auth,e)}onIdTokenChanged(e){return l("[PLUTO-RTC][AUTH-HOST] onIdTokenChanged listener registered"),onIdTokenChanged(this.auth,e)}async getIdToken(e){return this.auth.currentUser?getIdToken(this.auth.currentUser,e?.forceRefresh??true):null}async checkForSSOToken(){if(typeof window>"u")return;let e=new URLSearchParams(window.location.search),n=new URLSearchParams(window.location.hash.startsWith("#")?window.location.hash.slice(1):window.location.hash),r=e.get("token")||n.get("token")||(e.get("custom_token")==="true"||n.get("custom_token")==="true"?e.get("id_token")||n.get("id_token"):null);if(r)try{await this.persistenceReady,await signInWithCustomToken(this.auth,r),window.history.replaceState({},document.title,window.location.pathname);}catch(o){console.error("[PLUTO-RTC][AUTH-HOST] SSO sign-in failed:",o);}}async signInWithCustomTokenValue(e){return await this.persistenceReady,(await signInWithCustomToken(this.auth,e)).user}async signInWithPluto(e){if(typeof window>"u")throw new Error("Pluto SSO requires a browser environment.");let n=e?.redirectUri||window.location.href,r=e?.authorizeBaseUrl||"https://pluto.openrtc.app/sso/authorize",o=new URL(r);o.searchParams.set("redirect_uri",n),window.location.assign(o.toString());}async waitForAuth(){if(await this.persistenceReady,!this.auth.currentUser)return new Promise(e=>{let n=onAuthStateChanged(this.auth,r=>{r&&(n(),e());});})}async signInAnonymously(){await signInAnonymously(this.auth);}async signIn(e,n){return (await signInWithEmailAndPassword(this.auth,e,n)).user}async signUp(e,n){return (await createUserWithEmailAndPassword(this.auth,e,n)).user}async signOut(){await signOut(this.auth);}async deleteAccount(){if(!this.auth.currentUser)throw new Error("No user signed in");await deleteUser(this.auth.currentUser);}async signInWithCredential(e){let n=Date.now();if(l("[PLUTO-RTC][AUTH-HOST] signInWithCredential start",{callbackId:e.callbackId,provider:e.provider,hasIdToken:!!e.idToken,hasAccessToken:!!e.accessToken,hasNonce:!!e.nonce}),e.isCustomToken){l("[PLUTO-RTC][AUTH-HOST] signInWithCredential: custom token detected, using signInWithCustomToken");try{if(ee())l("[PLUTO-RTC][AUTH-HOST] Skipping authStateReady before custom token sign-in on Tauri mobile",{callbackId:e.callbackId});else {l("[PLUTO-RTC][AUTH-HOST] Awaiting authStateReady...");try{await g(this.auth.authStateReady(),5e3,"authStateReady"),l("[PLUTO-RTC][AUTH-HOST] Auth state ready, signing in with custom token...");}catch(a){console.warn("[PLUTO-RTC][AUTH-HOST] authStateReady did not resolve in time; continuing custom token sign-in",{callbackId:e.callbackId,message:a?.message});}}let i;try{i=await g(signInWithCustomToken(this.auth,e.idToken),25e3,"signInWithCustomToken (custom token path)");}catch(a){console.warn("[PLUTO-RTC][AUTH-HOST] First custom token sign-in attempt failed; retrying once",{callbackId:e.callbackId,message:a?.message,code:a?.code}),await z(250),i=await g(signInWithCustomToken(this.auth,e.idToken),25e3,"signInWithCustomToken (custom token path retry)");}if(l("[PLUTO-RTC][AUTH-HOST] signInWithCustomToken success",{callbackId:e.callbackId,provider:e.provider,uid:i.user?.uid,elapsedMs:Date.now()-n}),i.user&&(e.displayName||e.photoURL))try{await updateProfile(i.user,{displayName:e.displayName||i.user.displayName||void 0,photoURL:e.photoURL||i.user.photoURL||void 0});}catch(a){console.warn("[PLUTO-RTC][AUTH-HOST] Failed to update custom-token user profile",{callbackId:e.callbackId,message:a?.message});}return i.user}catch(o){throw console.error("[PLUTO-RTC][AUTH-HOST] signInWithCustomToken failed",{callbackId:e.callbackId,error:o?.message,code:o?.code,stack:o?.stack,elapsedMs:Date.now()-n}),o}}let r;e.provider==="google"?r=GoogleAuthProvider.credential(e.idToken,e.accessToken):r=new OAuthProvider("apple.com").credential({idToken:e.idToken,rawNonce:e.nonce,accessToken:e.accessToken});try{let o=await g(signInWithCredential(this.auth,r),1e4,"firebase signInWithCredential");return l("[PLUTO-RTC][AUTH-HOST] signInWithCredential success",{callbackId:e.callbackId,provider:e.provider,uid:o.user?.uid,elapsedMs:Date.now()-n}),o.user}catch(o){console.warn("[PLUTO-RTC][AUTH-HOST] signInWithCredential primary path failed; trying custom token fallback",{callbackId:e.callbackId,provider:e.provider,elapsedMs:Date.now()-n,code:o?.code,message:o?.message});let i=await g(this.mintSessionTokenFromProviderToken(e),15e3,"mintSessionTokenFromProviderToken"),a=await g(signInWithCustomToken(this.auth,i),15e3,"signInWithCustomToken");return l("[PLUTO-RTC][AUTH-HOST] signInWithCustomToken fallback success",{callbackId:e.callbackId,provider:e.provider,uid:a.user?.uid,elapsedMs:Date.now()-n}),a.user}}async mintSessionTokenFromProviderToken(e){let n=httpsCallable(this.functions,"mintSessionToken");l("[PLUTO-RTC][AUTH-HOST] mintSessionToken fallback request start",{provider:e.provider,hasIdToken:!!e.idToken,hasNonce:!!e.nonce});let o=(await n({provider:e.provider,idToken:e.idToken,nonce:e.nonce,idempotencyKey:`provider-token:${e.callbackId}`})).data?.token;if(!o)throw new Error("mintSessionToken did not return a token for provider exchange");return l("[PLUTO-RTC][AUTH-HOST] mintSessionToken fallback request success",{provider:e.provider}),o}async signInWithPopup(e){if(e==="google"){let i=new GoogleAuthProvider;i.addScope("email"),i.addScope("profile"),i.setCustomParameters({prompt:"select_account"});let a=await signInWithPopup(this.auth,i);return {idToken:await getIdToken(a.user,true),refreshToken:a.user.refreshToken}}let n=new OAuthProvider("apple.com");n.addScope("email"),n.addScope("name");let r=te(32);typeof sessionStorage<"u"&&sessionStorage.setItem("apple_auth_nonce",r),n.setCustomParameters({nonce:await ne(r)});let o=await signInWithPopup(this.auth,n);return {idToken:await getIdToken(o.user,true),refreshToken:o.user.refreshToken}}async signInWithRedirect(e,n){if(e==="google"){let i=new GoogleAuthProvider;i.addScope("email"),i.addScope("profile"),i.setCustomParameters({prompt:"select_account"}),await signInWithRedirect(this.auth,i);return}let r=new OAuthProvider("apple.com");r.addScope("email"),r.addScope("name");let o=n?.nonce||te(32);typeof sessionStorage<"u"&&sessionStorage.setItem("apple_auth_nonce",o),r.setCustomParameters({nonce:await ne(o)}),await signInWithRedirect(this.auth,r);}async consumeRedirectResult(){return this.redirectResultConsumed?(l("[PLUTO-RTC][AUTH-HOST] consumeRedirectResult skipped (already consumed)"),null):this.redirectResultPromise?this.redirectResultPromise:(this.redirectResultPromise=(async()=>{try{l("[PLUTO-RTC][AUTH-HOST] consumeRedirectResult start");let e=await getRedirectResult(this.auth);if(!e)return l("[PLUTO-RTC][AUTH-HOST] consumeRedirectResult: no redirect result"),{fromRedirect:!1,user:null};this.redirectResultConsumed=!0;let n=await getIdToken(e.user,!0).catch(()=>null),r=e.providerId||e.user.providerData?.[0]?.providerId||null;return l("[PLUTO-RTC][AUTH-HOST] consumeRedirectResult success",{uid:e.user.uid,providerId:r,hasIdToken:!!n}),{fromRedirect:!0,user:e.user,providerId:r,idToken:n}}finally{this.redirectResultPromise=null;}})(),this.redirectResultPromise)}async startGoogleSignIn(){await this.signInWithRedirect("google");}async startAppleSignIn(){await this.signInWithRedirect("apple");}async mintSessionToken(){let e=httpsCallable(this.functions,"mintSessionToken");if(typeof globalThis.crypto?.randomUUID!="function")throw new Error("Secure request identity is unavailable for token minting.");let r=(await e({idempotencyKey:`hosted-token:${globalThis.crypto.randomUUID()}`})).data;if(!r?.token)throw new Error("mintSessionToken did not return a token");return r.token}},E=null;function je(){return E||(E=new N),E}var Gt=new Proxy({},{get(t,e,n){let r=je(),o=r[e];return typeof o=="function"?o.bind(r):o}});
2
- export{Rt as A,Ct as B,At as C,kt as D,Q as E,jt as F,je as G,Gt as H,Qe as a,R as b,T as c,Ye as d,$e as e,Je as f,se as g,F as h,Xe as i,et as j,tt as k,rt as l,ot as m,it as n,k as o,pt as p,mt as q,gt as r,ht as s,S as t,z as u,Pt as v,Tt as w,vt as x,St as y,It as z};
@@ -1 +0,0 @@
1
- import {J,I}from'./chunk-LAUABWCB.js';var n=class extends J{constructor(e){super(new I(e));}setWasmClient(e){this.unwrap().setWasmClient(e);}};export{n as a};
@@ -1 +0,0 @@
1
- import {b as b$1,e as e$1}from'./chunk-C7YN5MSV.js';var i=b$1,l=new Set(i);function e(n){if(typeof n!="string")return;let r=n.trim().toLowerCase();return l.has(r)?r:void 0}function c(n){let r=e(n);return r?e$1(r).baseProtocol==="iroh":false}function u(n){let r=e(n);if(!r)return false;let t=e$1(r);return t.baseProtocol==="iroh"&&(t.locality==="nearby"||t.locality==="direct-internet")}function p(n){let r=e(n);return r?e$1(r).family==="optional-route":false}function b(n){let r=e(n);return r?e$1(r).baseProtocol==="webrtc":false}function f(n,r,t=false){return n==="relay"||r==="relay"?"webrtc-turn":n==="host"&&r==="host"||t&&n&&r?"webrtc-lan":"webrtc"}function d(n){let r=e(n);return r?e$1(r).independentlyInstantiable:false}export{i as a,e as b,c,u as d,p as e,b as f,f as g,d as h};
@@ -1,29 +0,0 @@
1
- /**
2
- * Pure byte / stream / timing helpers.
3
- *
4
- * Extracted from the `Client` god object (see
5
- * `docs/plans/client-ts-decomposition.md` Phase 1). These functions are
6
- * deliberately pure — no `Client` state, no `this`, no logging side effects — so
7
- * the same helper is reused everywhere instead of being re-implemented inline
8
- * (e.g. `concatBytes` previously existed both here and in `applicationCrypto.ts`,
9
- * and three near-identical exponential-backoff helpers existed across the class).
10
- */
11
-
12
- type ByteArray = Uint8Array<ArrayBuffer>;
13
- type ByteArrayLike = Uint8Array<ArrayBufferLike>;
14
-
15
- type RuntimeU32BEFrameHandler = (payload: ByteArray) => void;
16
- type RuntimeJsonFrameHandler<T = unknown> = (value: T, payload: ByteArray) => void;
17
- interface RuntimeJsonFrameDecoderOptions {
18
- onInvalidJson?: (error: unknown, payload: ByteArray) => void;
19
- }
20
- declare function encodeRuntimeU32BEFrame(payload: ByteArrayLike): ByteArray;
21
- declare function createRuntimeU32BEFrameDecoder(onFrame: RuntimeU32BEFrameHandler): (chunk: ByteArrayLike) => void;
22
- declare function encodeRuntimeJsonPayload(value: unknown): ByteArray;
23
- declare function decodeRuntimeJsonPayload<T = unknown>(payload: ByteArrayLike): T;
24
- declare function encodeRuntimeJsonFrame(value: unknown): ByteArray;
25
- declare function createRuntimeJsonFrameDecoder<T = unknown>(onValue: RuntimeJsonFrameHandler<T>, options?: RuntimeJsonFrameDecoderOptions): (chunk: ByteArrayLike) => void;
26
- declare function concatRuntimeBytes(a: ByteArrayLike, b: ByteArrayLike): ByteArray;
27
- declare function readRuntimeU32BE(bytes: ByteArrayLike, offset: number): number;
28
-
29
- export { type RuntimeJsonFrameHandler as R, type RuntimeU32BEFrameHandler as a, createRuntimeU32BEFrameDecoder as b, createRuntimeJsonFrameDecoder as c, decodeRuntimeJsonPayload as d, encodeRuntimeJsonFrame as e, encodeRuntimeJsonPayload as f, encodeRuntimeU32BEFrame as g, type RuntimeJsonFrameDecoderOptions as h, concatRuntimeBytes as i, readRuntimeU32BE as r };