openrtc 1.0.11 → 1.0.13

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 (35) hide show
  1. package/dist/{DelegatingRuntimeAdapter-lFDUNBy9.d.ts → DelegatingRuntimeAdapter-D_kGKQtW.d.ts} +9 -1
  2. package/dist/{assembly-C2G0P2L5.d.ts → assembly-DisGbrdH.d.ts} +2 -2
  3. package/dist/auth/index.js +1 -1
  4. package/dist/auth/internal.js +1 -1
  5. package/dist/chunk-3SND2COC.js +1 -0
  6. package/dist/chunk-HXTGHALT.js +2 -0
  7. package/dist/chunk-KP5H3SYJ.js +2 -0
  8. package/dist/{chunk-MIWX2SUB.js → chunk-LVJSU53Y.js} +1 -1
  9. package/dist/chunk-NP3JZ2LD.js +3 -0
  10. package/dist/{chunk-N6UBUNGC.js → chunk-WFUW3BHK.js} +1 -1
  11. package/dist/chunk-YFNRKQEA.js +2 -0
  12. package/dist/{chunk-SJ5BFL6W.js → chunk-ZZIIBIEC.js} +1 -1
  13. package/dist/index.d.ts +7 -7
  14. package/dist/index.js +1 -1
  15. package/dist/native.d.ts +5 -5
  16. package/dist/native.js +1 -1
  17. package/dist/openrtc_bg.wasm +0 -0
  18. package/dist/runtime/WasmRuntimeAdapter.d.ts +2 -2
  19. package/dist/runtime/WasmRuntimeAdapter.js +1 -1
  20. package/dist/runtime/device-status.d.ts +2 -2
  21. package/dist/runtime/index.d.ts +20 -8
  22. package/dist/runtime/index.js +1 -1
  23. package/dist/runtime/tauri.d.ts +3 -3
  24. package/dist/runtime/tauri.js +1 -1
  25. package/dist/{spaceTokens-3sbs1mUF.d.ts → spaceTokens-Dc1CsMQt.d.ts} +3 -3
  26. package/dist/{tauri-WEvOC_Z6.d.ts → tauri-DSkrSuO-.d.ts} +2 -2
  27. package/dist/transport/index.d.ts +2 -2
  28. package/dist/{types-N9s66nF8.d.ts → types-BSJ8IyBq.d.ts} +1 -1
  29. package/dist/{types-ZDsZknDI.d.ts → types-Cb_GFANp.d.ts} +28 -1
  30. package/package.json +3 -2
  31. package/dist/chunk-DI5IPRPM.js +0 -2
  32. package/dist/chunk-HVTYSEU7.js +0 -2
  33. package/dist/chunk-MNI6JGR2.js +0 -1
  34. package/dist/chunk-QAZ4NA4F.js +0 -3
  35. package/dist/chunk-YTUWXCRO.js +0 -1
@@ -1 +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,u,a,w,t,E as E$1,x}from'./chunk-HVTYSEU7.js';import {xchacha20poly1305}from'@noble/ciphers/chacha.js';import {getFirestore,connectFirestoreEmulator,getDoc,serverTimestamp as serverTimestamp$1,setDoc,updateDoc,deleteDoc,collection,doc,getDocs,query,where,limit,onSnapshot,getDocFromServer}from'firebase/firestore';import {getDatabase,connectDatabaseEmulator,onValue,ref,onDisconnect,set,onChildAdded,onChildChanged,onChildRemoved,serverTimestamp,get}from'firebase/database';import {httpsCallable,getFunctions}from'firebase/functions';import*as we from'tweetnacl';function Vt(){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 De(i,e,t){if(Vt()){if(typeof t>"u"){console[i](e);return}console[i](e,t);}}function de(i,e){De("debug",i,e);}function R(i,e){De("info",i,e);}function ui(i,e){De("log",i,e);}var B=new Uint8Array([79,82,84,67,69,49]),le=2,W=8,$=24,it=32,qt=3,$t=16*1024*1024,Yt=4096;function Jt(i,e){if(i.byteLength<e.byteLength)return false;let t=0;for(let n=0;n<e.byteLength;n+=1)t|=i[n]^e[n];return t===0}function Xt(i){let e=new Uint8Array(i),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 Qt(i,e){let t="";for(let n of e)t+=n.toString(16).padStart(2,"0");return `${i}:${t}`}function rt(i){if(!Jt(i,B))return null;let e=i[B.byteLength];return e===le?e:null}function Zt(i){return rt(i)===le&&i.byteLength>B.byteLength+1+W+$}function gi(i,e={}){if(!(i instanceof Uint8Array)||i.byteLength!==it)throw new Error(`[OpenRTC] application payload crypto key must be ${it} bytes`);let t=new Uint8Array(i),n=e.requireEncrypted??true,r=e.randomBytes??Xt,s=e.replayProtection??true,o=0,a=new Set,c=[];return {requireEncrypted:n,protectPayload(l,d){let u=r($);if(!(u instanceof Uint8Array)||u.byteLength!==$)throw new Error(`[OpenRTC] application payload crypto nonce must be ${$} bytes`);let p=new Uint8Array(1+d.byteLength);p[0]=l,p.set(d,1);let f=xchacha20poly1305(t,u).encrypt(p);if(!s)throw new Error("[OpenRTC] ORTCE1 v1 envelopes are not supported; replay protection is required");let h=new Uint8Array(B.byteLength+1+W+u.byteLength+f.byteLength),g=0;h.set(B,g),g+=B.byteLength,h[g]=le,g+=1;let v=o;return o+=1,new DataView(h.buffer,h.byteOffset+g,W).setBigUint64(0,BigInt(v),false),g+=W,h.set(u,g),g+=u.byteLength,h.set(f,g),h},openPayload(l,d){if(!Zt(d))return n?null:d;if(rt(d)!==le)return null;let p=B.byteLength+1,f=Number(new DataView(d.buffer,d.byteOffset+p,W).getBigUint64(0,false));if(!Number.isFinite(f))return null;let h=p+W,g=h+$,v=d.slice(h,g),S=s?Qt(f,v):null;if(S&&a.has(S))return null;let D=d.slice(g),I;try{I=xchacha20poly1305(t,v).decrypt(D);}catch{return null}if(I.byteLength<1||I[0]!==l)return null;if(S)for(a.add(S),c.push(S);c.length>Yt;){let w=c.shift();w&&a.delete(w);}return I.slice(1)}}}function en(i){let e=new Uint8Array(4+i.byteLength);return new DataView(e.buffer,e.byteOffset,e.byteLength).setUint32(0,i.byteLength,false),e.set(i,4),e}function st(i,e={}){let t=e.typeId??qt,n=e.maxFrameBytes??$t;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(n)||n<=0)throw new Error("[OpenRTC] raw application crypto maxFrameBytes must be a positive integer");let r=d=>i.protectPayload(t,d),s=d=>i.openPayload(t,d),o=()=>new TransformStream({transform(d,u){u.enqueue(en(r(new Uint8Array(d))));}}),a=()=>{let d=new Uint8Array(0);return new TransformStream({transform(u,p){for(d=w([d,new Uint8Array(u)]);d.byteLength>=4;){let f=new DataView(d.buffer,d.byteOffset,d.byteLength).getUint32(0,false);if(f===0||f>n)throw new Error("[OpenRTC] invalid encrypted raw stream frame length");if(d.byteLength<4+f)return;let h=d.slice(4,4+f);d=d.slice(4+f);let g=s(h);if(!g)throw new Error("[OpenRTC] encrypted raw stream frame failed authentication");p.enqueue(g);}},flush(){if(d.byteLength!==0)throw new Error("[OpenRTC] encrypted raw stream ended mid-frame")}})},c=d=>d.pipeThrough(a()),l=d=>{let u=o();return u.readable.pipeTo(d).catch(()=>{}),u.writable};return {typeId:t,protectFrame:r,openFrame:s,createOutboundTransform:o,createInboundTransform:a,wrapReadable:c,wrapWritable:l,wrapBiStream(d){return {...d,send:l(d.send),recv:c(d.recv)}}}}var tn="[OpenRTC][teardown-trace]";function nn(){try{let i=globalThis;if(i.OPENRTC_TEARDOWN_TRACE===!0||i.localStorage?.getItem("OPENRTC_TEARDOWN_TRACE")==="1")return !0}catch{}return false}function ot(i,e={}){console.info(tn,{kind:i,ts:new Date().toISOString(),...e}),nn()&&console.info("[OpenRTC][teardown-trace:stack]",{kind:i,stack:new Error(`teardown: ${i}`).stack});}var Y={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 vi(){return Y}var rn={adapter:"browser-wasm",signaling:{firestore:true,nativeIpc:false,rtdbPresence: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}},sn={adapter:"native-ipc",signaling:{firestore:true,nativeIpc:true,rtdbPresence: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 at(i){return {adapter:i.adapter,signaling:{...i.signaling},transport:{...i.transport},nativeProtocols:{...i.nativeProtocols},lifecycle:{...i.lifecycle},transfers:{...i.transfers},fallback:{...i.fallback}}}function ue(i=globalThis){let e=at(rn),t=typeof i?.RTCPeerConnection=="function";return e.transport.webRtcUpgrade=t,e.transport.webRtcLan=t,e}function L(i){return i?.compiled===true&&i.enabled===true}function Si(i,e=false){let t=at(sn),n=i?.transport;return n&&(t.transport.irohQuic=L(n.irohQuic),t.transport.irohLan=L(n.irohLan),t.transport.webRtcUpgrade=L(n.webRtc),t.transport.nativeWebRtc=L(n.webRtc),t.transport.webRtcLan=L(n.webRtcLan),t.transport.moq=L(n.moq),t.transport.ble=L(n.ble)),t.transport.wasm=false,t.fallback.wasm=e,t}function Ii(i){return {environment:i.adapter==="native-ipc"||i.adapter==="tauri-ipc"?"native":i.adapter==="browser-wasm"?"web":"unknown",transports:{quic:i.transport.irohQuic,irohRelay:i.transport.irohQuic,irohLan:i.transport.irohLan,webRtc:i.transport.webRtcUpgrade||i.transport.nativeWebRtc,webRtcLan:i.transport.webRtcLan,moq:i.transport.moq,ble:i.transport.ble},lifecycle:{...i.lifecycle},storage:{localFileSystem:i.transfers.explicitFilePath,transferHistory:i.transfers.history},nativeProtocols:{...i.nativeProtocols}}}function _(i){if(!i)return null;let e=2166136261;for(let t=0;t<i.length;t+=1)e^=i.charCodeAt(t),e=Math.imul(e,16777619);return `fp-${(e>>>0).toString(16).padStart(8,"0")}`}var pn=9e4,fn=3e4;function Me(i=Date.now()){return i+pn}function P(i,e=Date.now()){return !i||i.online!==true?false:typeof i.leaseExpiresAt!="number"?true:i.leaseExpiresAt>e}function hn(i,e){switch(i.kind){case "user-scoped":return `presence/${i.appTag}/users/${i.userId}/devices/${e}`;case "space":return `presence/spaces/${i.namespaceId}/devices/${e}`}}function Ee(i,e,t){return `${hn(i,e)}/instances/${t}`}function dt(i){switch(i.kind){case "user-scoped":return `presence/${i.appTag}/users/${i.userId}/devices`;case "space":return `presence/spaces/${i.namespaceId}/devices`}}function lt(i,e,t){return `presence/${i}/rooms/${e}/members/${t}`}function gn(i,e){return `presence/${i}/rooms/${e}/members`}function J(i){let e={},t=(n,r)=>{if(typeof r!="string")return;let s=r.trim();s&&(e[n]=s);};if(t("ticket",i?.ticket),t("nodeId",i?.nodeId),t("deviceName",i?.deviceName),t("platformType",i?.platformType),t("metadata",i?.metadata),Array.isArray(i?.excludedPeers)){let n=i.excludedPeers.map(r=>typeof r=="string"?r.trim().toLowerCase():"").filter(Boolean).filter((r,s,o)=>o.indexOf(r)===s).sort();n.length>0&&(e.excludedPeers=n);}return e}function yn(i,e){if(!i||typeof i!="object")return null;let t=i,n=J({ticket:t.ticket,nodeId:t.nodeId,deviceName:t.deviceName,platformType:t.platformType,metadata:t.metadata,excludedPeers:t.excludedPeers});return {online:P({online:t.online===true,leaseExpiresAt:typeof t.leaseExpiresAt=="number"?t.leaseExpiresAt:void 0},e),ticketVersion:typeof t.ticketVersion=="number"?t.ticketVersion:0,leaseExpiresAt:typeof t.leaseExpiresAt=="number"?t.leaseExpiresAt:void 0,...n}}function ut(i,e=Date.now()){if(!i||typeof i!="object")return null;let t=i.instances;if(!t||typeof t!="object")return null;let n=Object.entries(t).map(([r,s])=>({instanceId:r,state:yn(s,e)})).filter(r=>!!r.state).sort((r,s)=>s.instanceId.localeCompare(r.instanceId));return n.length===0?null:n.find(r=>r.state.online)?.state??n[0].state}function mn(){let i=Date.now().toString().padStart(13,"0"),e=globalThis.crypto?.randomUUID?.().replace(/-/g,"")??Math.random().toString(36).slice(2);return `${i}-${e}`}function Ae(i,e){return {online:true,lastSeenAt:serverTimestamp(),ticketVersion:i,leaseExpiresAt:Me(),...J(e)}}function _e(i,e){return {online:false,lastSeenAt:serverTimestamp(),ticketVersion:i,leaseExpiresAt:Date.now(),...J(e)}}function pe(i){return {...i}}function ke(i,e){return {...i,lastSeenAt:serverTimestamp(),leaseExpiresAt:e?Me():Date.now()}}var fe=class{constructor(e,t=mn()){this.desiredOnlineNodes=new Map;this.connected=null;this.connectedUnsubscribe=null;this.leaseRefreshTimer=null;this.db=getDatabase(e);let n=t.trim().replace(/[^a-zA-Z0-9_-]/g,"-");if(!n)throw new Error("runtimeInstanceId is required");this.runtimeInstanceId=n;try{let r=globalThis?.__OPENRTC_RTDB_EMULATOR_HOST__,s=typeof r=="string"?r.trim():"";if(s){let[o,a]=s.split(":"),c=(o??"").trim()||"127.0.0.1",l=Number(a??9001);try{connectDatabaseEmulator(this.db,c,l);}catch{}}else {let o=import.meta?.env;if(!!o?.DEV&&String(o?.VITE_USE_EMULATORS)==="true"){let c=String(o?.VITE_OPENRTC_EMULATOR_HOST??"127.0.0.1").trim()||"127.0.0.1",l=Number(o?.VITE_OPENRTC_RTDB_EMULATOR_PORT??9001);try{connectDatabaseEmulator(this.db,c,l);}catch{}}}}catch{}}ensureReconnectWatch(){this.connectedUnsubscribe||(this.connectedUnsubscribe=onValue(ref(this.db,".info/connected"),e=>{let t=e.val()===true,n=t&&this.connected===false;if(this.connected=t,!!n)for(let r of this.desiredOnlineNodes.keys())this.publishDesiredOnline(r).catch(s=>{console.warn("[RtdbPresence] failed to republish presence after reconnect:",{path:r,error:s});});}));}async publishDesiredOnline(e){let t=this.desiredOnlineNodes.get(e);if(!t)return;t.online=ke(t.online,true),t.offline=ke(t.offline,false);let n=ref(this.db,e);await onDisconnect(n).set(t.offline),await set(n,t.online);}ensureLeaseRefresh(){this.leaseRefreshTimer||(this.leaseRefreshTimer=setInterval(()=>{for(let e of this.desiredOnlineNodes.keys())this.publishDesiredOnline(e).catch(t=>{console.warn("[RtdbPresence] failed to refresh RTDB presence lease:",{path:e,error:t});});},fn));}stopLeaseRefreshIfIdle(){this.desiredOnlineNodes.size>0||!this.leaseRefreshTimer||(clearInterval(this.leaseRefreshTimer),this.leaseRefreshTimer=null);}async registerOnlineNode(e,t,n){this.ensureReconnectWatch(),this.desiredOnlineNodes.set(e,{online:t,offline:n}),this.ensureLeaseRefresh(),await this.publishDesiredOnline(e);}async markNodeOffline(e,t){this.desiredOnlineNodes.delete(e),this.stopLeaseRefreshIfIdle();let n=ref(this.db,e);await onDisconnect(n).cancel(),await set(n,ke(t,false));}subscribeIncremental(e,t,n,r){let s=ref(this.db,e),o={},a=()=>n({...o}),c=u=>{let p=typeof u.key=="string"?u.key:"";if(!p)return;let f=t(p,u.val());f?o[p]=f:delete o[p],a();},l=u=>{console.warn(`[RtdbPresence] ${r} presence subscription error:`,u);},d=[onChildAdded(s,c,l),onChildChanged(s,c,l),onChildRemoved(s,u=>{let p=typeof u.key=="string"?u.key:"";p&&(delete o[p],a());},l)];return ()=>{for(let u of d)u();}}async registerDevice(e,t,n=0,r){let s=Ee(e,t,this.runtimeInstanceId);try{await this.registerOnlineNode(s,pe(Ae(n,r)),pe(_e(n,r))),R("[RtdbPresence] registered device presence",{path:s,scopeKind:e.kind,deviceId:t,ticketVersion:n,hasTicket:typeof r?.ticket=="string"&&r.ticket.length>0,hasNodeId:typeof r?.nodeId=="string"&&r.nodeId.length>0});}catch(o){let a=o;throw console.warn("[RtdbPresence] registerDevice failed",{path:s,scopeKind:e.kind,deviceId:t,ticketVersion:n,code:typeof a?.code=="string"?a.code:null,message:typeof a?.message=="string"?a.message:String(o)}),o}}async bumpTicketVersion(e,t,n,r){let s=Ee(e,t,this.runtimeInstanceId),o=ref(this.db,s),a=this.desiredOnlineNodes.get(s),c=J(r);if(a){let l=a.online;c=J({ticket:r?.ticket??l.ticket,nodeId:r?.nodeId??l.nodeId,deviceName:r?.deviceName??l.deviceName,platformType:r?.platformType??l.platformType,metadata:r?.metadata??l.metadata,excludedPeers:r?.excludedPeers??l.excludedPeers}),a.online=pe(Ae(n,c)),a.offline=pe(_e(n,c));}await onDisconnect(o).set(_e(n,c)),await set(o,Ae(n,c));}async markOffline(e,t,n=0){await this.markNodeOffline(Ee(e,t,this.runtimeInstanceId),{online:false,lastSeenAt:serverTimestamp(),ticketVersion:n,leaseExpiresAt:Date.now()});}async registerRoomMember(e,t,n){await this.registerOnlineNode(lt(e,t,n),{online:true,lastSeenAt:serverTimestamp(),leaseExpiresAt:Me()},{online:false,lastSeenAt:serverTimestamp(),leaseExpiresAt:Date.now()});}async markRoomMemberOffline(e,t,n){await this.markNodeOffline(lt(e,t,n),{online:false,lastSeenAt:serverTimestamp(),leaseExpiresAt:Date.now()});}onRoomPresenceChange(e,t,n){return this.subscribeIncremental(gn(e,t),(r,s)=>{if(!s||typeof s!="object")return null;let o=s;return {online:P({online:o.online===true,leaseExpiresAt:typeof o.leaseExpiresAt=="number"?o.leaseExpiresAt:void 0}),leaseExpiresAt:typeof o.leaseExpiresAt=="number"?o.leaseExpiresAt:void 0}},n,"room")}onPresenceChange(e,t){return this.subscribeIncremental(dt(e),(n,r)=>ut(r),t,"device")}async readPresenceMap(e){let n=(await get(ref(this.db,dt(e)))).val();if(!n||typeof n!="object")return {};let r={};for(let[s,o]of Object.entries(n)){if(!o||typeof o!="object")continue;let a=ut(o);a&&(r[s]=a);}return r}};var Be=100;function yt(i,e){return !i||i.kind!==e.kind?false:i.kind==="user-scoped"&&e.kind==="user-scoped"?i.appTag===e.appTag&&i.userId===e.userId:i.kind==="space"&&e.kind==="space"&&i.namespaceId===e.namespaceId}function Rn(i){try{let e=i.replace(/-/g,"+").replace(/_/g,"/"),t=(4-e.length%4)%4,n=e+"=".repeat(t);if(typeof atob=="function")return JSON.parse(atob(n));let r=globalThis.Buffer;if(r)return JSON.parse(r.from(n,"base64").toString("utf8"))}catch{return null}return null}function G(i){let e=typeof i=="string"?i.trim():"";if(!e)return {present:false};let t=e.lastIndexOf("."),n=t>=0?e.slice(0,t):e,r=t>=0?e.slice(t+1):null,s=r?Rn(r):null,o=s&&typeof s.t=="string"&&s.t.trim().length>0?s.t.trim():null,a=s&&typeof s.s=="string"&&s.s.trim().length>0?s.s.trim():null,c=s&&typeof s.m=="number"&&Number.isFinite(s.m)?s.m:null;return {present:true,irohFingerprint:_(n),tokenFingerprint:_(o),tokenSuffixFingerprint:_(r),scope:a,maxConnections:c}}var K=class K{constructor(e){this.hooks=e;this.deviceListeners=new Map;this.devicesById=new Map;this.staleDeviceOfflineWrites=new Set;this.nextListenerIdSeed={value:1};this.activeDeviceScopeKey=null;this.activeDeviceUnsubscribe=null;this.deviceWatchSetup=null;this.deviceWatchGeneration=0;this.hasDeviceRosterSnapshot=false;this.durableRosterRead=null;this.freshnessRecheckTimer=null;this.rtdbPresence=null;this.rtdbScope=null;this.rtdbPresenceMap={};this.rtdbUnsubscribe=null;this.hasRtdbPresenceSnapshot=false;this.rtdbPresenceRead=null;this.knownTicketVersions=new Map;this.autoConnectRefreshes=new Map;}get options(){return this.hooks.options}setRtdbPresence(e,t){let n=this.rtdbPresence===e,r=yt(this.rtdbScope,t);if(n&&r)return;let s=this.deviceListeners.size>0;R("[BrowserDeviceDiscovery][rtdb] adapter or scope changed",{sameAdapter:n,sameScope:r,hasActiveListeners:s,scopeKind:t.kind}),this.rtdbUnsubscribe&&(this.rtdbUnsubscribe(),this.rtdbUnsubscribe=null),this.rtdbPresence=e,this.rtdbScope=t,this.rtdbPresenceMap={},this.hasRtdbPresenceSnapshot=false,this.rtdbPresenceRead=null,this.knownTicketVersions.clear(),s&&this.handleScopeChange().catch(o=>{console.warn("[BrowserDeviceDiscovery] failed to restart device watch after RTDB scope change:",o);});}stopRtdbPresence(){this.rtdbUnsubscribe?.(),this.rtdbUnsubscribe=null,this.rtdbPresence=null,this.rtdbScope=null,this.rtdbPresenceMap={},this.hasRtdbPresenceSnapshot=false,this.rtdbPresenceRead=null,this.knownTicketVersions.clear();}stopAuthScopedActivity(){this.stopRtdbPresence(),this.stopDeviceWatch({clearDevices:true});}async searchDevices(e){let n=(this.rtdbPresence&&this.rtdbScope?await this.readLiveRtdbDeviceSnapshot():await this.readCurrentDeviceSnapshot()).filter(r=>r.online);return e?this.filterDevices(n,e):n}async listDevices(e){let t=await this.readCurrentDeviceSnapshot();return e?this.filterDevices(t,e):t}async subscribeDevices(){let e=await this.hooks.getDevicesCollectionRef();if(!e)return new ReadableStream({start(n){n.close();}});let t=null;return new ReadableStream({start:n=>{t=onSnapshot(query(e,limit(Be)),r=>{let s=Date.now(),o=[];for(let a of r.docChanges()){let c=this.toDevice(a.doc,s);if(a.type==="removed"){o.push({type:"removed",deviceId:a.doc.id});continue}if(!c){o.push({type:"removed",deviceId:a.doc.id});continue}o.push({type:a.type==="added"?"added":"modified",device:c});}o.length>0&&n.enqueue(o);},r=>{console.warn("[BrowserDeviceDiscovery] subscribeDevices snapshot error:",{message:r?.message,code:r?.code});try{n.close();}catch{}});},cancel:()=>{t?.(),t=null;}})}onDevicesChange(e,t){let n=this.nextListenerIdSeed.value++;return this.deviceListeners.set(n,{callback:e,excludeNodeId:t}),this.emitDevicesToListener(n),this.ensureDeviceWatch(),()=>{this.deviceListeners.delete(n),this.deviceListeners.size===0&&this.stopDeviceWatch({clearDevices:true});}}async handleScopeChange(){let e=this.deviceListeners.size>0;this.stopDeviceWatch({clearDevices:true}),e&&await this.ensureDeviceWatch();}async cleanupStaleDevices(){let e=await this.hooks.getDevicesCollectionRef();if(!e)return;let t=Date.now(),n=!!(this.rtdbPresence&&this.rtdbScope),r=await getDocs(query(e,where("online","==",false),where("expiresAt","<",t),limit(100)));if(await Promise.allSettled(r.docs.map(async c=>{let l=c.data();l.online===false&&this.isDeviceExpired(l,t)&&await deleteDoc(c.ref);})),n)return;let s=this.rtdbPresence&&this.rtdbScope?await this.rtdbPresence.readPresenceMap(this.rtdbScope).catch(()=>this.rtdbPresenceMap):this.rtdbPresenceMap,o=await getDocs(query(e,where("online","==",true),limit(100))),a=new Map;for(let c of o.docs)a.set(c.ref.path,c);await Promise.allSettled([...a.values()].map(async c=>{let l=c.data();this.isDeviceExpired(l,t);let u=l.online===true,p=this.toMillis(l.updatedAt)??this.toMillis(l.lastSeenAt)??0,f=this.rtdbPresence&&this.rtdbScope?3e4:3e5;if(!(!u||!p||p+f>t)){if(this.rtdbPresence&&this.rtdbScope){let h=typeof l.deviceId=="string"&&l.deviceId.trim()?l.deviceId.trim():c.id;if(P(s[h]))return}await updateDoc(c.ref,{online:false,updatedAt:serverTimestamp$1(),expiresAt:t+2592e6});}}));}async refreshDeviceForAutoConnect(e){let t=e.trim();if(!t)return null;let n=this.autoConnectRefreshes.get(t);if(n)return n;let r=this.refreshDeviceForAutoConnectOnce(t);this.autoConnectRefreshes.set(t,r);try{return await r}finally{this.autoConnectRefreshes.get(t)===r&&this.autoConnectRefreshes.delete(t);}}async refreshDeviceForAutoConnectOnce(e){if(this.rtdbPresence&&this.rtdbScope){let f=false,h=await this.readRtdbPresenceSnapshot().then(g=>g[e]).catch(g=>(f=true,console.warn("[BrowserDeviceDiscovery][auto-connect][refresh] RTDB read failed; refusing Firestore liveness fallback",{deviceId:e,error:g}),this.rtdbPresenceMap[e]));if(P(h)&&(h.ticket||h.nodeId)){let g=this.devicesById.get(e)??null,v=this.mergeRtdbPresenceIntoDevice(e,g,h)??this.deviceFromRtdbPresence(e,h);if(v){let S=this.upsertDeviceProjection(e,v);return R("[BrowserDeviceDiscovery][auto-connect][refresh]",{deviceId:e,source:"rtdb",ticketChanged:(g?.ticket??null)!==(v.ticket??null),previousTicket:G(g?.ticket),refreshedTicket:G(v.ticket),previousNodeId:g?.nodeId??null,refreshedNodeId:v.nodeId??null}),S&&this.emitDevicesToAll(),this.devicesById.get(e)??v}}if(f||!P(h))return null}let t=await this.hooks.getDevicesCollectionRef();if(!t)return this.devicesById.get(e)??null;let n=doc(t,e),r=this.devicesById.get(e)??null,s="server",o=null;try{o=await getDocFromServer(n);}catch(f){s="cache",console.warn("[BrowserDeviceDiscovery][auto-connect][refresh] getDocFromServer failed; falling back to getDoc",{deviceId:e,error:f}),o=await getDoc(n).catch(()=>null);}if(!o?.exists()){let f=this.devicesById.delete(e);return R("[BrowserDeviceDiscovery][auto-connect][refresh] device doc missing during refresh",{deviceId:e,source:s,previousTicket:G(r?.ticket)}),f&&this.emitDevicesToAll(),null}let a=typeof o.data=="function"?o.data():null,c=this.deviceFromSnapshot(e,a,Date.now());if(!c){let f=this.devicesById.delete(e);return R("[BrowserDeviceDiscovery][auto-connect][refresh] refreshed device doc was filtered out",{deviceId:e,source:s,previousTicket:G(r?.ticket)}),f&&this.emitDevicesToAll(),null}let l=this.rtdbPresenceMap[e],d=l?this.mergeRtdbPresenceIntoDevice(e,c,l)??c:c,u=this.upsertDeviceProjection(e,d),p=(r?.ticket??null)!==(d.ticket??null);return R("[BrowserDeviceDiscovery][auto-connect][refresh]",{deviceId:e,source:s,ticketChanged:p,previousTicket:G(r?.ticket),refreshedTicket:G(d.ticket),previousNodeId:r?.nodeId??null,refreshedNodeId:d.nodeId??null}),u&&this.emitDevicesToAll(),this.devicesById.get(e)??d}resolveKnownDeviceId(e){let t=e.trim();if(!t)return null;let n=this.devicesById.get(t);if(n?.deviceId)return n.deviceId;for(let r of this.devicesById.values())if(r.deviceId===t||r.nodeId===t||r.ticket===t)return r.deviceId;return null}stopDeviceWatch(e){this.deviceWatchGeneration+=1,this.deviceWatchSetup=null,this.clearFreshnessRecheckTimer(),this.activeDeviceUnsubscribe?.(),this.activeDeviceUnsubscribe=null,this.activeDeviceScopeKey=null,e?.clearDevices&&(this.devicesById.clear(),this.hasDeviceRosterSnapshot=false,this.emitDevicesToAll());}clearFreshnessRecheckTimer(){this.freshnessRecheckTimer&&(clearTimeout(this.freshnessRecheckTimer),this.freshnessRecheckTimer=null);}scheduleFreshnessRecheck(e){this.deviceListeners.size===0||this.freshnessRecheckTimer||(this.freshnessRecheckTimer=setTimeout(()=>{if(this.freshnessRecheckTimer=null,e!==this.deviceWatchGeneration||this.deviceListeners.size===0)return;let t=Date.now(),n=false;for(let[r,s]of this.devicesById){let o=s;if(this.isStaleOnlineDevice(o,t)){this.shouldRetainStaleDevice(o)?this.devicesById.set(r,this.retainedStaleDevice(s,r,t)):this.devicesById.delete(r),n=true;continue}this.isDeviceExpired(o,t)&&(this.devicesById.delete(r),n=true);}n&&this.emitDevicesToAll(),this.scheduleFreshnessRecheck(e);},K.DEVICE_FRESHNESS_RECHECK_MS));}emitDevicesToAll(){for(let e of this.deviceListeners.keys())this.emitDevicesToListener(e);}emitDevicesToListener(e){let t=this.deviceListeners.get(e);if(!t)return;let n=Array.from(this.devicesById.values()),r=t.excludeNodeId?this.filterDevices(n,t.excludeNodeId):n;t.callback(r);}filterDevices(e,t){return e.filter(n=>n.ticket!==t&&n.deviceId!==t&&n.nodeId!==t)}deviceProjectionKey(e){return JSON.stringify({deviceId:e.deviceId,deviceName:e.deviceName,online:e.online,ticket:e.ticket,nodeId:e.nodeId??null,userId:e.userId??null,metadata:e.metadata??null,capabilities:e.capabilities??null,excludedPeers:[...e.excludedPeers??[]].sort()})}upsertDeviceProjection(e,t){let n=this.devicesById.get(e);return n&&this.deviceProjectionKey(n)===this.deviceProjectionKey(t)?false:(this.devicesById.set(e,t),true)}watchedDeviceSnapshot(e){return this.activeDeviceScopeKey!==e||!this.hasDeviceRosterSnapshot||!this.activeDeviceUnsubscribe&&!this.deviceWatchSetup?null:Array.from(this.devicesById.values())}async readDurableRosterDocuments(e,t){let n=this.durableRosterRead;if(n?.scopeKey===t)return n.promise;let r=getDocs(query(e,limit(Be))).then(s=>s.docs);this.durableRosterRead={scopeKey:t,promise:r};try{return await r}finally{this.durableRosterRead?.promise===r&&(this.durableRosterRead=null);}}async readRtdbPresenceSnapshot(){if(!this.rtdbPresence||!this.rtdbScope)return {};if(this.rtdbUnsubscribe&&this.hasRtdbPresenceSnapshot)return this.rtdbPresenceMap;if(this.rtdbPresenceRead)return this.rtdbPresenceRead;let e=this.rtdbPresence,t=this.rtdbScope,n=e.readPresenceMap(t).then(r=>(this.rtdbPresence===e&&yt(this.rtdbScope,t)&&(this.rtdbPresenceMap=r,this.hasRtdbPresenceSnapshot=true),r));this.rtdbPresenceRead=n;try{return await n}finally{this.rtdbPresenceRead===n&&(this.rtdbPresenceRead=null);}}async readCurrentDeviceSnapshot(){let e=await this.hooks.getDevicesCollectionRef();if(!e)return [];let t=e.path,n=this.deviceWatchSetup;n?.scopeKey===t&&await n.promise;let r=this.watchedDeviceSnapshot(t);if(r)return r;let s=this.rtdbPresenceMap;if(this.rtdbPresence&&this.rtdbScope)try{s=await this.readRtdbPresenceSnapshot();}catch(d){console.warn("[BrowserDeviceDiscovery] RTDB direct presence read failed:",d);}let o=await this.readDurableRosterDocuments(e,t),a=Date.now(),c=[],l=new Set;for(let d of o){let u=d.data();if(!this.options.matchesTag(u))continue;let p=typeof u.deviceId=="string"&&u.deviceId.trim().length>0?u.deviceId.trim():d.id;if(l.add(p),this.isStaleFirestoreOnlyRtdbDevice(p,u,a))continue;if(this.isStaleOnlineDevice(u,a)||u.online===true&&this.isDeviceExpired(u,a)){if((!this.rtdbPresence||!this.rtdbScope)&&await this.markStaleDeviceOffline(d,u,a),this.shouldRetainStaleDevice(u)){let S=this.retainedStaleDevice(this.options.normalizeDevice({...u,deviceId:u.deviceId??d.id,online:false},d.id),d.id,a);S.deviceId&&c.push(S);}continue}if(this.isDeviceExpired(u,a))continue;let h=this.options.normalizeDevice({...u,deviceId:u.deviceId??d.id},d.id);if(!h?.deviceId)continue;let g=s[h.deviceId],v=g?this.mergeRtdbPresenceIntoDevice(h.deviceId,h,g):h;v&&c.push(v);}if(this.rtdbPresence&&this.rtdbScope)for(let[d,u]of Object.entries(s)){if(l.has(d)||!P(u))continue;let p=this.deviceFromRtdbPresence(d,u);p&&c.push(p);}this.devicesById.clear();for(let d of c)this.devicesById.set(d.deviceId,d);return this.hasDeviceRosterSnapshot=true,c}async readLiveRtdbDeviceSnapshot(){if(!this.rtdbPresence||!this.rtdbScope)return this.readCurrentDeviceSnapshot();let e;try{e=await this.readRtdbPresenceSnapshot();}catch(n){return console.warn("[BrowserDeviceDiscovery] RTDB live search read failed; refusing Firestore liveness fallback:",n),[]}let t=[];for(let[n,r]of Object.entries(e)){if(!P(r))continue;let s=this.devicesById.get(n),o=this.mergeRtdbPresenceIntoDevice(n,s,r)??this.deviceFromRtdbPresence(n,r);o?.deviceId&&(this.devicesById.set(o.deviceId,o),t.push(o));}return t}toDevice(e,t){return this.deviceFromSnapshot(e.id,e.data(),t,e)}deviceFromSnapshot(e,t,n,r){if(!t||!this.options.matchesTag(t))return null;let s=typeof t.deviceId=="string"&&t.deviceId.trim().length>0?t.deviceId.trim():e;if(this.isStaleFirestoreOnlyRtdbDevice(s,t,n))return null;if(this.isStaleOnlineDevice(t,n)||t.online===true&&this.isDeviceExpired(t,n)){if(r&&(!this.rtdbPresence||!this.rtdbScope)&&this.markStaleDeviceOffline(r,t,n),!this.shouldRetainStaleDevice(t))return null;let c=this.retainedStaleDevice(this.options.normalizeDevice({...t,deviceId:t.deviceId??e,online:false},e),e,n);return c.deviceId?c:null}if(this.isDeviceExpired(t,n))return null;let a=this.options.normalizeDevice({...t,deviceId:t.deviceId??e},e);return a.deviceId?a:null}shouldRetainStaleDevice(e){return this.options.discoveryMode!=="user-scoped"||this.rtdbPresence&&this.rtdbScope&&e.online===true?false:(typeof e.kind=="string"?e.kind.trim().toLowerCase():"device")!=="ephemeral"}retainedStaleDevice(e,t,n){let r=this.toMillis(e.lastSeenAt)??this.toMillis(e.updatedAt)??this.toMillis(e.createdAt)??n;return {...e,deviceId:e.deviceId||t,online:false,presenceStatus:"idle",presenceUpdatedAt:r,presenceExpiresAt:this.toMillis(e.expiresAt)??n+2592e6,connectable:false}}isStaleOnlineDevice(e,t){if(e.online!==true)return false;if(this.rtdbPresence&&this.rtdbScope){let s=typeof e.deviceId=="string"&&e.deviceId.trim().length>0?e.deviceId.trim():"";if(s&&P(this.rtdbPresenceMap[s]))return false}let n=this.toMillis(e.updatedAt)??this.toMillis(e.lastSeenAt)??this.toMillis(e.createdAt);if(typeof n!="number")return false;let r=this.rtdbPresence&&this.rtdbScope?3e4:3e5;return n+r<=t}isStaleFirestoreOnlyRtdbDevice(e,t,n){if(!this.rtdbPresence||!this.rtdbScope||t.online!==true||P(this.rtdbPresenceMap[e]))return false;let r=this.toMillis(t.updatedAt)??this.toMillis(t.lastSeenAt)??this.toMillis(t.createdAt);return typeof r!="number"?false:r+3e4<=n}async markStaleDeviceOffline(e,t,n){let r=typeof t.deviceId=="string"&&t.deviceId.trim().length>0?t.deviceId:e.id,s=e.ref?.path||r;if(!(!s||this.staleDeviceOfflineWrites.has(s))){this.staleDeviceOfflineWrites.add(s);try{let o=await this.hooks.resolveDeviceRef(r);if(!o)return;await updateDoc(o,{online:!1,updatedAt:serverTimestamp$1(),expiresAt:n+2592e6});}catch(o){console.warn("[BrowserDeviceDiscovery] failed to mark stale device offline:",o);}finally{this.staleDeviceOfflineWrites.delete(s);}}}isDeviceExpired(e,t){let n=this.toMillis(e.expiresAt);if(typeof n=="number")return n<=t;let r=e.online===true?3e5:2592e6,s=this.toMillis(e.updatedAt);if(typeof s=="number")return s+r<=t;let o=this.toMillis(e.lastSeenAt);return typeof o=="number"?o+r<=t:false}toMillis(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let t=Date.parse(e);return Number.isNaN(t)?void 0:t}if(e instanceof Date)return e.getTime();if(e&&typeof e=="object"&&typeof e.toMillis=="function")return e.toMillis()}async ensureDeviceWatch(){if(this.deviceListeners.size===0)return;let e=await this.hooks.getDevicesCollectionRef(),t=e?.path??null;if(!e||!t){this.devicesById.clear(),this.emitDevicesToAll();return}if(this.activeDeviceUnsubscribe&&this.activeDeviceScopeKey===t)return;let n=this.deviceWatchSetup;if(n?.scopeKey===t)return n.promise;if(this.stopDeviceWatch({clearDevices:true}),this.rtdbPresence&&this.rtdbScope){let r=this.ensureDeviceWatchRtdb(e,t);this.deviceWatchSetup={scopeKey:t,promise:r};try{await r;}finally{this.deviceWatchSetup?.promise===r&&(this.deviceWatchSetup=null);}return}this.startFirestoreDeviceWatch(e,t);}startFirestoreDeviceWatch(e,t){let n=++this.deviceWatchGeneration;this.activeDeviceScopeKey=t,this.activeDeviceUnsubscribe=onSnapshot(query(e,limit(Be)),r=>{if(n!==this.deviceWatchGeneration)return;let s=Date.now();this.devicesById.clear();for(let o of r.docs){let a=this.toDevice(o,s);a&&this.devicesById.set(a.deviceId,a);}this.hasDeviceRosterSnapshot=true,this.emitDevicesToAll(),this.scheduleFreshnessRecheck(n);},r=>{if(n!==this.deviceWatchGeneration)return;let s=r?.code,o=String(r?.message??"");if((s==="permission-denied"||s==="PERMISSION_DENIED"||/permission.?denied/i.test(o)||/missing or insufficient permissions/i.test(o))&&!this.options.auth.currentUser){console.warn("[BrowserDeviceDiscovery] device watch permission-denied before auth; retrying after auth establishes"),this.stopDeviceWatch({clearDevices:false}),setTimeout(()=>{n===this.deviceWatchGeneration&&this.options.auth.currentUser&&this.ensureDeviceWatch();},500);return}console.warn("[BrowserDeviceDiscovery] device watch failed:",r);});}async ensureDeviceWatchRtdb(e,t){let n=++this.deviceWatchGeneration;this.activeDeviceScopeKey=t;let r=null,s=null;for(let l=0;l<3;l+=1)try{r=await E$1(this.readDurableRosterDocuments(e,t),K.RTDB_ROSTER_READ_TIMEOUT_MS,()=>new Error("RTDB-backed device roster read timed out")),s=null;break}catch(d){if(s=d,n!==this.deviceWatchGeneration)return;await u(x(l+1,250,Number.MAX_SAFE_INTEGER));}if(!r)throw new Error(`[BrowserDeviceDiscovery] RTDB-backed device watch setup failed after retries: ${s instanceof Error?s.message:String(s)}`);if(n!==this.deviceWatchGeneration)return;let o=Date.now();this.devicesById.clear(),this.replaceDevicesFromDocuments(r,o),this.hasDeviceRosterSnapshot=true;let a=this.rtdbPresence,c=this.rtdbScope;this.rtdbUnsubscribe&&this.rtdbUnsubscribe();try{this.rtdbUnsubscribe=a.onPresenceChange(c,l=>{if(n!==this.deviceWatchGeneration)return;R("[BrowserDeviceDiscovery][rtdb] presence update",{generation:n,devices:Object.keys(l).length,online:Object.values(l).filter(u=>P(u)).length}),this.rtdbPresenceMap=l,this.hasRtdbPresenceSnapshot=!0;let d=[];for(let[u,p]of Object.entries(l)){let f=this.knownTicketVersions.get(u)??-1,h=this.devicesById.has(u),g=!!(p.ticket||p.nodeId);p.ticketVersion!==f?(this.knownTicketVersions.set(u,p.ticketVersion),!g&&(f!==-1||!h&&P(p))&&d.push(u)):!g&&!h&&P(p)&&d.push(u);}this.applyRtdbOverlay(),this.scheduleFreshnessRecheck(n),d.length>0&&this.refetchDeviceTickets(d,n);});}catch(l){if(n!==this.deviceWatchGeneration)return;throw new Error(`[BrowserDeviceDiscovery] RTDB presence subscription setup failed; refusing Firestore-only liveness fallback: ${l instanceof Error?l.message:String(l)}`)}this.activeDeviceUnsubscribe=()=>{this.rtdbUnsubscribe?.(),this.rtdbUnsubscribe=null;},this.emitDevicesToAll(),this.scheduleFreshnessRecheck(n);}replaceDevicesFromDocuments(e,t){this.devicesById.clear();for(let n of e){let r=this.toDevice(n,t);r&&this.devicesById.set(r.deviceId,r);}}applyRtdbOverlay(){let e=false;for(let[t,n]of this.devicesById){let r=this.rtdbPresenceMap[t];if(!r)continue;let s=this.mergeRtdbPresenceIntoDevice(t,n,r);s&&(e=this.upsertDeviceProjection(t,s)||e);}for(let[t,n]of Object.entries(this.rtdbPresenceMap)){if(this.devicesById.has(t)||!P(n))continue;let r=this.deviceFromRtdbPresence(t,n);r&&(e=this.upsertDeviceProjection(t,r)||e);}e&&this.emitDevicesToAll();}mergeRtdbPresenceIntoDevice(e,t,n){if(!n)return t??null;let r=P(n),s={...t??{},appTag:this.options.appTag,tag:this.options.appTag,deviceId:e,deviceName:n.deviceName??t?.deviceName??"Device",online:r,ticket:n.ticket??t?.ticket??"",nodeId:n.nodeId??t?.nodeId,platformType:n.platformType??t?.platformType,metadata:n.metadata??t?.metadata,excludedPeers:n.excludedPeers??t?.excludedPeers,userId:t?.userId??this.options.getCurrentUserId()??void 0,updatedAt:Date.now(),lastSeenAt:Date.now()};if(!this.options.matchesTag(s))return null;let o=this.options.normalizeDevice(s,e);return o.deviceId?{...t??o,...o,online:r,ticket:n.ticket??o.ticket??t?.ticket??"",nodeId:n.nodeId??o.nodeId??t?.nodeId,deviceName:n.deviceName??o.deviceName??t?.deviceName??"Device",platformType:n.platformType??o.platformType??t?.platformType,metadata:n.metadata??o.metadata??t?.metadata,excludedPeers:n.excludedPeers??o.excludedPeers??t?.excludedPeers}:null}deviceFromRtdbPresence(e,t){if(!t.ticket&&!t.nodeId)return null;let n={appTag:this.options.appTag,tag:this.options.appTag,deviceId:e,deviceName:t.deviceName||"Device",online:P(t),ticket:t.ticket||"",nodeId:t.nodeId,platformType:t.platformType,metadata:t.metadata,excludedPeers:t.excludedPeers,userId:this.options.getCurrentUserId()??void 0,updatedAt:Date.now(),lastSeenAt:Date.now()};if(!this.options.matchesTag(n))return null;let r=this.options.normalizeDevice(n,e);return r.deviceId?r:null}async refetchDeviceTickets(e,t){await Promise.allSettled(e.map(async n=>{try{if(await this.refreshDeviceForAutoConnect(n),t!==this.deviceWatchGeneration)return}catch(r){console.warn("[BrowserDeviceDiscovery] refetch device ticket failed:",r);}}));}};K.RTDB_ROSTER_READ_TIMEOUT_MS=5e3,K.DEVICE_FRESHNESS_RECHECK_MS=3e4;var he=K;var ge=class{constructor(e){this.ctx=e;this.friendDeviceUnsubscribes=new Map;this.firestore=getFirestore(e.app);}watchFriendDevices(e,t){if(this.usesSpaceMode())return ()=>{};let n=new Map,r=new Set(e);for(let[s,o]of this.friendDeviceUnsubscribes)r.has(s)||(o(),this.friendDeviceUnsubscribes.delete(s),n.delete(s));for(let s of e){if(this.friendDeviceUnsubscribes.has(s))continue;let o=`apps/${this.ctx.appTag}/users/${s}/devices`,a=collection(this.firestore,o),c=onSnapshot(a,l=>{let d=[];l.forEach(u=>{let p=u.data();if(!p||p.kind!=="device"||!this.ctx.matchesTag(p))return;let f=this.ctx.normalizeDevice(p,u.id);f.online&&d.push(f);}),n.set(s,d),t(new Map(n));},l=>{console.warn("[BrowserFriendDiscovery] friend device watch failed:",{friendUid:s,message:l?.message,code:l?.code});});this.friendDeviceUnsubscribes.set(s,c);}return ()=>{for(let[,s]of this.friendDeviceUnsubscribes)s();this.friendDeviceUnsubscribes.clear();}}async updateFriendTicket(e){let t=await this.ctx.resolveOrCreateLocalDeviceRef();t&&await updateDoc(t,{friendTicket:e??null});}usesSpaceMode(){return this.ctx.usesSpaceMode?this.ctx.usesSpaceMode():(this.ctx.discoveryMode??"space")==="space"&&typeof this.ctx.apiKey=="string"&&this.ctx.apiKey.trim().length>0&&typeof this.ctx.spaceKey=="string"&&this.ctx.spaceKey.trim().length>0}};var Mn="createSignalingSession",bt=50,ve=class{constructor(e){this.ctx=e;}async createSession(e){if(this.shouldUseHostedSessionCallable()){await this.createHostedSession(e);return}let t=await this.ctx.getSessionsCollectionRef();if(!t)throw new Error("createSession requires an active browser signaling namespace");let n=doc(t,e.connectionId),r=Date.now(),s=600*1e3;await setDoc(n,{appTag:e.appTag??this.ctx.appTag,connectionId:e.connectionId,initiator:e.initiator??this.ctx.getCurrentUserId(),target:e.target??this.ctx.getCurrentUserId(),initiatorDeviceId:e.initiatorDeviceId,targetDeviceId:e.targetDeviceId,connectionType:e.connectionType??null,state:e.state,offer:e.offer?JSON.stringify(e.offer):null,offerE2ee:e.offerE2ee?JSON.stringify(e.offerE2ee):null,answer:e.answer?JSON.stringify(e.answer):null,answerE2ee:e.answerE2ee?JSON.stringify(e.answerE2ee):null,iceCandidates:Array.isArray(e.iceCandidates)?JSON.stringify(e.iceCandidates):null,initiatorNodeId:e.initiatorNodeId??null,targetNodeId:e.targetNodeId??null,initiatorEndpointAddr:e.initiatorEndpointAddr??null,targetEndpointAddr:e.targetEndpointAddr??null,intent:e.intent??null,createdAt:e.createdAt??r,updatedAt:r,expiresAt:r+s},{merge:true});}async updateSession(e,t){let n=await this.ctx.getSessionsCollectionRef();if(!n)throw new Error("updateSession requires an active browser signaling namespace");let r=doc(n,this.ctx.parseScopedId(e)),s={};if(t&&typeof t=="object"){for(let[o,a]of Object.entries(t))if(a!==void 0){if(a===null||typeof a=="string"||typeof a=="number"||typeof a=="boolean"){s[o]=a;continue}s[o]=JSON.stringify(a);}}Object.keys(s).length!==0&&(s.updatedAt=Date.now(),await updateDoc(r,s));}async sendMessage(e,t,n,r){let s=await this.ctx.getMessagesCollectionRef();if(!s)throw new Error("sendMessage requires an active browser signaling namespace");let o=this.createDocumentId(),a=doc(s,o),c=this.ctx.getCurrentUserId()??this.ctx.getLocalDeviceId(),l=this.ctx.getCurrentUserId();if(!l&&(this.ctx.discoveryMode??"space")!=="space")throw new Error("sendMessage requires an authenticated user in app-scoped signaling mode");let d=Date.now(),u=1440*60*1e3,p={appTag:this.ctx.appTag,senderId:c,targetId:e,payload:t,state:n??null,replyPayload:r??null,timestamp:d,expiresAt:d+u};return l&&(p.senderUserId=l,p.targetUserId=l),await setDoc(a,p),a.path}async pollMessages(e){let t=await this.ctx.getMessagesCollectionRef();if(!t)return [];let n=this.ctx.getCurrentUserId();if(!n&&(this.ctx.discoveryMode??"space")!=="space")return [];let r=n?[where("targetId","==",e),where("targetUserId","==",n),limit(50)]:[where("targetId","==",e),limit(50)],s=await getDocs(query(t,...r)),o=[];for(let a of s.docs){let c=a.data(),l=typeof c.senderId=="string"?c.senderId:"",d=typeof c.targetId=="string"?c.targetId:"",u=typeof c.payload=="string"?c.payload:"";!l||!d||!u||o.push({appTag:typeof c.appTag=="string"?c.appTag:this.ctx.appTag,senderId:l,targetId:d,senderUserId:typeof c.senderUserId=="string"?c.senderUserId:void 0,targetUserId:typeof c.targetUserId=="string"?c.targetUserId:void 0,payload:u,state:typeof c.state=="string"?c.state:void 0,replyPayload:typeof c.replyPayload=="string"?c.replyPayload:void 0,timestamp:this.ctx.toMillis(c.timestamp),expiresAt:this.ctx.toMillis(c.expiresAt),_documentId:a.id});}return o.sort((a,c)=>(a.timestamp??0)-(c.timestamp??0)),await Promise.allSettled(o.map(async a=>{await deleteDoc(doc(t,a._documentId));})),o.map(({_documentId:a,...c})=>c)}async subscribeSessions(e){let t=await this.ctx.getSessionsCollectionRef(),n=this.ctx.parseScopedId(e);if(!t||!n)return new ReadableStream({start(a){a.close();}});let r=null,s=null,o=false;return new ReadableStream({start:a=>{let c={initiator:new Set,target:new Set},l=new Map,d=(u,p)=>{if(o)return;let f=[];for(let h of p.docChanges()){let g=h.doc.id;if(h.type==="removed"){c[u].delete(g),!(c.initiator.has(g)||c.target.has(g))&&l.delete(g)&&f.push({type:"removed",sessionId:g});continue}let v=this.toSession(h.doc.id,h.doc.data());if(!v)continue;c[u].add(g);let S=l.has(g);l.set(g,v),f.push({type:S?"modified":"added",session:v});}f.length>0&&a.enqueue(f);};r=onSnapshot(query(t,where("initiatorDeviceId","==",n),limit(bt)),u=>d("initiator",u),u=>{o||a.error(u);}),s=onSnapshot(query(t,where("targetDeviceId","==",n),limit(bt)),u=>d("target",u),u=>{o||a.error(u);});},cancel:()=>{o=true,r?.(),s?.(),r=null,s=null;}})}shouldUseHostedSessionCallable(){return (this.ctx.discoveryMode??"space")!=="space"&&!!this.ctx.getCurrentUserId()}async createHostedSession(e){await httpsCallable(getFunctions(this.ctx.app),Mn)({...e,appTag:e.appTag??this.ctx.appTag,initiator:e.initiator??this.ctx.getCurrentUserId()??void 0,target:e.target??this.ctx.getCurrentUserId()??void 0});}toSession(e,t){let n=typeof t.initiatorDeviceId=="string"?t.initiatorDeviceId:"",r=typeof t.targetDeviceId=="string"?t.targetDeviceId:"";return !n&&!r?null:{connectionId:typeof t.connectionId=="string"?t.connectionId:e,initiator:typeof t.initiator=="string"?t.initiator:"",target:typeof t.target=="string"?t.target:"",initiatorDeviceId:n,targetDeviceId:r,connectionType:typeof t.connectionType=="string"?t.connectionType:void 0,offer:this.parseMaybeJson(t.offer),offerE2ee:this.parseMaybeJson(t.offerE2ee),answer:this.parseMaybeJson(t.answer),answerE2ee:this.parseMaybeJson(t.answerE2ee),iceCandidates:Array.isArray(t.iceCandidates)?t.iceCandidates:[],initiatorNodeId:typeof t.initiatorNodeId=="string"?t.initiatorNodeId:void 0,targetNodeId:typeof t.targetNodeId=="string"?t.targetNodeId:void 0,initiatorEndpointAddr:typeof t.initiatorEndpointAddr=="string"?t.initiatorEndpointAddr:void 0,targetEndpointAddr:typeof t.targetEndpointAddr=="string"?t.targetEndpointAddr:void 0,intent:typeof t.intent=="string"?t.intent:void 0,appTag:typeof t.appTag=="string"?t.appTag:this.ctx.appTag,createdAt:this.ctx.toMillis(t.createdAt),expiresAt:this.ctx.toMillis(t.expiresAt),state:typeof t.state=="string"?t.state:""}}parseMaybeJson(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}createDocumentId(){return `${Date.now()}-${Math.random().toString(36).slice(2,10)}`}};function Bn(i){return typeof i=="object"&&i!==null&&"code"in i&&i.code==="not-found"}var Se=class{constructor(e){this.options=e;this.rtdbPresence=null;this.namespaceRootPromise=null;this.resolvedDeviceDocIds=new Map;this.firestore=getFirestore(e.app);try{let t=globalThis?.__OPENRTC_FIRESTORE_EMULATOR_HOST__,n=typeof t=="string"?t.trim():"";if(n){let[r,s]=n.split(":"),o=(r??"").trim()||"127.0.0.1",a=Number(s??8082);try{connectFirestoreEmulator(this.firestore,o,a);}catch{}}else {let r=import.meta?.env;if(!!r?.DEV&&String(r?.VITE_USE_EMULATORS)==="true"){let o=String(r?.VITE_OPENRTC_EMULATOR_HOST??"127.0.0.1").trim()||"127.0.0.1",a=Number(r?.VITE_OPENRTC_FIRESTORE_EMULATOR_PORT??8082);try{connectFirestoreEmulator(this.firestore,o,a);}catch{}}}}catch{}this.discovery=new he({options:this.options,firestore:this.firestore,getDevicesCollectionRef:()=>this.getDevicesCollectionRef(),resolveDeviceRef:t=>this.resolveDeviceRef(t)}),this.friendDiscovery=new ge({app:e.app,appTag:e.appTag,discoveryMode:e.discoveryMode,apiKey:e.apiKey,spaceKey:e.spaceKey,matchesTag:e.matchesTag,normalizeDevice:e.normalizeDevice,resolveOrCreateLocalDeviceRef:()=>this.resolveOrCreateLocalDeviceRef(),usesSpaceMode:()=>this.usesSpaceMode()}),this.sessionSignaling=new ve({app:e.app,appTag:e.appTag,discoveryMode:e.discoveryMode,getCurrentUserId:()=>e.getCurrentUserId(),getLocalDeviceId:()=>e.getLocalDeviceId(),getSessionsCollectionRef:()=>this.getSessionsCollectionRef(),getMessagesCollectionRef:()=>this.getMessagesCollectionRef(),parseScopedId:t=>this.parseScopedId(t),toMillis:t=>this.toMillis(t)});}setRtdbPresence(e,t){this.rtdbPresence=e,this.discovery.setRtdbPresence(e,t);}getRtdbPresence(){return this.rtdbPresence}stopRtdbPresence(){this.rtdbPresence=null,this.discovery.stopRtdbPresence();}searchDevices(e){return this.discovery.searchDevices(e)}listDevices(e){return this.discovery.listDevices(e)}subscribeDevices(){return this.discovery.subscribeDevices()}onDevicesChange(e,t){return this.discovery.onDevicesChange(e,t)}async handleScopeChange(){await this.discovery.handleScopeChange();}stopAuthScopedActivity(){this.discovery.stopAuthScopedActivity();}async updatePresence(e,t,n,r,s,o){let a=await this.resolveOrCreateLocalDeviceRef();if(!a)return;let c=this.options.getLocalDeviceId(),l=Date.now(),d=o?.trim()||this.options.getDefaultDeviceName(),u=this.options.getCurrentUserId(),p=n?l+Math.max(0,Math.trunc(r)):l+2592e6,f=await getDoc(a).catch(()=>null),h={appTag:this.options.appTag,tag:this.options.appTag,kind:"device",deviceId:c,deviceName:d,nodeId:e,platformType:"web",online:n,ticket:t,metadata:s??null,capabilities:{canHost:false,canSync:false,readOnly:false},lastSeenAt:serverTimestamp$1(),updatedAt:serverTimestamp$1(),expiresAt:p};u&&(h.userId=u),f?.exists()||(h.createdAt=serverTimestamp$1()),await setDoc(a,h,{merge:true});}async setOffline(e){let t=await this.resolveOrCreateLocalDeviceRef();if(!t)return;let n={appTag:this.options.appTag,tag:this.options.appTag,kind:"device",deviceId:this.options.getLocalDeviceId(),deviceName:this.options.getDefaultDeviceName(),nodeId:e,platformType:"web",online:false,updatedAt:serverTimestamp$1(),lastSeenAt:serverTimestamp$1(),expiresAt:Date.now()+2592e6},r=this.options.getCurrentUserId();r&&(n.userId=r);try{await updateDoc(t,n);}catch(s){if(!Bn(s))throw s}}async cleanupStaleDevices(){await this.discovery.cleanupStaleDevices();}async updateDevice(e,t){let n=await this.resolveDeviceRef(e);if(!n)throw new Error("updateDevice requires a known device record");let r={updatedAt:serverTimestamp$1()};typeof t.deviceName=="string"&&(r.deviceName=t.deviceName),t.capabilities&&(r.capabilities={canHost:t.capabilities.canHost??t.capabilities.can_host??false,canSync:t.capabilities.canSync??t.capabilities.can_sync??false,readOnly:t.capabilities.readOnly??t.capabilities.read_only??false}),typeof t.metadata=="string"&&(r.metadata=t.metadata),await updateDoc(n,r);}async deleteDevice(e){let t=await this.resolveDeviceRef(e);t&&await deleteDoc(t);}async createSession(e){await this.sessionSignaling.createSession(e);}async updateSession(e,t){await this.sessionSignaling.updateSession(e,t);}async sendMessage(e,t,n,r){return this.sessionSignaling.sendMessage(e,t,n,r)}async pollMessages(e){return this.sessionSignaling.pollMessages(e)}async subscribeSessions(e){return this.sessionSignaling.subscribeSessions(e)}refreshDeviceForAutoConnect(e){return this.discovery.refreshDeviceForAutoConnect(e)}toMillis(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let t=Date.parse(e);return Number.isNaN(t)?void 0:t}if(e instanceof Date)return e.getTime();if(e&&typeof e=="object"&&typeof e.toMillis=="function")return e.toMillis()}async getDevicesCollectionRef(){let e=await this.getDevicesCollectionPath();return e?collection(this.firestore,e):null}async getSessionsCollectionRef(){let e=await this.getNamespaceRoot();return e?collection(this.firestore,`${e}/sessions`):null}async getMessagesCollectionRef(){let e=await this.getNamespaceRoot();return e?collection(this.firestore,`${e}/messages`):null}async getDevicesCollectionPath(){let e=await this.getNamespaceRoot();if(!e)return null;if(this.usesSpaceMode())return `${e}/devices`;let t=this.options.getDiscoveryScopeId();return t?`${e}/users/${t}/devices`:null}async getNamespaceRoot(){if(this.usesSpaceMode()){if(!this.namespaceRootPromise){let e=this.options.apiKey?.trim()??"",t=this.options.spaceKey?.trim()??"";this.namespaceRootPromise=a(e,t).then(n=>`spaces/${n}`);}return this.namespaceRootPromise}return `apps/${this.options.appTag}`}usesSpaceMode(){return (this.options.discoveryMode??"space")==="space"&&typeof this.options.apiKey=="string"&&this.options.apiKey.trim().length>0&&typeof this.options.spaceKey=="string"&&this.options.spaceKey.trim().length>0}parseScopedId(e){let t=e.split("::");return t.length===2?t[1]:e}async resolveOrCreateLocalDeviceRef(){let e=await this.getDevicesCollectionRef();return e?doc(e,this.options.getLocalDeviceId()):null}async resolveDeviceRef(e){let t=await this.getDevicesCollectionRef();if(!t)return null;let n=e.trim();if(!n)return null;let r=this.resolvedDeviceDocIds.get(n);if(r)return doc(t,r);let s=this.discovery.resolveKnownDeviceId(n);if(s)return this.resolvedDeviceDocIds.set(n,s),doc(t,s);let o=doc(t,n);if((await getDoc(o)).exists())return this.resolvedDeviceDocIds.set(n,n),o;let a=await getDocs(query(t,where("deviceId","==",n),limit(1)));if(!a.empty){let l=a.docs[0].id;return this.resolvedDeviceDocIds.set(n,l),a.docs[0].ref}let c=await getDocs(query(t,where("nodeId","==",n),limit(1)));if(!c.empty){let l=c.docs[0].id;return this.resolvedDeviceDocIds.set(n,l),c.docs[0].ref}return null}watchFriendDevices(e,t){return this.friendDiscovery.watchFriendDevices(e,t)}updateFriendTicket(e){return this.friendDiscovery.updateFriendTicket(e)}};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.queuedDesiredPeers=null;this.desiredPeersByDeviceId=new Map;this.wakeSubmission=null;this.presenceState=null;this.presenceStartGeneration=0;this.rtdbPresenceRetryTimer=null;this.rtdbPresenceRetryAttempt=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 n=t.trim()||this.deps.resolveWebLogicalDeviceId(),r=`${e}::${n}`;this.startedAutoConnectKey===r&&this.browserAutoConnectUnsubscribe||(this.stopAutoConnect(),this.startedAutoConnectKey=r,this.browserAutoConnectUnsubscribe=this.deps.getBrowserFirestoreSignaling().onDevicesChange(s=>this.submitDesiredPeers(s),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=e.map(r=>({deviceId:String(r.deviceId??"").trim(),nodeId:typeof r.nodeId=="string"&&r.nodeId.trim()||null,ticket:typeof r.ticket=="string"&&r.ticket.trim()||null,online:r.online===true,sessionId:typeof r.sessionId=="string"&&r.sessionId.trim()||null,excludedPeers:Array.isArray(r.excludedPeers)?[...new Set(r.excludedPeers.map(s=>String(s??"").trim().toLowerCase()).filter(Boolean))].sort():[]})).filter(r=>r.deviceId.length>0).sort((r,s)=>r.deviceId.localeCompare(s.deviceId));this.desiredPeersByDeviceId=new Map(t.map(r=>[r.deviceId,r]));let n=JSON.stringify(t);n!==this.desiredPeerSignature&&(this.desiredPeerSignature=n,this.deps.onDesiredPeersChanged?.(),this.queuedDesiredPeers=t,this.flushDesiredPeerSubmission());}resolveDesiredPeer(e,t){let n=typeof e=="string"?e.trim():"",r=typeof t=="string"?t.trim():"";if(n){let s=this.desiredPeersByDeviceId.get(n);if(s&&(!r||!s.nodeId||s.nodeId===r))return s}return r?Array.from(this.desiredPeersByDeviceId.values()).find(s=>s.nodeId===r)??null:null}flushDesiredPeerSubmission(){if(this.desiredPeerSubmission||!this.queuedDesiredPeers||!this.startedAutoConnectKey)return;let e=this.startedAutoConnectKey,t=this.queuedDesiredPeers,n=++this.desiredPeerRevision;this.queuedDesiredPeers=null,this.desiredPeerSubmission=this.deps.waitForWasmClient().then(async r=>{if(this.startedAutoConnectKey===e){if(!r||typeof r.submit_browser_desired_peers!="function"){this.deps.warnMissingWasmOnce("submitBrowserDesiredPeers");return}await Promise.all(t.map(async s=>{if(s.ticket)try{await this.deps.rememberRouteRepairTokenFromTicket(s.ticket);}catch(o){console.warn("[WasmSignaling] failed to retain desired-peer admission token",{deviceId:s.deviceId,nodeId:s.nodeId,error:o});}})),await r.submit_browser_desired_peers(n,JSON.stringify(t));}}).catch(r=>{console.warn("[WasmSignaling] failed to submit browser desired peers to Rust",{revision:n,error:r});}).finally(()=>{this.desiredPeerSubmission=null,this.flushDesiredPeerSubmission();});}async setAutoConnectExcluded(e,t){let n=await this.deps.waitForWasmClient();n&&typeof n.set_auto_connect_excluded=="function"&&await n.set_auto_connect_excluded(e,t),await this.recordAutoConnectExcludedForPresence(e,t);}async recordAutoConnectExcludedForPresence(e,t){let n=e.trim().toLowerCase();n&&(t?this.localExcludedPeers.add(n):this.localExcludedPeers.delete(n),await this.republishRtdbPresence("excluded-peers-updated"));}startPresenceLoop(e,t,n,r,s){if(this.deps.isTicketOnlyMode())return;this.stopPresenceLoop();let o=++this.presenceStartGeneration;this.presenceState={userId:e,localNodeId:t,ticket:r,metadata:s,deviceName:n};let a=this.deps.resolveWebLogicalDeviceId(),c=async l=>{let d=await this.deps.withWebPresenceMetadata(s,a),u=()=>o===this.presenceStartGeneration&&this.presenceState!==null;if(!u())return;if(!this.deps.isRtdbPresenceDisabledForSession()&&l&&a){let f=false,h=false,g=null,v=null,S=(I,w)=>{this.scheduleDurableRosterRetry(a,o,10080*60*1e3,I,w);},D=(I,w)=>{u()&&(this.deps.isRtdbPresenceDisabledForSession()||this.scheduleRtdbPresenceRetry(l,a,o,I,w));};g=setTimeout(()=>{f||S("initial durable roster write timed out");},T.INITIAL_PRESENCE_WRITE_TIMEOUT_MS),v=setTimeout(()=>{h||D("RTDB presence register timed out");},T.RTDB_PRESENCE_REGISTER_TIMEOUT_MS),this.deps.updatePresence(t,r,false,10080*60*1e3,d,n).then(()=>{f=true,g&&(clearTimeout(g),g=null),this.clearDurablePresenceRetryTimer(),this.durablePresenceRetryAttempt=0;}).catch(I=>{g&&(clearTimeout(g),g=null),S("initial durable roster write failed",I);}),this.deps.registerRtdbPresence(l,a,this.deps.getRtdbTicketVersion(),{ticket:r,nodeId:t,deviceName:n,platformType:"web",metadata:d,excludedPeers:this.currentExcludedPeersSnapshot()}).then(()=>{h=true,this.rtdbPresenceRetryAttempt=0,this.clearRtdbPresenceRetryTimer(),v&&(clearTimeout(v),v=null);}).catch(I=>{v&&(clearTimeout(v),v=null),D("RTDB presence register failed",I);});return}let p=Y.browserIdentity.ephemeralDeviceIdTtlMs;this.deps.updatePresence(t,r,false,p,d,n).then(()=>{this.clearDurablePresenceRetryTimer(),this.durablePresenceRetryAttempt=0;}).catch(f=>{this.scheduleDurableRosterRetry(a,o,p,"durable roster write failed without RTDB presence",f);});};if(this.deps.resolveRtdbScope){this.deps.resolveRtdbScope(e).then(l=>c(l));return}c(this.deps.buildRtdbScope(e));}clearDurablePresenceRetryTimer(){this.durablePresenceRetryTimer&&(clearTimeout(this.durablePresenceRetryTimer),this.durablePresenceRetryTimer=null);}scheduleDurableRosterRetry(e,t,n,r,s){if(t!==this.presenceStartGeneration||this.presenceState===null||this.durablePresenceRetryTimer)return;let o=this.durablePresenceRetryAttempt+1;this.durablePresenceRetryAttempt=o;let a=Math.min(T.RTDB_PRESENCE_RETRY_MIN_DELAY_MS*2**Math.min(8,o-1),T.RTDB_PRESENCE_RETRY_MAX_DELAY_MS),c=(o*17%21-10)/100,l=Math.max(T.RTDB_PRESENCE_RETRY_MIN_DELAY_MS,Math.trunc(a+a*c));console.warn(`[WasmBridge] ${r}; retrying durable roster registration in ${l}ms without Firestore heartbeat`,s),this.durablePresenceRetryTimer=setTimeout(()=>{this.durablePresenceRetryTimer=null,!(t!==this.presenceStartGeneration||this.presenceState===null)&&(async()=>{if(this.presenceState===null)return;let d=await this.deps.withWebPresenceMetadata(this.presenceState.metadata,e);t!==this.presenceStartGeneration||this.presenceState===null||await this.deps.updatePresence(this.presenceState.localNodeId,this.presenceState.ticket,false,n,d,this.presenceState.deviceName);})().then(()=>{this.durablePresenceRetryAttempt=0,this.clearDurablePresenceRetryTimer();}).catch(d=>{this.scheduleDurableRosterRetry(e,t,n,"durable roster registration retry failed",d);});},l);}clearRtdbPresenceRetryTimer(){this.rtdbPresenceRetryTimer&&(clearTimeout(this.rtdbPresenceRetryTimer),this.rtdbPresenceRetryTimer=null);}scheduleRtdbPresenceRetry(e,t,n,r,s){if(n!==this.presenceStartGeneration||this.presenceState===null||this.rtdbPresenceRetryTimer||this.deps.isRtdbPresenceDisabledForSession())return;let o=this.rtdbPresenceRetryAttempt+1;this.rtdbPresenceRetryAttempt=o;let a=Math.min(T.RTDB_PRESENCE_RETRY_MIN_DELAY_MS*2**Math.min(8,o-1),T.RTDB_PRESENCE_RETRY_MAX_DELAY_MS),c=(o*29%21-10)/100,l=Math.max(T.RTDB_PRESENCE_RETRY_MIN_DELAY_MS,Math.trunc(a+a*c));console.warn(`[WasmBridge] ${r}; retrying RTDB presence in ${l}ms without Firestore heartbeat fallback`,s),this.rtdbPresenceRetryTimer=setTimeout(()=>{this.rtdbPresenceRetryTimer=null,!(n!==this.presenceStartGeneration||this.presenceState===null||this.deps.isRtdbPresenceDisabledForSession())&&(async()=>{if(this.presenceState===null)return;let d=await this.deps.withWebPresenceMetadata(this.presenceState.metadata,t);n!==this.presenceStartGeneration||this.presenceState===null||this.deps.isRtdbPresenceDisabledForSession()||await this.deps.registerRtdbPresence(e,t,this.deps.getRtdbTicketVersion(),{ticket:this.presenceState.ticket,nodeId:this.presenceState.localNodeId,deviceName:this.presenceState.deviceName,platformType:"web",metadata:d,excludedPeers:this.currentExcludedPeersSnapshot()});})().then(()=>{this.rtdbPresenceRetryAttempt=0;}).catch(d=>{this.scheduleRtdbPresenceRetry(e,t,n,"RTDB presence retry failed",d);});},l);}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}async republishRtdbPresence(e){let t=this.presenceState;if(!t||this.deps.isRtdbPresenceDisabledForSession())return;let n=this.deps.resolveWebLogicalDeviceId();if(!n)return;let r=this.deps.resolveRtdbScope?await this.deps.resolveRtdbScope(t.userId):this.deps.buildRtdbScope(t.userId);if(!r)return;let s=await this.deps.withWebPresenceMetadata(t.metadata,n);await this.deps.registerRtdbPresence(r,n,this.deps.getRtdbTicketVersion(),{ticket:t.ticket,nodeId:t.localNodeId,deviceName:t.deviceName,platformType:"web",metadata:s,excludedPeers:this.currentExcludedPeersSnapshot()});}stopPresenceLoop(){this.presenceStartGeneration+=1,this.clearRtdbPresenceRetryTimer(),this.rtdbPresenceRetryAttempt=0,this.clearDurablePresenceRetryTimer(),this.durablePresenceRetryAttempt=0,this.presenceState=null;}};T.RTDB_PRESENCE_REGISTER_TIMEOUT_MS=5e3,T.INITIAL_PRESENCE_WRITE_TIMEOUT_MS=5e3,T.RTDB_PRESENCE_RETRY_MIN_DELAY_MS=2e3,T.RTDB_PRESENCE_RETRY_MAX_DELAY_MS=6e4;var Ie=T;var Pe="trustedDevice",Ln="plutonium:e2ee:identity:v1",On="plutonium:e2ee:identity:session:v1",Un="openrtc-trust",j="identity",Ct="transport-trust:v1",Wn=1,E=null,te=null;function A(i){let e=atob(i),t=new Uint8Array(e.length);for(let n=0;n<e.length;n+=1)t[n]=e.charCodeAt(n);return t}function ne(i){let e="";for(let t=0;t<i.length;t+=1)e+=String.fromCharCode(i[t]);return btoa(e)}async function Et(i){let e=await crypto.subtle.digest("SHA-256",i),t=new Uint8Array(e);return Array.from(t).map(n=>n.toString(16).padStart(2,"0")).join("")}function Hn(){return typeof sessionStorage>"u"?null:sessionStorage}function Gn(){if(!(typeof localStorage>"u"))try{localStorage.removeItem(Ln);}catch{}}var Re=null;async function At(){return Re||(Re=(async()=>{let i=globalThis.crypto?.subtle;if(!i||typeof i.generateKey!="function")return false;try{let e=await i.generateKey({name:"Ed25519"},!1,["sign","verify"]);return !!(e&&e.privateKey&&e.publicKey)}catch{return false}})(),Re)}async function Kn(i){let e=await crypto.subtle.exportKey("raw",i);return new Uint8Array(e)}function zn(){try{return typeof indexedDB<"u"?indexedDB:null}catch{return null}}function _t(){let i=zn();return i?new Promise(e=>{let t;try{t=i.open(Un,1);}catch{e(null);return}t.onupgradeneeded=()=>{let n=t.result;n.objectStoreNames.contains(j)||n.createObjectStore(j);},t.onsuccess=()=>e(t.result),t.onerror=()=>e(null),t.onblocked=()=>e(null);}):Promise.resolve(null)}async function jn(){let i=await _t();if(!i)return null;try{return await new Promise(e=>{let r=i.transaction(j,"readonly").objectStore(j).get(Ct);r.onsuccess=()=>{let s=r.result;e(s&&s.privateKey&&s.publicKey?s:null);},r.onerror=()=>e(null);})}catch{return null}finally{i.close();}}async function Vn(i){let e=await _t();if(!e)return false;try{return await new Promise(t=>{let n=e.transaction(j,"readwrite");n.objectStore(j).put(i,Ct),n.oncomplete=()=>t(!0),n.onerror=()=>t(!1),n.onabort=()=>t(!1);})}catch{return false}finally{e.close();}}async function kt(i,e){let t=await Kn(i.publicKey),n=await Et(t),r=i.privateKey;return {publicKey:t,fingerprint:n,backend:"webcrypto-nonextractable",durable:e,privateKey:r,async signChallenge(s){let o=await crypto.subtle.sign({name:"Ed25519"},r,A(s));return ne(new Uint8Array(o))}}}function qn(i,e,t){let n=i.secretKey;return {publicKey:i.publicKey,secretKey:n,fingerprint:e,backend:"tweetnacl",durable:t,async signChallenge(r){return $n(r,n)}}}function Zi(i=32){let e=crypto.getRandomValues(new Uint8Array(i));return ne(e)}function $n(i,e){let t=we.sign.detached(A(i),e);return ne(t)}function Yn(i,e,t){try{return we.sign.detached.verify(A(i),A(e),A(t))}catch{return false}}async function er(i,e,t){let n=globalThis.crypto?.subtle;if(n&&typeof n.importKey=="function"&&typeof n.verify=="function")try{let r=await n.importKey("raw",A(t),{name:"Ed25519"},!1,["verify"]);return await n.verify({name:"Ed25519"},r,A(e),A(i))}catch{}return Yn(i,e,t)}function tr(i){return ne(i)}function nr(i){if(!i||!i.trim())return null;try{let e=JSON.parse(i),t=e&&typeof e=="object"&&!Array.isArray(e)?e[Pe]:null;if(!t||typeof t!="object"||Array.isArray(t))return null;let n=t,r=typeof n.version=="number"?n.version:null,s=typeof n.identityPublicKey=="string"?n.identityPublicKey:null,o=typeof n.identityFingerprint=="string"?n.identityFingerprint:null;return !r||!s||!o?null:{version:r,identityPublicKey:s,identityFingerprint:o}}catch{return null}}async function Jn(){let i=await ti().catch(()=>null);return i?{version:Wn,identityPublicKey:ne(i.publicKey),identityFingerprint:i.fingerprint}:null}async function Ue(i){let e=await Jn();if(!e)return i??void 0;let t=typeof i=="string"?i.trim():"";if(!t)return JSON.stringify({[Pe]:e});try{let n=JSON.parse(t);if(n&&typeof n=="object"&&!Array.isArray(n))return JSON.stringify({...n,[Pe]:e})}catch{}return JSON.stringify({metadata:i,[Pe]:e})}function Xn(){if(typeof window>"u")return null;let i=window.__TAURI_INTERNALS__;return !i||typeof i.invoke!="function"?null:i.invoke.bind(i)}async function Qn(){if(!t()||typeof window>"u"||/iPhone|iPad|iPod|Android/i.test(navigator.userAgent||""))return null;let i=Xn();if(!i)return null;try{let e=await i("openrtc_get_transport_trust_identity");return {publicKey:A(e.publicKeyBase64),fingerprint:e.fingerprint,backend:"native-keychain",durable:!0,async signChallenge(n){return i("openrtc_sign_transport_trust_challenge",{challenge:n})}}}catch{return null}}function Zn(){let i=Hn();i&&i.removeItem(On);}async function ei(){if(Gn(),Zn(),E)return E;let i=await Qn();if(i)return E=i,E;if(await At()){let e=await jn();if(e)return E=await kt(e,true),E}return null}async function ti(i={}){let e=await ei();if(e)return e;if(te)return te;let t=ni(i);te=t;try{return await t}finally{te===t&&(te=null);}}async function ni(i){if(E)return E;let e=i.ephemeral===true;if(await At())try{let t=await crypto.subtle.generateKey({name:"Ed25519"},!1,["sign","verify"]),n=!1;return e||(n=await Vn(t)),E=await kt(t,n),E}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=we.sign.keyPair(),n=await Et(v(t.publicKey));return E=qn(t,n,!1),E}catch{return null}}function V(i){return !i||typeof i!="object"?{}:i instanceof Map?Object.fromEntries(i):i}function We(i){let e=V(i),t=V(e.device);if(!Object.keys(t).length)return e;let n={...t,...e};return delete n.device,n}function y(i,...e){for(let t of e){let n=i[t];if(typeof n=="string"&&n.trim().length>0)return n}}function U(i,...e){for(let t of e){let n=i[t];if(typeof n=="boolean")return n}}function m(i,...e){for(let t of e){let n=i[t];if(typeof n=="number"&&Number.isFinite(n))return n}}function k(i){if(typeof i=="number"&&Number.isFinite(i))return i;if(i instanceof Date){let e=i.getTime();return Number.isFinite(e)?e:void 0}if(typeof i=="string"){let e=Date.parse(i);return Number.isFinite(e)?e:void 0}if(i&&typeof i=="object"){let e=i;if(typeof e.toMillis=="function"){let n=e.toMillis();return Number.isFinite(n)?n: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 n=typeof e.nanoseconds=="number"?e.nanoseconds:typeof e._nanoseconds=="number"?e._nanoseconds:0;return t*1e3+Math.floor((Number.isFinite(n)?n:0)/1e6)}}}function He(...i){let e=i.map(k).filter(t=>typeof t=="number"&&Number.isFinite(t));return e.length?Math.max(...e):void 0}function Ge(i){if(typeof i!="string")return;let e=i.trim().toLowerCase();return e==="online"||e==="idle"||e==="offline"?e:void 0}function Mt(i){let e=Ge("presenceStatus"in i?i.presenceStatus:void 0),t="presenceUpdatedAt"in i?k(i.presenceUpdatedAt):void 0,n="presenceExpiresAt"in i?k(i.presenceExpiresAt):void 0,r=t??He(i.lastSeenAt,i.updatedAt,i.createdAt),s=n??k(i.expiresAt),o=e;o||(i.online?r!==void 0&&r+3e5<=Date.now()?o="idle":o="online":o="offline");let a=typeof i.ticket=="string"?i.ticket.trim():"",c="connectable"in i&&typeof i.connectable=="boolean"?i.connectable:o==="online"&&a.length>0;return {presenceStatus:o,presenceUpdatedAt:r,presenceExpiresAt:s,connectable:c}}function xt(i){return b$2(i)}function q(i,...e){return xt(y(i,...e))}function re(i){if(!Array.isArray(i))return;let e=Array.from(new Set(i.map(xt).filter(t=>!!t)));return e.length?e:void 0}function Nt(i){let e=V(i),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(n=>n!==void 0)?t:void 0}function Ft(i){return (i.discoveryMode??"space")==="space"&&typeof i.apiKey=="string"&&i.apiKey.trim().length>0&&typeof i.spaceKey=="string"&&i.spaceKey.trim().length>0}function Bt(i,e,t){return t?true:(typeof i.appTag=="string"?i.appTag:typeof i.tag=="string"?i.tag:void 0)===e}function Ke(i,e){let t=We(i),n=y(t,"deviceId","device_id")||e||"",r=y(t,"nodeId","node_id")||"",s=y(t,"ticket")||"";return {deviceId:n,deviceName:y(t,"deviceName","device_name")||"Unknown Device",online:!!t.online,ticket:s,presenceStatus:Ge(y(t,"presenceStatus","presence_status","livenessStatus","liveness_status")),presenceUpdatedAt:m(t,"presenceUpdatedAt","presence_updated_at")??He(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")??k(t.presenceExpiresAt??t.presence_expires_at)??k(t.expiresAt??t.expires_at),connectable:U(t,"connectable"),kind:y(t,"kind"),nodeId:r||void 0,platformType:y(t,"platformType","platform_type"),capabilities:t.capabilities||void 0,sessionId:y(t,"sessionId","session_id"),userId:y(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:y(t,"metadata"),excludedPeers:ze(t.excludedPeers??t.excluded_peers),availableTransports:re(t.availableTransports??t.available_transports),transports:re(t.transports)}}function ze(i){return Array.isArray(i)?i.filter(e=>typeof e=="string"):[]}function ii(i){let e=Mt(i);return {...i,...e,connectionStatus:"connectionStatus"in i&&typeof i.connectionStatus=="string"?i.connectionStatus:i.online?"online":"disconnected",settledReady:"settledReady"in i&&typeof i.settledReady=="boolean"?i.settledReady:false,readinessState:"readinessState"in i&&typeof i.readinessState=="string"?i.readinessState:void 0,readinessReason:"readinessReason"in i&&typeof i.readinessReason=="string"?i.readinessReason:void 0,peerHealth:"peerHealth"in i&&typeof i.peerHealth=="string"?i.peerHealth:"unknown",peerId:"peerId"in i&&typeof i.peerId=="string"?i.peerId:void 0,promotionEligible:"promotionEligible"in i&&typeof i.promotionEligible=="boolean"?i.promotionEligible:true,scopes:"scopes"in i?ze(i.scopes):[],connectionId:"connectionId"in i&&typeof i.connectionId=="string"?i.connectionId:void 0,deviceIdHint:"deviceIdHint"in i&&typeof i.deviceIdHint=="string"?i.deviceIdHint:void 0,activeTransportStableId:"activeTransportStableId"in i&&typeof i.activeTransportStableId=="number"?i.activeTransportStableId:"activeTransportStableId"in i?i.activeTransportStableId??null:void 0,transportGeneration:"transportGeneration"in i&&typeof i.transportGeneration=="number"?i.transportGeneration:void 0,routeGeneration:"routeGeneration"in i&&typeof i.routeGeneration=="number"?i.routeGeneration:void 0,activeTransport:"activeTransport"in i?i.activeTransport:void 0,parallelTransport:"parallelTransport"in i?i.parallelTransport:void 0,availableTransports:"availableTransports"in i?re(i.availableTransports):"transports"in i?re(i.transports):void 0,latencyMs:"latencyMs"in i&&typeof i.latencyMs=="number"?i.latencyMs:void 0,latencyByTransport:"latencyByTransport"in i?Nt(i.latencyByTransport):void 0}}function ie(i,e){return e===void 0?true:e===null?i==null:i==null||i===e}function Lt(i,e){let t=ie(i.connectionId,e.connectionId)&&ie(i.nodeId,e.nodeId)&&ie(i.activeTransportStableId,e.activeTransportStableId)&&ie(i.transportGeneration,e.transportGeneration)&&ie(i.routeGeneration,e.routeGeneration),n=(r,s)=>r!==void 0?r:t?s:void 0;return {inheritsSnapshot:t,fields:{connectionId:n(e.connectionId??void 0,i.connectionId),activeTransportStableId:n(e.activeTransportStableId,i.activeTransportStableId),transportGeneration:n(e.transportGeneration,i.transportGeneration),routeGeneration:n(e.routeGeneration,i.routeGeneration),activeTransport:n(e.activeTransport,i.activeTransport),parallelTransport:n(e.parallelTransport,i.parallelTransport),latencyMs:t?i.latencyMs:void 0,latencyByTransport:t?i.latencyByTransport:void 0}}}var ri={connectionId:void 0,activeTransportStableId:null,transportGeneration:void 0,routeGeneration:void 0,activeTransport:void 0,parallelTransport:void 0,latencyMs:void 0,latencyByTransport:void 0};function si(i,e,t){let n=Lt(i,{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}):i.promotionEligible??true;if(!r)return {...i,peerHealth:e.health??i.peerHealth,peerId:e.peerId??i.peerId,promotionEligible:r,scopes:e.scopes?.length?[...e.scopes]:i.scopes,nodeId:e.nodeId===void 0?i.nodeId:e.nodeId??void 0,deviceIdHint:e.deviceIdHint??i.deviceIdHint,...n.fields,readinessReason:e.readinessReason??i.readinessReason};let s=e.status??i.connectionStatus,o=typeof s=="string"?s.trim().toLowerCase():"",a=o==="failed"||o==="closed"||o==="disconnected",l=typeof e.readinessState=="string"&&e.readinessState.trim().length>0?e.readinessState==="routable":e.settledReady===true,d=i.settledReady===true||i.readinessState==="routable";if(n.inheritsSnapshot&&d&&!a&&!l)return {...i,peerHealth:e.health??i.peerHealth,peerId:e.peerId??i.peerId,promotionEligible:r,scopes:e.scopes?.length?[...e.scopes]:i.scopes,nodeId:e.nodeId===void 0?i.nodeId:e.nodeId??void 0,deviceIdHint:e.deviceIdHint??i.deviceIdHint,...n.fields,readinessReason:e.readinessReason??i.readinessReason};let u=a?false:l,p=l&&!a&&(o==="connecting"||o==="connected")?"connected":s,f=l?"routable":e.readinessState??(n.inheritsSnapshot?i.readinessState:void 0),h=u?e.readinessReason??"peer-session-settled":e.readinessReason??(n.inheritsSnapshot?i.readinessReason:void 0);return {...i,connectionStatus:p,settledReady:u,readinessState:f,readinessReason:h,peerHealth:e.health??i.peerHealth,peerId:e.peerId??i.peerId,promotionEligible:r,scopes:e.scopes?.length?[...e.scopes]:i.scopes,nodeId:e.nodeId===void 0?i.nodeId:e.nodeId??void 0,deviceIdHint:e.deviceIdHint??i.deviceIdHint,...n.fields}}function oi(i,e){let t=Lt(i,{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 {...i,peerHealth:e.health??i.peerHealth,peerId:e.peerId??i.peerId,promotionEligible:false,nodeId:e.nodeId??i.nodeId,deviceIdHint:e.deviceIdHint??i.deviceIdHint,...t.fields,scopes:e.scopes?.length?[...e.scopes]:i.scopes};let n=e.status??i.connectionStatus,r=typeof n=="string"?n.trim().toLowerCase():"",s=r==="failed"||r==="closed"||r==="disconnected",o=i.settledReady===true||i.readinessState==="routable",a=e.routable===false;if(t.inheritsSnapshot&&o&&s&&!a)return {...i,peerHealth:i.peerHealth??e.health,peerId:i.peerId??e.peerId,promotionEligible:e.promotionEligible??i.promotionEligible??true,connectionId:i.connectionId??e.connectionId,deviceIdHint:i.deviceIdHint??e.deviceIdHint,scopes:i.scopes?.length?i.scopes:e.scopes??i.scopes};if(o&&s)return {...i,connectionStatus:n,settledReady:false,readinessState:void 0,readinessReason:e.error??i.readinessReason,peerHealth:e.health??i.peerHealth,peerId:e.peerId??i.peerId,promotionEligible:e.promotionEligible??i.promotionEligible??true,deviceIdHint:e.deviceIdHint??i.deviceIdHint,...ri,scopes:e.scopes?.length?[...e.scopes]:i.scopes};let c=e.routable===true||e.protocolState==="routable";if(t.inheritsSnapshot&&o&&!s&&!c)return {...i,peerHealth:i.peerHealth??e.health,peerId:i.peerId??e.peerId,promotionEligible:e.promotionEligible??i.promotionEligible??true,connectionId:i.connectionId??e.connectionId,deviceIdHint:i.deviceIdHint??e.deviceIdHint,activeTransportStableId:i.activeTransportStableId??e.activeTransportStableId,transportGeneration:i.transportGeneration??e.transportGeneration,routeGeneration:i.routeGeneration??e.routeGeneration,activeTransport:i.activeTransport??e.activeTransport,parallelTransport:i.parallelTransport===void 0?e.parallelTransport:i.parallelTransport,scopes:i.scopes?.length?i.scopes:e.scopes??i.scopes};let l=e.transportState==="connected"&&e.health==="healthy",d=s?false:c,u=!s&&(c||l)&&(r==="connecting"||r==="connected"||e.transportState==="connected")?"connected":n,p=d?"routable":(e.routable===false&&e.protocolState?e.protocolState:void 0)??(t.inheritsSnapshot?i.readinessState:void 0)??(e.status==="connecting"?e.transportState==="connected"?"transport-only":"connecting":void 0),f=d?(t.inheritsSnapshot?i.readinessReason:void 0)??(e.routable===true?"peer-projection-routable":void 0):(e.routable===false&&e.error?e.error:void 0)??(t.inheritsSnapshot?i.readinessReason:void 0)??(e.status==="connecting"?e.transportState==="connected"?"peer-projection-transport-ready":"peer-projection-connecting":void 0);return {...i,connectionStatus:u,settledReady:d,readinessState:p,readinessReason:f,peerHealth:e.health??i.peerHealth,peerId:e.peerId??i.peerId,promotionEligible:e.promotionEligible??i.promotionEligible??true,nodeId:e.nodeId??i.nodeId,deviceIdHint:e.deviceIdHint??i.deviceIdHint,...t.fields,scopes:e.scopes?.length?[...e.scopes]:i.scopes}}function ai(i){let{device:e,session:t=null,peer:n=null,isPromotionEligible:r}=i,s=ii(e);return t&&(s=si(s,t,r)),n&&(s=oi(s,n)),s}function Ot(i){let e=We(i),t=Ke(e),n=Ge(y(e,"presenceStatus","presence_status","livenessStatus","liveness_status")),r=Mt({...t,...n?{presenceStatus:n}:{},presenceUpdatedAt:m(e,"presenceUpdatedAt","presence_updated_at")??He(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")??k(e.presenceExpiresAt??e.presence_expires_at)??k(e.expiresAt??e.expires_at),connectable:U(e,"connectable")}),s={...t,...r,connectionStatus:y(e,"connectionStatus","connection_status")||"disconnected",settledReady:U(e,"settledReady","settled_ready")??false,readinessState:y(e,"readinessState","readiness_state")??void 0,readinessReason:y(e,"readinessReason","readiness_reason")??void 0,peerHealth:y(e,"peerHealth","peer_health")||"unknown",peerId:y(e,"peerId","peer_id"),scopes:ze(e.scopes),connectionId:y(e,"connectionId","connection_id"),deviceIdHint:y(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:q(e,"activeTransport","active_transport"),parallelTransport:q(e,"parallelTransport","parallel_transport")??null,availableTransports:re(e.availableTransports??e.available_transports),latencyMs:m(e,"latencyMs","latency_ms"),latencyByTransport:Nt(e.latencyByTransport??e.latency_by_transport)};return ai({device:s})}function Ut(i){let e=We(i);return {peerId:y(e,"peerId","peer_id")||"",deviceId:y(e,"deviceId","device_id"),deviceIdHint:y(e,"deviceIdHint","device_id_hint"),nodeId:y(e,"nodeId","node_id"),activeConnectionId:y(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:y(e,"status")||"disconnected",health:y(e,"health")||"unknown",settledReady:U(e,"settledReady","settled_ready")??false,readinessState:y(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:q(e,"activeTransport","active_transport"),parallelTransport:q(e,"parallelTransport","parallel_transport")??null,replacementPending:U(e,"replacementPending","replacement_pending")??void 0,lastLifecycleTransitionAtMs:m(e,"lastLifecycleTransitionAtMs","last_lifecycle_transition_at_ms")??void 0,readinessReason:y(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:y(e,"lastDisconnectReason","last_disconnect_reason")??void 0,lastReconnectReason:y(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:y(e,"error")}}function sr(i){let e=V(i);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 or(i){let e=V(i);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 ci(i){switch(i){case "connected":return "connected";case "connecting":return "connecting";case "failed":return "failed";default:return "closed"}}function Wt(i){let e=i.activeConnectionId||i.candidateConnectionIds[0]||null;if(!e)return null;let t=ci(i.status),n=t==="connected"?"connected":t==="connecting"?"connecting":"closed",r=t==="connected"?i.settledReady?"routable":"transport-only":t==="connecting"?"connecting":"closed";return {connectionId:e,deviceId:i.deviceId??null,deviceIdHint:i.deviceIdHint??null,remoteNodeId:i.nodeId??null,state:t,transportState:n,protocolState:r,routable:!!i.settledReady,readinessState:i.readinessState,readinessReason:i.readinessReason,transportGeneration:i.transportGeneration,routeGeneration:i.routeGeneration,activeTransportStableId:i.activeTransportStableId,activeTransport:i.activeTransport,parallelTransport:i.parallelTransport??null,replacementInProgress:i.replacementPending,lastLifecycleTransitionAtMs:i.lastLifecycleTransitionAtMs,transitionCount:i.transitionCount,connectingTransitionCount:i.connectingTransitionCount,replacementCount:i.replacementCount,retireCount:i.retireCount,lastDisconnectReason:i.lastDisconnectReason??void 0,lastReconnectReason:i.lastReconnectReason??void 0,updatedAt:i.lastSeenAtMs,error:i.error??void 0}}function Ht(i){let e=V(i),t=y(e,"connectionId","connection_id");if(!t)return null;let n=y(e,"state")||"connecting",r=m(e,"createdAt","created_at")??m(e,"updatedAt","updated_at")??Date.now(),s=m(e,"updatedAt","updated_at")??r;return {connectionId:t,deviceId:y(e,"deviceId","device_id"),deviceIdHint:y(e,"deviceIdHint","device_id_hint"),remoteNodeId:y(e,"remoteNodeId","remote_node_id"),state:n,transportState:y(e,"transportState","transport_state")??(n==="connected"?"connected":n==="connecting"?"connecting":"closed"),protocolState:y(e,"protocolState","protocol_state")??(n==="connected"?"routable":n==="connecting"?"connecting":"closed"),routable:U(e,"routable")??false,readinessState:y(e,"readinessState","readiness_state")??void 0,readinessReason:y(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:q(e,"activeTransport","active_transport"),parallelTransport:q(e,"parallelTransport","parallel_transport")??null,replacementInProgress:U(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:y(e,"lastDisconnectReason","last_disconnect_reason")??void 0,lastReconnectReason:y(e,"lastReconnectReason","last_reconnect_reason")??void 0,error:y(e,"error")??void 0,createdAt:r,updatedAt:s}}function Gt(i,e){return i?i.connectionId===e.connectionId&&(i.deviceId??null)===(e.deviceId??null)&&(i.deviceIdHint??null)===(e.deviceIdHint??null)&&(i.remoteNodeId??null)===(e.remoteNodeId??null)&&i.state===e.state&&(i.transportState??null)===(e.transportState??null)&&(i.protocolState??null)===(e.protocolState??null)&&!!i.routable==!!e.routable&&(i.activeTransport??null)===(e.activeTransport??null)&&(i.parallelTransport??null)===(e.parallelTransport??null)&&(i.activeTransportStableId??null)===(e.activeTransportStableId??null)&&(i.transportGeneration??null)===(e.transportGeneration??null)&&(i.routeGeneration??null)===(e.routeGeneration??null)&&!!i.replacementInProgress==!!e.replacementInProgress&&(i.transitionCount??null)===(e.transitionCount??null)&&(i.connectingTransitionCount??null)===(e.connectingTransitionCount??null)&&(i.replacementCount??null)===(e.replacementCount??null)&&(i.retireCount??null)===(e.retireCount??null)&&(i.lastDisconnectReason??null)===(e.lastDisconnectReason??null)&&(i.lastReconnectReason??null)===(e.lastReconnectReason??null)&&(i.error??null)===(e.error??null):false}function di(i){try{let e=i.replace(/-/g,"+").replace(/_/g,"/"),t=(4-e.length%4)%4,n=e+"=".repeat(t);if(typeof atob=="function")return JSON.parse(atob(n));let r=globalThis.Buffer;if(r)return JSON.parse(r.from(n,"base64").toString("utf8"))}catch{return null}return null}function li(i){let e=typeof i=="string"?i.trim():"";if(!e)return {present:false};let t=e.lastIndexOf("."),n=t>=0?e.slice(0,t):e,r=t>=0?e.slice(t+1):null,s=r?di(r):null,o=s&&typeof s.t=="string"&&s.t.trim().length>0?s.t.trim():null,a=s&&typeof s.s=="string"&&s.s.trim().length>0?s.s.trim():null,c=s&&typeof s.m=="number"&&Number.isFinite(s.m)?s.m:null;return {present:true,irohFingerprint:_(n),tokenFingerprint:_(o),tokenSuffixFingerprint:_(r),scope:a,maxConnections:c}}function se(i,e,t={}){let n=typeof i.finishSend=="function"?i.finishSend.bind(i):typeof i.finish_send=="function"?i.finish_send.bind(i):null;if(!n){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:s=>r.write(s),async close(){await r.close(),await n();},abort:s=>r.abort(s)})}var b=class b{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.browserFirestoreSignaling=null;this.lastObservedFirebaseUserId=null;this.sessionReaders=new Set;this.authContext=null;this.injectedBrowserAuthSessionActive=false;this._rtdbPresence=null;this.rtdbPresenceScope=null;this.rtdbTicketVersion=0;this.rtdbPresenceDisabledForSession=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;try{let n=typeof import.meta<"u"?import.meta.env:null;if(!!n&&String(n.VITE_USE_EMULATORS)==="true"&&(n.DEV||String(n.VITE_E2E)==="true")){let s=String(n.VITE_OPENRTC_FIRESTORE_EMULATOR_HOST||"").trim()||"127.0.0.1:8082";globalThis.__OPENRTC_FIRESTORE_EMULATOR_HOST__=s;}}catch{}if(this.appTag=b$1(e),this.options={...e,appTag:this.appTag,authMode:c(e),projectId:d(e)},this.presenceManager=new Ie({isTicketOnlyMode:()=>this.isTicketOnlyMode(),waitForWasmClient:(n,r)=>this.waitForWasmClient(n,r),warnMissingWasmOnce:n=>this.warnMissingWasmOnce(n),resolveWebLogicalDeviceId:()=>this.resolveWebLogicalDeviceId(),withWebPresenceMetadata:(n,r)=>this.withWebPresenceMetadata(n,r),updatePresence:(n,r,s,o,a,c)=>this.updatePresence(n,r,s,o,a,c),buildRtdbScope:n=>this.buildRtdbScope(n),resolveRtdbScope:n=>this.resolveRtdbScope(n),registerRtdbPresence:(n,r,s,o)=>this.registerRtdbPresence(n,r,s,o),isRtdbPresenceDisabledForSession:()=>this.rtdbPresenceDisabledForSession,getRtdbTicketVersion:()=>this.rtdbTicketVersion,getBrowserFirestoreSignaling:()=>this.getBrowserFirestoreSignaling(),rememberRouteRepairTokenFromTicket:n=>this.coreClient?.rememberRouteRepairTokenFromTicket?.(n)??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(n=>{if(this.authContext)return;if(this.isSpaceMode()){this.authListeners.forEach(o=>o(this.toRuntimeIdentity(n)));return}let r=n?.uid??null,s=this.lastObservedFirebaseUserId;this.lastObservedFirebaseUserId=r,s&&s!==r&&this.stopAuthScopedActivity({userId:s}),this.browserFirestoreSignaling?.handleScopeChange(),this.authListeners.forEach(o=>o(this.toRuntimeIdentity(n)));});}get rtdbPresence(){return this._rtdbPresence}get tag(){return this.appTag}getRuntimeCapabilities(){return ue()}getDeviceIdentityStorageKey(){let e$1=e(this.options);return `${b.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 n=this.getDeviceIdentityStorageKey(),r=Date.now(),s=null;try{let d=localStorage.getItem(n);s=d?JSON.parse(d):null;}catch{s=null;}let o=typeof s?.deviceId=="string"?s.deviceId.trim():"",a=typeof s?.expiresAt=="number"?s.expiresAt:void 0;if(t==="persistent"){let d=o||this.createRandomDeviceId();return localStorage.setItem(n,JSON.stringify({deviceId:d})),d}if(o&&typeof a=="number"&&a>r){let d=r+b.EPHEMERAL_DEVICE_ID_TTL_MS;return localStorage.setItem(n,JSON.stringify({deviceId:o,expiresAt:d})),o}let c=this.createRandomDeviceId(),l=r+b.EPHEMERAL_DEVICE_ID_TTL_MS;return localStorage.setItem(n,JSON.stringify({deviceId:c,expiresAt:l})),c}getDefaultBrowserDeviceName(){return this.options.deviceName?.trim()||(this.options.storagePrefix?`Web (${this.options.storagePrefix.replace(/_$/,"")})`:"Web Browser")}getBrowserFirestoreSignaling(){if(this.isTicketOnlyMode())throw new Error('[openrtc] Browser signaling is disabled when signalingMode="ticket-only".');return this.browserFirestoreSignaling||(this.browserFirestoreSignaling=new Se({app:this.app,auth:this.auth,appTag:this.appTag,apiKey:this.options.apiKey,spaceKey:this.options.spaceKey,discoveryMode:this.options.discoveryMode,getCurrentUserId:()=>this.getCurrentUserId(),getDiscoveryScopeId:()=>this.getDiscoveryScopeId(),getLocalDeviceId:()=>this.resolveWebLogicalDeviceId(),getDefaultDeviceName:()=>this.getDefaultBrowserDeviceName(),matchesTag:e=>this.matchesTag(e),normalizeDevice:(e,t)=>this.normalizeDevice(e,t)})),this.browserFirestoreSignaling}async withWebPresenceMetadata(e,t){let n;if(!e||!e.trim())n=JSON.stringify({deviceId:t});else {try{let r=JSON.parse(e);if(r&&typeof r=="object"&&!Array.isArray(r))return n=JSON.stringify({...r,deviceId:t}),await Ue(n)??n}catch{}n=JSON.stringify({deviceId:t,metadata:e});}return await Ue(n)??n}async setAuthContext(e){let t=this.injectedBrowserAuthSessionActive;if(this.authContext=e,!this.isTicketOnlyMode()&&e?.customToken?.trim())try{await this.ensureBrowserFirestoreAuth(e.userId,e.customToken.trim());}catch(n){console.warn("[WasmBridge] ensureBrowserFirestoreAuth failed (non-fatal):",n);}else if(!this.isTicketOnlyMode()&&!e&&t)try{await this.auth?.signOut();}catch(n){console.warn("[WasmBridge] Failed to clear injected browser auth session:",n);}finally{this.injectedBrowserAuthSessionActive=false;}this.syncWasmAuthToken(),this.isTicketOnlyMode()||await this.browserFirestoreSignaling?.handleScopeChange(),this.authListeners.forEach(n=>n(this.currentUser));}async ensureBrowserFirestoreAuth(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 Ft(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 Bt(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);}}disableRtdbPresenceForSession(e,t){this.rtdbPresenceDisabledForSession||console.warn(`[WasmBridge] Disabling RTDB presence for this browser session (${e})`,t),this.rtdbPresenceDisabledForSession=true,this.rtdbPresenceScope=null,this.browserFirestoreSignaling?.stopRtdbPresence();}async registerRtdbPresence(e,t,n,r){if(this.isTicketOnlyMode())return;if(!this._rtdbPresence)try{this._rtdbPresence=new fe(this.app);}catch(a){throw this.disableRtdbPresenceForSession("RTDB service unavailable",a),a}this.rtdbPresenceScope=e;let s=n??this.rtdbTicketVersion;this.getBrowserFirestoreSignaling().setRtdbPresence(this._rtdbPresence,e);try{await this._rtdbPresence.registerDevice(e,t,s,r);}catch(a){throw a}}buildRtdbPresenceFields(e,t,n,r){return {ticket:t,nodeId:e,deviceName:r?.trim()||this.getDefaultBrowserDeviceName(),platformType:"web",metadata:n}}async refreshRtdbPresenceTicket(e,t,n,r){if(this.isTicketOnlyMode()||this.rtdbPresenceDisabledForSession)return;let s=this.resolveWebLogicalDeviceId();if(!s)return;let o=this.rtdbPresenceScope??await this.resolveRtdbScope(this.getCurrentUserId()??void 0);if(!o)return;this.rtdbTicketVersion+=1;let a=this.rtdbTicketVersion,c=this.buildRtdbPresenceFields(e,t,n,r);if(this._rtdbPresence&&this.rtdbPresenceScope){await this._rtdbPresence.bumpTicketVersion(o,s,a,c);return}await this.registerRtdbPresence(o,s,a,c);}async stopAuthScopedActivity(e){ot("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(n){console.warn("[WasmBridge] user-device revoke during auth-scoped shutdown failed:",n);}this.presenceManager.stop(),this.rtdbPresenceDisabledForSession=false,this.rtdbPresenceScope=null,this.rtdbTicketVersion=0,this.browserFirestoreSignaling?.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 n=Date.now();for(;!this.wasmClient&&Date.now()-n<e;)await u(t);return this.wasmClient??null}normalizeDevice(e,t){return Ke(e,t)}normalizeDeviceRecord(e,t){return this.normalizeDevice(e,t)}getResolvedWebLogicalDeviceId(){return this.resolveWebLogicalDeviceId()}normalizeDeviceStatusSnapshot(e){return Ot(e)}normalizePeerSessionSnapshot(e){return Ut(e)}toBackendConnectionStateFromPeerSession(e){return Wt(e)}normalizeConnectionStateSnapshot(e){return Ht(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 Gt(e,t)}deliverConnectionState(e,t,n,r){let s=this.stabilizeConnectionState(e);this.escalateManagedApplicationRoute(s),this.lastDeliveredConnectionStates.set(s.connectionId,s);let a=(r??this.lastDeliveredConnectionStates).get(s.connectionId);this.sameConnectionState(a,s)||(r&&r.set(s.connectionId,s),t(s));}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(n=false)=>{if(e&&(!n||!t))return e;if(t)try{let s=await t(n);if(s)return s}catch{}let r=this.isTicketOnlyMode()?null:this.auth?.currentUser??null;if(r&&r.uid===this.authContext?.userId)try{return await r.getIdToken(n)}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,n=true,r=3e5,s,o){if(this.isTicketOnlyMode())return;let a=this.resolveWebLogicalDeviceId(),c=this.getDeviceIdPersistenceMode()==="ephemeral"?b.EPHEMERAL_DEVICE_ID_TTL_MS:r,l=await this.withWebPresenceMetadata(s,a);this.presenceManager.updatePresenceLoopState({userId:this.getCurrentUserId()??"",localNodeId:e,ticket:t,metadata:l,deviceName:o?.trim()||this.getDefaultBrowserDeviceName()}),await this.getBrowserFirestoreSignaling().updatePresence(e,t,n,c,l,o),await this.refreshRtdbPresenceTicket(e,t,l,o);}async refreshLivePresence(e,t,n,r){if(this.isTicketOnlyMode())return;let s=this.resolveWebLogicalDeviceId(),o=await this.withWebPresenceMetadata(n,s);this.presenceManager.updatePresenceLoopState({userId:this.getCurrentUserId()??"",localNodeId:e,ticket:t,metadata:o,deviceName:r?.trim()||this.getDefaultBrowserDeviceName()}),await this.refreshRtdbPresenceTicket(e,t,o,r);}async setOffline(e){if(this.presenceManager.stopPresence(),!this.isTicketOnlyMode()){if(this._rtdbPresence&&this.rtdbPresenceScope){let t=this.resolveWebLogicalDeviceId();t&&await this._rtdbPresence.markOffline(this.rtdbPresenceScope,t,this.rtdbTicketVersion).catch(n=>console.warn("[WasmBridge] RTDB markOffline failed:",n));}await this.getBrowserFirestoreSignaling().setOffline(e);}}async updateDevice(e,t){if(!e?.trim())throw new Error("updateDevice requires a deviceId");this.isTicketOnlyMode()||await this.getBrowserFirestoreSignaling().updateDevice(e,t);}async deleteDevice(e){if(!e?.trim())throw new Error("deleteDevice requires a deviceId");this.isTicketOnlyMode()||await this.getBrowserFirestoreSignaling().deleteDevice(e);}async cleanupStaleDevices(){this.isTicketOnlyMode()||await this.getBrowserFirestoreSignaling().cleanupStaleDevices();}async sendMessage(e,t,n,r){if(this.isTicketOnlyMode())throw new Error('[openrtc] sendMessage() is unavailable when signalingMode="ticket-only".');return this.getBrowserFirestoreSignaling().sendMessage(e,t,n,r)}async pollMessages(e){return this.isTicketOnlyMode()?[]:this.getBrowserFirestoreSignaling().pollMessages(e)}async searchDevices(e){return this.isTicketOnlyMode()?[]:this.getBrowserFirestoreSignaling().searchDevices(e)}async listDevicesWithStatus(){if(this.isTicketOnlyMode())return [];if(!this.getDiscoveryScopeId())return [];let t=await this.getBrowserFirestoreSignaling().listDevices(),n=this.wasmClient;return Promise.all(t.map(async r=>{let s=this.normalizeDeviceStatusSnapshot({...r,connectionStatus:r.online?"online":"disconnected"}),o=typeof r.nodeId=="string"?r.nodeId.trim():"";if(!o||typeof n?.iroh_path_kind!="function"||typeof n?.iroh_transport_rtt_ms!="function")return s;try{let[a,c]=await Promise.all([n.iroh_path_kind(o),n.iroh_transport_rtt_ms(o)]);if(typeof c!="number"||!Number.isFinite(c))return s;let l=Math.max(0,Math.round(c)),d={};if(a==="direct-lan")d.irohLan=l;else if(a==="direct-quic")d.iroh=l;else if(a==="ble")d.ble=l;else if(a==="relay")d.irohRelay=l;else return s;return {...s,latencyMs:l,latencyByTransport:d}}catch(a){return de("[WasmBridge] iroh transport latency unavailable",{deviceId:r.deviceId,error:a instanceof Error?a.message:String(a)}),s}}))}async getPeerSession(e){let t=await this.waitForWasmClient(500);if(t&&typeof t.peer_session=="function"){let n=await t.peer_session(e);return !n||typeof n!="object"?null:this.normalizePeerSessionSnapshot(n)}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 n=await this.waitForWasmClient(500);if(n&&typeof n.wait_for_settled_peer=="function"){let r=await n.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 n=await this.waitForWasmClient(500);if(n&&typeof n.open_peer_bi=="function"){let r=await n.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:se(r,r.send)}}throw this.warnMissingWasmOnce("openPeerBi"),new Error("WASM runtime does not support open_peer_bi()")}async openPeerNativeBi(e,t,n){let r=await this.waitForWasmClient(500),s=r&&r.open_peer_native_bi;if(typeof s=="function"){let o=await s.call(r,e,t,n);if(!o?.recv||!o?.send)throw new Error("WASM open_peer_native_bi returned an invalid bidirectional stream");return {readable:o.recv,writable:se(o,o.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 n=await this.waitForWasmClient(500),r=n&&typeof n.open_peer_bi_transport_only=="function";if(console.debug("[WasmBridge] openPeerBiTransportOnly",{peerId:e,hasWasmClient:!!n,hasTransportOnly:r,timeoutMs:t}),r){let s=await n.open_peer_bi_transport_only(e,t);if(!s?.recv||!s?.send)throw new Error("WASM open_peer_bi_transport_only returned an invalid bidirectional stream");return {readable:s.recv,writable:se(s,s.send)}}return console.debug("[WasmBridge] openPeerBiTransportOnly falling back to openPeerBi",{peerId:e}),this.openPeerBi(e,t)}async openPeerUni(e,t){let n=await this.waitForWasmClient(500);if(n&&typeof n.open_peer_uni=="function"){let r=await n.open_peer_uni(e,t),s=r?.writable??r;if(!s)throw new Error("WASM open_peer_uni returned an invalid writable stream");return {writable:se(r,s)}}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 n=await t.resolve_peer_connection_records(e);return (Array.isArray(n)?n:[]).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 n=r=>{if(!r||typeof r!="object")return {peerId:null,deviceId:null,deviceIdHint:null,nodeId:null};let s=r;return {peerId:typeof s.peerId=="string"?s.peerId:null,deviceId:typeof s.deviceId=="string"?s.deviceId:null,deviceIdHint:typeof s.deviceIdHint=="string"?s.deviceIdHint:null,nodeId:typeof s.nodeId=="string"?s.nodeId:null}};if(typeof t.peer_session=="function")try{let r=await t.peer_session(e),s=n(r);if(s.peerId||s.deviceId||s.deviceIdHint||s.nodeId)return s}catch{}if(typeof t.peer_snapshot=="function")try{return n(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.getBrowserFirestoreSignaling().onDevicesChange(e,t)}async subscribeDevices(e){return this.isTicketOnlyMode()?new ReadableStream({start(t){t.close();}}):this.getBrowserFirestoreSignaling().subscribeDevices()}async startAutoConnect(e,t){if(this.isTicketOnlyMode())return;this.startApplicationRouteEscalationSubscription();let n=this.authScopedRuntimeGeneration;try{let r=await this.waitForWasmClient();if(n!==this.authScopedRuntimeGeneration||!r||typeof r.start_auto_connect!="function")return;await r.start_auto_connect(e,t),n===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(n){throw console.warn("[WasmBridge] disconnect_device failed",{deviceId:e,error:n?.message??String(n)}),n}}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,n=this.onConnectionStateChange(()=>{});this.applicationRouteEscalationUnsubscribe=()=>{},this.applicationRouteEscalationSubscriptionGeneration=e,Promise.resolve(n).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 n=this.authScopedRuntimeGeneration,r=this.coreClient,s;s=(async()=>{let o=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(n!==this.authScopedRuntimeGeneration)return;let a=o,c=a.id?.trim()||e.connectionId,l=a.remoteNodeId?.trim()||e.remoteNodeId?.trim()||a.deviceId?.trim()||t.deviceId;if(r.hasApplicationRouteForPeer?.(c,l)!==true&&r.hasApplicationRouteForPeer?.(c,l)!==true)throw new Error(`application crypto was not ready for ${l}`)})().catch(o=>{n===this.authScopedRuntimeGeneration&&console.warn("[WasmBridge][ROUTE-ESCALATION] Rust-managed route remains pending",{connectionId:e.connectionId,deviceId:t.deviceId,remoteNodeId:e.remoteNodeId??t.nodeId,error:o?.message??String(o)});}).finally(()=>{this.applicationRouteEscalations.get(e.connectionId)===s&&this.applicationRouteEscalations.delete(e.connectionId);}),this.applicationRouteEscalations.set(e.connectionId,s);}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 n=Date.now();R("[WasmBridge][ROUTE-ESCALATION] starting managed transport dial",{deviceId:e.deviceId??null,ticket:li(e.endpointTicket),hasCoreClient:!!this.coreClient});let r=await t.connect_device(e.deviceId??null,e.endpointTicket);R("[WasmBridge][ROUTE-ESCALATION] managed transport dial completed",{deviceId:e.deviceId??null,remoteNodeId:r?.remoteNodeId??null,connectionId:r?.connectionId??null,elapsedMs:Date.now()-n});let s=e.endpointTicket;if(s&&this.coreClient){let o=this.coreClient;try{R("[WasmBridge][ROUTE-ESCALATION] starting typed application connection",{deviceId:e.deviceId??null,remoteNodeId:r?.remoteNodeId??null,connectionId:r?.connectionId??null});let a=typeof o.ensureManagedApplicationRoute=="function"?await o.ensureManagedApplicationRoute({ticket:s,connectionId:r?.connectionId??null,remoteNodeId:r?.remoteNodeId??null,expectedDeviceId:e.deviceId??null,timeoutMs:2e4}):await o.connect(s,2e4,e.deviceId??null,void 0,{admissionAlreadyPresented:!0}),c=typeof a?.remoteNodeId=="string"?a.remoteNodeId.trim():"",l=typeof a?.deviceId=="string"?a.deviceId.trim():"",d=c||r?.remoteNodeId?.trim?.()||l||e.deviceId?.trim?.()||"",u=typeof o.hasApplicationRouteForPeer=="function"?o.hasApplicationRouteForPeer.bind(o):null;if(!(!!d&&u?.(a?.id??void 0,d)===!0)&&d&&typeof o.waitForApplicationCryptoForPeer=="function"&&!(!!await o.waitForApplicationCryptoForPeer(d,2e4)&&(!u||u(a?.id??void 0,d)===!0)))throw console.warn("[WasmBridge][ROUTE-ESCALATION] application route still pending after managed dial",{deviceId:e.deviceId??null,remoteNodeId:c||(r?.remoteNodeId??null),connectionId:r?.connectionId??null,peerForCrypto:d,elapsedMs:Date.now()-n}),Object.assign(new Error(`application crypto was not ready for ${d}`),{applicationCryptoNotReady:!0});R("[WasmBridge][ROUTE-ESCALATION] application route ready",{deviceId:e.deviceId??null,remoteNodeId:c||(r?.remoteNodeId??null),connectionId:r?.connectionId??null,elapsedMs:Date.now()-n});}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,n,r,s){this.presenceManager.startPresenceLoop(e,t,n,r,s);}usesSpaceScopedRtdb(){return (this.options.discoveryMode??"space")==="space"}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(n=>(this.cachedSpaceNamespaceId=n,n)).catch(()=>null);}return this.spaceNamespaceIdPromise}buildRtdbScope(e){if(this.isTicketOnlyMode())return null;let t=this.options.discoveryMode??"space",n=this.appTag;if(t==="space")return this.usesSpaceScopedRtdb()&&this.cachedSpaceNamespaceId?{kind:"space",namespaceId:this.cachedSpaceNamespaceId}:null;let r=e||this.getDiscoveryScopeId()||this.getCurrentUserId();return r?{kind:"user-scoped",appTag:n,userId:r}:null}async resolveRtdbScope(e){let t=this.buildRtdbScope(e);if(t||(this.options.discoveryMode??"space")!=="space")return t;if(!this.usesSpaceScopedRtdb())return null;let n=await this.ensureSpaceNamespaceIdPromise();return n?{kind:"space",namespaceId:n}:null}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 n={...e,appTag:e.appTag??this.appTag,initiator:e.initiator??t??void 0,target:e.target??t??void 0};await this.getBrowserFirestoreSignaling().createSession(n);}async updateSession(e,t){if(this.isTicketOnlyMode())throw new Error('[openrtc] updateSession() is unavailable when signalingMode="ticket-only".');await this.getBrowserFirestoreSignaling().updateSession(e,t);}async subscribeSessions(e){return this.isTicketOnlyMode()?new ReadableStream({start(t){t.close();}}):this.getBrowserFirestoreSignaling().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 n=t.trim(),r=[];if(typeof e.peer_session=="function")try{let s=await e.peer_session(n);s&&typeof s=="object"&&r.push(this.normalizePeerSessionSnapshot(s));}catch{}if(typeof e.peer_sessions=="function")try{let s=await e.peer_sessions();Array.isArray(s)&&r.push(...s.filter(o=>!!o&&typeof o=="object").map(o=>this.normalizePeerSessionSnapshot(o)));}catch{}return r.some(s=>{let o=typeof s.peerId=="string"?s.peerId.trim():"",a=typeof s.deviceId=="string"?s.deviceId.trim():"",c=typeof s.deviceIdHint=="string"?s.deviceIdHint.trim():"",l=typeof s.nodeId=="string"?s.nodeId.trim():"";return (n===o||n===a||n===c||n===l)&&s.status==="connected"&&s.settledReady===true&&s.replacementPending!==true&&h(s.activeTransport)})}async getConnectionStates(){let e=await this.waitForWasmClient(500);if(e&&typeof e.connection_states=="function"){let r=await e.connection_states(),s=(Array.isArray(r)?r:[]).map(o=>this.normalizeConnectionStateSnapshot(o)).filter(o=>!!o);return s.length>0&&de("[WasmBridge] replaying current wasm connection states",s.map(o=>({connectionId:o.connectionId,deviceId:o.deviceId??null,deviceIdHint:o.deviceIdHint??null,remoteNodeId:o.remoteNodeId??null,state:o.state,transportState:o.transportState??null,protocolState:o.protocolState??null,routable:o.routable??null}))),s}let n=(await this.listPeerSessions().catch(()=>[])).map(r=>this.toBackendConnectionStateFromPeerSession(r)).filter(r=>!!r);return n.length>0&&de("[WasmBridge] replaying current wasm connection states",n.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}))),n}onConnectionStateChange(e){let t=new Map,n=new Map,r=this.authScopedRuntimeGeneration,s=false,o=l=>{let d=l.detail,u=typeof d?.connectionId=="string"?d.connectionId.trim():"";if(!u||s)return;let p=(n.get(u)??0)+1;n.set(u,p);let f=this.authScopedRuntimeGeneration;(async()=>{let h=this.normalizeConnectionStateSnapshot(d),g=await this.waitForWasmClient(500);if(!(s||f!==this.authScopedRuntimeGeneration||n.get(u)!==p)){if(g&&typeof g.connection_state=="function"){let v=await g.connection_state(u),S=this.normalizeConnectionStateSnapshot(v);if(!s&&f===this.authScopedRuntimeGeneration&&n.get(u)===p&&S){this.deliverConnectionState(S,e,"rust-event",t);return}}!s&&f===this.authScopedRuntimeGeneration&&n.get(u)===p&&h&&this.deliverConnectionState(h,e,"rust-event-detail",t);}})().catch(h=>{s||console.warn("[WasmBridge] Failed to read Rust connection state after lifecycle event",{connectionId:u,error:h});});},a=typeof window<"u"?window:null,c=typeof a?.addEventListener=="function"&&typeof a?.removeEventListener=="function";return c&&a.addEventListener("connection-state-changed",o),this.getConnectionStates().then(l=>{!s&&r===this.authScopedRuntimeGeneration&&l.forEach(d=>{n.has(d.connectionId)||this.deliverConnectionState(d,e,"replay",t);});}).catch(l=>{console.warn("[WasmBridge] Failed to replay wasm connection states after subscription:",l);}),()=>{s=true,n.clear(),c&&a.removeEventListener("connection-state-changed",o);}}async sendExplicitFilePath(e,t,n=""){throw new Error("sendExplicitFilePath is native-only. Use sendExplicitFileData in web/wasm runtime.")}sanitizeExplicitFileName(e){let n=(typeof e=="string"?e.replace(/\\/g,"/"):"").split("/").reverse().find(o=>o.trim().length>0)?.trim()??"";if(!n||n==="."||n==="..")return b.FALLBACK_EXPLICIT_FILE_NAME;let r="";for(let o of n){if([...r].length>=b.MAX_EXPLICIT_FILE_NAME_CHARS)break;let a=o.charCodeAt(0);o==="/"||o==="\\"||o==="\0"||a<32||a===127?r+="_":r+=o;}let s=r.trim();return !s||s==="."||s===".."?b.FALLBACK_EXPLICIT_FILE_NAME:s}sanitizeExplicitMimeType(e){let t=typeof e=="string"?e.trim():"";if(!t)return b.FALLBACK_EXPLICIT_MIME_TYPE;let n="";for(let r of t){if(n.length>=b.MAX_EXPLICIT_MIME_TYPE_CHARS)break;let s=r.charCodeAt(0);s<33||s>126||r==='"'||r==="\\"?n+="_":n+=r;}return n.length>0?n:b.FALLBACK_EXPLICIT_MIME_TYPE}assertExplicitTransferHeaderSize(e){if(e.byteLength===0||e.byteLength>b.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 n=0;n<e.byteLength;n+=1)e[n]=Math.floor(Math.random()*256);return e}createWebRTCExplicitTransferFrame(e,t,n,r,s){let o=s?.headerFrame===true?4:0,a=new Uint8Array(25+o+r.byteLength);a[0]=b.EXPLICIT_FILE_PROTOCOL_TYPE,a.set(e,1);let c=new DataView(a.buffer);c.setUint32(17,t,false),c.setUint32(21,n,false);let l=s?.headerFrame===true?29:25;return s?.headerFrame===true&&c.setUint32(25,r.byteLength,false),a.set(r,l),a}async sendExplicitFileData(e){let t=e.connection,n=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 o=e.transferId&&e.transferId.trim().length>0?e.transferId:`transfer-${Date.now()}`,a=typeof e.receiverPlatformType=="string"?e.receiverPlatformType.trim().toLowerCase():null,c=e.remoteNodeId?.trim()||t?.remoteNodeId?.trim()||t?.deviceId?.trim();if(R("[WasmBridge] sendExplicitFileData start",{connectionId:e.connectionId??null,connectionRemoteNodeId:t?.remoteNodeId??null,remoteNodeId:c??null,fileName:n.name,fileSize:n.size,transferId:o}),!c)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 d=new TextEncoder,u={transfer_id:o,filename:this.sanitizeExplicitFileName(n.name),size:n.size,mime_type:this.sanitizeExplicitMimeType(n.type)},p=d.encode(JSON.stringify(u));this.assertExplicitTransferHeaderSize(p);let f=new Uint8Array(4);new DataView(f.buffer).setUint32(0,p.byteLength,false);let h=new Uint8Array(f.byteLength+p.byteLength);h.set(f,0),h.set(p,f.byteLength);let g=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&&R("[WasmBridge] sendExplicitFileData kept on Iroh for non-browser receiver",{remoteNodeId:c,transferId:o,receiverPlatformType:a}),false;let S=r?st(r):null,D=N=>S?S.protectFrame(N):N,I=new Uint8Array(await n.arrayBuffer()),w=this.createWebRTCExplicitTransferId(),M=Math.max(1,Math.ceil(I.byteLength/b.EXPLICIT_FILE_CHUNK_SIZE_BYTES)),C=typeof t.getWebRTCTransport=="function"?t.getWebRTCTransport():null,x=async()=>{C&&typeof C.getBufferedAmount=="function"&&typeof C.waitForDrain=="function"&&C.getBufferedAmount()>b.EXPLICIT_FILE_CHUNK_SIZE_BYTES*4&&await C.waitForDrain(b.EXPLICIT_FILE_CHUNK_SIZE_BYTES*2);};if(await t.sendOnWebRTC(this.createWebRTCExplicitTransferFrame(w,4294967295,M,D(p),{headerFrame:true})),await x(),I.byteLength===0)return await t.sendOnWebRTC(this.createWebRTCExplicitTransferFrame(w,0,M,D(new Uint8Array(0)))),true;let oe=0;for(let N=0;N<I.byteLength;N+=b.EXPLICIT_FILE_CHUNK_SIZE_BYTES){let jt=I.slice(N,Math.min(N+b.EXPLICIT_FILE_CHUNK_SIZE_BYTES,I.byteLength));await t.sendOnWebRTC(this.createWebRTCExplicitTransferFrame(w,oe,M,D(jt))),oe+=1,await x();}return R("[WasmBridge] sendExplicitFileData sent over WebRTC explicit route",{connectionId:e.connectionId??null,remoteNodeId:c,transferId:o,chunks:M,encrypted:!!S}),true},v=async()=>{let S=l.open_peer_bi_explicit_file_sender;if(typeof S!="function")return false;let D=await S.call(l,c,5e3),I=D?.writable??D?.send;if(!I||typeof I.getWriter!="function")throw new Error("WASM explicit peer stream returned an invalid writable stream");R("[WasmBridge] sendExplicitFileData open_peer_bi_explicit_file_sender resolved",{remoteNodeId:c,transferId:e.transferId??null,applicationCryptoWrapped:D.applicationCryptoWrapped===true});let w=se(D,I,{requireFinish:true}).getWriter(),M=false;try{await w.write(h);let C=new Uint8Array(await n.arrayBuffer());for(let x=0;x<C.byteLength;x+=b.EXPLICIT_FILE_CHUNK_SIZE_BYTES){let oe=C.slice(x,Math.min(x+b.EXPLICIT_FILE_CHUNK_SIZE_BYTES,C.byteLength));await w.write(oe);}}catch(C){throw M=true,C}finally{try{await w.close();}catch(C){if(!M)throw C}finally{w.releaseLock();}}return true};try{try{if(await g())return}catch(S){R("[WasmBridge] sendExplicitFileData WebRTC explicit route failed; falling back",{remoteNodeId:c,transferId:o,error:S instanceof Error?S.message:String(S)});}if(await v())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{R("[WasmBridge] sendExplicitFileData completed",{remoteNodeId:c,transferId:o,fileName:n.name,fileSize:n.size});}}async getTransferHistory(e=50){return []}async deleteTransferJob(e){}watchFriendDevices(e,t){return this.isTicketOnlyMode()?()=>{}:this.getBrowserFirestoreSignaling().watchFriendDevices(e,t)}async updateFriendTicket(e){this.isTicketOnlyMode()||await this.getBrowserFirestoreSignaling().updateFriendTicket(e);}};b.EXPLICIT_FILE_PROTOCOL_TYPE=2,b.EXPLICIT_FILE_CHUNK_SIZE_BYTES=64*1024,b.MAX_EXPLICIT_TRANSFER_HEADER_BYTES=64*1024,b.FALLBACK_EXPLICIT_FILE_NAME="openrtc-transfer.bin",b.MAX_EXPLICIT_FILE_NAME_CHARS=180,b.FALLBACK_EXPLICIT_MIME_TYPE="application/octet-stream",b.MAX_EXPLICIT_MIME_TYPE_CHARS=255,b.WEB_DEVICE_ID_STORAGE_PREFIX="pluto_rtc_web_device_identity",b.EPHEMERAL_DEVICE_ID_TTL_MS=Y.browserIdentity.ephemeralDeviceIdTtlMs;var Kt=b;var zt=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();}async getTurnCredentials(){return this.backend.getTurnCredentials()}async updatePresence(e,t,n,r,s){return this.backend.updatePresence(e,t,n,r,s)}async refreshLivePresence(e,t,n){if(typeof this.backend.refreshLivePresence!="function")throw new Error("Selected runtime adapter does not support refreshLivePresence().");return this.backend.refreshLivePresence(e,t,n)}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,n,r){return this.backend.sendMessage(e,t,n,r)}async pollMessages(e){return this.backend.pollMessages(e)}async subscribeDevices(e){return this.backend.subscribeDevices(e)}startAutoConnect(e,t){this.backend.startAutoConnect(e,t);}startPresenceLoop(e,t,n,r,s){this.backend.startPresenceLoop(e,t,n,r,s);}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,n,r,s){let o=this.backend;if(typeof o.startPresenceLoopOnce!="function")throw new Error("Selected runtime adapter does not support startPresenceLoopOnce().");return o.startPresenceLoopOnce(e,t,n,r,s)}async startAutoConnectOnce(e,t){let n=this.backend;if(typeof n.startAutoConnectOnce!="function")throw new Error("Selected runtime adapter does not support startAutoConnectOnce().");return n.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 n=this.backend;return typeof n.getEndpointTicketWithToken!="function"?null:n.getEndpointTicketWithToken(e,t)}async registerSessionToken(e,t,n){let r=this.backend;typeof r.registerSessionToken=="function"&&await r.registerSessionToken(e,t,n);}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 n=this.backend;return typeof n.is_current_transport_stable_id!="function"?false:n.is_current_transport_stable_id(e,t)}async openPeerNativeBi(e,t,n){let r=this.backend;if(typeof r.openPeerNativeBi!="function")throw new Error("Selected runtime adapter does not support openPeerNativeBi().");return r.openPeerNativeBi(e,t,n)}async openPeerBiTransportOnly(e,t){let n=this.backend;return typeof n.openPeerBiTransportOnly=="function"?n.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 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,n){if(typeof this.backend.sendExplicitFilePath!="function")throw new Error("Selected runtime adapter does not support sendExplicitFilePath().");return this.backend.sendExplicitFilePath(e,t,n)}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():ue()}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);}};export{at as A,ue as B,Si as C,Ii as D,Kt as E,zt as F,Vt as a,de as b,R as c,ui as d,fe as e,Zi as f,er as g,tr as h,nr as i,Ue as j,ti as k,Zt as l,gi as m,st as n,ot as o,We as p,ai as q,Ot as r,Ut as s,sr as t,or as u,Ht as v,Y as w,vi as x,rn as y,sn as z};